text
string
size
int64
token_count
int64
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // Name : // Author : Avi // Revision : $Revision: #10 $ // // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 #include <boost/test/unit_test.hpp> #include "Defs.hpp" #include "Suite.hpp" #include "Task.hpp" #include "ExprAst.hpp" using namespace std; using namespace ecf; BOOST_AUTO_TEST_SUITE( NodeTestSuite ) BOOST_AUTO_TEST_CASE( test_repeat_data_arithmetic ) { cout << "ANode:: ...test_repeat_data_arithmetic\n" ; Defs theDefs; task_ptr t2,t1; { suite_ptr s1 = theDefs.add_suite("s1"); t1 = s1->add_task("t1"); t1->addRepeat( RepeatDate("YMD",20090101,20091231,1)); t2 = s1->add_task("t2"); t2->add_trigger("t1:YMD ge 20080601"); } theDefs.beginAll(); // Check trigger expressions std::string errorMsg, warningMsg; BOOST_REQUIRE_MESSAGE(theDefs.check(errorMsg,warningMsg),"Expected triggers expressions to parse " << errorMsg); // Get the trigger AST AstTop* trigger = t2->triggerAst(); BOOST_REQUIRE_MESSAGE(trigger,"Expected trigger"); // check evaluation BOOST_CHECK_MESSAGE(trigger->evaluate(),"Expected trigger to evaluate i.e 20090101 >= 20080601"); // Check date arithmetic. Basics, end of months t2->changeTrigger("t1:YMD - 1 eq 20081231"); // 20090101 - 1 == 20081231 BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic for evaluation"); t2->changeTrigger("t1:YMD + 1 eq 20090102"); // 20090101 + 1 == 20090102 BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic for evaluation"); } BOOST_AUTO_TEST_CASE( test_repeat_data_arithmetic_add_to_end_of_month ) { cout << "ANode:: ...test_repeat_data_arithmetic_add_to_end_of_month\n" ; Defs theDefs; task_ptr t2,t1; { suite_ptr s1 = theDefs.add_suite("s1"); t1 = s1->add_task("t1"); t1->addRepeat( RepeatDate("YMD",20090101,20091231,1)); t2 = s1->add_task("t2"); t2->add_trigger("t1:YMD ge 20080601"); } theDefs.beginAll(); // Check trigger expressions std::string errorMsg, warningMsg; BOOST_REQUIRE_MESSAGE(theDefs.check(errorMsg,warningMsg),"Expected triggers expressions to parse " << errorMsg); // Check the end of each month + 1 t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090131,20101231,1)); // jan t2->changeTrigger("t1:YMD + 1 eq 20090201"); // 20090131 + 1 == 20090201 BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090228,20101231,1)); // feb t2->changeTrigger("t1:YMD + 1 eq 20090301"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090331,20101231,1)); // mar t2->changeTrigger("t1:YMD + 1 eq 20090401"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090430,20101231,1)); // apr t2->changeTrigger("t1:YMD + 1 eq 20090501"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090531,20101231,1)); // may t2->changeTrigger("t1:YMD + 1 eq 20090601"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090630,20101231,1)); // June t2->changeTrigger("t1:YMD + 1 eq 20090701"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090731,20101231,1)); // July t2->changeTrigger("t1:YMD + 1 eq 20090801"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090831,20101231,1)); // Aug t2->changeTrigger("t1:YMD + 1 eq 20090901"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090930,20101231,1)); // Sept t2->changeTrigger("t1:YMD + 1 eq 20091001"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091031,20101231,1)); // Oct t2->changeTrigger("t1:YMD + 1 eq 20091101"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091130,20101231,1)); // Nov t2->changeTrigger("t1:YMD + 1 eq 20091201"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091231,20101231,1)); // Dec t2->changeTrigger("t1:YMD + 1 eq 20100101"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); } BOOST_AUTO_TEST_CASE( test_repeat_data_arithmetic_take_from_end_of_month ) { cout << "ANode:: ...test_repeat_data_arithmetic_take_from_end_of_month\n" ; Defs theDefs; task_ptr t2,t1; { suite_ptr s1 = theDefs.add_suite("s1"); t1 = s1->add_task("t1"); t1->addRepeat( RepeatDate("YMD",20090101,20091231,1)); t2 = s1->add_task("t2"); t2->add_trigger("t1:YMD ge 20080601"); } theDefs.beginAll(); // Check trigger expressions std::string errorMsg, warningMsg; BOOST_REQUIRE_MESSAGE(theDefs.check(errorMsg,warningMsg),"Expected triggers expressions to parse " << errorMsg); // Check the end of each month - 1 t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090201,20101231,1)); // jan t2->changeTrigger("t1:YMD - 1 eq 20090131"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090301,20101231,1)); // feb t2->changeTrigger("t1:YMD - 1 eq 20090228"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090401,20101231,1)); // mar t2->changeTrigger("t1:YMD - 1 eq 20090331"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090501,20101231,1)); // apr t2->changeTrigger("t1:YMD - 1 eq 20090430"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090601,20101231,1)); // may t2->changeTrigger("t1:YMD - 1 eq 20090531"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090701,20101231,1)); // June t2->changeTrigger("t1:YMD - 1 eq 20090630"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090801,20101231,1)); // July t2->changeTrigger("t1:YMD - 1 eq 20090731"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090901,20101231,1)); // Aug t2->changeTrigger("t1:YMD - 1 eq 20090831"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091001 ,20101231,1)); // Sept t2->changeTrigger("t1:YMD - 1 eq 20090930"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091101 ,20101231,1)); // Oct t2->changeTrigger("t1:YMD - 1 eq 20091031"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091201 ,20101231,1)); // Nov t2->changeTrigger("t1:YMD - 1 eq 20091130"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20100101 ,20101231,1)); // Dec t2->changeTrigger("t1:YMD - 1 eq 20091231"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); } BOOST_AUTO_TEST_SUITE_END()
9,045
3,937
#include "stf.h" #include "Core/Defer.h" #include "Core/StaticVector.h" STF_SUITE_NAME("Core.StaticVector") /* _ _ | | | | | |_ ___ __| | ___ | __/ _ \ / _` |/ _ \ | || (_) | (_| | (_) | \__\___/ \__,_|\___/ #define CHECK_VECTOR(v, len, cap, data) \ do { \ STF_ASSERT(v.Length() == len); \ STF_ASSERT(v.Capacity() == cap); \ STF_ASSERT(v.Data() data); \ } while (0) #define CHECK_VECTOR_CONTENTS(v, ...) \ STF_ASSERT(v.Sub() == Slice<const int>({__VA_ARGS__})) STF_TEST("StaticVector::Init()") { StaticVector<int, 4> v; v.Init(); CHECK_VECTOR(v, 0, 4, == v.m_static); v.Free(); } STF_TEST("StaticVector::Append(const T&)") { StaticVector<int, 4> v = StaticVector<int, 4>().Init(); DEFER { v.Free(); }; CHECK_VECTOR(v, 0, 4, == v.m_static); v.Append(1); CHECK_VECTOR(v, 1, 4, == v.m_static); CHECK_VECTOR_CONTENTS(v, 1); v.Append(2); v.Append(3); v.Append(4); CHECK_VECTOR(v, 4, 4, == v.m_static); CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4); v.Append(5); STF_ASSERT(v.Length() == 5); STF_ASSERT(v.Capacity() >= 5); STF_ASSERT(v.Data() == v.m_dynamic.m_data); CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4, 5); v.Append(6); v.Append(7); v.Append(8); STF_ASSERT(v.Length() == 8); STF_ASSERT(v.Capacity() >= 8); STF_ASSERT(v.Data() == v.m_dynamic.m_data); CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4, 5, 6, 7, 8); } STF_TEST("StaticVector::Append(const T&)") { StaticVector<int, 4> v = StaticVector<int, 4>().Init(); DEFER { v.Free(); }; v.Append(1); v.Append(2); CHECK_VECTOR_CONTENTS(v, 1, 2); v.QuickRemove(1); CHECK_VECTOR_CONTENTS(v, 1); v.Append(2); v.Append(3); v.Append(4); v.Append(5); v.Append(6); CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4, 5, 6); v.QuickRemove(0); v.QuickRemove(0); STF_ASSERT(v.Data() == v.m_static); CHECK_VECTOR_CONTENTS(v, 5, 2, 3, 4); } */
1,871
977
#include "constants.h" #include "target/target.h" #include "env/env.h" // NOTE, Make sure all these includes are AFTER the system and header includes #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/MemoryLeakDetectorNewMacros.h" #include "CppUTest/TestHarness.h" #include "CppUTest/Utest.h" #include "CppUTestExt/MockSupport.h" // clang-format off TEST_GROUP(TargetTestSyncGroup) { void teardown() { } }; // clang-format on buildcc::base::Toolchain gcc(buildcc::base::Toolchain::Id::Gcc, "gcc", "as", "gcc", "g++", "ar", "ldd"); TEST(TargetTestSyncGroup, CopyByConstRef) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); srcTarget.AddSource("dummy_main.c"); srcTarget.AddIncludeDir("include", true); srcTarget.AddPch("include/include_header.h"); srcTarget.AddLibDep(srcTarget); srcTarget.AddLibDep("testLib.a"); srcTarget.AddLibDir("include"); srcTarget.AddPreprocessorFlag("-DTEST"); srcTarget.AddCommonCompileFlag("-O0"); srcTarget.AddPchCompileFlag("-pch_compile"); srcTarget.AddPchObjectFlag("-pch_object"); srcTarget.AddAsmCompileFlag("-march=test"); srcTarget.AddCCompileFlag("-std=c11"); srcTarget.AddCppCompileFlag("-std=c++17"); srcTarget.AddLinkFlag("-nostdinc"); srcTarget.AddCompileDependency("new_source.cpp"); srcTarget.AddLinkDependency("new_source.cpp"); destTarget.Copy(srcTarget, { buildcc::base::SyncOption::SourceFiles, buildcc::base::SyncOption::HeaderFiles, buildcc::base::SyncOption::PchFiles, buildcc::base::SyncOption::LibDeps, buildcc::base::SyncOption::IncludeDirs, buildcc::base::SyncOption::LibDirs, buildcc::base::SyncOption::ExternalLibDeps, buildcc::base::SyncOption::PreprocessorFlags, buildcc::base::SyncOption::CommonCompileFlags, buildcc::base::SyncOption::PchCompileFlags, buildcc::base::SyncOption::PchObjectFlags, buildcc::base::SyncOption::AsmCompileFlags, buildcc::base::SyncOption::CCompileFlags, buildcc::base::SyncOption::CppCompileFlags, buildcc::base::SyncOption::LinkFlags, buildcc::base::SyncOption::CompileDependencies, buildcc::base::SyncOption::LinkDependencies, }); CHECK_EQUAL(destTarget.GetSourceFiles().size(), 1); CHECK_EQUAL(destTarget.GetHeaderFiles().size(), 1); CHECK_EQUAL(destTarget.GetPchFiles().size(), 1); CHECK_EQUAL(destTarget.GetLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetExternalLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetIncludeDirs().size(), 1); CHECK_EQUAL(destTarget.GetLibDirs().size(), 1); CHECK_EQUAL(destTarget.GetPreprocessorFlags().size(), 1); CHECK_EQUAL(destTarget.GetCommonCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchObjectFlags().size(), 1); CHECK_EQUAL(destTarget.GetAsmCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCppCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetLinkFlags().size(), 1); CHECK_EQUAL(destTarget.GetCompileDependencies().size(), 1); CHECK_EQUAL(destTarget.GetLinkDependencies().size(), 1); } TEST(TargetTestSyncGroup, CopyByMove) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); srcTarget.AddSource("dummy_main.c"); srcTarget.AddIncludeDir("include", true); srcTarget.AddPch("include/include_header.h"); srcTarget.AddLibDep(srcTarget); srcTarget.AddLibDep("testLib.a"); srcTarget.AddLibDir("include"); srcTarget.AddPreprocessorFlag("-DTEST"); srcTarget.AddCommonCompileFlag("-O0"); srcTarget.AddPchCompileFlag("-pch_compile"); srcTarget.AddPchObjectFlag("-pch_object"); srcTarget.AddAsmCompileFlag("-march=test"); srcTarget.AddCCompileFlag("-std=c11"); srcTarget.AddCppCompileFlag("-std=c++17"); srcTarget.AddLinkFlag("-nostdinc"); srcTarget.AddCompileDependency("new_source.cpp"); srcTarget.AddLinkDependency("new_source.cpp"); destTarget.Copy(std::move(srcTarget), { buildcc::base::SyncOption::SourceFiles, buildcc::base::SyncOption::HeaderFiles, buildcc::base::SyncOption::PchFiles, buildcc::base::SyncOption::LibDeps, buildcc::base::SyncOption::IncludeDirs, buildcc::base::SyncOption::LibDirs, buildcc::base::SyncOption::ExternalLibDeps, buildcc::base::SyncOption::PreprocessorFlags, buildcc::base::SyncOption::CommonCompileFlags, buildcc::base::SyncOption::PchCompileFlags, buildcc::base::SyncOption::PchObjectFlags, buildcc::base::SyncOption::AsmCompileFlags, buildcc::base::SyncOption::CCompileFlags, buildcc::base::SyncOption::CppCompileFlags, buildcc::base::SyncOption::LinkFlags, buildcc::base::SyncOption::CompileDependencies, buildcc::base::SyncOption::LinkDependencies, }); CHECK_EQUAL(destTarget.GetSourceFiles().size(), 1); CHECK_EQUAL(destTarget.GetHeaderFiles().size(), 1); CHECK_EQUAL(destTarget.GetPchFiles().size(), 1); CHECK_EQUAL(destTarget.GetLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetExternalLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetIncludeDirs().size(), 1); CHECK_EQUAL(destTarget.GetLibDirs().size(), 1); CHECK_EQUAL(destTarget.GetPreprocessorFlags().size(), 1); CHECK_EQUAL(destTarget.GetCommonCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchObjectFlags().size(), 1); CHECK_EQUAL(destTarget.GetAsmCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCppCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetLinkFlags().size(), 1); CHECK_EQUAL(destTarget.GetCompileDependencies().size(), 1); CHECK_EQUAL(destTarget.GetLinkDependencies().size(), 1); } TEST(TargetTestSyncGroup, CopyCrash) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); CHECK_THROWS(std::exception, destTarget.Copy(srcTarget, { (buildcc::base::SyncOption)65535, })); } TEST(TargetTestSyncGroup, InsertByConstRef) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); srcTarget.AddSource("dummy_main.c"); srcTarget.AddIncludeDir("include", true); srcTarget.AddPch("include/include_header.h"); srcTarget.AddLibDep(srcTarget); srcTarget.AddLibDep("testLib.a"); srcTarget.AddLibDir("include"); srcTarget.AddPreprocessorFlag("-DTEST"); srcTarget.AddCommonCompileFlag("-O0"); srcTarget.AddPchCompileFlag("-pch_compile"); srcTarget.AddPchObjectFlag("-pch_object"); srcTarget.AddAsmCompileFlag("-march=test"); srcTarget.AddCCompileFlag("-std=c11"); srcTarget.AddCppCompileFlag("-std=c++17"); srcTarget.AddLinkFlag("-nostdinc"); srcTarget.AddCompileDependency("new_source.cpp"); srcTarget.AddLinkDependency("new_source.cpp"); destTarget.Insert(srcTarget, { buildcc::base::SyncOption::SourceFiles, buildcc::base::SyncOption::HeaderFiles, buildcc::base::SyncOption::PchFiles, buildcc::base::SyncOption::LibDeps, buildcc::base::SyncOption::IncludeDirs, buildcc::base::SyncOption::LibDirs, buildcc::base::SyncOption::ExternalLibDeps, buildcc::base::SyncOption::PreprocessorFlags, buildcc::base::SyncOption::CommonCompileFlags, buildcc::base::SyncOption::PchCompileFlags, buildcc::base::SyncOption::PchObjectFlags, buildcc::base::SyncOption::AsmCompileFlags, buildcc::base::SyncOption::CCompileFlags, buildcc::base::SyncOption::CppCompileFlags, buildcc::base::SyncOption::LinkFlags, buildcc::base::SyncOption::CompileDependencies, buildcc::base::SyncOption::LinkDependencies, }); CHECK_EQUAL(destTarget.GetSourceFiles().size(), 1); CHECK_EQUAL(destTarget.GetHeaderFiles().size(), 1); CHECK_EQUAL(destTarget.GetPchFiles().size(), 1); CHECK_EQUAL(destTarget.GetLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetExternalLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetIncludeDirs().size(), 1); CHECK_EQUAL(destTarget.GetLibDirs().size(), 1); CHECK_EQUAL(destTarget.GetPreprocessorFlags().size(), 1); CHECK_EQUAL(destTarget.GetCommonCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchObjectFlags().size(), 1); CHECK_EQUAL(destTarget.GetAsmCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCppCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetLinkFlags().size(), 1); CHECK_EQUAL(destTarget.GetCompileDependencies().size(), 1); CHECK_EQUAL(destTarget.GetLinkDependencies().size(), 1); } TEST(TargetTestSyncGroup, InsertByMove) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); srcTarget.AddSource("dummy_main.c"); srcTarget.AddIncludeDir("include", true); srcTarget.AddPch("include/include_header.h"); srcTarget.AddLibDep(srcTarget); srcTarget.AddLibDep("testLib.a"); srcTarget.AddLibDir("include"); srcTarget.AddPreprocessorFlag("-DTEST"); srcTarget.AddCommonCompileFlag("-O0"); srcTarget.AddPchCompileFlag("-pch_compile"); srcTarget.AddPchObjectFlag("-pch_object"); srcTarget.AddAsmCompileFlag("-march=test"); srcTarget.AddCCompileFlag("-std=c11"); srcTarget.AddCppCompileFlag("-std=c++17"); srcTarget.AddLinkFlag("-nostdinc"); srcTarget.AddCompileDependency("new_source.cpp"); srcTarget.AddLinkDependency("new_source.cpp"); destTarget.Insert(std::move(srcTarget), { buildcc::base::SyncOption::SourceFiles, buildcc::base::SyncOption::HeaderFiles, buildcc::base::SyncOption::PchFiles, buildcc::base::SyncOption::LibDeps, buildcc::base::SyncOption::IncludeDirs, buildcc::base::SyncOption::LibDirs, buildcc::base::SyncOption::ExternalLibDeps, buildcc::base::SyncOption::PreprocessorFlags, buildcc::base::SyncOption::CommonCompileFlags, buildcc::base::SyncOption::PchCompileFlags, buildcc::base::SyncOption::PchObjectFlags, buildcc::base::SyncOption::AsmCompileFlags, buildcc::base::SyncOption::CCompileFlags, buildcc::base::SyncOption::CppCompileFlags, buildcc::base::SyncOption::LinkFlags, buildcc::base::SyncOption::CompileDependencies, buildcc::base::SyncOption::LinkDependencies, }); CHECK_EQUAL(destTarget.GetSourceFiles().size(), 1); CHECK_EQUAL(destTarget.GetHeaderFiles().size(), 1); CHECK_EQUAL(destTarget.GetPchFiles().size(), 1); CHECK_EQUAL(destTarget.GetLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetExternalLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetIncludeDirs().size(), 1); CHECK_EQUAL(destTarget.GetLibDirs().size(), 1); CHECK_EQUAL(destTarget.GetPreprocessorFlags().size(), 1); CHECK_EQUAL(destTarget.GetCommonCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchObjectFlags().size(), 1); CHECK_EQUAL(destTarget.GetAsmCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCppCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetLinkFlags().size(), 1); CHECK_EQUAL(destTarget.GetCompileDependencies().size(), 1); CHECK_EQUAL(destTarget.GetLinkDependencies().size(), 1); } TEST(TargetTestSyncGroup, InsertCrash) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); CHECK_THROWS( std::exception, destTarget.Insert(srcTarget, { (buildcc::base::SyncOption)65535, })); } int main(int ac, char **av) { buildcc::env::init(BUILD_SCRIPT_SOURCE, BUILD_TARGET_SYNC_INTERMEDIATE_DIR); fs::remove_all(buildcc::env::get_project_build_dir()); return CommandLineTestRunner::RunAllTests(ac, av); }
14,252
4,516
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=2020; const int inf=1000000000; int n,mxP,W; int F[maxN][maxN]; int Q[maxN]; int main(){ int TTT;scanf("%d",&TTT); while (TTT--){ scanf("%d%d%d",&n,&mxP,&W); for (int i=0;i<=n;i++) for (int j=0;j<=mxP;j++) F[i][j]=-inf; F[0][0]=0; for (int i=1;i<=n;i++){ int as,bs,ap,bp;scanf("%d%d%d%d",&ap,&bp,&as,&bs); int lst=max(0,i-W-1); for (int j=0;j<=mxP;j++) F[i][j]=max(F[i][j],F[i-1][j]); int L=1,R=0; for (int j=0;j<=mxP;j++){ while ((L<=R)&&(Q[L]<j-as)) L++; if (L<=R) F[i][j]=max(F[i][j],F[lst][Q[L]]+ap*Q[L]-ap*j); while ((L<=R)&&(F[lst][Q[R]]+ap*Q[R]<=F[lst][j]+ap*j)) R--; Q[++R]=j; } L=1;R=0; for (int j=mxP;j>=0;j--){ while ((L<=R)&&(Q[L]>j+bs)) L++; if (L<=R) F[i][j]=max(F[i][j],F[lst][Q[L]]+bp*Q[L]-bp*j); while ((L<=R)&&(F[lst][Q[R]]+bp*Q[R]<=F[lst][j]+bp*j)) R--; Q[++R]=j; } } /* for (int i=1;i<=n;i++){ for (int j=0;j<=mxP;j++) cout<<F[i][j]<<" "; cout<<endl; } //*/ int Ans=0; for (int i=0;i<=mxP;i++) Ans=max(Ans,F[n][i]); printf("%d\n",Ans); } return 0; }
1,267
787
/******************************************************************************* * Copyright 2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions * and limitations under the License. * * * SPDX-License-Identifier: Apache-2.0 *******************************************************************************/ #include <CL/sycl.hpp> #include "cpu_common.hpp" namespace onemkl { namespace mklcpu { void asum(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_sasum>(cgh, [=]() { accessor_result[0] = ::sasum((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void asum(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_dasum>(cgh, [=]() { accessor_result[0] = ::dasum((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void asum(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_scasum>(cgh, [=]() { accessor_result[0] = ::scasum((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void asum(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_dzasum>(cgh, [=]() { accessor_result[0] = ::dzasum((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void axpy(cl::sycl::queue &queue, int64_t n, float alpha, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_saxpy>(cgh, [=]() { ::saxpy((const MKL_INT *)&n, (const float *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void axpy(cl::sycl::queue &queue, int64_t n, double alpha, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_daxpy>(cgh, [=]() { ::daxpy((const MKL_INT *)&n, (const double *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void axpy(cl::sycl::queue &queue, int64_t n, std::complex<float> alpha, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { float alpha_real = alpha.real(), alpha_imag = alpha.imag(); auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_caxpy>(cgh, [=]() { MKL_Complex8 alpha_ = { alpha_real, alpha_imag }; ::caxpy((const MKL_INT *)&n, (const MKL_Complex8 *)&alpha_, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void axpy(cl::sycl::queue &queue, int64_t n, std::complex<double> alpha, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { double alpha_real = alpha.real(), alpha_imag = alpha.imag(); auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zaxpy>(cgh, [=]() { MKL_Complex16 alpha_ = { alpha_real, alpha_imag }; ::zaxpy((const MKL_INT *)&n, (const MKL_Complex16 *)&alpha_, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void copy(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_scopy>(cgh, [=]() { ::scopy((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void copy(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_dcopy>(cgh, [=]() { ::dcopy((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void copy(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_ccopy>(cgh, [=]() { ::ccopy((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void copy(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zcopy>(cgh, [=]() { ::zcopy((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_sdot>(cgh, [=]() { accessor_result[0] = ::sdot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_ddot>(cgh, [=]() { accessor_result[0] = ::ddot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_dsdot>(cgh, [=]() { accessor_result[0] = ::dsdot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dotc(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy, cl::sycl::buffer<std::complex<float>, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_cdotc>(cgh, [=]() { ::cdotc(accessor_result.get_pointer(), (const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dotc(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy, cl::sycl::buffer<std::complex<double>, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zdotc>(cgh, [=]() { ::zdotc(accessor_result.get_pointer(), (const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dotu(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy, cl::sycl::buffer<std::complex<float>, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_cdotu>(cgh, [=]() { ::cdotu(accessor_result.get_pointer(), (const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dotu(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy, cl::sycl::buffer<std::complex<double>, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zdotu>(cgh, [=]() { ::zdotu(accessor_result.get_pointer(), (const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void iamin(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_isamin>(cgh, [=]() { accessor_result[0] = ::cblas_isamin((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamin(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.template get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.template get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_idamin>(cgh, [=]() { accessor_result[0] = ::cblas_idamin((const MKL_INT)n, accessor_x.get_pointer(), (const MKL_INT)incx); }); }); } void iamin(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_icamin>(cgh, [=]() { accessor_result[0] = ::cblas_icamin((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamin(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_izamin>(cgh, [=]() { accessor_result[0] = ::cblas_izamin((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamax(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_isamax>(cgh, [=]() { accessor_result[0] = ::cblas_isamax((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamax(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_idamax>(cgh, [=]() { accessor_result[0] = ::cblas_idamax((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamax(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_icamax>(cgh, [=]() { accessor_result[0] = ::cblas_icamax((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamax(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_izamax>(cgh, [=]() { accessor_result[0] = ::cblas_izamax((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void nrm2(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.template get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.template get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_snrm2>(cgh, [=]() { accessor_result[0] = ::snrm2((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void nrm2(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_dnrm2>(cgh, [=]() { accessor_result[0] = ::dnrm2((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void nrm2(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_scnrm2>(cgh, [=]() { accessor_result[0] = ::scnrm2((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void nrm2(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_dznrm2>(cgh, [=]() { accessor_result[0] = ::dznrm2((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void rot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy, float c, float s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_srot>(cgh, [=]() { ::srot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, &c, &s); }); }); } void rot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy, double c, double s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_drot>(cgh, [=]() { ::drot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, &c, &s); }); }); } void rot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy, float c, float s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_csrot>(cgh, [=]() { ::csrot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, &c, &s); }); }); } void rot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy, double c, double s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zdrot>(cgh, [=]() { ::zdrot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, &c, &s); }); }); } void rotg(cl::sycl::queue &queue, cl::sycl::buffer<float, 1> &a, cl::sycl::buffer<float, 1> &b, cl::sycl::buffer<float, 1> &c, cl::sycl::buffer<float, 1> &s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_a = a.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_b = b.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_c = c.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_s = s.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_srotg>(cgh, [=]() { ::srotg(accessor_a.get_pointer(), accessor_b.get_pointer(), accessor_c.get_pointer(), accessor_s.get_pointer()); }); }); } void rotg(cl::sycl::queue &queue, cl::sycl::buffer<double, 1> &a, cl::sycl::buffer<double, 1> &b, cl::sycl::buffer<double, 1> &c, cl::sycl::buffer<double, 1> &s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_a = a.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_b = b.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_c = c.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_s = s.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_drotg>(cgh, [=]() { ::drotg(accessor_a.get_pointer(), accessor_b.get_pointer(), accessor_c.get_pointer(), accessor_s.get_pointer()); }); }); } void rotg(cl::sycl::queue &queue, cl::sycl::buffer<std::complex<float>, 1> &a, cl::sycl::buffer<std::complex<float>, 1> &b, cl::sycl::buffer<float, 1> &c, cl::sycl::buffer<std::complex<float>, 1> &s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_a = a.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_b = b.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_c = c.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_s = s.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_crotg>(cgh, [=]() { ::crotg(accessor_a.get_pointer(), accessor_b.get_pointer(), accessor_c.get_pointer(), accessor_s.get_pointer()); }); }); } void rotg(cl::sycl::queue &queue, cl::sycl::buffer<std::complex<double>, 1> &a, cl::sycl::buffer<std::complex<double>, 1> &b, cl::sycl::buffer<double, 1> &c, cl::sycl::buffer<std::complex<double>, 1> &s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_a = a.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_b = b.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_c = c.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_s = s.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zrotg>(cgh, [=]() { ::zrotg(accessor_a.get_pointer(), accessor_b.get_pointer(), accessor_c.get_pointer(), accessor_s.get_pointer()); }); }); } void rotm(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy, cl::sycl::buffer<float, 1> &param) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_param = param.get_access<cl::sycl::access::mode::read>(cgh); host_task<class mkl_kernel_srotm>(cgh, [=]() { ::srotm((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, accessor_param.get_pointer()); }); }); } void rotm(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy, cl::sycl::buffer<double, 1> &param) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_param = param.get_access<cl::sycl::access::mode::read>(cgh); host_task<class mkl_kernel_drotm>(cgh, [=]() { ::drotm((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, accessor_param.get_pointer()); }); }); } void rotmg(cl::sycl::queue &queue, cl::sycl::buffer<float, 1> &d1, cl::sycl::buffer<float, 1> &d2, cl::sycl::buffer<float, 1> &x1, float y1, cl::sycl::buffer<float, 1> &param) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_d1 = d1.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_d2 = d2.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_x1 = x1.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_param = param.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_srotmg>(cgh, [=]() { ::srotmg(accessor_d1.get_pointer(), accessor_d2.get_pointer(), accessor_x1.get_pointer(), (float *)&y1, accessor_param.get_pointer()); }); }); } void rotmg(cl::sycl::queue &queue, cl::sycl::buffer<double, 1> &d1, cl::sycl::buffer<double, 1> &d2, cl::sycl::buffer<double, 1> &x1, double y1, cl::sycl::buffer<double, 1> &param) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_d1 = d1.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_d2 = d2.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_x1 = x1.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_param = param.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_drotmg>(cgh, [=]() { ::drotmg(accessor_d1.get_pointer(), accessor_d2.get_pointer(), accessor_x1.get_pointer(), (double *)&y1, accessor_param.get_pointer()); }); }); } void scal(cl::sycl::queue &queue, int64_t n, float alpha, cl::sycl::buffer<float, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_sscal>(cgh, [=]() { ::sscal((const MKL_INT *)&n, (const float *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void scal(cl::sycl::queue &queue, int64_t n, double alpha, cl::sycl::buffer<double, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_dscal>(cgh, [=]() { ::dscal((const MKL_INT *)&n, (const double *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void scal(cl::sycl::queue &queue, int64_t n, std::complex<float> alpha, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { float alpha_real = alpha.real(), alpha_imag = alpha.imag(); auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_cscal>(cgh, [=]() { MKL_Complex8 alpha_ = { alpha_real, alpha_imag }; ::cscal((const MKL_INT *)&n, (const MKL_Complex8 *)&alpha_, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void scal(cl::sycl::queue &queue, int64_t n, float alpha, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_csscal>(cgh, [=]() { ::csscal((const MKL_INT *)&n, (const float *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void scal(cl::sycl::queue &queue, int64_t n, std::complex<double> alpha, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { double alpha_real = alpha.real(), alpha_imag = alpha.imag(); auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zscal>(cgh, [=]() { MKL_Complex16 alpha_ = { alpha_real, alpha_imag }; ::zscal((const MKL_INT *)&n, (const MKL_Complex16 *)&alpha_, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void scal(cl::sycl::queue &queue, int64_t n, double alpha, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zdscal>(cgh, [=]() { ::zdscal((const MKL_INT *)&n, (const double *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void sdsdot(cl::sycl::queue &queue, int64_t n, float sb, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_sdsdot>(cgh, [=]() { accessor_result[0] = ::sdsdot((const MKL_INT *)&n, (const float *)&sb, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void swap(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_sswap>(cgh, [=]() { ::sswap((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void swap(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_dswap>(cgh, [=]() { ::dswap((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void swap(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_cswap>(cgh, [=]() { ::cswap((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void swap(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zswap>(cgh, [=]() { ::zswap((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } } // namespace mklcpu } // namespace onemkl
36,023
14,379
/***************************************************************** * * $Id: StTrsAnalogSignal.hh,v 1.7 2005/09/09 22:12:48 perev Exp $ * * Author: brian Nov 1, 1998 * ***************************************************************** * Description: * ***************************************************************** * * $Log: StTrsAnalogSignal.hh,v $ * Revision 1.7 2005/09/09 22:12:48 perev * Bug fix + IdTruth added * * Revision 1.6 2003/12/24 13:44:51 fisyak * Add (GEANT) track Id information in Trs; propagate it via St_tpcdaq_Maker; account interface change in StTrsZeroSuppressedReaded in StMixerMaker * * Revision 1.5 2003/09/02 17:59:16 perev * gcc 3.2 updates + WarnOff * * Revision 1.4 2000/01/10 23:11:30 lasiuk * Include MACROS for compatibility with SUN CC5.0 * * Revision 1.3 1999/01/15 11:03:14 lasiuk * modify << operator for STL use * * Revision 1.2 1998/11/13 21:29:46 lasiuk * << operator * * Revision 1.1 1998/11/10 17:12:08 fisyak * Put Brian trs versin into StRoot * * Revision 1.1 1998/11/01 13:46:43 lasiuk * Initial Revision * ******************************************************************/ #ifndef ST_TRS_ANALOGSIGNAL_HH #define ST_TRS_ANALOGSIGNAL_HH #include <assert.h> #include <Stiostream.h> #include <utility> #if defined (__SUNPRO_CC) && __SUNPRO_CC >= 0x500 using std::pair; #endif class StTrsAnalogSignal { public: StTrsAnalogSignal(); StTrsAnalogSignal(float, float, int id=0); ~StTrsAnalogSignal(); //StTrsAnalogSignal(const StTrsAnalogSignal&); // use default //StTrsAnalogSignal& operator=(const StTrsAnalogSignal&); // use default StTrsAnalogSignal& operator+=(const StTrsAnalogSignal&); // access functions float time() const; float amplitude() const; int id() const {return mId;} void setTime(float); void setAmplitude(float); void scaleAmplitude(float); void setId(int id) {mId = id;} protected: int mId; // geant track no. float mTime; float mAmp; }; inline float StTrsAnalogSignal::time() const {return mTime;} inline float StTrsAnalogSignal::amplitude() const {return mAmp; } inline void StTrsAnalogSignal::setTime(float t) { mTime = t; } inline void StTrsAnalogSignal::setAmplitude(float a) { mAmp = a; } inline void StTrsAnalogSignal::scaleAmplitude(float fac){ mAmp *= fac;} // Non-member function ostream& operator<<(ostream&, const StTrsAnalogSignal&); class StTrsAnalogSignalComparator { public: bool operator()(StTrsAnalogSignal x, StTrsAnalogSignal y) { return (x.time() < y.time()); } }; #endif
2,722
1,079
// null_polarity_generator.cpp // // Anton Betten // December 11, 2015 #include "foundations.h" using namespace std; namespace orbiter { namespace foundations { null_polarity_generator::null_polarity_generator() { null(); } null_polarity_generator::~null_polarity_generator() { freeself(); } void null_polarity_generator::null() { nb_candidates = NULL; cur_candidate = NULL; candidates = NULL; Mtx = NULL; v = NULL; w = NULL; Points = NULL; nb_gens = 0; Data = NULL; transversal_length = NULL; } void null_polarity_generator::freeself() { int i; if (nb_candidates) { FREE_int(nb_candidates); } if (cur_candidate) { FREE_int(cur_candidate); } if (candidates) { for (i = 0; i < n + 1; i++) { FREE_int(candidates[i]); } FREE_pint(candidates); } if (Mtx) { FREE_int(Mtx); } if (v) { FREE_int(v); } if (w) { FREE_int(w); } if (Points) { FREE_int(Points); } if (Data) { FREE_int(Data); } if (transversal_length) { FREE_int(transversal_length); } null(); } void null_polarity_generator::init(finite_field *F, int n, int verbose_level) { int f_v = (verbose_level >= 1); int i; number_theory_domain NT; geometry_global Gg; if (f_v) { cout << "null_polarity_generator::init" << endl; } null_polarity_generator::F = F; null_polarity_generator::n = n; q = F->q; qn = NT.i_power_j(q, n); nb_candidates = NEW_int(n + 1); cur_candidate = NEW_int(n); candidates = NEW_pint(n + 1); for (i = 0; i < n + 1; i++) { candidates[i] = NEW_int(qn); } Mtx = NEW_int(n * n); v = NEW_int(n); w = NEW_int(n); Points = NEW_int(qn * n); for (i = 0; i < qn; i++) { Gg.AG_element_unrank(q, Points + i * n, 1, n, i); } create_first_candidate_set(verbose_level); if (f_v) { cout << "first candidate set has size " << nb_candidates[0] << endl; } //backtrack_search(0 /* depth */, verbose_level); int first_moved = n; int nb; nb_gens = 0; first_moved = n; transversal_length = NEW_int(n); for (i = 0; i < n; i++) { transversal_length[i] = 1; } count_strong_generators(nb_gens, transversal_length, first_moved, 0, verbose_level); if (f_v) { cout << "We found " << nb_gens << " strong generators" << endl; cout << "transversal_length = "; Orbiter->Int_vec.print(cout, transversal_length, n); cout << endl; cout << "group order: "; print_longinteger_after_multiplying(cout, transversal_length, n); cout << endl; } Data = NEW_int(nb_gens * n * n); nb = 0; first_moved = n; get_strong_generators(Data, nb, first_moved, 0, verbose_level); if (nb != nb_gens) { cout << "nb != nb_gens" << endl; exit(1); } if (f_v) { cout << "The strong generators are:" << endl; for (i = 0; i < nb_gens; i++) { cout << "generator " << i << " / " << nb_gens << ":" << endl; Orbiter->Int_vec.matrix_print(Data + i * n * n, n, n); } } if (f_v) { cout << "null_polarity_generator::init done" << endl; } } int null_polarity_generator::count_strong_generators( int &nb, int *transversal_length, int &first_moved, int depth, int verbose_level) { //int f_v = (verbose_level >= 1); int a; if (depth == n) { //cout << "solution " << nb << endl; //int_matrix_print(Mtx, n, n); if (first_moved < n) { transversal_length[first_moved]++; } nb++; return FALSE; } for (cur_candidate[depth] = 0; cur_candidate[depth] < nb_candidates[depth]; cur_candidate[depth]++) { if (cur_candidate[depth] && depth < first_moved) { first_moved = depth; } a = candidates[depth][cur_candidate[depth]]; if (FALSE) { cout << "depth " << depth << " " << cur_candidate[depth] << " / " << nb_candidates[depth] << " which is " << a << endl; } Orbiter->Int_vec.copy(Points + a * n, Mtx + depth * n, n); create_next_candidate_set(depth, 0 /* verbose_level */); if (!count_strong_generators(nb, transversal_length, first_moved, depth + 1, verbose_level) && depth > first_moved) { return FALSE; } } return TRUE; } int null_polarity_generator::get_strong_generators( int *Data, int &nb, int &first_moved, int depth, int verbose_level) { //int f_v = (verbose_level >= 1); int a; if (depth == n) { //cout << "solution " << nb << endl; //int_matrix_print(Mtx, n, n); Orbiter->Int_vec.copy(Mtx, Data + nb * n * n, n * n); nb++; return FALSE; } for (cur_candidate[depth] = 0; cur_candidate[depth] < nb_candidates[depth]; cur_candidate[depth]++) { if (cur_candidate[depth] && depth < first_moved) { first_moved = depth; } a = candidates[depth][cur_candidate[depth]]; if (FALSE) { cout << "depth " << depth << " " << cur_candidate[depth] << " / " << nb_candidates[depth] << " which is " << a << endl; } Orbiter->Int_vec.copy(Points + a * n, Mtx + depth * n, n); create_next_candidate_set(depth, 0 /* verbose_level */); if (!get_strong_generators(Data, nb, first_moved, depth + 1, verbose_level) && depth > first_moved) { return FALSE; } } return TRUE; } void null_polarity_generator::backtrack_search( int &nb_sol, int depth, int verbose_level) { int f_v = (verbose_level >= 1); int a; if (depth == n) { if (f_v) { cout << "solution " << nb_sol << endl; Orbiter->Int_vec.matrix_print(Mtx, n, n); } nb_sol++; return; } for (cur_candidate[depth] = 0; cur_candidate[depth] < nb_candidates[depth]; cur_candidate[depth]++) { a = candidates[depth][cur_candidate[depth]]; if (FALSE) { cout << "depth " << depth << " " << cur_candidate[depth] << " / " << nb_candidates[depth] << " which is " << a << endl; } Orbiter->Int_vec.copy(Points + a * n, Mtx + depth * n, n); create_next_candidate_set(depth, 0 /* verbose_level */); backtrack_search(nb_sol, depth + 1, verbose_level); } } void null_polarity_generator::create_first_candidate_set( int verbose_level) { int f_v = (verbose_level >= 1); int i, nb; if (f_v) { cout << "null_polarity_generator::create_" "first_candidate_set" << endl; } nb = 0; for (i = 0; i < qn; i++) { Orbiter->Int_vec.copy(Points + i * n, v, n); if (dot_product(v, v) == 1) { candidates[0][nb++] = i; } } nb_candidates[0] = nb; if (f_v) { cout << "null_polarity_generator::create_" "first_candidate_set done" << endl; } } void null_polarity_generator::create_next_candidate_set( int level, int verbose_level) { int f_v = (verbose_level >= 1); int i, ai, nb; if (f_v) { cout << "null_polarity_generator::create_next_candidate_set " "level=" << level << endl; } nb = 0; Orbiter->Int_vec.copy(Mtx + level * n, v, n); for (i = 0; i < nb_candidates[level]; i++) { ai = candidates[level][i]; Orbiter->Int_vec.copy(Points + ai * n, w, n); if (dot_product(v, w) == 0) { candidates[level + 1][nb++] = ai; } } nb_candidates[level + 1] = nb; if (f_v) { cout << "null_polarity_generator::create_next_candidate_set " "done, found " << nb_candidates[level + 1] << " candidates at level " << level + 1 << endl; } } int null_polarity_generator::dot_product(int *u1, int *u2) { return F->dot_product(n, u1, u2); } } }
7,128
3,357
/* * reads.cpp for FR-HIT * Copyright (c) 2010-2011 Beifang Niu All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "reads.h" //#define DEBUG using namespace std; void ReadClass::CheckFile(ifstream &fin) { //check fasta or fastq format | for frhit, only fasta format can be processed string s1,s2,s3,s4; char ch[1000]; fin>>s1; fin.getline(ch, 1000); fin>>s2; fin.getline(ch, 1000); if ('>' == s1[0]) _file_format=1; else if ('@' == s1[0]) { fin>>s3; fin.getline(ch, 1000); fin>>s4; fin.getline(ch, 1000); _file_format=0; if (s2.size() != s4.size()) { cerr << "fatal error: fq format, sequence length not equal to quality length\n"; exit(1); } } else { cerr << "fatal error: unrecognizable format of reads file.\n"; exit(1); } fin.seekg(0); } int ReadClass::LoadBatchReads(ifstream &fin) { char ch[1000]; char c; string s; mreads.resize(BatchNum*param.ncpu); vector<ReadInf>::iterator p=mreads.begin(); for (num=0; num<BatchNum*param.ncpu; num++,p++,_index++) { p->seq.clear(); p->seq.resize(param.max_read_size); string::iterator z = p->seq.begin(); fin>>c; if (fin.eof()) break; p->index = _index; fin>>p->name; fin.getline(ch,1000); p->length = 0; while(!fin.eof()) { fin>>c; if (fin.eof()) break; fin.unget(); if (c == '>') break; fin>>s; if (p->length+s.size() >= param.max_read_size) { param.max_read_size+=param.append_read_size; p->seq.resize(param.max_read_size); z=p->seq.begin() + p->length; } copy(s.begin(), s.end(), z); z += s.size(); p->length+=s.size(); } p->seq.resize(p->length); #ifdef DEBUG // test seq info cerr<<" seq "<<p->seq<<endl<<" length "<<p->length<<endl; #endif } return num; } int ReadClass::LoadBatchFastqReads(ifstream &fin) { char ch[1000]; char c; string s; string plus; string q; mreads.resize(BatchNum*param.ncpu); vector<ReadInf>::iterator p=mreads.begin(); for (num=0; num<BatchNum*param.ncpu; num++,p++,_index++) { p->seq.clear(); p->seq.resize(param.max_read_size); string::iterator z = p->seq.begin(); //fin>>c; if (fin.eof()) break; p->index = _index; fin>>p->name; fin.getline(ch,1000); p->length = 0; while(!fin.eof()) { fin>>c; if (fin.eof()) break; fin.unget(); if (c == '@') break; fin>>s; fin>>plus; fin>>q; if (p->length+s.size() >= param.max_read_size) { param.max_read_size+=param.append_read_size; p->seq.resize(param.max_read_size); z=p->seq.begin() + p->length; } copy(s.begin(), s.end(), z); z += s.size(); p->length+=s.size(); } p->seq.resize(p->length); #ifdef DEBUG // test seq info cout<<" seq "<<p->seq<<endl<<" length "<<p->length<<endl; #endif } return num; }
4,491
1,590
#include "common/stl/base.h" #include "common/vector/read_lines.h" #include "common/vector/sum.h" int main_2120b() { auto vs = nvector::ReadLines(); vector<unsigned> vm; for (auto c : vs[0]) vm.push_back((c == '#') ? 1 : 0); unsigned steps = 50, shift = steps + 2, n = vs.size() - 2, m = vs[2].size(); unsigned N = n + 2 * shift, M = m + 2 * shift; vector<vector<unsigned>> v(N, vector<unsigned>(M, 0)); for (unsigned i = 0; i < n; ++i) { auto& s = vs[i + 2]; for (unsigned j = 0; j < s.size(); ++j) v[i + shift][j + shift] = ((s[j] == '#') ? 1 : 0); } auto v2 = v; unsigned d = 0; for (unsigned is = 0; is < steps; ++is) { for (unsigned i = 0; i + 2 < N; ++i) { for (unsigned j = 0; j + 2 < M; ++j) { unsigned x = 0; for (unsigned di = 0; di < 3; ++di) { for (unsigned dj = 0; dj < 3; ++dj) { x = 2 * x + v[i + di][j + dj]; } } v2[i + 1][j + 1] = vm[x]; } } d = vm[d * 511]; for (unsigned i = 0; i < N; ++i) v2[i][0] = v2[i][M - 1] = d; for (unsigned j = 0; j < M; ++j) v2[0][j] = v2[N - 1][j] = d; v.swap(v2); } cout << nvector::SumVV(v) << endl; return 0; }
1,204
557
/** * \file * * \brief Enhanced Embedded Flash Controller (EEFC) driver for SAM. * * Copyright (c) 2011-2012 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * 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. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ #include "efc.h" /// @cond 0 /**INDENT-OFF**/ #ifdef __cplusplus extern "C" { #endif /**INDENT-ON**/ /// @endcond /** * \defgroup sam_drivers_efc_group Enhanced Embedded Flash Controller (EEFC) * * The Enhanced Embedded Flash Controller ensures the interface of the Flash * block with the 32-bit internal bus. * * @{ */ /* Address definition for read operation */ # define READ_BUFF_ADDR0 IFLASH0_ADDR # define READ_BUFF_ADDR1 IFLASH1_ADDR /* Flash Writing Protection Key */ #define FWP_KEY 0x5Au #if (SAM4S || SAM4E) #define EEFC_FCR_FCMD(value) \ ((EEFC_FCR_FCMD_Msk & ((value) << EEFC_FCR_FCMD_Pos))) #define EEFC_ERROR_FLAGS (EEFC_FSR_FLOCKE | EEFC_FSR_FCMDE | EEFC_FSR_FLERR) #else #define EEFC_ERROR_FLAGS (EEFC_FSR_FLOCKE | EEFC_FSR_FCMDE) #endif /* * Local function declaration. * Because they are RAM functions, they need 'extern' declaration. */ extern void efc_write_fmr(Efc *p_efc, uint32_t ul_fmr); extern uint32_t efc_perform_fcr(Efc *p_efc, uint32_t ul_fcr); /** * \brief Initialize the EFC controller. * * \param ul_access_mode 0 for 128-bit, EEFC_FMR_FAM for 64-bit. * \param ul_fws The number of wait states in cycle (no shift). * * \return 0 if successful. */ uint32_t efc_init(Efc *p_efc, uint32_t ul_access_mode, uint32_t ul_fws) { efc_write_fmr(p_efc, ul_access_mode | EEFC_FMR_FWS(ul_fws)); return EFC_RC_OK; } /** * \brief Enable the flash ready interrupt. * * \param p_efc Pointer to an EFC instance. */ void efc_enable_frdy_interrupt(Efc *p_efc) { uint32_t ul_fmr = p_efc->EEFC_FMR; efc_write_fmr(p_efc, ul_fmr | EEFC_FMR_FRDY); } /** * \brief Disable the flash ready interrupt. * * \param p_efc Pointer to an EFC instance. */ void efc_disable_frdy_interrupt(Efc *p_efc) { uint32_t ul_fmr = p_efc->EEFC_FMR; efc_write_fmr(p_efc, ul_fmr & (~EEFC_FMR_FRDY)); } /** * \brief Set flash access mode. * * \param p_efc Pointer to an EFC instance. * \param ul_mode 0 for 128-bit, EEFC_FMR_FAM for 64-bit. */ void efc_set_flash_access_mode(Efc *p_efc, uint32_t ul_mode) { uint32_t ul_fmr = p_efc->EEFC_FMR & (~EEFC_FMR_FAM); efc_write_fmr(p_efc, ul_fmr | ul_mode); } /** * \brief Get flash access mode. * * \param p_efc Pointer to an EFC instance. * * \return 0 for 128-bit or EEFC_FMR_FAM for 64-bit. */ uint32_t efc_get_flash_access_mode(Efc *p_efc) { return (p_efc->EEFC_FMR & EEFC_FMR_FAM); } /** * \brief Set flash wait state. * * \param p_efc Pointer to an EFC instance. * \param ul_fws The number of wait states in cycle (no shift). */ void efc_set_wait_state(Efc *p_efc, uint32_t ul_fws) { uint32_t ul_fmr = p_efc->EEFC_FMR & (~EEFC_FMR_FWS_Msk); efc_write_fmr(p_efc, ul_fmr | EEFC_FMR_FWS(ul_fws)); } /** * \brief Get flash wait state. * * \param p_efc Pointer to an EFC instance. * * \return The number of wait states in cycle (no shift). */ uint32_t efc_get_wait_state(Efc *p_efc) { return ((p_efc->EEFC_FMR & EEFC_FMR_FWS_Msk) >> EEFC_FMR_FWS_Pos); } /** * \brief Perform the given command and wait until its completion (or an error). * * \note Unique ID commands are not supported, use efc_read_unique_id. * * \param p_efc Pointer to an EFC instance. * \param ul_command Command to perform. * \param ul_argument Optional command argument. * * \note This function will automatically choose to use IAP function. * * \return 0 if successful, otherwise returns an error code. */ uint32_t efc_perform_command(Efc *p_efc, uint32_t ul_command, uint32_t ul_argument) { /* Unique ID commands are not supported. */ if (ul_command == EFC_FCMD_STUI || ul_command == EFC_FCMD_SPUI) { return EFC_RC_NOT_SUPPORT; } /* Use IAP function with 2 parameters in ROM. */ static uint32_t(*iap_perform_command) (uint32_t, uint32_t); uint32_t ul_efc_nb = (p_efc == EFC0) ? 0 : 1; iap_perform_command = (uint32_t(*)(uint32_t, uint32_t)) *((uint32_t *) CHIP_FLASH_IAP_ADDRESS); iap_perform_command(ul_efc_nb, EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(ul_argument) | EEFC_FCR_FCMD(ul_command)); return (p_efc->EEFC_FSR & EEFC_ERROR_FLAGS); } /** * \brief Get the current status of the EEFC. * * \note This function clears the value of some status bits (FLOCKE, FCMDE). * * \param p_efc Pointer to an EFC instance. * * \return The current status. */ uint32_t efc_get_status(Efc *p_efc) { return p_efc->EEFC_FSR; } /** * \brief Get the result of the last executed command. * * \param p_efc Pointer to an EFC instance. * * \return The result of the last executed command. */ uint32_t efc_get_result(Efc *p_efc) { return p_efc->EEFC_FRR; } /** * \brief Perform read sequence. Supported sequences are read Unique ID and * read User Signature * * \param p_efc Pointer to an EFC instance. * \param ul_cmd_st Start command to perform. * \param ul_cmd_sp Stop command to perform. * \param p_ul_buf Pointer to an data buffer. * \param ul_size Buffer size. * * \return 0 if successful, otherwise returns an error code. */ RAMFUNC uint32_t efc_perform_read_sequence(Efc *p_efc, uint32_t ul_cmd_st, uint32_t ul_cmd_sp, uint32_t *p_ul_buf, uint32_t ul_size) { volatile uint32_t ul_status; uint32_t ul_cnt; uint32_t *p_ul_data = (uint32_t *) ((p_efc == EFC0) ? READ_BUFF_ADDR0 : READ_BUFF_ADDR1); if (p_ul_buf == NULL) { return EFC_RC_INVALID; } p_efc->EEFC_FMR |= (0x1u << 16); /* Send the Start Read command */ p_efc->EEFC_FCR = EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(0) | EEFC_FCR_FCMD(ul_cmd_st); /* Wait for the FRDY bit in the Flash Programming Status Register * (EEFC_FSR) falls. */ do { ul_status = p_efc->EEFC_FSR; } while ((ul_status & EEFC_FSR_FRDY) == EEFC_FSR_FRDY); /* The data is located in the first address of the Flash * memory mapping. */ for (ul_cnt = 0; ul_cnt < ul_size; ul_cnt++) { p_ul_buf[ul_cnt] = p_ul_data[ul_cnt]; } /* To stop the read mode */ p_efc->EEFC_FCR = EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(0) | EEFC_FCR_FCMD(ul_cmd_sp); /* Wait for the FRDY bit in the Flash Programming Status Register (EEFC_FSR) * rises. */ do { ul_status = p_efc->EEFC_FSR; } while ((ul_status & EEFC_FSR_FRDY) != EEFC_FSR_FRDY); p_efc->EEFC_FMR &= ~(0x1u << 16); return EFC_RC_OK; } /** * \brief Set mode register. * * \param p_efc Pointer to an EFC instance. * \param ul_fmr Value of mode register */ RAMFUNC void efc_write_fmr(Efc *p_efc, uint32_t ul_fmr) { p_efc->EEFC_FMR = ul_fmr; } /** * \brief Perform command. * * \param p_efc Pointer to an EFC instance. * \param ul_fcr Flash command. * * \return The current status. */ RAMFUNC uint32_t efc_perform_fcr(Efc *p_efc, uint32_t ul_fcr) { volatile uint32_t ul_status; p_efc->EEFC_FCR = ul_fcr; do { ul_status = p_efc->EEFC_FSR; } while ((ul_status & EEFC_FSR_FRDY) != EEFC_FSR_FRDY); return (ul_status & EEFC_ERROR_FLAGS); } //@} /// @cond 0 /**INDENT-OFF**/ #ifdef __cplusplus } #endif /**INDENT-ON**/ /// @endcond
8,707
3,779
#include "stdafx.h" #include "LightningPumpkinSkill.h" #include "ClientSession.h" #include "Game.h" #include "Player.h" #include "Unit.h" #include "Timer.h" #include <time.h> LightningPumpkinSkill::LightningPumpkinSkill(Player* owner) { m_Owner = owner; m_Damage = 64; m_Scale = Reduce(80.0f); } LightningPumpkinSkill::~LightningPumpkinSkill() { } void LightningPumpkinSkill::SkillCast(SkillKey key, const b2Vec2& heroPos, const b2Vec2& targetPos) { auto hero = m_Owner->GetMyHero(); hero->EndMove(); m_TaretPos = targetPos; auto client = m_Owner->GetClient(); client->SkillBroadCast(hero->GetUnitID(), heroPos, targetPos, key); auto game = m_Owner->GetGame(); Timer::Push(game, 200, 10, this, &LightningPumpkinSkill::RandomAttack, Reduce(200.0f), 200, 5, 10, EF_LIGHTNING); }
825
348
// -*- C++ -*- // // Package: L1RPCConeDefinitionProducer // Class: L1RPCConeDefinitionProducer // /**\class L1RPCConeDefinitionProducer L1RPCConeDefinitionProducer.h L1TriggerConfig/L1RPCConeDefinitionProducer/src/L1RPCConeDefinitionProducer.cc Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Tomasz Maciej Frueboes // Created: Mon Feb 23 12:09:06 CET 2009 // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/ModuleFactory.h" #include "FWCore/Framework/interface/ESProducer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "CondFormats/L1TObjects/interface/L1RPCConeDefinition.h" #include "CondFormats/DataRecord/interface/L1RPCConeDefinitionRcd.h" // // class decleration // class L1RPCConeDefinitionProducer : public edm::ESProducer { public: L1RPCConeDefinitionProducer(const edm::ParameterSet&); ~L1RPCConeDefinitionProducer() override; using ReturnType = std::unique_ptr<L1RPCConeDefinition>; ReturnType produce(const L1RPCConeDefinitionRcd&); private: // ----------member data --------------------------- int m_towerBeg; int m_towerEnd; int m_rollBeg; int m_rollEnd; int m_hwPlaneBeg; int m_hwPlaneEnd; //L1RPCConeDefinition::TLPSizesInTowers m_LPSizesInTowers; L1RPCConeDefinition::TLPSizeVec m_LPSizeVec; //L1RPCConeDefinition::TRingsToTowers m_RingsToTowers; L1RPCConeDefinition::TRingToTowerVec m_ringToTowerVec; //L1RPCConeDefinition::TRingsToLP m_RingsToLP; L1RPCConeDefinition::TRingToLPVec m_ringToLPVec; }; // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // L1RPCConeDefinitionProducer::L1RPCConeDefinitionProducer(const edm::ParameterSet& iConfig) : m_towerBeg(iConfig.getParameter<int>("towerBeg")), m_towerEnd(iConfig.getParameter<int>("towerEnd")), m_rollBeg(iConfig.getParameter<int>("rollBeg")), m_rollEnd(iConfig.getParameter<int>("rollEnd")), m_hwPlaneBeg(iConfig.getParameter<int>("hwPlaneBeg")), m_hwPlaneEnd(iConfig.getParameter<int>("hwPlaneEnd")) { //the following line is needed to tell the framework what // data is being produced setWhatProduced(this); for (int t = m_towerBeg; t <= m_towerEnd; ++t) { std::stringstream name; name << "lpSizeTower" << t; std::vector<int> newSizes = iConfig.getParameter<std::vector<int> >(name.str().c_str()); for (unsigned int lp = 0; lp < newSizes.size(); ++lp) { // L1RPCConeDefinition::TLPSize lps(t, lp, newSizes[lp]); L1RPCConeDefinition::TLPSize lps; lps.m_tower = t; lps.m_LP = lp; lps.m_size = newSizes[lp]; m_LPSizeVec.push_back(lps); } } //now do what ever other initialization is needed // hw planes numbered from 0 to 5 // rolls from 0 to 17 (etaPartition) // // rollConnLP_[roll]_[hwPlane-1] // rollConnLP_5_3 = cms.vint32(6, 0, 0), // ----- roll 5, hwPlane 4 (3+1) is logplane 6 (OK) // // rollConnT_[roll]_[hwPlane-1] // rollConnT_5_3 = cms.vint32(4, -1, -1), // ----- roll 5, hwPlane 4 (3+1) contirubtes to tower 4 (OK) for (int roll = m_rollBeg; roll <= m_rollEnd; ++roll) { //L1RPCConeDefinition::THWplaneToTower newHwPlToTower; //L1RPCConeDefinition::THWplaneToLP newHWplaneToLP; for (int hwpl = m_hwPlaneBeg; hwpl <= m_hwPlaneEnd; ++hwpl) { std::stringstream name; name << "rollConnLP_" << roll << "_" << hwpl; std::vector<int> hwPl2LPVec = iConfig.getParameter<std::vector<int> >(name.str().c_str()); //newHWplaneToLP.push_back(newListLP); for (unsigned int i = 0; i < hwPl2LPVec.size(); ++i) { if (hwPl2LPVec[i] >= 0) { // L1RPCConeDefinition::TRingToLP lp(roll, hwpl, hwPl2LPVec[i],i); L1RPCConeDefinition::TRingToLP lp; lp.m_etaPart = roll; lp.m_hwPlane = hwpl; lp.m_LP = hwPl2LPVec[i]; lp.m_index = i; m_ringToLPVec.push_back(lp); } } std::stringstream name1; name1 << "rollConnT_" << roll << "_" << hwpl; /*L1RPCConeDefinition::TLPList newListT = iConfig.getParameter<std::vector<int> >(name1.str().c_str()); newHwPlToTower.push_back(newListT);*/ std::vector<int> hwPl2TowerVec = iConfig.getParameter<std::vector<int> >(name1.str().c_str()); for (unsigned int i = 0; i < hwPl2TowerVec.size(); ++i) { if (hwPl2TowerVec[i] >= 0) { // L1RPCConeDefinition::TRingToTower rt(roll, hwpl, hwPl2TowerVec[i],i); L1RPCConeDefinition::TRingToTower rt; rt.m_etaPart = roll; rt.m_hwPlane = hwpl; rt.m_tower = hwPl2TowerVec[i]; rt.m_index = i; m_ringToTowerVec.push_back(rt); } } } //m_RingsToTowers.push_back(newHwPlToTower); //m_RingsToLP.push_back(newHWplaneToLP); } } L1RPCConeDefinitionProducer::~L1RPCConeDefinitionProducer() {} // // member functions // // ------------ method called to produce the data ------------ L1RPCConeDefinitionProducer::ReturnType L1RPCConeDefinitionProducer::produce(const L1RPCConeDefinitionRcd& iRecord) { auto pL1RPCConeDefinition = std::make_unique<L1RPCConeDefinition>(); pL1RPCConeDefinition->setFirstTower(m_towerBeg); pL1RPCConeDefinition->setLastTower(m_towerEnd); pL1RPCConeDefinition->setLPSizeVec(m_LPSizeVec); pL1RPCConeDefinition->setRingToLPVec(m_ringToLPVec); pL1RPCConeDefinition->setRingToTowerVec(m_ringToTowerVec); return pL1RPCConeDefinition; } //define this as a plug-in DEFINE_FWK_EVENTSETUP_MODULE(L1RPCConeDefinitionProducer);
5,707
2,301
/* * Copyright (C) 2007 Apple Computer, Inc. * Copyright (c) 2007, 2008, 2009, Google 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: * * * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "FontCustomPlatformData.h" #if OS(WINDOWS) #include "Base64.h" #include "ChromiumBridge.h" #include "OpenTypeUtilities.h" #elif OS(LINUX) #include "SkStream.h" #endif #include "FontPlatformData.h" #include "NotImplemented.h" #include "OpenTypeSanitizer.h" #include "SharedBuffer.h" #if OS(WINDOWS) #include <objbase.h> #elif OS(LINUX) #include <cstring> #endif namespace WebCore { FontCustomPlatformData::~FontCustomPlatformData() { #if OS(WINDOWS) if (m_fontReference) RemoveFontMemResourceEx(m_fontReference); #elif OS(LINUX) if (m_fontReference) m_fontReference->unref(); #endif } FontPlatformData FontCustomPlatformData::fontPlatformData(int size, bool bold, bool italic, FontRenderingMode mode) { #if OS(WINDOWS) ASSERT(m_fontReference); LOGFONT logFont; // m_name comes from createUniqueFontName, which, in turn, gets // it from base64-encoded uuid (128-bit). So, m_name // can never be longer than LF_FACESIZE (32). if (m_name.length() + 1 >= LF_FACESIZE) { ASSERT_NOT_REACHED(); return FontPlatformData(); } memcpy(logFont.lfFaceName, m_name.charactersWithNullTermination(), sizeof(logFont.lfFaceName[0]) * (1 + m_name.length())); // FIXME: almost identical to FillLogFont in FontCacheWin.cpp. // Need to refactor. logFont.lfHeight = -size; logFont.lfWidth = 0; logFont.lfEscapement = 0; logFont.lfOrientation = 0; logFont.lfUnderline = false; logFont.lfStrikeOut = false; logFont.lfCharSet = DEFAULT_CHARSET; logFont.lfOutPrecision = OUT_TT_ONLY_PRECIS; logFont.lfQuality = ChromiumBridge::layoutTestMode() ? NONANTIALIASED_QUALITY : DEFAULT_QUALITY; // Honor user's desktop settings. logFont.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; logFont.lfItalic = italic; logFont.lfWeight = bold ? 700 : 400; HFONT hfont = CreateFontIndirect(&logFont); return FontPlatformData(hfont, size); #elif OS(LINUX) ASSERT(m_fontReference); return FontPlatformData(m_fontReference, "", size, bold && !m_fontReference->isBold(), italic && !m_fontReference->isItalic()); #else notImplemented(); return FontPlatformData(); #endif } #if OS(WINDOWS) // Creates a unique and unpredictable font name, in order to avoid collisions and to // not allow access from CSS. static String createUniqueFontName() { Vector<char> fontUuid(sizeof(GUID)); CoCreateGuid(reinterpret_cast<GUID*>(fontUuid.data())); Vector<char> fontNameVector; base64Encode(fontUuid, fontNameVector); ASSERT(fontNameVector.size() < LF_FACESIZE); return String(fontNameVector.data(), fontNameVector.size()); } #endif #if OS(LINUX) class RemoteFontStream : public SkStream { public: explicit RemoteFontStream(PassRefPtr<SharedBuffer> buffer) : m_buffer(buffer) , m_offset(0) { } virtual ~RemoteFontStream() { } virtual bool rewind() { m_offset = 0; return true; } virtual size_t read(void* buffer, size_t size) { if (!buffer && !size) { // This is request for the length of the stream. return m_buffer->size(); } if (!buffer) { // This is a request to skip bytes. This operation is not supported. return 0; } // This is a request to read bytes. if (!m_buffer->data() || !m_buffer->size()) return 0; size_t left = m_buffer->size() - m_offset; size_t toRead = (left > size) ? size : left; std::memcpy(buffer, m_buffer->data() + m_offset, toRead); m_offset += toRead; return toRead; } private: RefPtr<SharedBuffer> m_buffer; size_t m_offset; }; #endif FontCustomPlatformData* createFontCustomPlatformData(SharedBuffer* buffer) { ASSERT_ARG(buffer, buffer); #if ENABLE(OPENTYPE_SANITIZER) OpenTypeSanitizer sanitizer(buffer); RefPtr<SharedBuffer> transcodeBuffer = sanitizer.sanitize(); if (!transcodeBuffer) return 0; // validation failed. buffer = transcodeBuffer.get(); #endif #if OS(WINDOWS) // Introduce the font to GDI. AddFontMemResourceEx should be used with care, because it will pollute the process's // font namespace (Windows has no API for creating an HFONT from data without exposing the font to the // entire process first). String fontName = createUniqueFontName(); HANDLE fontReference = renameAndActivateFont(buffer, fontName); if (!fontReference) return 0; return new FontCustomPlatformData(fontReference, fontName); #elif OS(LINUX) RemoteFontStream* stream = new RemoteFontStream(buffer); SkTypeface* typeface = SkTypeface::CreateFromStream(stream); if (!typeface) return 0; return new FontCustomPlatformData(typeface); #else notImplemented(); return 0; #endif } }
6,575
2,242
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. 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 any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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, THE UNITED STATES GOVERNMENT, OR ANY 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 "SurfacePropertyOtherSideConditionsModel.hpp" #include "SurfacePropertyOtherSideConditionsModel_Impl.hpp" #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/OS_SurfaceProperty_OtherSideConditionsModel_FieldEnums.hxx> #include "../utilities/core/Assert.hpp" namespace openstudio { namespace model { namespace detail { SurfacePropertyOtherSideConditionsModel_Impl::SurfacePropertyOtherSideConditionsModel_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : ResourceObject_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == SurfacePropertyOtherSideConditionsModel::iddObjectType()); } SurfacePropertyOtherSideConditionsModel_Impl::SurfacePropertyOtherSideConditionsModel_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : ResourceObject_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == SurfacePropertyOtherSideConditionsModel::iddObjectType()); } SurfacePropertyOtherSideConditionsModel_Impl::SurfacePropertyOtherSideConditionsModel_Impl(const SurfacePropertyOtherSideConditionsModel_Impl& other, Model_Impl* model, bool keepHandle) : ResourceObject_Impl(other,model,keepHandle) {} const std::vector<std::string>& SurfacePropertyOtherSideConditionsModel_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType SurfacePropertyOtherSideConditionsModel_Impl::iddObjectType() const { return SurfacePropertyOtherSideConditionsModel::iddObjectType(); } std::string SurfacePropertyOtherSideConditionsModel_Impl::typeOfModeling() const { boost::optional<std::string> value = getString(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling,true); OS_ASSERT(value); return value.get(); } bool SurfacePropertyOtherSideConditionsModel_Impl::isTypeOfModelingDefaulted() const { return isEmpty(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling); } bool SurfacePropertyOtherSideConditionsModel_Impl::setTypeOfModeling(const std::string& typeOfModeling) { bool result = setString(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling, typeOfModeling); return result; } void SurfacePropertyOtherSideConditionsModel_Impl::resetTypeOfModeling() { bool result = setString(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling, ""); OS_ASSERT(result); } } // detail SurfacePropertyOtherSideConditionsModel::SurfacePropertyOtherSideConditionsModel(const Model& model) : ResourceObject(SurfacePropertyOtherSideConditionsModel::iddObjectType(),model) { OS_ASSERT(getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()); // TODO: Appropriately handle the following required object-list fields. bool ok = true; // ok = setHandle(); OS_ASSERT(ok); } IddObjectType SurfacePropertyOtherSideConditionsModel::iddObjectType() { return IddObjectType(IddObjectType::OS_SurfaceProperty_OtherSideConditionsModel); } std::vector<std::string> SurfacePropertyOtherSideConditionsModel::typeOfModelingValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling); } std::string SurfacePropertyOtherSideConditionsModel::typeOfModeling() const { return getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->typeOfModeling(); } bool SurfacePropertyOtherSideConditionsModel::isTypeOfModelingDefaulted() const { return getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->isTypeOfModelingDefaulted(); } bool SurfacePropertyOtherSideConditionsModel::setTypeOfModeling(const std::string& typeOfModeling) { return getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->setTypeOfModeling(typeOfModeling); } void SurfacePropertyOtherSideConditionsModel::resetTypeOfModeling() { getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->resetTypeOfModeling(); } /// @cond SurfacePropertyOtherSideConditionsModel::SurfacePropertyOtherSideConditionsModel(std::shared_ptr<detail::SurfacePropertyOtherSideConditionsModel_Impl> impl) : ResourceObject(std::move(impl)) {} /// @endcond } // model } // openstudio
7,166
1,997
// Copyright (C) 2020-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "mvn_arm.hpp" using namespace ngraph; using namespace ArmPlugin; NGRAPH_RTTI_DEFINITION(opset::ArmMVN, "ArmMVN", 0); opset::ArmMVN::~ArmMVN() {} opset::ArmMVN::ArmMVN(const ngraph::Output<ngraph::Node>& data, float eps) : Op({data}), m_eps(eps) { constructor_validate_and_infer_types(); } std::shared_ptr<ngraph::Node> opset::ArmMVN::clone_with_new_inputs(const ngraph::OutputVector& new_args) const { auto num_args = new_args.size(); if (num_args == 1) { return std::make_shared<ArmMVN>(new_args.at(0), m_eps); } else { throw ngraph_error("Unsupported number of arguments for ArmMVN operation"); } }
743
300
/* ** EPITECH PROJECT, 2020 ** CPP_zia_2019 ** File description: ** zia common Network.hpp */ #pragma once #include "openZia/OperatingSystem.hpp" #if defined(SYSTEM_LINUX) || defined(SYSTEM_DARWIN) #include <arpa/inet.h> #include <unistd.h> typedef int socket_t; #elif defined(SYSTEM_WINDOWS) #define _WINSOCKAPI_ #include <winsock2.h> #include <ws2tcpip.h> #include <windows.h> #include <BaseTsd.h> #include <io.h> typedef SOCKET socket_t; #endif
493
208
#include "chapter_07_concurrency/problem_064_parallel_sort_algorithm.h" #include <algorithm> // shuffle, sort #include <fmt/ostream.h> #include <fmt/ranges.h> #include <iostream> // cout #include <numeric> // iota #include <ostream> #include <random> // default_random_engine, random_device #include <vector> void problem_64_main(std::ostream& os) { std::vector<int> v(20); std::iota(std::begin(v), std::end(v), -10); std::ranges::shuffle(v, std::default_random_engine{ std::random_device{}() }); fmt::print(os, "v = {}\n\n", v); { auto w{ v }; std::sort(std::begin(w), std::end(w)); fmt::print(os, "std::sort(v); v = {}\n", w); } { auto w{ v }; tmcppc::algorithm::quicksort(std::begin(w), std::end(w)); fmt::print(os, "quicksort(v); v = {}\n", w); } { auto w{ v }; tmcppc::algorithm::parallel_quicksort(std::begin(w), std::end(w)); fmt::print(os, "parallel_quicksort; v = {}\n\n", w); } } // Parallel sort algorithm // // Write a parallel version of the sort algorithm // as defined for problem "57. Sort Algorithm", in "Chapter 6, Algorithms and Data Structures", // which, given a pair of random access iterators to define its lower and upper bounds, // sorts the elements of the range using the quicksort algorithm. // The function should use the comparison operators for comparing the elements of the range. // The level of parallelism and the way to achieve it is an implementation detail. void problem_64_main() { problem_64_main(std::cout); }
1,576
527
#ifndef H_SHAREBUY_SESSION #define H_SHAREBUY_SESSION #include <Wt/Dbo/Session> #include <Wt/Dbo/ptr> #include <Wt/Dbo/backend/Sqlite3> #include <Wt/Auth/Login> #include <Wt/Auth/PasswordService> #include "User.hpp" namespace dbo = Wt::Dbo; typedef Wt::Auth::Dbo::UserDatabase<AuthInfo> UserDatabase; class Session : public dbo::Session { public: Session(const std::string& sqliteDb); virtual ~Session(); Wt::Auth::AbstractUserDatabase& users(); Wt::Auth::Login& login() { return login_; } static void configureAuth(); static const Wt::Auth::AuthService& auth(); static const Wt::Auth::PasswordService& passwordAuth(); static const std::vector<const Wt::Auth::OAuthService *>& oAuth(); dbo::ptr<User> user(); private: dbo::backend::Sqlite3 connection_; UserDatabase *users_; Wt::Auth::Login login_; }; #endif
830
300
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se) // For other contributors see Contributors.txt // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #pragma once #include <sfz/containers/DynArray.hpp> #include <sfz/memory/Allocator.hpp> #include "ph/config/Setting.hpp" namespace ph { using sfz::Allocator; using sfz::DynArray; // GlobalConfig // ------------------------------------------------------------------------------------------------ struct GlobalConfigImpl; // Pimpl pattern /// A global configuration class /// /// The singleton instance should be acquired from the Phantasy Engine global context /// /// Setting invariants: /// 1, All settings are owned by the singleton instance, no one else may delete the memory. /// 2, A setting, once created, can never be destroyed or removed during runtime. /// 3, A setting will occupy the same place in memory for the duration of the program's runtime. /// 4, A setting can not change section or key identifiers once created. /// /// These invariants mean that it is safe (and expected) to store direct pointers to settings and /// read/write to them when needed. However, settings may change type during runtime. So it is /// recommended to store a pointer to the setting itself and not its internal int value for /// example. /// /// Settings are expected to stay relatively static during the runtime of a program. They are not /// meant for communication and should not be changed unless the user specifically requests for /// them to be changed. class GlobalConfig { public: // Constructors & destructors // -------------------------------------------------------------------------------------------- inline GlobalConfig() noexcept : mImpl(nullptr) {} // Compile fix for Emscripten GlobalConfig(const GlobalConfig&) = delete; GlobalConfig& operator= (const GlobalConfig&) = delete; GlobalConfig(GlobalConfig&&) = delete; GlobalConfig& operator= (GlobalConfig&&) = delete; ~GlobalConfig() noexcept; // Methods // -------------------------------------------------------------------------------------------- void init(const char* basePath, const char* fileName, Allocator* allocator) noexcept; void destroy() noexcept; void load() noexcept; bool save() noexcept; /// Gets the specified Setting. If it does not exist it will be created (type int with value 0). /// The optional parameter "created" returns whether the Setting was created or already existed. Setting* createSetting(const char* section, const char* key, bool* created = nullptr) noexcept; // Getters // -------------------------------------------------------------------------------------------- /// Gets the specified Setting. Returns nullptr if it does not exist. Setting* getSetting(const char* section, const char* key) noexcept; Setting* getSetting(const char* key) noexcept; /// Returns pointers to all available settings void getAllSettings(DynArray<Setting*>& settings) noexcept; /// Returns all sections available void getSections(DynArray<str32>& sections) noexcept; /// Returns all settings available in a given section void getSectionSettings(const char* section, DynArray<Setting*>& settings) noexcept; // Sanitizers // -------------------------------------------------------------------------------------------- /// A sanitizer is basically a wrapper around createSetting, with the addition that it also /// ensures that the Setting is of the requested type and with values conforming to the /// specified bounds. If the setting does not exist or is of an incompatible type it will be /// set to the specified default value. Setting* sanitizeInt( const char* section, const char* key, bool writeToFile = true, const IntBounds& bounds = IntBounds(0)) noexcept; Setting* sanitizeFloat( const char* section, const char* key, bool writeToFile = true, const FloatBounds& bounds = FloatBounds(0.0f)) noexcept; Setting* sanitizeBool( const char* section, const char* key, bool writeToFile = true, const BoolBounds& bounds = BoolBounds(false)) noexcept; Setting* sanitizeInt( const char* section, const char* key, bool writeToFile = true, int32_t defaultValue = 0, int32_t minValue = INT32_MIN, int32_t maxValue = INT32_MAX, int32_t step = 1) noexcept; Setting* sanitizeFloat( const char* section, const char* key, bool writeToFile = true, float defaultValue = 0.0f, float minValue = FLT_MIN, float maxValue = FLT_MAX) noexcept; Setting* sanitizeBool( const char* section, const char* key, bool writeToFile = true, bool defaultValue = false) noexcept; private: // Private members // -------------------------------------------------------------------------------------------- GlobalConfigImpl* mImpl; }; // Statically owned global config // ------------------------------------------------------------------------------------------------ /// Statically owned global config. Default constructed. Only to be used for setContext() in /// PhantasyEngineMain.cpp during boot. GlobalConfig* getStaticGlobalConfigBoot() noexcept; } // namespace ph
5,934
1,570
#include "util.h" /*! Build a float from a uint8_t array Public function defined in util.h */ float Util_parseFloat(uint8_t *pArray) { return (Util_buildFloat(pArray[0], pArray[1], pArray[2], pArray[3])); } /*! Break and buffer a float value - LSB first Public function defined in util.h */ float Util_buildFloat(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) { float ret = 0; uint8_t * pF = (uint8_t * ) & ret; *pF++ = b0; *pF++ = b1; *pF++ = b2; *pF++ = b3; return ret; } /* * @brief: Break and buffer a float value - LSB first * @return: pointer to last buffer */ uint8_t * Util_bufferFloat(uint8_t * pBuf, float val) { uint8_t * pF = (uint8_t *) &val; *pBuf++ = *pF++; *pBuf++ = *pF++; *pBuf++ = *pF++; *pBuf++ = *pF++; return (pBuf); } /*! Build a uint32_t out of 4 uint8_t variables Public function defined in util.h */ uint32_t Util_buildUint32(uint8_t byte0, uint8_t byte1, uint8_t byte2, uint8_t byte3) { return ((uint32_t)((uint32_t)((byte0) & 0x00FF) + ((uint32_t)((byte1) & 0x00FF) << 8) + ((uint32_t)((byte2) & 0x00FF) << 16) + ((uint32_t)((byte3) & 0x00FF) << 24))); } /*! Build a uint32_t from a uint8_t array Public function defined in util.h */ uint32_t Util_parseUint32(uint8_t *pArray) { return (Util_buildUint32(pArray[0], pArray[1], pArray[2], pArray[3])); } /*! Pull 1 uint8_t out of a uint32_t Public function defined in util.h */ uint8_t Util_breakUint32(uint32_t var, int byteNum) { return (uint8_t)((uint32_t)(((var) >> ((byteNum) * 8)) & 0x00FF)); } /*! Break and buffer a uint32_t value - LSB first Public function defined in util.h */ uint8_t * Util_bufferUint32(uint8_t *pBuf, uint32_t val) { *pBuf++ = Util_breakUint32(val, 0); *pBuf++ = Util_breakUint32(val, 1); *pBuf++ = Util_breakUint32(val, 2); *pBuf++ = Util_breakUint32(val, 3); return (pBuf); }
1,962
877
//HEADER_GOES_HERE #include "../types.h" int doom_quest_time; // weak int doom_stars_drawn; // weak void *pDoomCel; int doomflag; // weak int DoomQuestState; // idb int __cdecl doom_get_frame_from_time() { int result; // eax if ( DoomQuestState == 36001 ) result = 31; else result = DoomQuestState / 1200; return result; } void __cdecl doom_alloc_cel() { pDoomCel = DiabloAllocPtr(229376); } void __cdecl doom_cleanup() { void *v0; // ecx v0 = pDoomCel; pDoomCel = 0; mem_free_dbg(v0); } void __cdecl doom_load_graphics() { if ( doom_quest_time == 31 ) { strcpy(tempstr, "Items\\Map\\MapZDoom.CEL"); } else if ( doom_quest_time >= 10 ) { sprintf(tempstr, "Items\\Map\\MapZ00%i.CEL", doom_quest_time); } else { sprintf(tempstr, "Items\\Map\\MapZ000%i.CEL", doom_quest_time); } LoadFileWithMem(tempstr, pDoomCel); } // 525750: using guessed type int doom_quest_time; void __cdecl doom_init() { int v0; // eax doomflag = 1; doom_alloc_cel(); v0 = -(doom_get_frame_from_time() != 31); _LOBYTE(v0) = v0 & 0xE1; doom_quest_time = v0 + 31; doom_load_graphics(); } // 525750: using guessed type int doom_quest_time; // 52575C: using guessed type int doomflag; void __cdecl doom_close() { if ( doomflag ) { doomflag = 0; doom_cleanup(); } } // 52575C: using guessed type int doomflag; void __cdecl doom_draw() { if ( doomflag ) { if ( doom_quest_time != 31 && ++doom_stars_drawn >= 5 ) { doom_stars_drawn = 0; if ( ++doom_quest_time > doom_get_frame_from_time() ) doom_quest_time = 0; doom_load_graphics(); } CelDecodeOnly(64, 511, pDoomCel, 1, 640); } } // 525750: using guessed type int doom_quest_time; // 525754: using guessed type int doom_stars_drawn; // 52575C: using guessed type int doomflag;
1,866
922
/* includes //{ */ #include <memory> #include <ros/init.h> #include <ros/ros.h> #include <ros/package.h> #include <nodelet/nodelet.h> #include <octomap/OcTree.h> #include <octomap_msgs/Octomap.h> #include <octomap_msgs/conversions.h> #include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <numeric> #include <mrs_lib/attitude_converter.h> #include <mrs_lib/batch_visualizer.h> #include <mrs_lib/param_loader.h> #include <mrs_lib/subscribe_handler.h> #include <mrs_lib/mutex.h> #include <mrs_lib/scope_timer.h> #include <mrs_lib/service_client_handler.h> #include <mrs_lib/transformer.h> #include <mrs_lib/geometry/misc.h> #include <mrs_lib/geometry/cyclic.h> #include <mrs_msgs/PositionCommand.h> #include <mrs_msgs/Vec4.h> #include <mrs_msgs/ReferenceStampedSrv.h> #include <mrs_msgs/GetPathSrv.h> #include <mrs_msgs/MpcPredictionFullState.h> #include <mrs_msgs/TrajectoryReferenceSrv.h> #include <mrs_msgs/ControlManagerDiagnostics.h> #include <mrs_msgs/DynamicsConstraints.h> #include <mrs_msgs/TrajectoryReference.h> #include <mrs_msgs/PathfinderDiagnostics.h> #include <std_srvs/Trigger.h> #include <pathfinder/astar_planner.hpp> //} namespace pathfinder { /* defines //{ */ typedef enum { STATE_IDLE, STATE_PLANNING, STATE_MOVING, } State_t; const std::string _state_names_[] = {"IDLE", "PLANNING", "MOVING"}; using OcTree_t = octomap::OcTree; using OcTreePtr_t = std::shared_ptr<octomap::OcTree>; using OcTreeMsgConstPtr_t = octomap_msgs::OctomapConstPtr; //} /* class Pathfinder //{ */ class Pathfinder : public nodelet::Nodelet { public: virtual void onInit(); private: ros::NodeHandle nh_; bool is_initialized_ = false; std::atomic<bool> ready_to_plan_ = false; std::string _uav_name_; // params double _euclidean_distance_cutoff_; double _safe_obstacle_distance_; double _distance_penalty_; double _greedy_penalty_; int _planning_tree_fractor_; double _map_resolution_; double _timeout_threshold_; double _time_for_trajectory_generator_; double _max_waypoint_distance_; double _min_altitude_; double _max_altitude_; double _rate_main_timer_; double _rate_diagnostics_timer_; double _rate_future_check_timer_; double _replan_after_; bool _unknown_is_occupied_; double planning_tree_resolution_; octomap_msgs::OctomapConstPtr octree_msg_ptr_; std::string octree_frame_; std::mutex mutex_octree_msg_ptr_; // visualizer params double _points_scale_; double _lines_scale_; // initial condition octomap::point3d initial_pos_; double initial_heading_; std::mutex mutex_initial_condition_; std::atomic<bool> got_initial_pos_; mrs_lib::BatchVisualizer bv_input_; std::mutex mutex_bv_input_; std::shared_ptr<mrs_lib::BatchVisualizer> bv_planner_; bool bv_planner_frame_set_ = false; mrs_lib::BatchVisualizer bv_processed_; std::mutex mutex_bv_processed_; // subscribers mrs_lib::SubscribeHandler<mrs_msgs::PositionCommand> sh_position_cmd_; mrs_lib::SubscribeHandler<octomap_msgs::Octomap> sh_octomap_; mrs_lib::SubscribeHandler<mrs_msgs::MpcPredictionFullState> sh_mpc_prediction_; mrs_lib::SubscribeHandler<mrs_msgs::ControlManagerDiagnostics> sh_control_manager_diag_; mrs_lib::SubscribeHandler<mrs_msgs::DynamicsConstraints> sh_constraints_; // publishers ros::Publisher pub_diagnostics_; // subscriber callbacks void callbackPositionCmd(mrs_lib::SubscribeHandler<mrs_msgs::PositionCommand>& wrp); void callbackOctomap(mrs_lib::SubscribeHandler<octomap_msgs::Octomap>& wrp); void callbackMpcPrediction(mrs_lib::SubscribeHandler<mrs_msgs::MpcPredictionFullState>& wrp); // service servers ros::ServiceServer service_server_goto_; ros::ServiceServer service_server_reference_; // service server callbacks bool callbackGoto([[maybe_unused]] mrs_msgs::Vec4::Request& req, mrs_msgs::Vec4::Response& res); bool callbackReference([[maybe_unused]] mrs_msgs::ReferenceStampedSrv::Request& req, mrs_msgs::ReferenceStampedSrv::Response& res); // service clients mrs_lib::ServiceClientHandler<mrs_msgs::GetPathSrv> sc_get_trajectory_; mrs_lib::ServiceClientHandler<mrs_msgs::TrajectoryReferenceSrv> sc_trajectory_reference_; mrs_lib::ServiceClientHandler<std_srvs::Trigger> sc_hover_; // timers ros::Timer timer_main_; void timerMain([[maybe_unused]] const ros::TimerEvent& evt); ros::Timer timer_diagnostics_; void timerDiagnostics([[maybe_unused]] const ros::TimerEvent& evt); ros::Timer timer_future_check_; void timerFutureCheck([[maybe_unused]] const ros::TimerEvent& evt); // diagnostics mrs_msgs::PathfinderDiagnostics diagnostics_; std::mutex mutex_diagnostics_; // timeouts void timeoutOctomap(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs); void timeoutPositionCmd(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs); void timeoutMpcPrediction(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs); void timeoutControlManagerDiag(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs); // transformer std::unique_ptr<mrs_lib::Transformer> transformer_; std::string current_control_frame_; std::mutex mutex_current_control_frame_; // planning std::atomic<int> replanning_counter_ = 0; ros::Time time_last_plan_; // state machine std::atomic<State_t> state_; void changeState(const State_t new_state); mrs_msgs::Reference user_goal_; std::mutex mutex_user_goal_; octomap::point3d internal_goal_; std::atomic<bool> set_timepoints_ = false; ros::Time replanning_start_timepoint_; ros::Time replanning_end_timepoint_; octomap::point3d replanning_point_; std::mutex mutex_replanning_point_; // routines void setReplanningPoint(const mrs_msgs::TrajectoryReference& traj); std::vector<double> estimateSegmentTimes(const std::vector<Eigen::Vector4d>& vertices, const bool use_heading); std::optional<OcTreePtr_t> msgToMap(const octomap_msgs::OctomapConstPtr octomap); /** * @brief returns planning initial condition for a given future time based on the MPC prediction horizon * * @param time * * @return x, y, z, heading reference */ std::optional<mrs_msgs::ReferenceStamped> getInitialCondition(const ros::Time time); void hover(void); }; //} /* onInit() //{ */ void Pathfinder::onInit() { nh_ = nodelet::Nodelet::getMTPrivateNodeHandle(); ros::Time::waitForValid(); ROS_INFO("[Pathfinder]: initializing"); mrs_lib::ParamLoader param_loader(nh_, "Pathfinder"); param_loader.loadParam("uav_name", _uav_name_); param_loader.loadParam("main_timer/rate", _rate_main_timer_); param_loader.loadParam("diagnostics_timer/rate", _rate_diagnostics_timer_); param_loader.loadParam("future_check_timer/rate", _rate_future_check_timer_); param_loader.loadParam("euclidean_distance_cutoff", _euclidean_distance_cutoff_); param_loader.loadParam("safe_obstacle_distance", _safe_obstacle_distance_); param_loader.loadParam("distance_penalty", _distance_penalty_); param_loader.loadParam("greedy_penalty", _greedy_penalty_); param_loader.loadParam("planning_tree_fractor", _planning_tree_fractor_); param_loader.loadParam("map_resolution", _map_resolution_); param_loader.loadParam("unknown_is_occupied", _unknown_is_occupied_); param_loader.loadParam("points_scale", _points_scale_); param_loader.loadParam("lines_scale", _lines_scale_); param_loader.loadParam("max_waypoint_distance", _max_waypoint_distance_); param_loader.loadParam("min_altitude", _min_altitude_); param_loader.loadParam("max_altitude", _max_altitude_); param_loader.loadParam("timeout_threshold", _timeout_threshold_); param_loader.loadParam("replan_after", _replan_after_); param_loader.loadParam("time_for_trajectory_generator", _time_for_trajectory_generator_); if (!param_loader.loadedSuccessfully()) { ROS_ERROR("[Pathfinder]: could not load all parameters"); ros::shutdown(); } planning_tree_resolution_ = _map_resolution_ * pow(2, _planning_tree_fractor_); // | ---------------------- state machine --------------------- | state_ = STATE_IDLE; // | ----------------------- publishers ----------------------- | pub_diagnostics_ = nh_.advertise<mrs_msgs::PathfinderDiagnostics>("diagnostics_out", 1); // | ----------------------- subscribers ---------------------- | mrs_lib::SubscribeHandlerOptions shopts; shopts.nh = nh_; shopts.node_name = "Pathfinder"; shopts.no_message_timeout = mrs_lib::no_timeout; shopts.threadsafe = true; shopts.autostart = true; shopts.queue_size = 1; shopts.transport_hints = ros::TransportHints().tcpNoDelay(); sh_position_cmd_ = mrs_lib::SubscribeHandler<mrs_msgs::PositionCommand>(shopts, "position_cmd_in", ros::Duration(3.0), &Pathfinder::timeoutPositionCmd, this, &Pathfinder::callbackPositionCmd, this); sh_octomap_ = mrs_lib::SubscribeHandler<octomap_msgs::Octomap>(shopts, "octomap_in", ros::Duration(5.0), &Pathfinder::timeoutOctomap, this, &Pathfinder::callbackOctomap, this); sh_mpc_prediction_ = mrs_lib::SubscribeHandler<mrs_msgs::MpcPredictionFullState>( shopts, "mpc_prediction_in", ros::Duration(3.0), &Pathfinder::timeoutMpcPrediction, this, &Pathfinder::callbackMpcPrediction, this); sh_control_manager_diag_ = mrs_lib::SubscribeHandler<mrs_msgs::ControlManagerDiagnostics>(shopts, "control_manager_diag_in", ros::Duration(3.0), &Pathfinder::timeoutControlManagerDiag, this); sh_constraints_ = mrs_lib::SubscribeHandler<mrs_msgs::DynamicsConstraints>(shopts, "constraints_in"); // | --------------------- service clients -------------------- | sc_get_trajectory_ = mrs_lib::ServiceClientHandler<mrs_msgs::GetPathSrv>(nh_, "trajectory_generation_out"); sc_trajectory_reference_ = mrs_lib::ServiceClientHandler<mrs_msgs::TrajectoryReferenceSrv>(nh_, "trajectory_reference_out"); sc_hover_ = mrs_lib::ServiceClientHandler<std_srvs::Trigger>(nh_, "hover_out"); // | --------------------- service servers -------------------- | service_server_goto_ = nh_.advertiseService("goto_in", &Pathfinder::callbackGoto, this); service_server_reference_ = nh_.advertiseService("reference_in", &Pathfinder::callbackReference, this); // | ----------------------- transformer ---------------------- | transformer_ = std::make_unique<mrs_lib::Transformer>("Pathfinder"); transformer_->setDefaultPrefix(_uav_name_); transformer_->retryLookupNewest(true); // | -------------------- batch visualiuzer ------------------- | bv_input_ = mrs_lib::BatchVisualizer(nh_, "visualize_input", ""); bv_input_.setPointsScale(_points_scale_); bv_input_.setLinesScale(_lines_scale_); bv_planner_ = std::make_shared<mrs_lib::BatchVisualizer>(nh_, "visualize_planner", ""); bv_planner_->setPointsScale(_points_scale_); bv_planner_->setLinesScale(_lines_scale_); bv_processed_ = mrs_lib::BatchVisualizer(nh_, "visualize_processed", ""); bv_processed_.setPointsScale(_points_scale_); bv_processed_.setLinesScale(_lines_scale_); // | ------------------------- timers ------------------------- | timer_main_ = nh_.createTimer(ros::Rate(_rate_main_timer_), &Pathfinder::timerMain, this); timer_future_check_ = nh_.createTimer(ros::Rate(_rate_future_check_timer_), &Pathfinder::timerFutureCheck, this); timer_diagnostics_ = nh_.createTimer(ros::Rate(_rate_diagnostics_timer_), &Pathfinder::timerDiagnostics, this); // | --------------------- finish the init -------------------- | is_initialized_ = true; ROS_INFO("[Pathfinder]: initialized"); } //} // | ------------------------ callbacks ----------------------- | /* callbackPositionCmd() //{ */ void Pathfinder::callbackPositionCmd(mrs_lib::SubscribeHandler<mrs_msgs::PositionCommand>& wrp) { if (!is_initialized_) { return; } ROS_INFO_ONCE("[Pathfinder]: getting position cmd"); } //} /* timeoutPositionCmd() //{ */ void Pathfinder::timeoutPositionCmd(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs) { if (!is_initialized_) { return; } if (!sh_position_cmd_.hasMsg()) { return; } if (state_ != STATE_IDLE) { ROS_WARN_THROTTLE(1.0, "[Pathfinder]: position cmd timeouted!"); ready_to_plan_ = false; changeState(STATE_IDLE); hover(); } } //} /* callbackOctomap() //{ */ void Pathfinder::callbackOctomap(mrs_lib::SubscribeHandler<octomap_msgs::Octomap>& wrp) { if (!is_initialized_) { return; } ROS_INFO_ONCE("[Pathfinder]: getting octomap"); OcTreeMsgConstPtr_t octomap_ptr = wrp.getMsg(); { std::scoped_lock lock(mutex_octree_msg_ptr_); octree_msg_ptr_ = octomap_ptr; octree_frame_ = octomap_ptr->header.frame_id; } if (!bv_planner_frame_set_) { bv_planner_->setParentFrame(octomap_ptr->header.frame_id); bv_planner_frame_set_ = true; } { std::scoped_lock lock(mutex_bv_input_); bv_input_.setParentFrame(octomap_ptr->header.frame_id); } { std::scoped_lock lock(mutex_bv_processed_); bv_processed_.setParentFrame(octomap_ptr->header.frame_id); } } //} /* timeoutOctomap() //{ */ void Pathfinder::timeoutOctomap(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs) { if (!is_initialized_) { return; } if (!sh_octomap_.hasMsg()) { return; } if (state_ != STATE_IDLE) { ROS_WARN_THROTTLE(1.0, "[Pathfinder]: octomap timeouted!"); ready_to_plan_ = false; changeState(STATE_IDLE); hover(); } } //} /* callbackMpcPrediction() //{ */ void Pathfinder::callbackMpcPrediction(mrs_lib::SubscribeHandler<mrs_msgs::MpcPredictionFullState>& wrp) { if (!is_initialized_) { return; } ROS_INFO_ONCE("[Pathfinder]: getting mpc prediction"); } //} /* timeoutMpcPrediction() //{ */ void Pathfinder::timeoutMpcPrediction(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs) { if (!is_initialized_) { return; } if (!sh_mpc_prediction_.hasMsg()) { return; } if (state_ != STATE_IDLE) { ROS_WARN_THROTTLE(1.0, "[Pathfinder]: MPC prediction timeouted!"); ready_to_plan_ = false; changeState(STATE_IDLE); hover(); } } //} /* timeoutControlManagerDiag() //{ */ void Pathfinder::timeoutControlManagerDiag(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs) { if (!is_initialized_) { return; } if (!sh_mpc_prediction_.hasMsg()) { return; } if (state_ != STATE_IDLE) { ROS_WARN_THROTTLE(1.0, "[Pathfinder]: Control manager diag timeouted!"); ready_to_plan_ = false; changeState(STATE_IDLE); hover(); } } //} /* callbackGoto() //{ */ bool Pathfinder::callbackGoto([[maybe_unused]] mrs_msgs::Vec4::Request& req, mrs_msgs::Vec4::Response& res) { /* prerequisities //{ */ if (!is_initialized_) { return false; } if (!ready_to_plan_) { std::stringstream ss; ss << "not ready to plan, missing data"; ROS_ERROR_STREAM_THROTTLE(0.5, "[Pathfinder]: " << ss.str()); res.success = false; res.message = ss.str(); return true; } //} // | -------- transform the reference to the map frame -------- | { mrs_msgs::PositionCommandConstPtr position_cmd = sh_position_cmd_.getMsg(); mrs_msgs::ReferenceStamped reference; reference.header.frame_id = position_cmd->header.frame_id; reference.reference.position.x = req.goal[0]; reference.reference.position.y = req.goal[1]; reference.reference.position.z = req.goal[2]; reference.reference.heading = req.goal[3]; auto result = transformer_->transformSingle(reference, octree_frame_); if (result) { std::scoped_lock lock(mutex_user_goal_); user_goal_ = result.value().reference; } else { std::stringstream ss; ss << "could not transform the reference from " << position_cmd->header.frame_id << " to " << octree_frame_; ROS_ERROR_STREAM("[Pathfinder]: " << ss.str()); res.success = false; res.message = ss.str(); return true; } } changeState(STATE_PLANNING); { std::scoped_lock lock(mutex_bv_input_, mutex_user_goal_); bv_input_.clearBuffers(); bv_input_.addPoint(Eigen::Vector3d(user_goal_.position.x, user_goal_.position.y, user_goal_.position.z)); bv_input_.publish(); } res.success = true; res.message = "goal set"; return true; } //} /* callbackReference() //{ */ bool Pathfinder::callbackReference([[maybe_unused]] mrs_msgs::ReferenceStampedSrv::Request& req, mrs_msgs::ReferenceStampedSrv::Response& res) { /* prerequisities //{ */ if (!is_initialized_) { return false; } if (!ready_to_plan_) { std::stringstream ss; ss << "not ready to plan, missing data"; ROS_ERROR_STREAM_THROTTLE(0.5, "[Pathfinder]: " << ss.str()); res.success = false; res.message = ss.str(); return true; } //} // | -------- transform the reference to the map frame -------- | { mrs_msgs::PositionCommandConstPtr position_cmd = sh_position_cmd_.getMsg(); mrs_msgs::ReferenceStamped reference; reference.header = req.header; reference.reference = req.reference; auto result = transformer_->transformSingle(reference, octree_frame_); if (result) { std::scoped_lock lock(mutex_user_goal_); user_goal_ = result.value().reference; } else { std::stringstream ss; ss << "could not transform the reference from " << req.header.frame_id << " to " << octree_frame_; ROS_ERROR_STREAM("[Pathfinder]: " << ss.str()); res.success = false; res.message = ss.str(); return true; } } changeState(STATE_PLANNING); { std::scoped_lock lock(mutex_bv_input_, mutex_user_goal_); bv_input_.clearBuffers(); bv_input_.addPoint(Eigen::Vector3d(user_goal_.position.x, user_goal_.position.y, user_goal_.position.z)); bv_input_.publish(); } res.success = true; res.message = "reference set"; return true; } //} // | ------------------------- timers ------------------------- | /* timerMain() //{ */ void Pathfinder::timerMain([[maybe_unused]] const ros::TimerEvent& evt) { if (!is_initialized_) { return; } /* prerequsitioes //{ */ const bool got_octomap = sh_octomap_.hasMsg() && (ros::Time::now() - sh_octomap_.lastMsgTime()).toSec() < 2.0; const bool got_position_cmd = sh_position_cmd_.hasMsg() && (ros::Time::now() - sh_position_cmd_.lastMsgTime()).toSec() < 2.0; const bool got_mpc_prediction = sh_mpc_prediction_.hasMsg() && (ros::Time::now() - sh_mpc_prediction_.lastMsgTime()).toSec() < 2.0; const bool got_control_manager_diag = sh_control_manager_diag_.hasMsg() && (ros::Time::now() - sh_control_manager_diag_.lastMsgTime()).toSec() < 2.0; const bool got_constraints = sh_constraints_.hasMsg() && (ros::Time::now() - sh_constraints_.lastMsgTime()).toSec() < 2.0; if (!got_octomap || !got_position_cmd || !got_mpc_prediction || !got_control_manager_diag || !got_constraints) { ROS_INFO_THROTTLE(1.0, "[Pathfinder]: waiting for data: octomap = %s, position cmd = %s, MPC prediction = %s, ControlManager diag = %s, constraints = %s", got_octomap ? "TRUE" : "FALSE", got_position_cmd ? "TRUE" : "FALSE", got_mpc_prediction ? "TRUE" : "FALSE", got_control_manager_diag ? "TRUE" : "FALSE", got_constraints ? "TRUE" : "FALSE"); return; } else { ready_to_plan_ = true; } //} ROS_INFO_ONCE("[Pathfinder]: main timer spinning"); const auto user_goal = mrs_lib::get_mutexed(mutex_user_goal_, user_goal_); const mrs_msgs::ControlManagerDiagnosticsConstPtr control_manager_diag = sh_control_manager_diag_.getMsg(); const mrs_msgs::PositionCommandConstPtr position_cmd = sh_position_cmd_.getMsg(); octomap::point3d user_goal_octpoint; user_goal_octpoint.x() = user_goal.position.x; user_goal_octpoint.y() = user_goal.position.y; user_goal_octpoint.z() = user_goal.position.z; { std::scoped_lock lock(mutex_diagnostics_); diagnostics_.header.stamp = ros::Time::now(); diagnostics_.header.frame_id = octree_frame_; diagnostics_.idle = false; diagnostics_.desired_reference.x = user_goal.position.x; diagnostics_.desired_reference.y = user_goal.position.y; diagnostics_.desired_reference.z = user_goal.position.z; } switch (state_) { /* STATE_IDLE //{ */ case STATE_IDLE: { { std::scoped_lock lock(mutex_diagnostics_); diagnostics_.idle = true; } break; } //} /* STATE_PLANNING //{ */ case STATE_PLANNING: { // copy the octomap locally OcTreeMsgConstPtr_t octree_msg_ptr; std::string octree_frame; { std::scoped_lock lock(mutex_octree_msg_ptr_); octree_msg_ptr = octree_msg_ptr_; octree_frame = octree_frame_; } std::optional<OcTreePtr_t> octree = msgToMap(octree_msg_ptr); if (!octree) { ROS_ERROR("[Pathfinder]: don't have a map"); break; } { std::scoped_lock lock(mutex_diagnostics_); diagnostics_.idle = false; } if (replanning_counter_ >= 2) { ROS_ERROR("[Pathfinder]: planning failed, the uav is stuck"); changeState(STATE_IDLE); break; } // get the initial condition double time_for_planning; if (control_manager_diag->tracker_status.have_goal) { time_for_planning = _timeout_threshold_; } else { time_for_planning = _timeout_threshold_ + pow(1.5, float(replanning_counter_)); } ROS_INFO("[Pathfinder]: planning timeout %.2f s", time_for_planning); ros::Time init_cond_time = ros::Time::now() + ros::Duration(time_for_planning + _time_for_trajectory_generator_); ROS_INFO("[Pathfinder]: init cond time %.2f s", init_cond_time.toSec()); auto initial_condition = getInitialCondition(init_cond_time); if (!initial_condition) { ROS_ERROR_THROTTLE(1.0, "[Pathfinder]: could not obtain initial condition for planning"); hover(); changeState(STATE_IDLE); break; } ROS_INFO("[Pathfinder]: init cond time stamp %.2f", initial_condition.value().header.stamp.toSec()); octomap::point3d plan_from; plan_from.x() = initial_condition.value().reference.position.x; plan_from.y() = initial_condition.value().reference.position.y; plan_from.z() = initial_condition.value().reference.position.z; pathfinder::AstarPlanner planner = pathfinder::AstarPlanner(_safe_obstacle_distance_, _euclidean_distance_cutoff_, planning_tree_resolution_, _planning_tree_fractor_, _distance_penalty_, _greedy_penalty_, _timeout_threshold_, _max_waypoint_distance_, _min_altitude_, _max_altitude_, _unknown_is_occupied_, bv_planner_); std::pair<std::vector<octomap::point3d>, bool> waypoints = planner.findPath(plan_from, user_goal_octpoint, octree.value(), time_for_planning); // path is complete if (waypoints.second) { replanning_counter_ = 0; waypoints.first.push_back(user_goal_octpoint); } else { if (waypoints.first.size() < 2) { ROS_WARN("[Pathfinder]: path not found"); replanning_counter_++; break; } double front_x = waypoints.first.front().x(); double front_y = waypoints.first.front().y(); double front_z = waypoints.first.front().z(); double back_x = waypoints.first.back().x(); double back_y = waypoints.first.back().y(); double back_z = waypoints.first.back().z(); double path_start_end_dist = sqrt(pow(front_x - back_x, 2) + pow(front_y - back_y, 2) + pow(front_z - back_z, 2)); if (path_start_end_dist < 0.1) { ROS_WARN("[Pathfinder]: path too short"); replanning_counter_++; changeState(STATE_PLANNING); break; } } time_last_plan_ = ros::Time::now(); diagnostics_.best_goal.x = waypoints.first.back().x(); diagnostics_.best_goal.y = waypoints.first.back().y(); diagnostics_.best_goal.z = waypoints.first.back().z(); { std::scoped_lock lock(mutex_initial_condition_); mrs_msgs::PositionCommandConstPtr position_cmd = sh_position_cmd_.getMsg(); auto octree_frame = mrs_lib::get_mutexed(mutex_octree_msg_ptr_, octree_frame_); // transform the position cmd to the map frame mrs_msgs::ReferenceStamped position_cmd_ref; position_cmd_ref.header = position_cmd->header; position_cmd_ref.reference.position.x = position_cmd->position.x; position_cmd_ref.reference.position.y = position_cmd->position.y; position_cmd_ref.reference.position.z = position_cmd->position.z; position_cmd_ref.reference.heading = position_cmd->heading; auto res = transformer_->transformSingle(position_cmd_ref, octree_frame); if (!res) { ROS_ERROR("[Pathfinder]: could not transform position cmd to the map frame"); return; } initial_pos_.x() = res.value().reference.position.x; initial_pos_.y() = res.value().reference.position.y; initial_pos_.z() = res.value().reference.position.z; initial_heading_ = res.value().reference.heading; } ros::Time path_stamp = initial_condition.value().header.stamp; if (ros::Time::now() > path_stamp || !control_manager_diag->tracker_status.have_goal) { path_stamp = ros::Time(0); } mrs_msgs::GetPathSrv srv_get_path; srv_get_path.request.path.header.frame_id = octree_frame_; srv_get_path.request.path.header.stamp = path_stamp; srv_get_path.request.path.fly_now = false; srv_get_path.request.path.relax_heading = true; srv_get_path.request.path.use_heading = true; std::vector<Eigen::Vector4d> eig_waypoints; // create an array of Eigen waypoints for (auto& w : waypoints.first) { Eigen::Vector4d eig_waypoint; eig_waypoint[0] = w.x(); eig_waypoint[1] = w.y(); eig_waypoint[2] = w.z(); eig_waypoint[4] = user_goal.heading; eig_waypoints.push_back(eig_waypoint); } std::vector<double> segment_times = estimateSegmentTimes(eig_waypoints, false); double cum_time = 0; for (int i = 0; i < waypoints.first.size(); i++) { mrs_msgs::Reference ref; ref.position.x = waypoints.first[i].x(); ref.position.y = waypoints.first[i].y(); ref.position.z = waypoints.first[i].z(); ref.heading = user_goal.heading; srv_get_path.request.path.points.push_back(ref); cum_time += segment_times[i]; if (i > 1 && cum_time > 15.0) { ROS_INFO("[Pathfinder]: cutting path in waypoint %d out of %d", i, int(waypoints.first.size())); break; } } ROS_INFO("[Pathfinder]: calling trajectory generation"); { bool success = sc_get_trajectory_.call(srv_get_path); if (!success) { ROS_ERROR("[Pathfinder]: service call for trajectory failed"); break; } else { if (!srv_get_path.response.success) { ROS_ERROR("[Pathfinder]: service call for trajectory failed: '%s'", srv_get_path.response.message.c_str()); break; } } } { std::scoped_lock lock(mutex_bv_processed_); bv_processed_.clearBuffers(); for (auto& p : srv_get_path.response.trajectory.points) { auto v = Eigen::Vector3d(p.position.x, p.position.y, p.position.z); bv_processed_.addPoint(v, 0, 1, 0, 1); } bv_processed_.publish(); } auto trajectory = srv_get_path.response.trajectory; ROS_INFO("[Pathfinder]: Setting replanning point"); setReplanningPoint(trajectory); set_timepoints_ = true; ROS_INFO("[Pathfinder]: publishing trajectory reference"); mrs_msgs::TrajectoryReferenceSrv srv_trajectory_reference; srv_trajectory_reference.request.trajectory = srv_get_path.response.trajectory; srv_trajectory_reference.request.trajectory.fly_now = true; { bool success = sc_trajectory_reference_.call(srv_trajectory_reference); if (!success) { ROS_ERROR("[Pathfinder]: service call for trajectory reference failed"); break; } else { if (!srv_trajectory_reference.response.success) { ROS_ERROR("[Pathfinder]: service call for trajectory reference failed: '%s'", srv_get_path.response.message.c_str()); break; } else { } } } changeState(STATE_MOVING); break; } //} /* STATE_MOVING //{ */ case STATE_MOVING: { { std::scoped_lock lock(mutex_diagnostics_); diagnostics_.idle = false; } auto initial_pos = mrs_lib::get_mutexed(mutex_initial_condition_, initial_pos_); double dist_to_goal = (initial_pos - user_goal_octpoint).norm(); ROS_INFO_THROTTLE(1.0, "[Pathfinder]: dist to goal: %.2f m", dist_to_goal); if (dist_to_goal < 2 * planning_tree_resolution_) { ROS_INFO("[Pathfinder]: user goal reached"); changeState(STATE_IDLE); break; } if ((ros::Time::now() - (time_last_plan_ + ros::Duration(_replan_after_))).toSec() > 0) { ROS_INFO("[Pathfinder]: triggering replanning"); changeState(STATE_PLANNING); } break; } //} } } //} /* timerFutureCheck() //{ */ void Pathfinder::timerFutureCheck([[maybe_unused]] const ros::TimerEvent& evt) { if (!is_initialized_) { return; } /* preconditions //{ */ if (!sh_control_manager_diag_.hasMsg()) { return; } if (!sh_octomap_.hasMsg()) { return; } if (!sh_mpc_prediction_.hasMsg()) { return; } //} if (state_ == STATE_IDLE) { return; } ROS_INFO_ONCE("[Pathfinder]: future check timer spinning"); // | ----------- check if the prediction is feasible ---------- | // copy the octomap locally OcTreeMsgConstPtr_t octree_msg_ptr; std::string octree_frame; { std::scoped_lock lock(mutex_octree_msg_ptr_); octree_msg_ptr = octree_msg_ptr_; octree_frame = octree_frame_; } auto octree_opt = msgToMap(octree_msg_ptr); if (!octree_opt) { ROS_ERROR("[Pathfinder]: cannot check for collision, don't have a map"); return; } OcTreePtr_t octree = octree_opt.value(); mrs_msgs::MpcPredictionFullStateConstPtr prediction = sh_mpc_prediction_.getMsg(); mrs_msgs::ControlManagerDiagnosticsConstPtr control_manager_diag = sh_control_manager_diag_.getMsg(); if (control_manager_diag->flying_normally && control_manager_diag->tracker_status.have_goal) { geometry_msgs::TransformStamped tf; auto ret = transformer_->getTransform(prediction->header.frame_id, octree_frame, prediction->header.stamp); if (!ret) { ROS_ERROR_THROTTLE(1.0, "[Pathfinder]: could not transform position cmd to the map frame! can not check for potential collisions!"); return; } tf = ret.value(); // prepare the potential future trajectory mrs_msgs::TrajectoryReference trajectory; trajectory.header.stamp = ret.value().header.stamp; trajectory.header.frame_id = transformer_->frame_to(ret.value()); trajectory.fly_now = true; trajectory.use_heading = true; trajectory.dt = 0.2; for (int i = 1; i < prediction->position.size(); i++) { mrs_msgs::ReferenceStamped pose; pose.header = prediction->header; pose.reference.position.x = prediction->position[i].x; pose.reference.position.y = prediction->position[i].y; pose.reference.position.z = prediction->position[i].z; pose.reference.heading = prediction->heading[i]; auto transformed_pose = transformer_->transform(pose, tf); if (!transformed_pose) { ROS_ERROR_THROTTLE(1.0, "[Pathfinder]: could not transform position cmd to the map frame! can not check for potential collisions!"); return; } trajectory.points.push_back(transformed_pose->reference); } // check if the trajectory is safe for (int i = 0; i < trajectory.points.size() - 1; i++) { octomap::point3d point1(trajectory.points[i].position.x, trajectory.points[i].position.y, trajectory.points[i].position.z); octomap::point3d point2(trajectory.points[i + 1].position.x, trajectory.points[i + 1].position.y, trajectory.points[i + 1].position.z); octomap::KeyRay key_ray; if (octree->computeRayKeys(point1, point2, key_ray)) { bool ray_is_cool = true; for (octomap::KeyRay::iterator it1 = key_ray.begin(), end = key_ray.end(); it1 != end; ++it1) { auto node = octree->search(*it1); if (node && octree->isNodeOccupied(node)) { ray_is_cool = false; break; } } if (!ray_is_cool) { ROS_ERROR_THROTTLE(0.1, "[Pathfinder]: future check found collision with prediction horizon between %d and %d, hovering!", i, i + 1); // shorten the trajectory for (int j = int(trajectory.points.size()) - 1; j >= floor(i / 2.0); j--) { trajectory.points.pop_back(); } mrs_msgs::TrajectoryReferenceSrv srv_trajectory_reference; srv_trajectory_reference.request.trajectory = trajectory; bool success = sc_trajectory_reference_.call(srv_trajectory_reference); if (!success) { ROS_ERROR("[Pathfinder]: service call for trajectory reference failed"); break; } else { if (!srv_trajectory_reference.response.success) { ROS_ERROR("[Pathfinder]: service call for trajectory reference failed: '%s'", srv_trajectory_reference.response.message.c_str()); break; } } break; } } else { ROS_ERROR_THROTTLE(0.1, "[Pathfinder]: future check failed, could not raytrace!"); hover(); break; } } } } //} /* timerDiagnostics() //{ */ void Pathfinder::timerDiagnostics([[maybe_unused]] const ros::TimerEvent& evt) { if (!is_initialized_) { return; } auto diagnostics = mrs_lib::get_mutexed(mutex_diagnostics_, diagnostics_); try { pub_diagnostics_.publish(diagnostics); } catch (...) { ROS_ERROR("exception caught during publishing topic '%s'", pub_diagnostics_.getTopic().c_str()); } } //} // | ------------------------ routines ------------------------ | /* setReplanningPoint() //{ */ void Pathfinder::setReplanningPoint(const mrs_msgs::TrajectoryReference& traj) { const float x = traj.points.back().position.x; const float y = traj.points.back().position.y; const float z = traj.points.back().position.z; { std::scoped_lock lock(mutex_replanning_point_); replanning_point_.x() = x; replanning_point_.y() = y; replanning_point_.z() = z; } mrs_lib::geometry::Cuboid c(Eigen::Vector3d(x, y, z), Eigen::Vector3d(0.4, 0.4, 0.4), Eigen::Quaterniond::Identity()); { std::scoped_lock lock(mutex_bv_input_); auto user_goal = mrs_lib::get_mutexed(mutex_user_goal_, user_goal_); bv_input_.clearBuffers(); bv_input_.addPoint(Eigen::Vector3d(user_goal.position.x, user_goal.position.y, user_goal.position.z), 0, 1, 0, 1); bv_input_.addCuboid(c, 0.5, 1.0, 1.0, 0.8, true); bv_input_.publish(); } } //} /* changeState() //{ */ void Pathfinder::changeState(const State_t new_state) { const State_t old_state = state_; switch (new_state) { case STATE_PLANNING: { if (old_state == STATE_IDLE) { replanning_counter_ = 0; } } default: { break; } } ROS_INFO("[Pathfinder]: changing state '%s' -> '%s'", _state_names_[old_state].c_str(), _state_names_[new_state].c_str()); state_ = new_state; } //} /* getInitialCondition() //{ */ std::optional<mrs_msgs::ReferenceStamped> Pathfinder::getInitialCondition(const ros::Time des_time) { const mrs_msgs::MpcPredictionFullStateConstPtr prediction_full_state = sh_mpc_prediction_.getMsg(); if ((des_time - prediction_full_state->stamps.back()).toSec() > 0) { ROS_ERROR_THROTTLE(1.0, "[Pathfinder]: could not obtain initial condition, the desired time is too far in the future"); return {}; } mrs_msgs::ReferenceStamped orig_reference; orig_reference.header = prediction_full_state->header; ros::Time future_time_stamp; for (int i = 0; i < prediction_full_state->stamps.size(); i++) { if ((prediction_full_state->stamps[i] - des_time).toSec() > 0) { orig_reference.reference.position.x = prediction_full_state->position[i].x; orig_reference.reference.position.y = prediction_full_state->position[i].y; orig_reference.reference.position.z = prediction_full_state->position[i].z; orig_reference.reference.heading = prediction_full_state->heading[i]; future_time_stamp = prediction_full_state->stamps[i]; break; } } // transform the initial condition to the current map frame auto result = transformer_->transformSingle(orig_reference, octree_frame_); if (result) { mrs_msgs::ReferenceStamped transfomed_reference = result.value(); transfomed_reference.header.stamp = future_time_stamp; return transfomed_reference; } else { std::stringstream ss; ss << "could not transform initial condition to the map frame"; ROS_ERROR_STREAM("[Pathfinder]: " << ss.str()); return {}; } } //} /* hover() //{ */ void Pathfinder::hover(void) { ROS_INFO("[Pathfinder]: triggering hover"); std_srvs::Trigger srv_out; sc_hover_.call(srv_out); } //} /* estimateSegmentTimes() //{ */ std::vector<double> Pathfinder::estimateSegmentTimes(const std::vector<Eigen::Vector4d>& vertices, const bool use_heading) { if (vertices.size() <= 1) { return std::vector<double>(0); } const mrs_msgs::DynamicsConstraintsConstPtr constraints = sh_constraints_.getMsg(); const double v_max_vertical = std::min(constraints->vertical_ascending_speed, constraints->vertical_descending_speed); const double a_max_vertical = std::min(constraints->vertical_ascending_acceleration, constraints->vertical_descending_acceleration); const double j_max_vertical = std::min(constraints->vertical_ascending_jerk, constraints->vertical_descending_jerk); const double v_max_horizontal = constraints->horizontal_speed; const double a_max_horizontal = constraints->horizontal_acceleration; const double j_max_horizontal = constraints->horizontal_jerk; const double heading_acc_max = constraints->heading_acceleration; const double heading_speed_max = constraints->heading_speed; std::vector<double> segment_times; segment_times.reserve(vertices.size() - 1); // for each vertex in the path for (size_t i = 0; i < vertices.size() - 1; i++) { Eigen::Vector3d start = vertices[i].head(3); Eigen::Vector3d end = vertices[i + 1].head(3); double start_hdg = vertices[i](3); double end_hdg = vertices[i + 1](3); double acceleration_time_1 = 0; double acceleration_time_2 = 0; double jerk_time_1 = 0; double jerk_time_2 = 0; double acc_1_coeff = 0; double acc_2_coeff = 0; double distance = (end - start).norm(); double inclinator = atan2(end(2) - start(2), sqrt(pow(end(0) - start(0), 2) + pow(end(1) - start(1), 2))); double v_max, a_max, j_max; if (inclinator > atan2(v_max_vertical, v_max_horizontal) || inclinator < -atan2(v_max_vertical, v_max_horizontal)) { v_max = fabs(v_max_vertical / sin(inclinator)); } else { v_max = fabs(v_max_horizontal / cos(inclinator)); } if (inclinator > atan2(a_max_vertical, a_max_horizontal) || inclinator < -atan2(a_max_vertical, a_max_horizontal)) { a_max = fabs(a_max_vertical / sin(inclinator)); } else { a_max = fabs(a_max_horizontal / cos(inclinator)); } if (inclinator > atan2(j_max_vertical, j_max_horizontal) || inclinator < -atan2(j_max_vertical, j_max_horizontal)) { j_max = fabs(j_max_vertical / sin(inclinator)); } else { j_max = fabs(j_max_horizontal / cos(inclinator)); } if (i >= 1) { Eigen::Vector3d pre = vertices[i - 1].head(3); Eigen::Vector3d vec1 = start - pre; Eigen::Vector3d vec2 = end - start; vec1.normalize(); vec2.normalize(); double scalar = vec1.dot(vec2) < 0 ? 0.0 : vec1.dot(vec2); acc_1_coeff = (1 - scalar); acceleration_time_1 = acc_1_coeff * ((v_max / a_max) + (a_max / j_max)); jerk_time_1 = acc_1_coeff * (2 * (a_max / j_max)); } // the first vertex if (i == 0) { acc_1_coeff = 1.0; acceleration_time_1 = (v_max / a_max) + (a_max / j_max); jerk_time_1 = (2 * (a_max / j_max)); } // last vertex if (i == vertices.size() - 2) { acc_2_coeff = 1.0; acceleration_time_2 = (v_max / a_max) + (a_max / j_max); jerk_time_2 = (2 * (a_max / j_max)); } // a vertex if (i < vertices.size() - 2) { Eigen::Vector3d post = vertices[i + 2].head(3); Eigen::Vector3d vec1 = end - start; Eigen::Vector3d vec2 = post - end; vec1.normalize(); vec2.normalize(); double scalar = vec1.dot(vec2) < 0 ? 0.0 : vec1.dot(vec2); acc_2_coeff = (1 - scalar); acceleration_time_2 = acc_2_coeff * ((v_max / a_max) + (a_max / j_max)); jerk_time_2 = acc_2_coeff * (2 * (a_max / j_max)); } if (acceleration_time_1 > sqrt(2 * distance / a_max)) { acceleration_time_1 = sqrt(2 * distance / a_max); } if (jerk_time_1 > sqrt(2 * v_max / j_max)) { jerk_time_1 = sqrt(2 * v_max / j_max); } if (acceleration_time_2 > sqrt(2 * distance / a_max)) { acceleration_time_2 = sqrt(2 * distance / a_max); } if (jerk_time_2 > sqrt(2 * v_max / j_max)) { jerk_time_2 = sqrt(2 * v_max / j_max); } double max_velocity_time; if (((distance - (2 * (v_max * v_max) / a_max)) / v_max) < 0) { max_velocity_time = ((distance) / v_max); } else { max_velocity_time = ((distance - (2 * (v_max * v_max) / a_max)) / v_max); } /* double t = max_velocity_time + acceleration_time_1 + acceleration_time_2 + jerk_time_1 + jerk_time_2; */ double t = max_velocity_time + acceleration_time_1 + acceleration_time_2; /* printf("segment %d, [%.2f %.2f %.2f] - > [%.2f %.2f %.2f] = %.2f\n", i, start(0), start(1), start(2), end(0), end(1), end(2), distance); */ /* printf("segment %d time %.2f, distance %.2f, %.2f, %.2f, %.2f, vmax: %.2f, amax: %.2f, jmax: %.2f\n", i, t, distance, max_velocity_time, */ /* acceleration_time_1, acceleration_time_2, v_max, a_max, j_max); */ if (t < 0.01) { t = 0.01; } // | ------------- check the heading rotation time ------------ | double angular_distance = fabs(mrs_lib::geometry::radians::dist(start_hdg, end_hdg)); double hdg_velocity_time = 0; double hdg_acceleration_time = 0; if (use_heading) { if (heading_speed_max < std::numeric_limits<float>::max() && heading_acc_max < std::numeric_limits<float>::max()) { if (((angular_distance - (2 * (heading_speed_max * heading_speed_max) / heading_acc_max)) / heading_speed_max) < 0) { hdg_velocity_time = ((angular_distance) / heading_speed_max); } else { hdg_velocity_time = ((angular_distance - (2 * (heading_speed_max * heading_speed_max) / heading_acc_max)) / heading_speed_max); } if (angular_distance > M_PI / 4) { hdg_acceleration_time = 2 * (heading_speed_max / heading_acc_max); } } } // what will take longer? to fix the lateral or the heading double heading_fix_time = 1.5 * (hdg_velocity_time + hdg_acceleration_time); if (heading_fix_time > t) { t = heading_fix_time; } segment_times.push_back(t); } return segment_times; } //} /* msgToMap() //{ */ std::optional<OcTreePtr_t> Pathfinder::msgToMap(const octomap_msgs::OctomapConstPtr octomap) { octomap::AbstractOcTree* abstract_tree = octomap_msgs::binaryMsgToMap(*octomap); if (!abstract_tree) { ROS_WARN("[Pathfinder]: octomap message is empty!"); return {}; } else { OcTreePtr_t octree_out = OcTreePtr_t(dynamic_cast<OcTree_t*>(abstract_tree)); return {octree_out}; } } //} } // namespace pathfinder #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(pathfinder::Pathfinder, nodelet::Nodelet)
45,898
16,307
#ifndef LATTICES_BRAVIAS_OFFSET_HPP #define LATTICES_BRAVIAS_OFFSET_HPP #include "lattice.hpp" #include <type_traits> #include <cassert> #include <algorithm> namespace lattices { namespace bravias { template <typename TAG, typename SIZE_TYPE> struct OffsetCat { typedef TAG Tag; typedef SIZE_TYPE VSize; typedef LatticeCat<TAG, VSize> LatticeCat; typedef typename LatticeCat::Lattice Lattice; typedef typename LatticeCat::Vertex Vertex; typedef typename LatticeCat::Vid Vid; typedef typename std::make_signed<Vid>::type OffsetType; static void offset_rewind(Vid& x, OffsetType dx, Vid l) { assert(dx > -((OffsetType)l)); if (dx < 0) dx += l; x += dx; x %= l; } struct Offset { OffsetType dx; OffsetType dy; }; static Vid dx_max(const Lattice& l) { return l.lx / 2; } static Vid dy_max(const Lattice& l) { return l.ly / 2; } static void shift(Vertex& v, const Vertex& dv, const Lattice& l) { v.x += dv.x; v.x %= l.lx; v.y += dv.y; v.y %= l.ly; } static void shift(Vertex& v, const Offset& dv, const Lattice& l) { offset_rewind(v.x, dv.dx, l.lx); offset_rewind(v.y, dv.dy, l.ly); } static void shift(Vid& vid, Vid dvid, const Lattice& l) { Vertex v = LatticeCat::vertex(vid, l); Vertex dv = LatticeCat::vertex(dvid, l); shift(v, dv, l); vid = LatticeCat::vid(v, l); } static Offset offset(const Vertex& v0, const Vertex& v1) { Offset dv = {v1.x - v0.x, v1.y - v0.y}; return dv; } static Vid dv2id(const Offset& dv, const Lattice& l) { Vertex v = LatticeCat::vertex(0, l); shift(v, dv, l); return LatticeCat::vid(v, l); } static Offset reverse_offset(const Offset& dv, const Lattice& l) { Offset dv2 = {-dv.dx, -dv.dy}; return dv2; } }; } } #endif
1,859
756
#include "asknamedialog.h" #include "ui_asknamedialog.h" AskNameDialog::AskNameDialog(QWidget *parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::AskNameDialog) { ui->setupUi(this); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); this->setFixedSize(this->size()); } AskNameDialog::~AskNameDialog() { delete ui; } void AskNameDialog::setHelpTitle(const QString &title) { ui->helpLabel->setText(title); } void AskNameDialog::on_lineEdit_textChanged(const QString &text) { bool isValid = (text.length() > 0); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(isValid); } QString AskNameDialog::name() { return ui->lineEdit->text(); } void AskNameDialog::setName(const QString &name) { ui->lineEdit->setText(name); } void AskNameDialog::setMaxLength(int maxLength) { ui->lineEdit->setMaxLength(maxLength); }
946
330
//////////////////////////////////////////////////////////////////////////////// // // cagey-engine - Toy 3D Engine // Copyright (c) 2014 Kyle Girard <theycallmecoach@gmail.com> // // The MIT License (MIT) // // 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 <cagey/math/Matrix.hh> #include "gtest/gtest.h" #include <algorithm> #include <type_traits> using namespace cagey::math; TEST(Matrix, DefaultConstructor) { typedef Matrix<int, 5, 5> Mat5f; Mat5f ident; EXPECT_EQ(1, ident(2,2)); EXPECT_EQ(0, ident(2,3)); } TEST(Matrix, FillConstructor) { Mat4<int> mat(4,4); EXPECT_EQ(4, mat(3,0)); EXPECT_EQ(0, mat(0,1)); Mat4<int> mata(2); EXPECT_EQ(2, mata(3,0)); } TEST(Matrix, ArrayConstructor) { Mat2i ma{{{1, 2, 3, 4}}}; EXPECT_EQ(4, ma(1,1)); std::array<int, 4> b{{1, 2, 3, 4}}; Mat2i mb{b}; EXPECT_EQ(4, mb(1,1)); } TEST(Matrix, DifferentTypeConstructor) { Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}}; Mat2i mb{ma}; EXPECT_EQ(4, mb(1,1)); } TEST(Matrix, PodTest) { EXPECT_EQ(false, std::is_pod<Mat2f>::value); } TEST(Matrix, operatorScale) { Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}}; ma *= 2.0f; EXPECT_EQ(8, ma(1,1)); } TEST(Matrix, operatorDivide) { Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}}; EXPECT_THROW(ma/=0.0f, cagey::core::DivideByZeroException); } TEST(Matrix, operatorNegate) { Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}}; ma = -ma; EXPECT_EQ(-4, ma(1,1)); } TEST(Matrix, adjugateTest) { Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}}; auto adj = adjugate(ma); EXPECT_EQ(1, adj(1,1)); EXPECT_EQ(4, adj(0,0)); } TEST(Matrix, makeScaleTest) { auto scale = makeScale(2.0f, 2.0f, 2.0f); EXPECT_EQ(2, scale(1,1)); } TEST(Matrix, makeTranslationTest) { auto trans = makeTranslation(2.0f, 2.0f, 2.0f); EXPECT_EQ(2, trans(0,3)); }
2,884
1,226
/* * CallbackScreenShooter.cpp * * Copyright (C) 2019 by VISUS (Universitaet Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "mmcore/job/TickCall.h" #include "mmcore/view/special/CallbackScreenShooter.h" #include <functional> namespace megamol { namespace core { namespace view { namespace special { CallbackScreenShooter::CallbackScreenShooter() : ScreenShooter(true), AbstractWriterParams(std::bind(&CallbackScreenShooter::MakeSlotAvailable, this, std::placeholders::_1)), inputSlot("inputSlot", "Slot for registering the screen shot callback function"), tickSlot("tickSlot", "Slot for receiving a tick") { // In- and output slots this->inputSlot.SetCompatibleCall<CallbackScreenShooterCall::CallbackScreenShooterDescription>(); Module::MakeSlotAvailable(&this->inputSlot); this->tickSlot.SetCallback(job::TickCall::ClassName(), job::TickCall::FunctionName(0), &CallbackScreenShooter::Run); this->MakeSlotAvailable(&this->tickSlot); } CallbackScreenShooter::~CallbackScreenShooter() { Module::Release(); } bool CallbackScreenShooter::create() { return true; } void CallbackScreenShooter::release() { } bool CallbackScreenShooter::Run(Call&) { auto* call = this->inputSlot.CallAs<CallbackScreenShooterCall>(); if (call != nullptr) { call->SetCallback(std::bind(&CallbackScreenShooter::CreateScreenshot, this)); return (*call)(); } return true; } void CallbackScreenShooter::CreateScreenshot() { const auto filename = AbstractWriterParams::getNextFilename(); if (filename.first) { ScreenShooter::createScreenshot(filename.second); } } } } } }
1,813
561
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER */ // Experimental unified task-data parallel manycore LDRD #ifndef KOKKOS_IMPL_TASKBASE_HPP #define KOKKOS_IMPL_TASKBASE_HPP #include <Kokkos_Macros.hpp> #if defined(KOKKOS_ENABLE_TASKDAG) #include <Kokkos_TaskScheduler_fwd.hpp> #include <Kokkos_Core_fwd.hpp> #include <impl/Kokkos_LIFO.hpp> #include <string> #include <typeinfo> #include <stdexcept> //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- namespace Kokkos { namespace Impl { /** \brief Base class for task management, access, and execution. * * Inheritance structure to allow static_cast from the task root type * and a task's FunctorType. * * // Enable a functor to access the base class * // and provide memory for result value. * TaskBase< Space , ResultType , FunctorType > * : TaskBase< void , void , void > * , FunctorType * { ... }; * Followed by memory allocated for result value. * * * States of a task: * * Constructing State, NOT IN a linked list * m_wait == 0 * m_next == 0 * * Scheduling transition : Constructing -> Waiting * before: * m_wait == 0 * m_next == this task's initial dependence, 0 if none * after: * m_wait == EndTag * m_next == EndTag * * Waiting State, IN a linked list * m_apply != 0 * m_queue != 0 * m_ref_count > 0 * m_wait == head of linked list of tasks waiting on this task * m_next == next of linked list of tasks * * transition : Waiting -> Executing * before: * m_next == EndTag * after:: * m_next == LockTag * * Executing State, NOT IN a linked list * m_apply != 0 * m_queue != 0 * m_ref_count > 0 * m_wait == head of linked list of tasks waiting on this task * m_next == LockTag * * Respawn transition : Executing -> Executing-Respawn * before: * m_next == LockTag * after: * m_next == this task's updated dependence, 0 if none * * Executing-Respawn State, NOT IN a linked list * m_apply != 0 * m_queue != 0 * m_ref_count > 0 * m_wait == head of linked list of tasks waiting on this task * m_next == this task's updated dependence, 0 if none * * transition : Executing -> Complete * before: * m_wait == head of linked list * after: * m_wait == LockTag * * Complete State, NOT IN a linked list * m_wait == LockTag: cannot add dependence (<=> complete) * m_next == LockTag: not a member of a wait queue * */ class TaskBase { public: enum : int16_t { TaskTeam = 0, TaskSingle = 1, Aggregate = 2 }; enum : uintptr_t { LockTag = ~uintptr_t(0), EndTag = ~uintptr_t(1) }; template <typename, typename> friend class Kokkos::BasicTaskScheduler; using queue_type = TaskQueueBase; using function_type = void (*)(TaskBase*, void*); using destroy_type = void (*)(TaskBase*); // sizeof(TaskBase) == 48 function_type m_apply = nullptr; ///< Apply function pointer queue_type* m_queue = nullptr; ///< Pointer to the scheduler TaskBase* m_next = nullptr; ///< next in linked list of ready tasks TaskBase* m_wait = nullptr; ///< Queue of tasks waiting on this int32_t m_ref_count = 0; int32_t m_alloc_size = 0; int32_t m_dep_count; ///< Aggregate's number of dependences int16_t m_task_type; ///< Type of task int16_t m_priority; ///< Priority of runnable task TaskBase(TaskBase&&) = delete; TaskBase(const TaskBase&) = delete; TaskBase& operator=(TaskBase&&) = delete; TaskBase& operator=(const TaskBase&) = delete; KOKKOS_DEFAULTED_FUNCTION ~TaskBase() = default; KOKKOS_INLINE_FUNCTION constexpr TaskBase() : m_apply(nullptr), m_queue(nullptr), m_next(nullptr), m_wait(nullptr), m_ref_count(0), m_alloc_size(0), m_dep_count(0), m_task_type(0), m_priority(0) {} //---------------------------------------- KOKKOS_INLINE_FUNCTION TaskBase* volatile* aggregate_dependences() volatile { return reinterpret_cast<TaskBase* volatile*>(this + 1); } KOKKOS_INLINE_FUNCTION bool requested_respawn() { // This should only be called when a task has finished executing and is // in the transition to either the complete or executing-respawn state. TaskBase* const lock = reinterpret_cast<TaskBase*>(LockTag); return lock != m_next; } KOKKOS_INLINE_FUNCTION void add_dependence(TaskBase* dep) { // Precondition: lock == m_next TaskBase* const lock = (TaskBase*)LockTag; // Assign dependence to m_next. It will be processed in the subsequent // call to schedule. Error if the dependence is reset. if (lock != Kokkos::atomic_exchange(&m_next, dep)) { Kokkos::abort("TaskScheduler ERROR: resetting task dependence"); } if (nullptr != dep) { // The future may be destroyed upon returning from this call // so increment reference count to track this assignment. Kokkos::atomic_increment(&(dep->m_ref_count)); } } //---------------------------------------- KOKKOS_INLINE_FUNCTION int32_t reference_count() const { return *((int32_t volatile*)(&m_ref_count)); } }; //------------------------------------------------------------------------------ // <editor-fold desc="Verify the size of TaskBase is as expected"> {{{2 // Workaround: some compilers implement int16_t as 4 bytes, so the size might // not actually be 48 bytes. // There's not a lot of reason to keep checking this here; the program will // work fine if this isn't true. I think this check was originally here to // emphasize the fact that adding to the size of TaskBase could have a // significant performance penalty, since doing so could substantially decrease // the number of full task types that fit into a cache line. We'll leave it // here for now, though, since we're probably going to be ripping all of the // old TaskBase stuff out eventually anyway. constexpr size_t unpadded_task_base_size = 44 + 2 * sizeof(int16_t); // don't forget padding: constexpr size_t task_base_misalignment = unpadded_task_base_size % alignof(void*); constexpr size_t task_base_padding_size = (alignof(void*) - task_base_misalignment) % alignof(void*); constexpr size_t expected_task_base_size = unpadded_task_base_size + task_base_padding_size; // Produce a more readable compiler error message than the plain static assert template <size_t Size> struct verify_task_base_size_is_48_note_actual_size_is_ {}; template <> struct verify_task_base_size_is_48_note_actual_size_is_< expected_task_base_size> { using type = int; }; static constexpr typename verify_task_base_size_is_48_note_actual_size_is_<sizeof( TaskBase)>::type verify = {}; static_assert(sizeof(TaskBase) == expected_task_base_size, "Verifying expected sizeof(TaskBase)"); // </editor-fold> end Verify the size of TaskBase is as expected }}}2 //------------------------------------------------------------------------------ } /* namespace Impl */ } /* namespace Kokkos */ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- namespace Kokkos { namespace Impl { template <class Scheduler, typename ResultType, class FunctorType> class Task : public TaskBase, public FunctorType { public: Task() = delete; Task(Task&&) = delete; Task(const Task&) = delete; Task& operator=(Task&&) = delete; Task& operator=(const Task&) = delete; using root_type = TaskBase; using functor_type = FunctorType; using result_type = ResultType; using specialization = TaskQueueSpecialization<Scheduler>; using member_type = typename specialization::member_type; KOKKOS_INLINE_FUNCTION void apply_functor(member_type* const member, void*) { this->functor_type::operator()(*member); } template <typename T> KOKKOS_INLINE_FUNCTION void apply_functor(member_type* const member, T* const result) { this->functor_type::operator()(*member, *result); } KOKKOS_FUNCTION static void destroy(root_type* root) { TaskResult<result_type>::destroy(root); } KOKKOS_FUNCTION static void apply(root_type* root, void* exec) { Task* const task = static_cast<Task*>(root); member_type* const member = reinterpret_cast<member_type*>(exec); result_type* const result = TaskResult<result_type>::ptr(task); // Task may be serial or team. // If team then must synchronize before querying if respawn was requested. // If team then only one thread calls destructor. const bool only_one_thread = #if defined(KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_CUDA) 0 == threadIdx.x && 0 == threadIdx.y; #else 0 == member->team_rank(); #endif task->apply_functor(member, result); member->team_barrier(); if (only_one_thread && !(task->requested_respawn())) { // Did not respawn, destroy the functor to free memory. task->functor_type::~functor_type(); // Cannot destroy and deallocate the task until its dependences // have been processed. } } // Constructor for runnable task KOKKOS_INLINE_FUNCTION constexpr Task(FunctorType&& arg_functor) : root_type(), functor_type(std::move(arg_functor)) {} KOKKOS_INLINE_FUNCTION ~Task() = delete; }; } /* namespace Impl */ } /* namespace Kokkos */ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- #endif /* #if defined( KOKKOS_ENABLE_TASKDAG ) */ #endif /* #ifndef KOKKOS_IMPL_TASKBASE_HPP */
11,860
3,761
#include <iostream> using namespace std; /* Sameer Hussain - CSCE 221 – PA 1*/ enum class Stress_ball_colors { // enum for stress ball colors red, blue, yellow, green }; enum class Stress_ball_sizes { // enum for stress ball sizes small, medium, large }; class Stress_ball { private: Stress_ball_colors color; Stress_ball_sizes size; public: Stress_ball() : color(Stress_ball_colors(rand() % 4)), size(Stress_ball_sizes(rand() % 3)) {} // random generation for the vals Stress_ball(Stress_ball_colors col, Stress_ball_sizes siz) : color(col), size(siz) {} Stress_ball_colors get_color() const { return color; } Stress_ball_sizes get_size() const { return size; } bool operator==(Stress_ball &c) { // operator for getting color and size bool c1 = false; bool c2 = false; if (get_color() == c.get_color()) { c1 = true; } if (get_size() == c.get_size()) { c2 = true; } return c1 && c2; } }; inline std::ostream &operator<<( std::ostream &os, const Stress_ball &sb ) { switch (sb.get_color()) { case Stress_ball_colors::red: // using switch statements to run through the different cases of color/size and outputting os << "(red,"; break; case Stress_ball_colors::blue: os << "(blue,"; break; case Stress_ball_colors::yellow: os << "(yellow,"; break; case Stress_ball_colors::green: os << "(green,"; } switch(sb.get_size()) { case Stress_ball_sizes::small: os << "small)"; break; case Stress_ball_sizes::medium: os << "medium)"; break; case Stress_ball_sizes::large: os << "large)"; break; } return os; // returning os which has both color and size } int main() { // setting a stress ball Stress_ball s1(Stress_ball_colors::red, Stress_ball_sizes::small); //printing stress ball cout << s1; return 0; }
2,149
711
#include <mbgl/style/style.hpp> #include <mbgl/style/observer.hpp> #include <mbgl/style/source_impl.hpp> #include <mbgl/style/layers/symbol_layer.hpp> #include <mbgl/style/layers/symbol_layer_impl.hpp> #include <mbgl/style/layers/custom_layer.hpp> #include <mbgl/style/layers/custom_layer_impl.hpp> #include <mbgl/style/layers/background_layer.hpp> #include <mbgl/style/layers/background_layer_impl.hpp> #include <mbgl/style/layers/fill_layer.hpp> #include <mbgl/style/layers/fill_extrusion_layer.hpp> #include <mbgl/style/layers/line_layer.hpp> #include <mbgl/style/layers/circle_layer.hpp> #include <mbgl/style/layers/raster_layer.hpp> #include <mbgl/style/layer_impl.hpp> #include <mbgl/style/parser.hpp> #include <mbgl/style/query_parameters.hpp> #include <mbgl/style/transition_options.hpp> #include <mbgl/style/class_dictionary.hpp> #include <mbgl/style/update_parameters.hpp> #include <mbgl/style/cascade_parameters.hpp> #include <mbgl/style/property_evaluation_parameters.hpp> #include <mbgl/sprite/sprite_atlas.hpp> #include <mbgl/text/glyph_atlas.hpp> #include <mbgl/geometry/line_atlas.hpp> #include <mbgl/renderer/render_item.hpp> #include <mbgl/renderer/render_tile.hpp> #include <mbgl/util/constants.hpp> #include <mbgl/util/string.hpp> #include <mbgl/util/logging.hpp> #include <mbgl/math/minmax.hpp> #include <algorithm> namespace mbgl { namespace style { static Observer nullObserver; Style::Style(FileSource& fileSource_, float pixelRatio) : fileSource(fileSource_), glyphAtlas(std::make_unique<GlyphAtlas>(Size{ 2048, 2048 }, fileSource)), spriteAtlas(std::make_unique<SpriteAtlas>(Size{ 1024, 1024 }, pixelRatio)), lineAtlas(std::make_unique<LineAtlas>(Size{ 256, 512 })), observer(&nullObserver) { glyphAtlas->setObserver(this); spriteAtlas->setObserver(this); } Style::~Style() { for (const auto& source : sources) { source->baseImpl->setObserver(nullptr); } for (const auto& layer : layers) { if (CustomLayer* customLayer = layer->as<CustomLayer>()) { customLayer->impl->deinitialize(); } } glyphAtlas->setObserver(nullptr); spriteAtlas->setObserver(nullptr); } bool Style::addClass(const std::string& className) { if (hasClass(className)) return false; classes.push_back(className); return true; } bool Style::hasClass(const std::string& className) const { return std::find(classes.begin(), classes.end(), className) != classes.end(); } bool Style::removeClass(const std::string& className) { const auto it = std::find(classes.begin(), classes.end(), className); if (it != classes.end()) { classes.erase(it); return true; } return false; } void Style::setClasses(const std::vector<std::string>& classNames) { classes = classNames; } std::vector<std::string> Style::getClasses() const { return classes; } void Style::setTransitionOptions(const TransitionOptions& options) { transitionOptions = options; } TransitionOptions Style::getTransitionOptions() const { return transitionOptions; } void Style::setJSON(const std::string& json) { sources.clear(); layers.clear(); classes.clear(); transitionOptions = {}; updateBatch = {}; Parser parser; auto error = parser.parse(json); if (error) { Log::Error(Event::ParseStyle, "Failed to parse style: %s", util::toString(error).c_str()); observer->onStyleError(); observer->onResourceError(error); return; } for (auto& source : parser.sources) { addSource(std::move(source)); } for (auto& layer : parser.layers) { addLayer(std::move(layer)); } name = parser.name; defaultLatLng = parser.latLng; defaultZoom = parser.zoom; defaultBearing = parser.bearing; defaultPitch = parser.pitch; glyphAtlas->setURL(parser.glyphURL); spriteAtlas->load(parser.spriteURL, fileSource); loaded = true; observer->onStyleLoaded(); } void Style::addSource(std::unique_ptr<Source> source) { //Guard against duplicate source ids auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& existing) { return existing->getID() == source->getID(); }); if (it != sources.end()) { std::string msg = "Source " + source->getID() + " already exists"; throw std::runtime_error(msg.c_str()); } source->baseImpl->setObserver(this); sources.emplace_back(std::move(source)); } std::unique_ptr<Source> Style::removeSource(const std::string& id) { auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& source) { return source->getID() == id; }); if (it == sources.end()) { throw std::runtime_error("no such source"); } auto source = std::move(*it); sources.erase(it); updateBatch.sourceIDs.erase(id); return source; } std::vector<const Layer*> Style::getLayers() const { std::vector<const Layer*> result; result.reserve(layers.size()); for (const auto& layer : layers) { result.push_back(layer.get()); } return result; } std::vector<Layer*> Style::getLayers() { std::vector<Layer*> result; result.reserve(layers.size()); for (auto& layer : layers) { result.push_back(layer.get()); } return result; } std::vector<std::unique_ptr<Layer>>::const_iterator Style::findLayer(const std::string& id) const { return std::find_if(layers.begin(), layers.end(), [&](const auto& layer) { return layer->baseImpl->id == id; }); } Layer* Style::getLayer(const std::string& id) const { auto it = findLayer(id); return it != layers.end() ? it->get() : nullptr; } Layer* Style::addLayer(std::unique_ptr<Layer> layer, optional<std::string> before) { // TODO: verify source // Guard against duplicate layer ids auto it = std::find_if(layers.begin(), layers.end(), [&](const auto& existing) { return existing->getID() == layer->getID(); }); if (it != layers.end()) { throw std::runtime_error(std::string{"Layer "} + layer->getID() + " already exists"); } if (SymbolLayer* symbolLayer = layer->as<SymbolLayer>()) { if (!symbolLayer->impl->spriteAtlas) { symbolLayer->impl->spriteAtlas = spriteAtlas.get(); } } if (CustomLayer* customLayer = layer->as<CustomLayer>()) { customLayer->impl->initialize(); } layer->baseImpl->setObserver(this); return layers.emplace(before ? findLayer(*before) : layers.end(), std::move(layer))->get(); } std::unique_ptr<Layer> Style::removeLayer(const std::string& id) { auto it = std::find_if(layers.begin(), layers.end(), [&](const auto& layer) { return layer->baseImpl->id == id; }); if (it == layers.end()) throw std::runtime_error("no such layer"); auto layer = std::move(*it); if (CustomLayer* customLayer = layer->as<CustomLayer>()) { customLayer->impl->deinitialize(); } layers.erase(it); return layer; } std::string Style::getName() const { return name; } LatLng Style::getDefaultLatLng() const { return defaultLatLng; } double Style::getDefaultZoom() const { return defaultZoom; } double Style::getDefaultBearing() const { return defaultBearing; } double Style::getDefaultPitch() const { return defaultPitch; } void Style::updateTiles(const UpdateParameters& parameters) { for (const auto& source : sources) { if (source->baseImpl->enabled) { source->baseImpl->updateTiles(parameters); } } } void Style::updateSymbolDependentTiles() { for (const auto& source : sources) { source->baseImpl->updateSymbolDependentTiles(); } } void Style::relayout() { for (const auto& sourceID : updateBatch.sourceIDs) { Source* source = getSource(sourceID); if (source && source->baseImpl->enabled) { source->baseImpl->reloadTiles(); } } updateBatch.sourceIDs.clear(); } void Style::cascade(const TimePoint& timePoint, MapMode mode) { // When in continuous mode, we can either have user- or style-defined // transitions. Still mode is always immediate. static const TransitionOptions immediateTransition {}; std::vector<ClassID> classIDs; for (const auto& className : classes) { classIDs.push_back(ClassDictionary::Get().lookup(className)); } classIDs.push_back(ClassID::Default); const CascadeParameters parameters { classIDs, mode == MapMode::Continuous ? timePoint : Clock::time_point::max(), mode == MapMode::Continuous ? transitionOptions : immediateTransition }; for (const auto& layer : layers) { layer->baseImpl->cascade(parameters); } } void Style::recalculate(float z, const TimePoint& timePoint, MapMode mode) { // Disable all sources first. If we find an enabled layer that uses this source, we will // re-enable it later. for (const auto& source : sources) { source->baseImpl->enabled = false; } zoomHistory.update(z, timePoint); const PropertyEvaluationParameters parameters { z, mode == MapMode::Continuous ? timePoint : Clock::time_point::max(), zoomHistory, mode == MapMode::Continuous ? util::DEFAULT_FADE_DURATION : Duration::zero() }; hasPendingTransitions = false; for (const auto& layer : layers) { const bool hasTransitions = layer->baseImpl->evaluate(parameters); // Disable this layer if it doesn't need to be rendered. const bool needsRendering = layer->baseImpl->needsRendering(zoomHistory.lastZoom); if (!needsRendering) { continue; } hasPendingTransitions |= hasTransitions; // If this layer has a source, make sure that it gets loaded. if (Source* source = getSource(layer->baseImpl->source)) { source->baseImpl->enabled = true; if (!source->baseImpl->loaded) { source->baseImpl->loadDescription(fileSource); } } } // Remove the existing tiles if we didn't end up re-enabling the source. for (const auto& source : sources) { if (!source->baseImpl->enabled) { source->baseImpl->removeTiles(); } } } std::vector<const Source*> Style::getSources() const { std::vector<const Source*> result; result.reserve(sources.size()); for (const auto& source : sources) { result.push_back(source.get()); } return result; } std::vector<Source*> Style::getSources() { std::vector<Source*> result; result.reserve(sources.size()); for (auto& source : sources) { result.push_back(source.get()); } return result; } Source* Style::getSource(const std::string& id) const { const auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& source) { return source->getID() == id; }); return it != sources.end() ? it->get() : nullptr; } bool Style::hasTransitions() const { return hasPendingTransitions; } bool Style::isLoaded() const { if (!loaded) { return false; } for (const auto& source: sources) { if (source->baseImpl->enabled && !source->baseImpl->isLoaded()) { return false; } } if (!spriteAtlas->isLoaded()) { return false; } return true; } RenderData Style::getRenderData(MapDebugOptions debugOptions, float angle) const { RenderData result; for (const auto& source : sources) { if (source->baseImpl->enabled) { result.sources.insert(source.get()); } } const bool isLeft = std::abs(angle) > M_PI_2; const bool isBottom = angle < 0; for (const auto& layer : layers) { if (!layer->baseImpl->needsRendering(zoomHistory.lastZoom)) { continue; } if (const BackgroundLayer* background = layer->as<BackgroundLayer>()) { if (debugOptions & MapDebugOptions::Overdraw) { // We want to skip glClear optimization in overdraw mode. result.order.emplace_back(*layer); continue; } const BackgroundPaintProperties::Evaluated& paint = background->impl->paint.evaluated; if (layer.get() == layers[0].get() && paint.get<BackgroundPattern>().from.empty()) { // This is a solid background. We can use glClear(). result.backgroundColor = paint.get<BackgroundColor>() * paint.get<BackgroundOpacity>(); } else { // This is a textured background, or not the bottommost layer. We need to render it with a quad. result.order.emplace_back(*layer); } continue; } if (layer->is<CustomLayer>()) { result.order.emplace_back(*layer); continue; } Source* source = getSource(layer->baseImpl->source); if (!source) { Log::Warning(Event::Render, "can't find source for layer '%s'", layer->baseImpl->id.c_str()); continue; } auto& renderTiles = source->baseImpl->getRenderTiles(); const bool symbolLayer = layer->is<SymbolLayer>(); // Sort symbol tiles in opposite y position, so tiles with overlapping // symbols are drawn on top of each other, with lower symbols being // drawn on top of higher symbols. std::vector<std::reference_wrapper<RenderTile>> sortedTiles; std::transform(renderTiles.begin(), renderTiles.end(), std::back_inserter(sortedTiles), [](auto& pair) { return std::ref(pair.second); }); if (symbolLayer) { std::sort(sortedTiles.begin(), sortedTiles.end(), [isLeft, isBottom](const RenderTile& a, const RenderTile& b) { bool sortX = a.id.canonical.x > b.id.canonical.x; bool sortW = a.id.wrap > b.id.wrap; bool sortY = a.id.canonical.y > b.id.canonical.y; return a.id.canonical.y != b.id.canonical.y ? (isLeft ? sortY : !sortY) : a.id.wrap != b.id.wrap ? (isBottom ? sortW : !sortW) : (isBottom ? sortX : !sortX); }); } for (auto& tileRef : sortedTiles) { auto& tile = tileRef.get(); if (!tile.tile.isRenderable()) { continue; } // We're not clipping symbol layers, so when we have both parents and children of symbol // layers, we drop all children in favor of their parent to avoid duplicate labels. // See https://github.com/mapbox/mapbox-gl-native/issues/2482 if (symbolLayer) { bool skip = false; // Look back through the buckets we decided to render to find out whether there is // already a bucket from this layer that is a parent of this tile. Tiles are ordered // by zoom level when we obtain them from getTiles(). for (auto it = result.order.rbegin(); it != result.order.rend() && (&it->layer == layer.get()); ++it) { if (tile.tile.id.isChildOf(it->tile->tile.id)) { skip = true; break; } } if (skip) { continue; } } auto bucket = tile.tile.getBucket(*layer); if (bucket) { result.order.emplace_back(*layer, &tile, bucket); tile.used = true; } } } return result; } std::vector<Feature> Style::queryRenderedFeatures(const QueryParameters& parameters) const { std::unordered_set<std::string> sourceFilter; if (parameters.layerIDs) { for (const auto& layerID : *parameters.layerIDs) { auto layer = getLayer(layerID); if (layer) sourceFilter.emplace(layer->baseImpl->source); } } std::vector<Feature> result; std::unordered_map<std::string, std::vector<Feature>> resultsByLayer; for (const auto& source : sources) { if (!sourceFilter.empty() && sourceFilter.find(source->getID()) == sourceFilter.end()) { continue; } auto sourceResults = source->baseImpl->queryRenderedFeatures(parameters); std::move(sourceResults.begin(), sourceResults.end(), std::inserter(resultsByLayer, resultsByLayer.begin())); } if (resultsByLayer.empty()) { return result; } // Combine all results based on the style layer order. for (const auto& layer : layers) { if (!layer->baseImpl->needsRendering(zoomHistory.lastZoom)) { continue; } auto it = resultsByLayer.find(layer->baseImpl->id); if (it != resultsByLayer.end()) { std::move(it->second.begin(), it->second.end(), std::back_inserter(result)); } } return result; } float Style::getQueryRadius() const { float additionalRadius = 0; for (auto& layer : layers) { if (!layer->baseImpl->needsRendering(zoomHistory.lastZoom)) { continue; } additionalRadius = util::max(additionalRadius, layer->baseImpl->getQueryRadius()); } return additionalRadius; } void Style::setSourceTileCacheSize(size_t size) { for (const auto& source : sources) { source->baseImpl->setCacheSize(size); } } void Style::onLowMemory() { for (const auto& source : sources) { source->baseImpl->onLowMemory(); } } void Style::setObserver(style::Observer* observer_) { observer = observer_; } void Style::onGlyphsLoaded(const FontStack& fontStack, const GlyphRange& glyphRange) { observer->onGlyphsLoaded(fontStack, glyphRange); updateSymbolDependentTiles(); } void Style::onGlyphsError(const FontStack& fontStack, const GlyphRange& glyphRange, std::exception_ptr error) { lastError = error; Log::Error(Event::Style, "Failed to load glyph range %d-%d for font stack %s: %s", glyphRange.first, glyphRange.second, fontStackToString(fontStack).c_str(), util::toString(error).c_str()); observer->onGlyphsError(fontStack, glyphRange, error); observer->onResourceError(error); } void Style::onSourceLoaded(Source& source) { observer->onSourceLoaded(source); observer->onUpdate(Update::Repaint); } void Style::onSourceAttributionChanged(Source& source, const std::string& attribution) { observer->onSourceAttributionChanged(source, attribution); } void Style::onSourceError(Source& source, std::exception_ptr error) { lastError = error; Log::Error(Event::Style, "Failed to load source %s: %s", source.getID().c_str(), util::toString(error).c_str()); observer->onSourceError(source, error); observer->onResourceError(error); } void Style::onSourceDescriptionChanged(Source& source) { observer->onSourceDescriptionChanged(source); if (!source.baseImpl->loaded) { source.baseImpl->loadDescription(fileSource); } } void Style::onTileChanged(Source& source, const OverscaledTileID& tileID) { observer->onTileChanged(source, tileID); observer->onUpdate(Update::Repaint); } void Style::onTileError(Source& source, const OverscaledTileID& tileID, std::exception_ptr error) { lastError = error; Log::Error(Event::Style, "Failed to load tile %s for source %s: %s", util::toString(tileID).c_str(), source.getID().c_str(), util::toString(error).c_str()); observer->onTileError(source, tileID, error); observer->onResourceError(error); } void Style::onSpriteLoaded() { observer->onSpriteLoaded(); observer->onUpdate(Update::Repaint); // For *-pattern properties. updateSymbolDependentTiles(); } void Style::onSpriteError(std::exception_ptr error) { lastError = error; Log::Error(Event::Style, "Failed to load sprite: %s", util::toString(error).c_str()); observer->onSpriteError(error); observer->onResourceError(error); } struct QueueSourceReloadVisitor { UpdateBatch& updateBatch; // No need to reload sources for these types; their visibility can change but // they don't participate in layout. void operator()(CustomLayer&) {} void operator()(RasterLayer&) {} void operator()(BackgroundLayer&) {} template <class VectorLayer> void operator()(VectorLayer& layer) { updateBatch.sourceIDs.insert(layer.getSourceID()); } }; void Style::onLayerFilterChanged(Layer& layer) { layer.accept(QueueSourceReloadVisitor { updateBatch }); observer->onUpdate(Update::Layout); } void Style::onLayerVisibilityChanged(Layer& layer) { layer.accept(QueueSourceReloadVisitor { updateBatch }); observer->onUpdate(Update::RecalculateStyle | Update::Layout); } void Style::onLayerPaintPropertyChanged(Layer&) { observer->onUpdate(Update::RecalculateStyle | Update::Classes); } void Style::onLayerLayoutPropertyChanged(Layer& layer, const char * property) { layer.accept(QueueSourceReloadVisitor { updateBatch }); auto update = Update::Layout; //Recalculate the style for certain properties bool needsRecalculation = strcmp(property, "icon-size") == 0 || strcmp(property, "text-size") == 0; if (needsRecalculation) { update |= Update::RecalculateStyle; } observer->onUpdate(update); } void Style::dumpDebugLogs() const { for (const auto& source : sources) { source->baseImpl->dumpDebugLogs(); } spriteAtlas->dumpDebugLogs(); } } // namespace style } // namespace mbgl
21,704
6,568
// https://practice.geeksforgeeks.org/problems/find-duplicates-in-an-array/1# #include <bits/stdc++.h> using namespace std; class Solution{ public: vector<int> duplicates(int arr[], int n) { int count=0; //raverse the given array from i= 0 to n-1 elements // Go to index arr[i]%n and increment its value by n. for(int i=0;i<n;i++){ int index=arr[i]%n; arr[index]+=n; } vector<int>ans; // Now traverse the array again and print all those // indexes i for which arr[i]/n is greater than 1 for(int i=0;i<n;i++){ if(arr[i]/n>=2){ ans.push_back(i); count++; } } if(count==0)ans.push_back(-1); return ans; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t-- > 0) { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; Solution obj; vector<int> ans = obj.duplicates(a, n); for (int i : ans) cout << i << ' '; cout << endl; } return 0; } // } Driver Code Ends
1,163
408
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { ListNode * dummy = new ListNode(0); ListNode * cur = dummy; priority_queue<pair<int, ListNode *>> pq; for(auto head : lists) { if (head != nullptr) { pq.push({-head->val, head}); } } while (!pq.empty()) { ListNode * node = pq.top().second; pq.pop(); cur->next = node; cur = cur->next; if (node->next != nullptr) { pq.push({-node->next->val, node->next}); } } cur->next = nullptr; return dummy->next; } };
847
267
/******************************************************************************* * * MIT License * * Copyright (c) 2019 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #pragma once #include <iostream> #include "Reference.hpp" namespace Tensile { namespace Client { template <typename T> struct NullComparison { inline void operator()(T referenceValue, T resultValue, size_t elemIndex, size_t elemNumber) { } template <typename... Args> inline void before(T value, size_t elemIndex, size_t elemCount) { } inline void inside(T value, size_t elemIndex, size_t elemCount) { } template <typename... Args> inline void after(T value, size_t elemIndex, size_t elemCount) { } void report() const {} bool error() const { return false; } }; template <typename T> class PointwiseComparison { public: PointwiseComparison(bool printValids, size_t printMax, bool printReport) : m_printValids(printValids), m_printMax(printMax), m_doPrint(printMax > 0), m_printReport(printReport) { } inline void operator()(T referenceValue, T resultValue, size_t elemIndex, size_t elemNumber) { m_values++; bool match = AlmostEqual(referenceValue, resultValue); if(!match) m_errors++; if(!match || m_printValids) { if(m_doPrint) { if(m_printed == 0) { std::cout << "Index: Device | Reference" << std::endl; } std::cout << "[" << (m_printed) << "] " << " elem=" << elemNumber << " idx=" << elemIndex << ": " << resultValue << (match ? "==" : "!=") << referenceValue << std::endl; m_printed++; if(m_printMax >= 0 && m_printed >= m_printMax) m_doPrint = false; } } } void report() const { if(0 && m_printReport) std::cout << "Found " << m_errors << " incorrect values in " << m_values << " total values compared." << std::endl; } bool error() const { return m_errors != 0; } private: size_t m_errors = 0; size_t m_values = 0; bool m_printValids = 0; size_t m_printMax = 0; size_t m_printed = 0; bool m_doPrint = false; bool m_printReport = false; }; template <typename T> struct Magnitude { inline static T abs(T val) { return std::abs(val); } }; template <typename T> struct Magnitude<std::complex<T>> { inline static T abs(std::complex<T> val) { return std::abs(val); } }; template <> struct Magnitude<Half> { inline static Half abs(Half val) { return static_cast<Half>(std::abs(static_cast<float>(val))); } }; template <typename T> class RMSComparison { public: RMSComparison(double threshold, bool printReport) : m_threshold(threshold), m_printReport(printReport) { } inline void operator()(T referenceValue, T resultValue, size_t elemIndex, size_t elemNumber) { m_values++; using m = Magnitude<T>; m_maxReference = std::max(m_maxReference, static_cast<double>(m::abs(referenceValue))); m_maxResult = std::max(m_maxResult, static_cast<double>(m::abs(resultValue))); auto diff = m::abs(referenceValue - resultValue); m_squareDifference += static_cast<double>(diff * diff); } inline void report() const { if(m_printReport) { std::cout << "Max reference value: " << m_maxReference << ", max result value: " << m_maxResult << " (" << m_values << " values)" << std::endl; std::cout << "RMS Error: " << errorValue() << " (threshold: " << m_threshold << ")" << std::endl; } } bool error() const { auto value = errorValue(); return value > m_threshold; } double errorValue() const { double maxMagnitude = std::max({m_maxReference, m_maxResult, std::numeric_limits<double>::min()}); double denom = std::sqrt(static_cast<double>(m_values)) * maxMagnitude; return std::sqrt(m_squareDifference) / denom; } private: size_t m_values = 0; bool m_printReport = false; double m_maxReference = 0; double m_maxResult = 0; double m_squareDifference = 0; double m_threshold = 1e-7; }; template <typename T> class InvalidComparison { public: InvalidComparison(size_t printMax, bool printReport) : m_printMax(printMax), m_printReport(printReport), m_doPrintBefore(printMax > 0), m_doPrintInside(printMax > 0), m_doPrintAfter(printMax > 0) { } inline void before(T value, size_t elemIndex, size_t elemCount) { m_checkedBefore++; if(!DataInitialization::isBadOutput(value)) { m_errorsBefore++; if(m_doPrintBefore) { if(m_printedBefore == 0) { std::cout << "Value written before output buffer:" << std::endl; m_printedBefore++; } std::cout << "Index " << elemIndex << " / " << elemCount << ": found " << value << " instead of " << DataInitialization::getValue<T, InitMode::BadOutput>() << std::endl; if(m_printedBefore >= m_printMax) m_doPrintBefore = false; } } } inline void inside(T value, size_t elemIndex, size_t elemCount) { m_checkedInside++; if(!DataInitialization::isBadOutput(value)) { m_errorsInside++; if(m_doPrintInside) { if(m_printedInside == 0) { std::cout << "Value written inside output buffer, ouside tensor:" << std::endl; m_printedInside++; } std::cout << "Index " << elemIndex << " / " << elemCount << ": found " << value << " instead of " << DataInitialization::getValue<T, InitMode::BadOutput>() << std::endl; if(m_printedInside >= m_printMax) m_doPrintInside = false; } } } inline void after(T value, size_t elemIndex, size_t elemCount) { m_checkedAfter++; if(!DataInitialization::isBadOutput(value)) { m_errorsAfter++; if(m_doPrintAfter) { if(m_printedAfter == 0) { std::cout << "Value written after output buffer:" << std::endl; m_printedAfter++; } std::cout << "Index " << elemIndex << " / " << elemCount << ": found " << value << " instead of " << DataInitialization::getValue<T, InitMode::BadOutput>() << std::endl; if(m_printedAfter >= m_printMax) m_doPrintAfter = false; } } } void report() const { if(m_printReport && (m_checkedBefore > 0 || m_checkedInside > 0 || m_checkedAfter > 0)) { std::cout << "BOUNDS CHECK:" << std::endl; std::cout << "Before buffer: found " << m_errorsBefore << " errors in " << m_checkedBefore << " values checked." << std::endl; std::cout << "Inside buffer: found " << m_errorsInside << " errors in " << m_checkedInside << " values checked." << std::endl; std::cout << "After buffer: found " << m_errorsAfter << " errors in " << m_checkedAfter << " values checked." << std::endl; } } bool error() const { return m_errorsBefore != 0 || m_errorsInside != 0 || m_errorsAfter != 0; } private: size_t m_printMax = 0; bool m_printReport = false; size_t m_checkedBefore = 0; size_t m_checkedInside = 0; size_t m_checkedAfter = 0; size_t m_errorsBefore = 0; size_t m_errorsInside = 0; size_t m_errorsAfter = 0; size_t m_printedBefore = 0; size_t m_printedInside = 0; size_t m_printedAfter = 0; bool m_doPrintBefore = false; bool m_doPrintInside = false; bool m_doPrintAfter = false; }; } }
11,954
3,066
#include "gtest/gtest.h" #include <Core/Array/Array.hpp> #include <Core/Array/ArrayView.hpp> using namespace CubbyFlow; TEST(ArrayView2, Constructors) { double data[20]; for (int i = 0; i < 20; ++i) { data[i] = static_cast<double>(i); } ArrayView2<double> acc(data, Vector2UZ(5, 4)); EXPECT_EQ(5u, acc.Size().x); EXPECT_EQ(4u, acc.Size().y); EXPECT_EQ(data, acc.data()); } TEST(ArrayView2, Iterators) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); auto acc = arr1.View(); float cnt = 1.f; for (float& elem : acc) { EXPECT_FLOAT_EQ(cnt, elem); cnt += 1.f; } cnt = 1.f; for (const float& elem : acc) { EXPECT_FLOAT_EQ(cnt, elem); cnt += 1.f; } } TEST(ArrayView2, ForEachIndex) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); ForEachIndex(arr1.Size(), [&](size_t i, size_t j) { size_t idx = i + (4 * j) + 1; EXPECT_FLOAT_EQ(static_cast<float>(idx), arr1(i, j)); }); } TEST(ArrayView2, ParallelForEachIndex) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); ParallelForEachIndex(arr1.Size(), [&](size_t i, size_t j) { size_t idx = i + (4 * j) + 1; EXPECT_FLOAT_EQ(static_cast<float>(idx), arr1(i, j)); }); } TEST(ConstArrayView2, Constructors) { double data[20]; for (int i = 0; i < 20; ++i) { data[i] = static_cast<double>(i); } // Construct with ArrayView2 ArrayView2<double> acc(data, Vector2UZ(5, 4)); ConstArrayView2<double> cacc(acc); EXPECT_EQ(5u, cacc.Size().x); EXPECT_EQ(4u, cacc.Size().y); EXPECT_EQ(data, cacc.data()); } TEST(ConstArrayView2, Iterators) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); auto acc = arr1.View(); float cnt = 1.f; for (const float& elem : acc) { EXPECT_FLOAT_EQ(cnt, elem); cnt += 1.f; } } TEST(ConstArrayView2, ForEach) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); auto acc = arr1.View(); size_t i = 0; std::for_each(acc.begin(), acc.end(), [&](float val) { EXPECT_FLOAT_EQ(acc[i], val); ++i; }); } TEST(ConstArrayView2, ForEachIndex) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); auto acc = arr1.View(); ForEachIndex(acc.Size(), [&](size_t i, size_t j) { size_t idx = i + (4 * j) + 1; EXPECT_FLOAT_EQ(static_cast<float>(idx), acc(i, j)); }); } TEST(ConstArrayView2, ParallelForEachIndex) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); auto acc = arr1.View(); ParallelForEachIndex(acc.Size(), [&](size_t i, size_t j) { size_t idx = i + (4 * j) + 1; EXPECT_FLOAT_EQ(static_cast<float>(idx), acc(i, j)); }); }
3,450
1,612
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX SQL_ENG #include "sql/engine/expr/ob_expr_not_in.h" #include "sql/engine/expr/ob_expr_in.h" #include "sql/session/ob_sql_session_info.h" namespace oceanbase { using namespace common; namespace sql { // ObExprNotIn::ObExprNotIn(ObIAllocator &alloc) // :ObVectorExprOperator(alloc, T_OP_NOT_IN, N_NOT_IN, 2, 1) {}; // // int ObExprNotIn::calc_result_typeN(ObExprResType &type, // ObExprResType *types, // int64_t param_num, // common::ObExprTypeCtx &type_ctx) const //{ // int ret = ObVectorExprOperator::calc_result_typeN(type, types, param_num, type_ctx); // type.set_scale(DEFAULT_SCALE_FOR_INTEGER); // type.set_precision(DEFAULT_PRECISION_FOR_BOOL); // return ret; //} // // int ObExprNotIn::calc_resultN(common::ObObj &result, const common::ObObj *objs, // int64_t param_num, ObExprCtx &expr_ctx) const //{ // int ret = OB_SUCCESS; // int64_t bv = 0; // EXPR_DEFINE_CAST_CTX(expr_ctx, CM_NONE); // const ObIArray<ObExprCalcType> &cmp_types = result_type_.get_row_calc_cmp_types(); // if (OB_FAIL(ObExprIn::calc(result, // objs, // cmp_types, // param_num, // real_param_num_, // row_dimension_, // cast_ctx))) { // LOG_WARN("not in op failed", K(ret)); // } else if (OB_UNLIKELY(result.is_null())) { // //do nothing // } else if (OB_FAIL(result.get_int(bv))) { // LOG_WARN("get int failed", K(ret), K(result)); // } else { // result.set_int(!bv); // } // return ret; //} } } // namespace oceanbase
2,292
833
// Copyright 2021 Dhiraj Wishal // SPDX-License-Identifier: Apache-2.0 #include "ImGuiAdapter.hpp" #include "GraphicsCore/ScreenBoundRenderTarget.hpp" #include "GraphicsCore/ResourcePackager.hpp" #include "Graphics/Tools/ShaderCompiler.hpp" #include <optick.h> constexpr Flint::uint64 ElementCount = 2500; namespace Flint { ImGuiAdapter::ImGuiAdapter() : pDynamicStateContainer(std::make_shared<DynamicStateContainer>()) { } void ImGuiAdapter::Initialize(const std::shared_ptr<Device>& pDevice, const std::shared_ptr<ScreenBoundRenderTarget>& pRenderTarget) { OPTICK_EVENT(); this->pDevice = pDevice; this->pRenderTarget = pRenderTarget; if (!std::filesystem::exists(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc"))) { ShaderCompiler shaderCompiler(std::filesystem::path(NormalizePath("Shaders\\ImGui\\UI.vert")), ShaderCodeType::GLSL, ShaderType::Vertex); pVertexShader = shaderCompiler.CreateShader(pDevice); pVertexShader->CreateCache(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc")); } else pVertexShader = pDevice->CreateShader(ShaderType::Vertex, std::filesystem::path(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc"))); if (!std::filesystem::exists(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc"))) { ShaderCompiler shaderCompiler(std::filesystem::path(NormalizePath("Shaders\\ImGui\\UI.frag")), ShaderCodeType::GLSL, ShaderType::Fragment); pFragmentShader = shaderCompiler.CreateShader(pDevice); pFragmentShader->CreateCache(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc")); } else pFragmentShader = pDevice->CreateShader(ShaderType::Fragment, std::filesystem::path(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc"))); SetupImGui(); SetupGeometryStore(); SetupPipeline(pRenderTarget); SetupImage(); pVertexShader->Terminate(); pFragmentShader->Terminate(); } void ImGuiAdapter::Initialize(const std::shared_ptr<Device>& pDevice, const std::shared_ptr<OffScreenRenderTarget>& pRenderTarget) { OPTICK_EVENT(); this->pDevice = pDevice; this->pRenderTarget = pRenderTarget; if (!std::filesystem::exists(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc"))) { ShaderCompiler shaderCompiler(std::filesystem::path(NormalizePath("Shaders\\ImGui\\UI.vert")), ShaderCodeType::GLSL, ShaderType::Vertex); pVertexShader = shaderCompiler.CreateShader(pDevice); pVertexShader->CreateCache(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc")); } else pVertexShader = pDevice->CreateShader(ShaderType::Vertex, std::filesystem::path(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc"))); if (!std::filesystem::exists(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc"))) { ShaderCompiler shaderCompiler(std::filesystem::path(NormalizePath("Shaders\\ImGui\\UI.frag")), ShaderCodeType::GLSL, ShaderType::Fragment); pFragmentShader = shaderCompiler.CreateShader(pDevice); pFragmentShader->CreateCache(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc")); } else pFragmentShader = pDevice->CreateShader(ShaderType::Fragment, std::filesystem::path(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc"))); SetupImGui(); SetupGeometryStore(); SetupPipeline(pRenderTarget); SetupImage(); pVertexShader->Terminate(); pFragmentShader->Terminate(); } void ImGuiAdapter::Render(const std::shared_ptr<CommandBuffer>& pCommandBuffer, const uint32 index) { OPTICK_EVENT(); ImGui::Render(); UpdateGeometryStore(); ImGuiIO& io = ImGui::GetIO(); ImDrawData* pDrawData = ImGui::GetDrawData(); if (!pDrawData) return; // Update and Render additional Platform Windows if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); } pushConstants.mScale = glm::vec2(2.0f / io.DisplaySize.x, 2.0f / io.DisplaySize.y); pushConstants.mTranslate = glm::vec2(-1.0f); pDynamicStateContainer->SetViewPort(FExtent2D<float>(io.DisplaySize.x, io.DisplaySize.y), FExtent2D<float>(0.0f, 1.0f), FExtent2D<float>()); pDynamicStateContainer->SetConstantData(ShaderType::Vertex, &pushConstants, sizeof(PushConstants)); if (pDrawData->CmdListsCount) { pCommandBuffer->BindGeometryStore(pGeometryStore.get()); pCommandBuffer->BindGraphicsPipeline(pPipeline.get()); uint64 vertexOffset = 0, indexOffset = 0; for (int32 i = 0; i < pDrawData->CmdListsCount; i++) { const auto pCommandList = pDrawData->CmdLists[i]; for (int32 j = 0; j < pCommandList->CmdBuffer.Size; j++) { const auto& pCommand = pCommandList->CmdBuffer[j]; pDynamicStateContainer->SetScissor( FBox2D(static_cast<uint32>(pCommand.ClipRect.z - pCommand.ClipRect.x), static_cast<uint32>(pCommand.ClipRect.w - pCommand.ClipRect.y)), FBox2D(std::max(static_cast<int32>(pCommand.ClipRect.x), 0), std::max(static_cast<int32>(pCommand.ClipRect.y), 0))); // Handle the texture. if (pCommand.TextureId != nullptr) { const ImGuiTextureContainer* pContainer = static_cast<ImGuiTextureContainer*>(pCommand.TextureId); pCommandBuffer->BindResourcePackage(pPipeline.get(), pContainer->pResourcePackage.get()); } else pCommandBuffer->BindResourcePackage(pPipeline.get(), pResourcePacks[index].get()); pCommandBuffer->BindDynamicStates(pPipeline.get(), pDynamicStateContainer.get()); pCommandBuffer->IssueDrawCall(WireFrame("", vertexOffset, 0, indexOffset, pCommand.ElemCount)); indexOffset += pCommand.ElemCount; } vertexOffset += pCommandList->VtxBuffer.Size; } } } void ImGuiAdapter::SetupPipeline(const std::shared_ptr<ScreenBoundRenderTarget>& pRenderTarget) { OPTICK_EVENT(); GraphicsPipelineSpecification specification = {}; specification.mRasterizationSamples = MultiSampleCount::One; specification.mDynamicStateFlags = DynamicStateFlags::ViewPort | DynamicStateFlags::Scissor; specification.mCullMode = CullMode::None; specification.mColorBlendAttachments[0].mEnableBlend = true; specification.mColorBlendAttachments[0].mSrcBlendFactor = ColorBlendFactor::SourceAlpha; specification.mColorBlendAttachments[0].mDstBlendFactor = ColorBlendFactor::OneMinusSourceAlpha; specification.mColorBlendAttachments[0].mSrcAlphaBlendFactor = ColorBlendFactor::OneMinusSourceAlpha; specification.mColorBlendAttachments[0].mDstAlphaBlendFactor = ColorBlendFactor::Zero; specification.mDepthCompareLogic = DepthCompareLogic::LessOrEqual; specification.mColorBlendConstants[0] = 0.0f; specification.mColorBlendConstants[1] = 0.0f; specification.mColorBlendConstants[2] = 0.0f; specification.mColorBlendConstants[3] = 0.0f; specification.bEnableSampleShading = false; specification.mMinSampleShading = 0.0f; specification.mVertexInputAttributeMap[0] = pVertexShader->GetInputAttributes(); pPipeline = pDevice->CreateGraphicsPipeline("ImGUI", pRenderTarget, pVertexShader, nullptr, nullptr, nullptr, pFragmentShader, specification); } void ImGuiAdapter::SetupPipeline(const std::shared_ptr<OffScreenRenderTarget>& pRenderTarget) { OPTICK_EVENT(); GraphicsPipelineSpecification specification = {}; //specification.mRasterizationSamples = pDevice->GetSupportedMultiSampleCount(); specification.mRasterizationSamples = MultiSampleCount::One; specification.mDynamicStateFlags = DynamicStateFlags::ViewPort | DynamicStateFlags::Scissor; specification.mCullMode = CullMode::None; specification.mColorBlendAttachments[0].mEnableBlend = true; specification.mColorBlendAttachments[0].mSrcBlendFactor = ColorBlendFactor::SourceAlpha; specification.mColorBlendAttachments[0].mDstBlendFactor = ColorBlendFactor::OneMinusSourceAlpha; specification.mColorBlendAttachments[0].mSrcAlphaBlendFactor = ColorBlendFactor::OneMinusSourceAlpha; specification.mColorBlendAttachments[0].mDstAlphaBlendFactor = ColorBlendFactor::Zero; specification.mDepthCompareLogic = DepthCompareLogic::LessOrEqual; specification.mColorBlendConstants[0] = 0.0f; specification.mColorBlendConstants[1] = 0.0f; specification.mColorBlendConstants[2] = 0.0f; specification.mColorBlendConstants[3] = 0.0f; specification.bEnableSampleShading = false; specification.mMinSampleShading = 0.0f; specification.mVertexInputAttributeMap[0] = pVertexShader->GetInputAttributes(); pPipeline = pDevice->CreateGraphicsPipeline("ImGUI", pRenderTarget, pVertexShader, nullptr, nullptr, nullptr, pFragmentShader, specification); } void ImGuiAdapter::Terminate() { pPipeline->Terminate(); pGeometryStore->UnmapVertexBuffer(); pGeometryStore->UnmapIndexBuffer(); pGeometryStore->Terminate(); pFontImage->Terminate(); pFontSampler->Terminate(); } void ImGuiAdapter::SetupImGui() { OPTICK_EVENT(); ImGui::CreateContext(); ImGuiStyle& style = ImGui::GetStyle(); style.Colors[ImGuiCol_TitleBg] = ImVec4(CreateColor256(34), CreateColor256(40), CreateColor256(49), 0.75f); style.Colors[ImGuiCol_WindowBg] = ImVec4(CreateColor256(34), CreateColor256(40), CreateColor256(49), 0.25f); style.Colors[ImGuiCol_MenuBarBg] = ImVec4(CreateColor256(34), CreateColor256(40), CreateColor256(49), 0.25f); style.Colors[ImGuiCol_TitleBgActive] = ImVec4(CreateColor256(57), CreateColor256(62), CreateColor256(70), 0.8f); style.Colors[ImGuiCol_Header] = ImVec4(CreateColor256(57), CreateColor256(62), CreateColor256(70), 0.6f); style.Colors[ImGuiCol_TabActive] = ImVec4(CreateColor256(57), CreateColor256(62), CreateColor256(70), 0.25f); style.Colors[ImGuiCol_TabUnfocusedActive] = ImVec4(CreateColor256(57), CreateColor256(62), CreateColor256(70), 0.25f); style.Colors[ImGuiCol_TabHovered] = ImVec4(CreateColor256(0), CreateColor256(173), CreateColor256(181), 1.0f); style.Colors[ImGuiCol_HeaderHovered] = ImVec4(CreateColor256(0), CreateColor256(173), CreateColor256(181), 0.5f); style.ChildRounding = 6.0f; style.FrameRounding = 3.0f; style.PopupRounding = 3.0f; style.TabRounding = 3.0f; style.WindowRounding = 3.0f; ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(static_cast<float>(pRenderTarget->GetExtent().mWidth), static_cast<float>(pRenderTarget->GetExtent().mHeight)); io.DisplayFramebufferScale = ImVec2(16.0f, 9.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/simvoni-font/Simvoni-d9vV6.otf").string().c_str(), 12.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/simvoni-font/Simvoni-d9vV6.otf").string().c_str(), 8.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/simvoni-font/Simvoni-d9vV6.otf").string().c_str(), 10.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/simvoni-font/Simvoni-d9vV6.otf").string().c_str(), 14.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/simvoni-font/Simvoni-d9vV6.otf").string().c_str(), 16.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/azonix-font/Azonix-1VB0.otf").string().c_str(), 10.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/a-atomic-md-font/AtomicMd-OVJ4A.otf").string().c_str(), 10.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/josefin-sans-font/JosefinSansRegular-x3LYV.ttf").string().c_str(), 12.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/salma-alfasans-font/SalmaalfasansLight-d9MJx.otf").string().c_str(), 12.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/swansea-font/Swansea-q3pd.ttf").string().c_str(), 6.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/rawengulk-font/RawengulkBold-r8o9.otf").string().c_str(), 13.0f); //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows } void ImGuiAdapter::SetupGeometryStore() { OPTICK_EVENT(); pGeometryStore = pDevice->CreateGeometryStore(pVertexShader->GetInputAttributes(), sizeof(uint16), BufferMemoryProfile::TransferFriendly); } void ImGuiAdapter::SetupImage() { OPTICK_EVENT(); ImGuiIO& imGuiIO = ImGui::GetIO(); unsigned char* pFontImageData = nullptr; int width = 0, height = 0, bitsPerPixel = 0; imGuiIO.Fonts->GetTexDataAsRGBA32(&pFontImageData, &width, &height, &bitsPerPixel); for (uint64 i = 0; i < pRenderTarget->GetBufferCount(); i++) { pFontImage = pDevice->CreateImage(ImageType::TwoDimension, ImageUsage::Graphics, FBox3D(width, height, 1), PixelFormat::R8G8B8A8_SRGB, 1, 1, pFontImageData); ImageSamplerSpecification specification = {}; specification.mBorderColor = BorderColor::OpaqueWhiteFLOAT; specification.mAddressModeU = AddressMode::ClampToEdge; specification.mAddressModeV = AddressMode::ClampToEdge; specification.mAddressModeW = AddressMode::ClampToEdge; pFontSampler = pDevice->CreateImageSampler(specification); auto pResourcePack = pPipeline->CreateResourcePackage(0); pResourcePack->BindResource(0, pFontImage, pFontImage->CreateImageView(0, pFontImage->GetLayerCount(), 0, pFontImage->GetMipLevels(), ImageUsage::Graphics), pFontSampler); pResourcePacks.push_back(pResourcePack); } } void ImGuiAdapter::UpdateGeometryStore() { OPTICK_EVENT(); ImDrawData* pDrawData = ImGui::GetDrawData(); if (!pDrawData) return; const uint64 vertexSize = GetNewVertexBufferSize(pDrawData->TotalVtxCount * sizeof(ImDrawVert)), indexSize = GetNewIndexBufferSize(pDrawData->TotalIdxCount * sizeof(ImDrawIdx)); if ((vertexSize == 0) || (indexSize == 0)) return; std::shared_ptr<Buffer> pVertexBuffer = nullptr; std::shared_ptr<Buffer> pIndexBuffer = nullptr; bool bShouldWaitIdle = false; if (pGeometryStore->GetVertexCount() < pDrawData->TotalVtxCount || pDrawData->TotalVtxCount < (pGeometryStore->GetVertexCount() - ElementCount)) { pGeometryStore->UnmapVertexBuffer(); pVertexBuffer = pDevice->CreateBuffer(BufferType::Staging, vertexSize); pVertexData = static_cast<ImDrawVert*>(pVertexBuffer->MapMemory(vertexSize)); bShouldWaitIdle = true; } if (pGeometryStore->GetIndexCount() < pDrawData->TotalIdxCount || pDrawData->TotalIdxCount < (pGeometryStore->GetIndexCount() - ElementCount)) { pGeometryStore->UnmapIndexBuffer(); pIndexBuffer = pDevice->CreateBuffer(BufferType::Staging, indexSize); pIndexData = static_cast<ImDrawIdx*>(pIndexBuffer->MapMemory(indexSize)); bShouldWaitIdle = true; } auto pCopyVertexPointer = pVertexData; auto pCopyIndexPointer = pIndexData; for (int32 i = 0; i < pDrawData->CmdListsCount; i++) { const ImDrawList* pCommandList = pDrawData->CmdLists[i]; std::copy_n(pCommandList->VtxBuffer.Data, pCommandList->VtxBuffer.Size, pCopyVertexPointer); std::copy_n(pCommandList->IdxBuffer.Data, pCommandList->IdxBuffer.Size, pCopyIndexPointer); pCopyVertexPointer += pCommandList->VtxBuffer.Size; pCopyIndexPointer += pCommandList->IdxBuffer.Size; } if (pVertexBuffer) pVertexBuffer->UnmapMemory(); if (pIndexBuffer) pIndexBuffer->UnmapMemory(); if (bShouldWaitIdle) pDevice->WaitForQueue(); pGeometryStore->SetData(pVertexBuffer.get(), pIndexBuffer.get()); if (pVertexBuffer) { pVertexBuffer->Terminate(); pVertexData = static_cast<ImDrawVert*>(pGeometryStore->MapVertexBuffer()); } if (pIndexBuffer) { pIndexBuffer->Terminate(); pIndexData = static_cast<ImDrawIdx*>(pGeometryStore->MapIndexBuffer()); } } uint64 ImGuiAdapter::GetNewVertexBufferSize(const uint64 newSize) const { constexpr uint64 VertexFactor = ElementCount * sizeof(ImDrawVert); const auto count = (newSize / VertexFactor) + 1; return count * VertexFactor; } uint64 ImGuiAdapter::GetNewIndexBufferSize(const uint64 newSize) const { constexpr uint64 IndexFactor = ElementCount * sizeof(ImDrawIdx); const auto count = (newSize / IndexFactor) + 1; return count * IndexFactor; } }
15,878
6,161
// Generated by Haxe 4.2.1+bf9ff69 namespace hx { unsigned char __res_49[] = { 0x80, 0x00, 0x00, 0x80, 60,63,120,109,108,32,118,101,114,115, 105,111,110,61,34,49,46,48,34,32, 101,110,99,111,100,105,110,103,61,34, 117,116,102,45,56,34,32,63,62,13, 10,60,100,97,116,97,62,9,13,10, 9,60,115,112,114,105,116,101,32,105, 100,61,34,98,108,97,99,107,34,32, 120,61,34,48,34,32,121,61,34,48, 34,32,119,105,100,116,104,61,34,49, 48,48,37,34,32,104,101,105,103,104, 116,61,34,49,48,48,37,34,32,99, 111,108,111,114,61,34,48,120,56,56, 48,48,48,48,48,48,34,47,62,13, 10,9,13,10,9,60,99,104,114,111, 109,101,32,105,100,61,34,98,97,99, 107,34,32,99,101,110,116,101,114,95, 120,61,34,116,114,117,101,34,32,99, 101,110,116,101,114,95,121,61,34,116, 114,117,101,34,32,119,105,100,116,104, 61,34,52,48,48,34,32,104,101,105, 103,104,116,61,34,49,48,48,34,47, 62,9,9,13,10,9,13,10,9,60, 116,101,120,116,32,105,100,61,34,116, 105,116,108,101,34,32,120,61,34,48, 34,32,121,61,34,53,34,32,119,105, 100,116,104,61,34,98,97,99,107,46, 119,105,100,116,104,34,32,116,101,120, 116,61,34,36,80,79,80,85,80,95, 84,73,84,76,69,95,68,69,70,65, 85,76,84,34,32,97,108,105,103,110, 61,34,99,101,110,116,101,114,34,62, 13,10,9,9,60,97,110,99,104,111, 114,32,120,61,34,98,97,99,107,46, 108,101,102,116,34,32,120,45,102,108, 117,115,104,61,34,108,101,102,116,34, 32,121,61,34,98,97,99,107,46,116, 111,112,34,32,121,45,102,108,117,115, 104,61,34,116,111,112,34,47,62,9, 9,13,10,9,60,47,116,101,120,116, 62,13,10,9,13,10,9,60,116,101, 120,116,32,105,100,61,34,98,111,100, 121,34,32,120,61,34,53,34,32,121, 61,34,53,34,32,119,105,100,116,104, 61,34,98,97,99,107,46,119,105,100, 116,104,45,49,48,34,32,116,101,120, 116,61,34,36,80,79,80,85,80,95, 66,79,68,89,95,68,69,70,65,85, 76,84,34,32,97,108,105,103,110,61, 34,108,101,102,116,34,62,13,10,9, 9,60,97,110,99,104,111,114,32,120, 61,34,98,97,99,107,46,108,101,102, 116,34,32,120,45,102,108,117,115,104, 61,34,108,101,102,116,34,32,121,61, 34,116,105,116,108,101,46,98,111,116, 116,111,109,34,32,121,45,102,108,117, 115,104,61,34,116,111,112,34,47,62, 9,9,13,10,9,60,47,116,101,120, 116,62,13,10,9,13,10,9,60,98, 117,116,116,111,110,32,105,100,61,34, 98,116,110,48,34,32,121,61,34,45, 53,34,32,108,97,98,101,108,61,34, 36,80,79,80,85,80,95,89,69,83, 34,62,13,10,9,9,60,97,110,99, 104,111,114,32,121,61,34,98,97,99, 107,46,98,111,116,116,111,109,34,32, 121,45,102,108,117,115,104,61,34,98, 111,116,116,111,109,34,47,62,13,10, 9,9,60,112,97,114,97,109,32,116, 121,112,101,61,34,105,110,116,34,32, 118,97,108,117,101,61,34,48,34,47, 62,9,9,13,10,9,60,47,98,117, 116,116,111,110,62,13,10,9,13,10, 9,60,98,117,116,116,111,110,32,105, 100,61,34,98,116,110,49,34,32,108, 97,98,101,108,61,34,36,80,79,80, 85,80,95,78,79,34,62,13,10,9, 9,60,97,110,99,104,111,114,32,121, 61,34,98,116,110,48,46,116,111,112, 34,32,121,45,102,108,117,115,104,61, 34,116,111,112,34,47,62,13,10,9, 9,60,112,97,114,97,109,32,116,121, 112,101,61,34,105,110,116,34,32,118, 97,108,117,101,61,34,49,34,47,62, 13,10,9,60,47,98,117,116,116,111, 110,62,13,10,9,9,13,10,9,60, 98,117,116,116,111,110,32,105,100,61, 34,98,116,110,50,34,32,108,97,98, 101,108,61,34,36,80,79,80,85,80, 95,67,65,78,67,69,76,34,62,13, 10,9,9,60,97,110,99,104,111,114, 32,121,61,34,98,116,110,48,46,116, 111,112,34,32,121,45,102,108,117,115, 104,61,34,116,111,112,34,47,62,9, 9,13,10,9,9,60,112,97,114,97, 109,32,116,121,112,101,61,34,105,110, 116,34,32,118,97,108,117,101,61,34, 50,34,47,62,13,10,9,60,47,98, 117,116,116,111,110,62,13,10,9,13, 10,9,60,109,111,100,101,32,105,100, 61,34,49,98,116,110,34,32,105,115, 95,100,101,102,97,117,108,116,61,34, 116,114,117,101,34,62,13,10,9,9, 60,115,104,111,119,32,105,100,61,34, 98,116,110,48,34,47,62,13,10,9, 9,60,104,105,100,101,32,105,100,61, 34,98,116,110,49,44,98,116,110,50, 34,47,62,13,10,9,9,60,99,104, 97,110,103,101,32,105,100,61,34,98, 116,110,48,34,32,108,97,98,101,108, 61,34,36,80,79,80,85,80,95,79, 75,34,32,119,105,100,116,104,61,34, 98,97,99,107,46,119,105,100,116,104, 42,48,46,50,53,34,47,62,13,10, 9,9,60,112,111,115,105,116,105,111, 110,32,105,100,61,34,98,116,110,48, 34,62,13,10,9,9,9,60,97,110, 99,104,111,114,32,120,61,34,98,97, 99,107,46,99,101,110,116,101,114,34, 32,120,45,102,108,117,115,104,61,34, 99,101,110,116,101,114,34,47,62,13, 10,9,9,60,47,112,111,115,105,116, 105,111,110,62,13,10,9,60,47,109, 111,100,101,62,13,10,9,13,10,9, 60,109,111,100,101,32,105,100,61,34, 50,98,116,110,34,62,13,10,9,9, 60,115,104,111,119,32,105,100,61,34, 98,116,110,48,44,98,116,110,49,34, 47,62,13,10,9,9,60,104,105,100, 101,32,105,100,61,34,98,116,110,50, 34,47,62,13,10,9,9,60,97,108, 105,103,110,32,97,120,105,115,61,34, 104,111,114,105,122,111,110,116,97,108, 34,32,115,112,97,99,105,110,103,61, 34,49,48,34,32,114,101,115,105,122, 101,61,34,116,114,117,101,34,62,13, 10,9,9,9,60,98,111,117,110,100, 115,32,108,101,102,116,61,34,98,97, 99,107,46,108,101,102,116,34,32,114, 105,103,104,116,61,34,98,97,99,107, 46,114,105,103,104,116,45,49,48,34, 47,62,9,9,13,10,9,9,9,60, 111,98,106,101,99,116,115,32,118,97, 108,117,101,61,34,98,116,110,48,44, 98,116,110,49,34,47,62,13,10,9, 9,60,47,97,108,105,103,110,62,13, 10,9,9,60,99,104,97,110,103,101, 32,105,100,61,34,98,116,110,48,34, 32,108,97,98,101,108,61,34,36,80, 79,80,85,80,95,79,75,34,47,62, 13,10,9,9,60,99,104,97,110,103, 101,32,105,100,61,34,98,116,110,49, 34,32,108,97,98,101,108,61,34,36, 80,79,80,85,80,95,67,65,78,67, 69,76,34,47,62,13,10,9,60,47, 109,111,100,101,62,13,10,9,9,13, 10,9,60,109,111,100,101,32,105,100, 61,34,51,98,116,110,34,62,13,10, 9,9,60,115,104,111,119,32,105,100, 61,34,98,116,110,48,44,98,116,110, 49,44,98,116,110,50,34,47,62,13, 10,9,9,60,97,108,105,103,110,32, 97,120,105,115,61,34,104,111,114,105, 122,111,110,116,97,108,34,32,115,112, 97,99,105,110,103,61,34,53,34,32, 114,101,115,105,122,101,61,34,116,114, 117,101,34,62,13,10,9,9,9,60, 98,111,117,110,100,115,32,108,101,102, 116,61,34,98,97,99,107,46,108,101, 102,116,43,53,34,32,114,105,103,104, 116,61,34,98,97,99,107,46,114,105, 103,104,116,45,53,34,47,62,9,9, 13,10,9,9,9,60,111,98,106,101, 99,116,115,32,118,97,108,117,101,61, 34,98,116,110,48,44,98,116,110,49, 44,98,116,110,50,34,47,62,13,10, 9,9,60,47,97,108,105,103,110,62, 13,10,9,9,60,99,104,97,110,103, 101,32,105,100,61,34,98,116,110,48, 34,32,108,97,98,101,108,61,34,36, 80,79,80,85,80,95,89,69,83,34, 47,62,13,10,9,9,60,99,104,97, 110,103,101,32,105,100,61,34,98,116, 110,49,34,32,108,97,98,101,108,61, 34,36,80,79,80,85,80,95,78,79, 34,47,62,13,10,9,9,60,99,104, 97,110,103,101,32,105,100,61,34,98, 116,110,50,34,32,108,97,98,101,108, 61,34,36,80,79,80,85,80,95,67, 65,78,67,69,76,34,47,62,13,10, 9,60,47,109,111,100,101,62,13,10, 60,47,100,97,116,97,62,0x00 }; }
6,676
6,632
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<vector> using namespace std; const int maxn=100000; int n,m; vector<int> a; int main() { while(cin>>n>>m) { a.clear(); for(int i=0;i<2*n;i++) a.push_back(i); int pos=0; for(int i=0;i<n;i++) { pos=(pos+m-1)%a.size(); a.erase(a.begin()+pos); } int temp=0; for(int i=0;i<2*n;i++) { if((i%50==0)&&i!=0) puts(""); if(temp<a.size()&&a[temp]==i) { cout<<'G'; temp++; } else cout<<'B'; } puts("");puts(""); } return 0; }
551
315
// BSD 2-Clause License // // Copyright (c) 2021, Antton Jokinen // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <slvn_buffer.h> #include <slvn_debug.h> namespace slvn_tech { SlvnBuffer::SlvnBuffer(VkDevice* device, uint32_t bufferSize, VkBufferUsageFlags usage, VkSharingMode sharingMode) { VkBufferCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.size = bufferSize; info.usage = usage; info.sharingMode = sharingMode; VkResult result = vkCreateBuffer(*device, &info, nullptr, &mBuffer); assert(result == VK_SUCCESS); } SlvnBuffer::SlvnBuffer() { SLVN_PRINT("ENTER"); } SlvnBuffer::~SlvnBuffer() { } SlvnResult SlvnBuffer::Deinitialize(VkDevice* device) { vkDestroyBuffer(*device, mBuffer, nullptr); vkFreeMemory(*device, mMemory, nullptr); return SlvnResult::cOk; } std::optional<VkDeviceSize> SlvnBuffer::getAllocationSize(VkDevice* device) const { VkMemoryRequirements memReqs; vkGetBufferMemoryRequirements(*device, mBuffer, &memReqs); return std::make_optional<VkDeviceSize>(memReqs.size); } std::optional<uint32_t> SlvnBuffer::getMemoryTypeIndex(VkDevice* device, VkPhysicalDevice* physDev, uint32_t wantedFlags) const { VkMemoryRequirements memReqs; vkGetBufferMemoryRequirements(*device, mBuffer, &memReqs); VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(*physDev, &memProperties); std::optional<uint32_t> value = std::nullopt; for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((memReqs.memoryTypeBits & (1 << i)) && ((memProperties.memoryTypes[i].propertyFlags & wantedFlags) == wantedFlags)) { value = i; break; } } return value; } SlvnResult SlvnBuffer::Insert(VkDevice* device, VkPhysicalDevice* physDev, uint32_t size, const void* data) { uint32_t memFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; mBufferByteSize = size; std::optional<VkDeviceSize> bufferSize = getAllocationSize(device); assert(bufferSize); std::optional<uint32_t> bufferMemIndex = getMemoryTypeIndex(device, physDev, memFlags); assert(bufferMemIndex); VkMemoryAllocateInfo allocateInfo = {}; allocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocateInfo.allocationSize = *bufferSize; allocateInfo.memoryTypeIndex = *bufferMemIndex; VkResult result = vkAllocateMemory(*device, &allocateInfo, nullptr, &mMemory); assert(result == VK_SUCCESS); result = vkBindBufferMemory(*device, mBuffer, mMemory, 0); assert(result == VK_SUCCESS); void* bufferMemory; result = vkMapMemory(*device, mMemory, 0, size, 0, &bufferMemory); assert(result == VK_SUCCESS); std::memcpy(bufferMemory, data, size); vkUnmapMemory(*device, mMemory); return SlvnResult::cOk; } }
4,193
1,492
#define HSL_MA86Z_HEADER_NOT_CPP_READY 1
41
24
#ifndef PYTHONIC_OPERATOR_GE__HPP #define PYTHONIC_OPERATOR_GE__HPP #include "pythonic/include/operator_/__ge__.hpp" #include "pythonic/operator_/ge.hpp" namespace pythonic { namespace operator_ { FPROXY_IMPL(pythonic::operator_, __ge__, ge); } } #endif
269
118
#include <cassert> #include <fstream> #include "BGFXWidget.h" struct PosColorVertex { float m_x; float m_y; float m_z; uint32_t m_abgr; static void init() { ms_layout .begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true) .end(); }; static bgfx::VertexLayout ms_layout; }; bgfx::VertexLayout PosColorVertex::ms_layout; static PosColorVertex s_cubeVertices[] = { {-1.0f, 1.0f, 1.0f, 0xff000000 }, { 1.0f, 1.0f, 1.0f, 0xff0000ff }, {-1.0f, -1.0f, 1.0f, 0xff00ff00 }, { 1.0f, -1.0f, 1.0f, 0xff00ffff }, {-1.0f, 1.0f, -1.0f, 0xffff0000 }, { 1.0f, 1.0f, -1.0f, 0xffff00ff }, {-1.0f, -1.0f, -1.0f, 0xffffff00 }, { 1.0f, -1.0f, -1.0f, 0xffffffff }, }; static const uint16_t s_cubeTriList[] = { 0, 1, 2, // 0 1, 3, 2, 4, 6, 5, // 2 5, 6, 7, 0, 2, 4, // 4 4, 2, 6, 1, 5, 3, // 6 5, 7, 3, 0, 4, 1, // 8 4, 5, 1, 2, 3, 6, // 10 6, 3, 7, }; inline const bgfx::Memory* loadMem(const std::string& filename) { std::ifstream in(filename.c_str(), std::ios_base::binary); in.exceptions(std::ifstream::failbit | std::ifstream::badbit); in.seekg(0, std::ifstream::end); const uint32_t file_size(static_cast<uint32_t>(in.tellg())); in.seekg(0, std::ifstream::beg); const bgfx::Memory* mem = bgfx::alloc(file_size + 1); if (mem && file_size > 0) { in.read(reinterpret_cast<char*>(mem->data), file_size); mem->data[mem->size - 1] = '\0'; } return mem; } inline bgfx::ShaderHandle loadShader(const std::string& filename) { std::string shader_path; switch (bgfx::getRendererType()) { default: case bgfx::RendererType::Noop: assert(false); case bgfx::RendererType::Direct3D9: shader_path = "shaders/dx9/"; break; case bgfx::RendererType::Direct3D11: case bgfx::RendererType::Direct3D12: shader_path = "shaders/dx11/"; break; case bgfx::RendererType::Gnm: shader_path = "shaders/pssl/"; break; case bgfx::RendererType::Metal: shader_path = "shaders/metal/"; break; case bgfx::RendererType::Nvn: shader_path = "shaders/nvn/"; break; case bgfx::RendererType::OpenGL: shader_path = "shaders/glsl/"; break; case bgfx::RendererType::OpenGLES: shader_path = "shaders/essl/"; break; case bgfx::RendererType::Vulkan: shader_path = "shaders/spirv/"; break; } std::string file_path = shader_path + filename + ".bin"; bgfx::ShaderHandle handle = bgfx::createShader(loadMem(file_path)); bgfx::setName(handle, filename.c_str()); return handle; } inline bgfx::ProgramHandle loadProgram(const std::string& vs_name, const std::string& fs_name) { bgfx::ShaderHandle vsh = loadShader(vs_name); bgfx::ShaderHandle fsh = BGFX_INVALID_HANDLE; if (!fs_name.empty()) { fsh = loadShader(fs_name); } return bgfx::createProgram(vsh, fsh); } BGFXWidget::BGFXWidget(QWidget *parent) : QOpenGLWidget(parent) { setDefaultCamera(); } void BGFXWidget::initializeBGFX(int width, int height, void* native_window_handle) { initial_width = width; initial_height = height; debug = BGFX_DEBUG_NONE; reset = BGFX_RESET_NONE; bgfx::Init init; init.type = bgfx::RendererType::Direct3D9; // Or OpenGL or Direct3D11 init.vendorId = BGFX_PCI_ID_NONE; init.resolution.width = width; init.resolution.height = height; init.resolution.reset = reset; init.platformData.nwh = native_window_handle; bgfx::init(init); bgfx::setDebug(debug); bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x303030ff, 1.0f, 0); PosColorVertex::init(); // Create static vertex buffer. m_vbh = bgfx::createVertexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices)) , PosColorVertex::ms_layout ); // Create static index buffer for triangle list rendering. m_ibh = bgfx::createIndexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_cubeTriList, sizeof(s_cubeTriList)) ); // Create program from shaders. m_program = loadProgram("vs_cubes", "fs_cubes"); } BGFXWidget::~BGFXWidget() { bgfx::destroy(m_ibh); bgfx::destroy(m_vbh); bgfx::destroy(m_program); bgfx::shutdown(); } void BGFXWidget::setDefaultCamera() { viewer_pos = bx::Vec3(0, 0, 10); viewer_target = bx::Vec3(0, 0, 0); viewer_up = bx::Vec3(0, 1, 0); rotation_radius = bx::length(sub(viewer_pos, viewer_target)); viewer_previous_pos = viewer_pos; viewer_previous_target = viewer_target; viewer_previous_up = viewer_up; minimum_rotation_radius = 0.1; maximum_rotation_radius = 1000.0; } void BGFXWidget::paintEvent(QPaintEvent* event) { float view_matrix[16]; bx::mtxLookAt( view_matrix, viewer_pos, viewer_target, viewer_up ); float projection_matrix[16]; bx::mtxProj( projection_matrix, 50.0f, static_cast<float>(width()) / static_cast<float>(height()), 1.0f, 1024.0f, bgfx::getCaps()->homogeneousDepth ); bgfx::setViewTransform(0, view_matrix, projection_matrix); bgfx::setViewRect(0, 0, 0, width(), height()); bgfx::touch(0); // Set vertex and index buffer. bgfx::setVertexBuffer(0, m_vbh); bgfx::setIndexBuffer(m_ibh); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0, m_program); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } void BGFXWidget::resizeEvent(QResizeEvent* event) { // TODO: } void BGFXWidget::mouseMoveEvent(QMouseEvent *event) { if (left_mouse_pressed && right_mouse_pressed) { // Pan mode QPointF current_point = event->localPos(); const double effective_rotation_radius = std::max(rotation_radius, 10.0); double delta_x = (current_point.x() - previous_point.x()) / width() * effective_rotation_radius; double delta_y = (current_point.y() - previous_point.y()) / height() * effective_rotation_radius; auto user_position = sub(viewer_previous_pos, viewer_previous_target); auto right = normalize(cross(viewer_up, user_position)); auto offset = add(mul(right, delta_x), mul(viewer_up, delta_y)); viewer_pos = add(viewer_previous_pos, offset); viewer_target = add(viewer_previous_target, offset); // Restore rotation orbit radius viewer_target = add(viewer_pos, mul(normalize(sub(viewer_target, viewer_pos)), rotation_radius)); update(); } else if (left_mouse_pressed) { // Rotation mode QPointF current_point = event->localPos(); double delta_x = previous_point.x() - current_point.x(); double delta_y = previous_point.y() - current_point.y(); double x_rotation_angle = delta_x / width() * bx::kPi; double y_rotation_angle = delta_y / height() * bx::kPi; auto user_position = sub(viewer_previous_pos, viewer_previous_target); auto rotation_x = bx::rotateAxis(viewer_previous_up, x_rotation_angle); bx::Vec3 temp_user_position = mul(user_position, rotation_x); auto left = normalize(cross(temp_user_position, viewer_previous_up)); auto rotation_y = bx::rotateAxis(left, y_rotation_angle); bx::Quaternion result_rotation = mul(rotation_x, rotation_y); auto rotated_user_position = mul(normalize(mul(user_position, result_rotation)), rotation_radius); viewer_pos = add(viewer_previous_target, rotated_user_position); viewer_up = normalize(mul(viewer_previous_up, result_rotation)); // Restore up vector property: up vector must be orthogonal to direction vector auto new_left = cross(rotated_user_position, viewer_up); viewer_up = normalize(cross(new_left, rotated_user_position)); update(); } else if (right_mouse_pressed) { // First person look mode QPointF current_point = event->localPos(); double delta_x = current_point.x() - previous_point.x(); double delta_y = current_point.y() - previous_point.y(); double x_rotation_angle = delta_x / width() * bx::kPi; double y_rotation_angle = delta_y / height() * bx::kPi; auto view_direction = sub(viewer_previous_target, viewer_previous_pos); auto rotation_x = bx::rotateAxis(viewer_previous_up, x_rotation_angle); bx::Vec3 temp_view_direction = mul(view_direction, rotation_x); auto left = normalize(cross(viewer_previous_up, temp_view_direction)); auto rotation_y = bx::rotateAxis(left, y_rotation_angle); bx::Quaternion result_rotation = mul(rotation_y, rotation_x); auto rotated_view_direction = mul(normalize(mul(view_direction, result_rotation)), rotation_radius); viewer_target = add(viewer_previous_pos, rotated_view_direction); viewer_up = normalize(mul(viewer_previous_up, result_rotation)); // Restore up vector property: up vector must be orthogonal to direction vector auto new_left = cross(viewer_up, rotated_view_direction); viewer_up = normalize(cross(rotated_view_direction, new_left)); update(); } } void BGFXWidget::mousePressEvent(QMouseEvent *event) { bool left_or_right = false; if (event->buttons() & Qt::LeftButton) { left_mouse_pressed = true; left_or_right = true; } if (event->buttons() & Qt::RightButton) { right_mouse_pressed = true; left_or_right = true; } if (left_or_right) { previous_point = event->localPos(); viewer_previous_pos = viewer_pos; viewer_previous_target = viewer_target; viewer_previous_up = viewer_up; } } void BGFXWidget::mouseReleaseEvent(QMouseEvent *event) { bool left_or_right = false; if (!(event->buttons() & Qt::LeftButton)) { left_mouse_pressed = false; left_or_right = true; } if (!(event->buttons() & Qt::RightButton)) { right_mouse_pressed = false; left_or_right = true; } if (left_or_right) { previous_point = event->localPos(); viewer_previous_pos = viewer_pos; viewer_previous_target = viewer_target; viewer_previous_up = viewer_up; } } void BGFXWidget::wheelEvent(QWheelEvent *event) { QPoint delta = event->angleDelta(); rotation_radius += delta.y() / 1000.0f * rotation_radius; if (rotation_radius < minimum_rotation_radius) { rotation_radius = minimum_rotation_radius; } if (rotation_radius > maximum_rotation_radius) { rotation_radius = maximum_rotation_radius; } auto user_position = sub(viewer_pos, viewer_target); auto new_user_position = mul(normalize(user_position), rotation_radius); viewer_pos = add(viewer_target, new_user_position); update(); }
11,226
4,067
#include "AlphaVantageConnection.h" // Forward declare the singleton instance AlphaVantageConnection* AlphaVantageConnection::m_instance = nullptr; // Default link for AlphaVantage HTTP requests const std::string AlphaVantageConnection::DEFAULT_URL = "https://www.alphavantage.co/query?"; AlphaVantageConnection* AlphaVantageConnection::getInstance() { if (!m_instance) { m_instance = new AlphaVantageConnection(); } return m_instance; } void AlphaVantageConnection::setApiKey(const std::string& api_key) { if (api_key == "FATAL_ERR_NO_KEY") { throw RuntimeException("No valid AlphaVantage API key was located in settings.json"); } m_api_key = api_key; } std::string AlphaVantageConnection::getApiKey() const { return m_api_key; } std::string AlphaVantageConnection::TimeSeriesHelper(const std::string& series, const std::string& ticker, bool all_data) const { std::string size = all_data ? "full" : "compact"; std::string url = AlphaVantageConnection::DEFAULT_URL + "function=" + series + "&" + "symbol=" + ticker + "&" + "outputsize=" + size + "&" + "apikey=" + m_api_key + "&"; return url; } std::string AlphaVantageConnection::GetQueryString_TIMESERIESDAILY(const std::string& ticker, bool all_data) const { return TimeSeriesHelper("TIME_SERIES_DAILY", ticker, all_data); } std::string AlphaVantageConnection::GetQueryString_TIMESERIESWEEKLY(const std::string& ticker, bool all_data) const { return TimeSeriesHelper("TIME_SERIES_WEEKLY", ticker, all_data); } std::string AlphaVantageConnection::GetQueryString_TIMESERIESMONTHLY(const std::string& ticker, bool all_data) const { return TimeSeriesHelper("TIME_SERIES_MONTHLY", ticker, all_data); } std::string AlphaVantageConnection::GetQueryString_INTRADAY(const std::string& ticker, const std::string& interval) const { std::string url = AlphaVantageConnection::DEFAULT_URL + "function=TIME_SERIES_INTRADAY&" + "symbol=" + ticker + "&" + "interval=" + interval + "&" + "apikey=" + m_api_key + "&"; return url; } std::string AlphaVantageConnection::GetQueryString_GLOBALQUOTE(const std::string& ticker) const { std::string url = AlphaVantageConnection::DEFAULT_URL + "function=GLOBAL_QUOTE&" + "symbol=" + ticker + "&" + "apikey=" + m_api_key + "&"; return url; }
2,448
812
#pragma once #include "../../os/ParcelFileDescriptor_AutoCloseOutputStream.hpp" class JByteArray; namespace android::content::res { class AssetFileDescriptor; } namespace android::content::res { class AssetFileDescriptor_AutoCloseOutputStream : public android::os::ParcelFileDescriptor_AutoCloseOutputStream { public: // Fields // QJniObject forward template<typename ...Ts> explicit AssetFileDescriptor_AutoCloseOutputStream(const char *className, const char *sig, Ts...agv) : android::os::ParcelFileDescriptor_AutoCloseOutputStream(className, sig, std::forward<Ts>(agv)...) {} AssetFileDescriptor_AutoCloseOutputStream(QJniObject obj); // Constructors AssetFileDescriptor_AutoCloseOutputStream(android::content::res::AssetFileDescriptor arg0); // Methods void write(JByteArray arg0) const; void write(jint arg0) const; void write(JByteArray arg0, jint arg1, jint arg2) const; }; } // namespace android::content::res
956
299
/************************************************************************** * Copyright(c) 1998-2016, ALICE Experiment at CERN, All rights reserved. * * * * Author: R. Haake. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include <iostream> #include <TRandom3.h> #include <AliLog.h> #include <TString.h> #include <TMath.h> #include <TClonesArray.h> #include <AliAODTrack.h> #include <AliPicoTrack.h> #include <AliEmcalJet.h> #include <AliRhoParameter.h> #include "TH1D.h" #include "TH2D.h" #include "AliAnalysisTaskEmcal.h" #include "AliAnalysisTaskParticleRandomizer.h" /// \cond CLASSIMP ClassImp(AliAnalysisTaskParticleRandomizer) /// \endcond //_____________________________________________________________________________________________________ AliAnalysisTaskParticleRandomizer::AliAnalysisTaskParticleRandomizer() : AliAnalysisTaskEmcal("AliAnalysisTaskParticleRandomizer", kFALSE), fRandomizeInPhi(1), fRandomizeInEta(0), fRandomizeInTheta(0), fRandomizeInPt(0), fMinPhi(0), fMaxPhi(TMath::TwoPi()), fMinEta(-0.9), fMaxEta(+0.9), fMinPt(0), fMaxPt(120), fDistributionV2(0), fDistributionV3(0), fDistributionV4(0), fDistributionV5(0), fInputArrayName(), fOutputArrayName(), fInputArray(0), fOutputArray(0), fJetRemovalRhoObj(), fJetRemovalArrayName(), fJetRemovalArray(0), fJetRemovalPtThreshold(999.), fJetEmbeddingArrayName(), fJetEmbeddingArray(0), fRandomPsi3(0), fRandom() { // constructor } //_____________________________________________________________________________________________________ AliAnalysisTaskParticleRandomizer::~AliAnalysisTaskParticleRandomizer() { // destructor } //_____________________________________________________________________________________________________ void AliAnalysisTaskParticleRandomizer::UserCreateOutputObjects() { // Check user input if(fInputArrayName.IsNull()) AliWarning(Form("Name of input array not given!")); if(fOutputArrayName.IsNull()) AliFatal(Form("Name of output array not given!")); fRandom = new TRandom3(0); } //_____________________________________________________________________________________________________ void AliAnalysisTaskParticleRandomizer::ExecOnce() { // Check if arrays are OK fInputArray = static_cast<TClonesArray*>(InputEvent()->FindListObject(Form("%s", fInputArrayName.Data()))); if(!fInputArrayName.IsNull() && !fInputArray) AliFatal(Form("Input array '%s' not found!", fInputArrayName.Data())); // On demand, load also jets if(!fJetRemovalArrayName.IsNull()) { fJetRemovalArray = static_cast<TClonesArray*>(InputEvent()->FindListObject(Form("%s", fJetRemovalArrayName.Data()))); if(!fJetRemovalArray) AliError(Form("Jet array '%s' demanded but not found in event!", fJetRemovalArrayName.Data())); } // On demand, load array for embedding if(!fJetEmbeddingArrayName.IsNull()) { fJetEmbeddingArray = static_cast<TClonesArray*>(InputEvent()->FindListObject(Form("%s", fJetEmbeddingArrayName.Data()))); if(!fJetEmbeddingArray) AliError(Form("Embedding array '%s' demanded but not found in event!", fJetEmbeddingArrayName.Data())); } if((InputEvent()->FindListObject(Form("%s", fOutputArrayName.Data())))) AliFatal(Form("Output array '%s' already exists in the event! Rename it.", fInputArrayName.Data())); if(fInputArray) if(strcmp(fInputArray->GetClass()->GetName(), "AliAODTrack")) AliError(Form("Track type %s not yet supported. Use AliAODTrack", fInputArray->GetClass()->GetName())); // Copy the input array to the output array fOutputArray = new TClonesArray("AliAODTrack"); fOutputArray->SetName(fOutputArrayName.Data()); InputEvent()->AddObject(fOutputArray); AliAnalysisTaskEmcal::ExecOnce(); } //_____________________________________________________________________________________________________ Bool_t AliAnalysisTaskParticleRandomizer::Run() { fRandomPsi3 = fRandom->Rndm()*TMath::Pi(); // once per event, create a random value dedicated for Psi3 fRandomPsi4 = fRandom->Rndm()*TMath::Pi(); // once per event, create a random value dedicated for Psi4 fRandomPsi5 = fRandom->Rndm()*TMath::Pi(); // once per event, create a random value dedicated for Psi5 Int_t accTracks = 0; // Add events in input array if(fInputArray) for(Int_t iPart=0; iPart<fInputArray->GetEntries(); iPart++) { // Remove particles contained in jet array (on demand) if(fJetRemovalArray && IsParticleInJet(iPart)) continue; // Take only particles from the randomization acceptance AliAODTrack* inputParticle = static_cast<AliAODTrack*>(fInputArray->At(iPart)); if(fRandomizeInPhi && (inputParticle->Phi() < fMinPhi || inputParticle->Phi() >= fMaxPhi) ) continue; if( (fRandomizeInTheta || fRandomizeInEta) && (inputParticle->Eta() < fMinEta || inputParticle->Eta() >= fMaxEta) ) continue; new ((*fOutputArray)[accTracks]) AliAODTrack(*((AliAODTrack*)fInputArray->At(iPart))); // Randomize on demand AliAODTrack* particle = static_cast<AliAODTrack*>(fOutputArray->At(accTracks)); RandomizeTrack(particle); accTracks++; } // Add particles for embedding (on demand) if(fJetEmbeddingArray) for(Int_t iPart=0; iPart<fJetEmbeddingArray->GetEntries(); iPart++) { // Take only particles from the randomization acceptance AliPicoTrack* inputParticle = static_cast<AliPicoTrack*>(fJetEmbeddingArray->At(iPart)); if(fRandomizeInPhi && (inputParticle->Phi() < fMinPhi || inputParticle->Phi() >= fMaxPhi) ) continue; if( (fRandomizeInTheta || fRandomizeInEta) && (inputParticle->Eta() < fMinEta || inputParticle->Eta() >= fMaxEta) ) continue; new ((*fOutputArray)[accTracks]) AliAODTrack(*(GetAODTrack(inputParticle))); // Randomize on demand AliAODTrack* particle = static_cast<AliAODTrack*>(fOutputArray->At(accTracks)); RandomizeTrack(particle); accTracks++; } // std::cout << Form("%i particles from jets removed out of %i tracks. ", fInputArray->GetEntries()-accTracks, fInputArray->GetEntries()) << std::endl; return kTRUE; } //_____________________________________________________________________________________________________ void AliAnalysisTaskParticleRandomizer::RandomizeTrack(AliAODTrack* particle) { if(fRandomizeInPhi) particle->SetPhi(fMinPhi + fRandom->Rndm()*(fMaxPhi-fMinPhi)); if(fRandomizeInTheta) { Double_t minTheta = 2.*atan(exp(-fMinEta)); Double_t maxTheta = 2.*atan(exp(-fMaxEta)); particle->SetTheta(minTheta + fRandom->Rndm()*(maxTheta-minTheta)); } if(fRandomizeInEta) { Double_t randomEta = fMinEta + fRandom->Rndm()*(fMaxEta-fMinEta); Double_t randomTheta = 2.*atan(exp(-randomEta)); particle->SetTheta(randomTheta); } if(fRandomizeInPt) particle->SetPt(fMinPt + fRandom->Rndm()*(fMaxPt-fMinPt)); if(fDistributionV2 || fDistributionV3 || fDistributionV4 || fDistributionV5) particle->SetPhi(AddFlow(particle->Phi(), particle->Pt())); } //_____________________________________________________________________________________________________ AliAODTrack* AliAnalysisTaskParticleRandomizer::GetAODTrack(AliPicoTrack* track) { AliAODTrack* newTrack = new AliAODTrack(); newTrack->SetPt(track->Pt()); newTrack->SetTheta(2.*atan(exp(-track->Eta()))); // there is no setter for eta newTrack->SetPhi(track->Phi()); newTrack->SetCharge(track->Charge()); newTrack->SetLabel(track->GetLabel()); // Hybrid tracks (compatible with LHC11h) UInt_t filterMap = BIT(8) | BIT(9); newTrack->SetIsHybridGlobalConstrainedGlobal(); newTrack->SetFilterMap(filterMap); return newTrack; } //_____________________________________________________________________________________________________ Bool_t AliAnalysisTaskParticleRandomizer::IsParticleInJet(Int_t part) { for(Int_t i=0; i<fJetRemovalArray->GetEntries(); i++) { AliEmcalJet* tmpJet = static_cast<AliEmcalJet*>(fJetRemovalArray->At(i)); Double_t tmpPt = tmpJet->Pt() - tmpJet->Area()*GetExternalRho(); if(tmpPt >= fJetRemovalPtThreshold) if(tmpJet->ContainsTrack(part)>=0) return kTRUE; } return kFALSE; } //_____________________________________________________________________________________________________ Double_t AliAnalysisTaskParticleRandomizer::GetExternalRho() { // Get rho from event. AliRhoParameter* rho = 0; if (!fJetRemovalRhoObj.IsNull()) { rho = dynamic_cast<AliRhoParameter*>(InputEvent()->FindListObject(fJetRemovalRhoObj.Data())); if (!rho) { AliError(Form("%s: Could not retrieve rho with name %s!", GetName(), fJetRemovalRhoObj.Data())); return 0; } } else return 0; return (rho->GetVal()); } //_____________________________________________________________________________________________________ Double_t AliAnalysisTaskParticleRandomizer::AddFlow(Double_t phi, Double_t pt) { // adapted from AliFlowTrackSimple Double_t precisionPhi = 1e-10; Int_t maxNumberOfIterations = 200; Double_t phi0=phi; Double_t f=0.; Double_t fp=0.; Double_t phiprev=0.; Int_t ptBin = 0; // Evaluate V2 for track pt/centrality Double_t v2 = 0; if(fDistributionV2) { ptBin = fDistributionV2->GetXaxis()->FindBin(pt); if(ptBin>fDistributionV2->GetNbinsX()) v2 = fDistributionV2->GetBinContent(fDistributionV2->GetNbinsX(), fDistributionV2->GetYaxis()->FindBin(fCent)); else if(ptBin>0) v2 = fDistributionV2->GetBinContent(ptBin, fDistributionV2->GetYaxis()->FindBin(fCent)); } // Evaluate V3 for track pt/centrality Double_t v3 = 0; if(fDistributionV3) { ptBin = fDistributionV3->GetXaxis()->FindBin(pt); if(ptBin>fDistributionV3->GetNbinsX()) v3 = fDistributionV3->GetBinContent(fDistributionV3->GetNbinsX(), fDistributionV3->GetYaxis()->FindBin(fCent)); else if(ptBin>0) v3 = fDistributionV3->GetBinContent(ptBin, fDistributionV3->GetYaxis()->FindBin(fCent)); } // Evaluate V4 for track pt/centrality Double_t v4 = 0; if(fDistributionV4) { ptBin = fDistributionV4->GetXaxis()->FindBin(pt); if(ptBin>fDistributionV4->GetNbinsX()) v4 = fDistributionV4->GetBinContent(fDistributionV4->GetNbinsX(), fDistributionV4->GetYaxis()->FindBin(fCent)); else if(ptBin>0) v4 = fDistributionV4->GetBinContent(ptBin, fDistributionV4->GetYaxis()->FindBin(fCent)); } // Evaluate V5 for track pt/centrality Double_t v5 = 0; if(fDistributionV5) { ptBin = fDistributionV5->GetXaxis()->FindBin(pt); if(ptBin>fDistributionV5->GetNbinsX()) v5 = fDistributionV5->GetBinContent(fDistributionV5->GetNbinsX(), fDistributionV5->GetYaxis()->FindBin(fCent)); else if(ptBin>0) v5 = fDistributionV5->GetBinContent(ptBin, fDistributionV5->GetYaxis()->FindBin(fCent)); } // Add all v's for (Int_t i=0; i<maxNumberOfIterations; i++) { phiprev=phi; //store last value for comparison f = phi-phi0 + v2*TMath::Sin(2.*(phi-(fEPV0+(TMath::Pi()/2.)))) +2./3.*v3*TMath::Sin(3.*(phi-fRandomPsi3)) +0.5 *v4*TMath::Sin(4.*(phi-fRandomPsi4)) +0.4 *v5*TMath::Sin(5.*(phi-fRandomPsi5)); fp = 1.0+2.0*( +v2*TMath::Cos(2.*(phi-(fEPV0+(TMath::Pi()/2.)))) +v3*TMath::Cos(3.*(phi-fRandomPsi3)) +v4*TMath::Cos(4.*(phi-fRandomPsi4)) +v5*TMath::Cos(5.*(phi-fRandomPsi5))); //first derivative phi -= f/fp; if (TMath::AreEqualAbs(phiprev,phi,precisionPhi)) break; } return phi; }
12,375
4,224
#ifndef INCLUDED_SROOK_CONFIG_PRAGMA_PUSH_WVARIADIC_MACROS_HPP #define INCLUDED_SROOK_CONFIG_PRAGMA_PUSH_WVARIADIC_MACROS_HPP #ifdef __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wvariadic-macros" #elif defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wvariadic-macros" #endif #endif
357
159
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/batch_fc_op.h" #include <string> namespace paddle { namespace operators { class BatchFCOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ( ctx->HasInput("Input"), true, platform::errors::InvalidArgument( "X(Input) of Batch Fully Connected should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("Out"), true, platform::errors::InvalidArgument( "Out(Output) of Batch Fully Connected should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("W"), true, platform::errors::InvalidArgument( "W(Input) of Batch Fully Connected should not be null.")); auto input_dims = ctx->GetInputDim("Input"); auto w_dims = ctx->GetInputDim("W"); PADDLE_ENFORCE_EQ(input_dims.size(), 3, platform::errors::InvalidArgument( "Input of BatchFCOp should have 3D.")); PADDLE_ENFORCE_EQ( w_dims.size(), 3, platform::errors::InvalidArgument("W of BatchFCOp should have 3D.")); PADDLE_ENFORCE_EQ( input_dims[0], w_dims[0], platform::errors::InvalidArgument( "Input.dim[0] and W.dim[0] of BatchFCOp should be same.")); PADDLE_ENFORCE_EQ( input_dims[2], w_dims[1], platform::errors::InvalidArgument( "Input.dim[2] and W.dim[1] of BatchFCOp should be same.")); auto bias_dims = ctx->GetInputDim("Bias"); PADDLE_ENFORCE_EQ(bias_dims[0], input_dims[0], platform::errors::InvalidArgument( "Bias.dim[0] should be same as input.dim[0].")); PADDLE_ENFORCE_EQ(bias_dims[1], w_dims[2], platform::errors::InvalidArgument( "Bias.dim[1] should be same as input.dim[2].")); ctx->SetOutputDim("Out", {input_dims[0], input_dims[1], w_dims[2]}); ctx->ShareLoD("Input", /*->*/ "Out"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "Input"), ctx.device_context()); } }; class BatchFCGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ( ctx->HasInput("Input"), true, platform::errors::InvalidArgument("Input should not be null")); PADDLE_ENFORCE_EQ( ctx->HasInput("W"), true, platform::errors::InvalidArgument("Input(W) should not be null")); ctx->SetOutputDim(framework::GradVarName("Input"), ctx->GetInputDim("Input")); ctx->SetOutputDim(framework::GradVarName("W"), ctx->GetInputDim("W")); ctx->SetOutputDim(framework::GradVarName("Bias"), ctx->GetInputDim("Bias")); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType( ctx, framework::GradVarName("Out")), ctx.device_context()); } }; class BatchFCOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("Input", "(Tensor) Input tensor of batch_fc_op operator."); AddInput("W", "(Tensor) Input tensor of batch_fc_op operator."); AddInput("Bias", "(Tensor) Input tensor of batch_fc_op operator."); AddOutput("Out", "Output tensor of batch_fc_op operator."); AddComment(R"DOC( BatchFC Operator. Notice: It currently supports GPU device. This Op exists in contrib, which means that it is not shown to the public. )DOC"); } }; template <typename T> class BatchFCGradOpMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("batch_fc_grad"); op->SetInput("Input", this->Input("Input")); op->SetInput("W", this->Input("W")); op->SetInput("Bias", this->Input("Bias")); op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out")); op->SetOutput(framework::GradVarName("Input"), this->InputGrad("Input")); op->SetOutput(framework::GradVarName("W"), this->InputGrad("W")); op->SetOutput(framework::GradVarName("Bias"), this->InputGrad("Bias")); op->SetAttrMap(this->Attrs()); } }; DECLARE_NO_NEED_BUFFER_VARS_INFERER(BatchFCGradOpNoNeedBufferVarsInferer, "Bias"); } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(batch_fc, ops::BatchFCOp, ops::BatchFCOpMaker, ops::BatchFCGradOpMaker<paddle::framework::OpDesc>, ops::BatchFCGradOpMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(batch_fc_grad, ops::BatchFCGradOp, ops::BatchFCGradOpNoNeedBufferVarsInferer); REGISTER_OP_CPU_KERNEL( batch_fc, ops::BatchFCKernel<paddle::platform::CPUDeviceContext, float>, ops::BatchFCKernel<paddle::platform::CPUDeviceContext, double>);
6,002
1,909
// // Cone2DParticleEmitter.cpp // Chilli Source // Created by Ian Copland on 03/12/2014. // // The MIT License (MIT) // // Copyright (c) 2014 Tag Games Limited // // 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 <ChilliSource/Rendering/Particle/Emitter/Cone2DParticleEmitter.h> #include <ChilliSource/Core/Math/Random.h> #include <ChilliSource/Rendering/Particle/ParticleEffect.h> #include <ChilliSource/Rendering/Particle/Emitter/Cone2DParticleEmitterDef.h> #include <cmath> namespace ChilliSource { namespace Rendering { namespace { //---------------------------------------------------------------- /// Generates a 2D direction within the given angle range with even /// distribution. /// /// @author Ian Copland /// /// @param The angle. /// /// @return The direction. //---------------------------------------------------------------- Core::Vector2 GenerateDirectionWithinAngle(f32 in_angle) { f32 angle = Core::MathUtils::k_pi * 0.5f + Core::Random::GenerateNormalised<f32>() * in_angle - 0.5f * in_angle; Core::Vector2 direction(std::cos(angle), std::sin(angle)); return direction; } //---------------------------------------------------------------- /// Generates a direction with the given angle with even /// distribution. /// /// @author Ian Copland /// /// @param The angle. /// /// @return The direction. //---------------------------------------------------------------- Core::Vector2 GenerateDirectionWithAngle(f32 in_angle) { f32 angle = 0.0f; if (Core::Random::Generate<u32>(0, 1) == 0) { angle = Core::MathUtils::k_pi * 0.5f - 0.5f * in_angle; } else { angle = Core::MathUtils::k_pi * 0.5f + 0.5f * in_angle; } Core::Vector2 direction(std::cos(angle), std::sin(angle)); return direction; } //---------------------------------------------------------------- /// Generates a position in a unit 2D cone with the given angle, with /// even distribution. /// /// @author Ian Copland /// /// @param The angle. /// /// @return The position. //---------------------------------------------------------------- Core::Vector2 GeneratePositionInUnitCone2D(f32 in_angle) { f32 dist = std::sqrt(Core::Random::GenerateNormalised<f32>()); return GenerateDirectionWithinAngle(in_angle) * dist; } //---------------------------------------------------------------- /// Generates a position on a the surface of a unit 2D cone with the /// given angle, with even distribution. /// /// @author Ian Copland /// /// @param The angle. /// /// @return The direction. //---------------------------------------------------------------- Core::Vector2 GeneratePositionOnUnitCone2D(f32 in_angle) { f32 dist = std::sqrt(Core::Random::GenerateNormalised<f32>()); return GenerateDirectionWithAngle(in_angle) * dist; } } //---------------------------------------------------------------- //---------------------------------------------------------------- Cone2DParticleEmitter::Cone2DParticleEmitter(const ParticleEmitterDef* in_particleEmitter, Core::dynamic_array<Particle>* in_particleArray) : ParticleEmitter(in_particleEmitter, in_particleArray) { //Only the sphere emitter def can create this, so this is safe. m_coneParticleEmitterDef = static_cast<const Cone2DParticleEmitterDef*>(in_particleEmitter); } //---------------------------------------------------------------- //---------------------------------------------------------------- void Cone2DParticleEmitter::GenerateEmission(f32 in_normalisedEmissionTime, Core::Vector3& out_position, Core::Vector3& out_direction) { f32 radius = m_coneParticleEmitterDef->GetRadiusProperty()->GenerateValue(in_normalisedEmissionTime); f32 angle = m_coneParticleEmitterDef->GetAngleProperty()->GenerateValue(in_normalisedEmissionTime); //calculate the position. switch (m_coneParticleEmitterDef->GetEmitFromType()) { case Cone2DParticleEmitterDef::EmitFromType::k_inside: out_position = Core::Vector3(GeneratePositionInUnitCone2D(angle) * radius, 0.0f); break; case Cone2DParticleEmitterDef::EmitFromType::k_edge: out_position = Core::Vector3(GeneratePositionOnUnitCone2D(angle) * radius, 0.0f); break; case Cone2DParticleEmitterDef::EmitFromType::k_base: out_position = Core::Vector3::k_zero; break; default: CS_LOG_FATAL("Invalid 'Emit From' type."); break; } //calculate the direction. switch (m_coneParticleEmitterDef->GetEmitDirectionType()) { case Cone2DParticleEmitterDef::EmitDirectionType::k_random: out_direction = Core::Vector3(GenerateDirectionWithinAngle(angle), 0.0f); break; case Cone2DParticleEmitterDef::EmitDirectionType::k_awayFromBase: if (out_position != Core::Vector3::k_zero) { out_direction = Core::Vector3(Core::Vector2::Normalise(out_position.XY()), 0.0f); } else { out_direction = Core::Vector3(GenerateDirectionWithinAngle(angle), 0.0f); } break; default: CS_LOG_FATAL("Invalid 'Emit Direction' type."); break; } } } }
6,246
2,277
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/ash/stub_user_accounts_delegate.h" #include <cctype> #include "base/logging.h" StubUserAccountsDelegate::StubUserAccountsDelegate(const std::string& owner_id) : primary_account_(owner_id) {} StubUserAccountsDelegate::~StubUserAccountsDelegate() {} std::string StubUserAccountsDelegate::GetPrimaryAccountId() { return primary_account_; } std::vector<std::string> StubUserAccountsDelegate::GetSecondaryAccountIds() { return secondary_accounts_; } std::string StubUserAccountsDelegate::GetAccountDisplayName( const std::string& account_id) { std::string res(1, std::toupper(account_id[0])); res += account_id.substr(1); return res; } void StubUserAccountsDelegate::DeleteAccount(const std::string& account_id) { secondary_accounts_.erase( std::remove( secondary_accounts_.begin(), secondary_accounts_.end(), account_id), secondary_accounts_.end()); NotifyAccountListChanged(); } void StubUserAccountsDelegate::AddAccount(const std::string& account_id) { if (primary_account_ == account_id) return; if (std::find(secondary_accounts_.begin(), secondary_accounts_.end(), account_id) != secondary_accounts_.end()) return; secondary_accounts_.push_back(account_id); NotifyAccountListChanged(); } void StubUserAccountsDelegate::LaunchAddAccountDialog() { NOTIMPLEMENTED(); }
1,564
496
// Copyright 2022 PingCAP, Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <Parsers/queryToString.h> #include <Storages/ColumnDefault.h> namespace DB { ColumnDefaultKind columnDefaultKindFromString(const std::string & str) { static const std::unordered_map<std::string, ColumnDefaultKind> map{ { "DEFAULT", ColumnDefaultKind::Default }, { "MATERIALIZED", ColumnDefaultKind::Materialized }, { "ALIAS", ColumnDefaultKind::Alias } }; const auto it = map.find(str); return it != std::end(map) ? it->second : throw Exception{"Unknown column default specifier: " + str}; } std::string toString(const ColumnDefaultKind kind) { static const std::unordered_map<ColumnDefaultKind, std::string> map{ { ColumnDefaultKind::Default, "DEFAULT" }, { ColumnDefaultKind::Materialized, "MATERIALIZED" }, { ColumnDefaultKind::Alias, "ALIAS" } }; const auto it = map.find(kind); return it != std::end(map) ? it->second : throw Exception{"Invalid ColumnDefaultKind"}; } bool operator==(const ColumnDefault & lhs, const ColumnDefault & rhs) { return lhs.kind == rhs.kind && queryToString(lhs.expression) == queryToString(rhs.expression); } }
1,739
525
/* Copyright 2018 Iakov Kirilenko, CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QProcess> #include <QsLog.h> #include <QVector> #include <trikNetwork/mailboxInterface.h> #include <trikKernel/paths.h> #include <trikKernel/exceptions/internalErrorException.h> #include <trikScriptRunnerInterface.h> #include "pythonEngineWorker.h" #include <Python.h> #include "PythonQtConversion.h" using namespace trikScriptRunner; QAtomicInt PythonEngineWorker::initCounter = 0; static int quitFromPython(void*) { PyErr_SetInterrupt(); return 0; } static void abortPythonInterpreter() { if(!Py_IsInitialized()) { return; } PythonQtGILScope _; Py_AddPendingCall(&quitFromPython, nullptr); } PythonEngineWorker::PythonEngineWorker(trikControl::BrickInterface &brick , trikNetwork::MailboxInterface * const mailbox ) : mBrick(brick) , mScriptExecutionControl(new ScriptExecutionControl(brick)) , mMailbox(mailbox) , mWorkingDirectory(trikKernel::Paths::userScriptsPath()) {} PythonEngineWorker::~PythonEngineWorker() { stopScript(); { // In python at least before 3.7 (3.5,3.6) // we need to make all pending calls before the context // is destroyed, otherwise python crashes PythonQtGILScope _; Py_MakePendingCalls(); mMainContext = nullptr; if (mPyInterpreter) { Py_EndInterpreter(mPyInterpreter); mPyInterpreter = nullptr; } } if (--initCounter == 0) { Py_Finalize(); PyMem_RawFree(mProgramName); PyMem_RawFree(mPythonPath); if (PythonQt::self()) { PythonQt::cleanup(); } } } void PythonEngineWorker::init() { if (initCounter++ == 0) { mProgramName = Py_DecodeLocale("trikPythonRuntime", nullptr); Py_SetProgramName(mProgramName); constexpr auto varName = "TRIK_PYTHONPATH"; auto const &path = QProcessEnvironment::systemEnvironment().value(varName); if (path.isEmpty()) { auto const &e = QString("%1 must be set to correct value").arg(varName); QLOG_FATAL() << e; throw trikKernel::InternalErrorException(e); } else { QLOG_INFO() << varName << ":" << path; } /// TODO: Must point to local .zip file mPythonPath = Py_DecodeLocale(path.toStdString().data(), nullptr); Py_SetPath(mPythonPath); /* uncomment for verbosity Py_VerboseFlag = 3; Py_InspectFlag = 1; Py_DebugFlag = 2; // */ Py_IsolatedFlag = 1; Py_BytesWarningFlag = 3; Py_DontWriteBytecodeFlag = 1; Py_NoSiteFlag = 1; Py_NoUserSiteDirectory = 1; Py_Initialize(); PyEval_InitThreads(); // For Python < 3.7 } if (!mPyInterpreter) { // mPyInterpreter = Py_NewInterpreter(); } if (!PythonQt::self()) { PythonQt::setEnableThreadSupport(true); PythonQtGILScope _; PythonQt::init(PythonQt::RedirectStdOut | PythonQt::PythonAlreadyInitialized); connect(PythonQt::self(), &PythonQt::pythonStdErr, this, &PythonEngineWorker::updateErrorMessage); connect(PythonQt::self(), &PythonQt::pythonStdOut, this, [this](const QString& str){ QTimer::singleShot(0, this, [this, str](){ Q_EMIT this->textInStdOut(str);}); mScriptExecutionControl->wait(0); }); PythonQtRegisterListTemplateConverter(QVector, uint8_t) PythonQt_QtAll::init(); } if (!mMainContext) { mMainContext = PythonQt::self()->getMainModule(); recreateContext(); } emit inited(); } bool PythonEngineWorker::recreateContext() { { PythonQtGILScope _; Py_MakePendingCalls(); PyErr_CheckSignals(); PyErr_Clear(); } PythonQt::self()->clearError(); return initTrik(); } bool PythonEngineWorker::evalSystemPy() { const QString systemPyPath = trikKernel::Paths::systemScriptsPath() + "system.py"; if (!QFileInfo::exists(systemPyPath)) { QLOG_ERROR() << "system.py not found, path:" << systemPyPath; return false; } // HACK: to avoid duplicate system.py try to check if basic feature like script.wait works. mMainContext.evalScript("script.wait(0)"); if (PythonQt::self()->hadError()) { // HACK: no script.wait means usually a problem with system.py, let's try to include it PythonQt::self()->clearError(); mMainContext.evalFile(systemPyPath); if (PythonQt::self()->hadError()) { QLOG_ERROR() << "Failed to eval system.py"; return false; } } return true; } void PythonEngineWorker::addSearchModuleDirectory(const QDir &path) { if (path.path().indexOf("'") != -1) return; mMainContext.evalScript("import sys; (lambda x: sys.path.append(x) if not x in sys.path else None)('" + path.path() + "')"); } bool PythonEngineWorker::initTrik() { PythonQt_init_PyTrikControl(mMainContext); mMainContext.addObject("brick", &mBrick); mMainContext.addObject("script_cpp", mScriptExecutionControl.data()); mMainContext.addObject("mailbox", mMailbox); return evalSystemPy(); } void PythonEngineWorker::resetBrick() { QLOG_INFO() << "Stopping robot"; if (mMailbox) { mMailbox->stopWaiting(); mMailbox->clearQueue(); } mBrick.reset(); } void PythonEngineWorker::brickBeep() { mBrick.playSound(trikKernel::Paths::mediaPath() + "media/beep_soft.wav"); } void PythonEngineWorker::stopScript() { QMutexLocker locker(&mScriptStateMutex); if (mState == stopping) { // Already stopping, so we can do nothing. return; } if (mState == ready) { // Engine is ready for execution. return; } QLOG_INFO() << "PythonEngineWorker: stopping script"; mState = stopping; if (QThread::currentThread() != thread()) { abortPythonInterpreter(); } else { QLOG_FATAL() << "Attempt to abort Python from main thread."; } if (mMailbox) { mMailbox->stopWaiting(); } mState = ready; /// @todo: is it actually stopped? QLOG_INFO() << "PythonEngineWorker: stopping complete"; } QStringList PythonEngineWorker::knownNames() const { QSet<QString> result = {"brick", "script", "threading"}; TrikScriptRunnerInterface::Helper::collectMethodNames(result, &trikControl::BrickInterface::staticMetaObject); /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mScriptControl.metaObject()); if (mMailbox) { result.insert("mailbox"); TrikScriptRunnerInterface::Helper::collectMethodNames(result, mMailbox->metaObject()); } /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mThreading.metaObject()); return result.toList(); } void PythonEngineWorker::setWorkingDirectory(const QDir &workingDir) { mWorkingDirectory = workingDir; } void PythonEngineWorker::run(const QString &script, const QFileInfo &scriptFile) { QMutexLocker locker(&mScriptStateMutex); mState = starting; QMetaObject::invokeMethod(this, [this, script, scriptFile](){this->doRun(script, scriptFile);}); } void PythonEngineWorker::doRun(const QString &script, const QFileInfo &scriptFile) { emit startedScript("", 0); mErrorMessage.clear(); /// When starting script execution (by any means), clear button states. mBrick.keys()->reset(); mState = running; auto ok = recreateContext(); if (!ok) { emit completed(mErrorMessage,0); return; } addSearchModuleDirectory(mWorkingDirectory.canonicalPath()); if (scriptFile.isFile()) { addSearchModuleDirectory(scriptFile.canonicalPath()); } mMainContext.evalScript(script); QLOG_INFO() << "PythonEngineWorker: evaluation ended"; auto wasError = mState != ready && PythonQt::self()->hadError(); mState = ready; if (wasError) { emit completed(mErrorMessage, 0); } else { emit completed("", 0); } } void PythonEngineWorker::runDirect(const QString &command) { QMutexLocker locker(&mScriptStateMutex); QMetaObject::invokeMethod(this, "doRunDirect", Q_ARG(QString, command)); } void PythonEngineWorker::doRunDirect(const QString &command) { emit startedDirectScript(0); if (PythonQt::self()->hadError()) { PythonQt::self()->clearError(); mErrorMessage.clear(); recreateContext(); } mMainContext.evalScript(command); emit completed(mErrorMessage, 0); } void PythonEngineWorker::updateErrorMessage(const QString &err) { mErrorMessage += err; } void PythonEngineWorker::onScriptRequestingToQuit() { throw std::logic_error("Not implemented"); }
8,498
3,038
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Siva Rajamanickam (srajama@sandia.gov) // // ************************************************************************ //@HEADER */ #ifndef _KOKKOS_SPGEMM_HPP #define _KOKKOS_SPGEMM_HPP #include "KokkosSparse_spgemm_numeric.hpp" #include "KokkosSparse_spgemm_symbolic.hpp" #include "KokkosSparse_spgemm_jacobi.hpp" namespace KokkosSparse { template <class KernelHandle, class AMatrix, class BMatrix, class CMatrix> void spgemm_symbolic(KernelHandle& kh, const AMatrix& A, const bool Amode, const BMatrix& B, const bool Bmode, CMatrix& C) { using row_map_type = typename CMatrix::row_map_type::non_const_type; using entries_type = typename CMatrix::index_type::non_const_type; using values_type = typename CMatrix::values_type::non_const_type; row_map_type row_mapC( Kokkos::view_alloc(Kokkos::WithoutInitializing, "non_const_lnow_row"), A.numRows() + 1); entries_type entriesC; values_type valuesC; KokkosSparse::Experimental::spgemm_symbolic( &kh, A.numRows(), B.numRows(), B.numCols(), A.graph.row_map, A.graph.entries, Amode, B.graph.row_map, B.graph.entries, Bmode, row_mapC); const size_t c_nnz_size = kh.get_spgemm_handle()->get_c_nnz(); if (c_nnz_size) { entriesC = entries_type(Kokkos::view_alloc(Kokkos::WithoutInitializing, "entriesC"), c_nnz_size); valuesC = values_type(Kokkos::view_alloc(Kokkos::WithoutInitializing, "valuesC"), c_nnz_size); } C = CMatrix("C=AB", A.numRows(), B.numCols(), c_nnz_size, valuesC, row_mapC, entriesC); } template <class KernelHandle, class AMatrix, class BMatrix, class CMatrix> void spgemm_numeric(KernelHandle& kh, const AMatrix& A, const bool Amode, const BMatrix& B, const bool Bmode, CMatrix& C) { // using row_map_type = typename CMatrix::index_type::non_const_type; // using entries_type = typename CMatrix::row_map_type::non_const_type; // using values_type = typename CMatrix::values_type::non_const_type; KokkosSparse::Experimental::spgemm_numeric( &kh, A.numRows(), B.numRows(), B.numCols(), A.graph.row_map, A.graph.entries, A.values, Amode, B.graph.row_map, B.graph.entries, B.values, Bmode, C.graph.row_map, C.graph.entries, C.values); kh.destroy_spgemm_handle(); } } // namespace KokkosSparse #endif
4,202
1,486
#ifndef ABSTRACT_GRAPH #define ABSTRACT_GRAPH 1 /* * An interface to represent any type of Graph */ class AbstractGraph { public: /* Destructor: * releases all resources acquired by the class */ virtual ~AbstractGraph() {}; /* * Function: edgeExists * Returns true if an edge exists between vertices i and j, false otherwise. */ virtual bool edgeExists(int i, int j) = 0; /* * Function: edges * Returns the number of edges in the adjacency structure. */ virtual int edges() = 0; /* * Function: vertices * Returns the number of vertices in the adjacency structure. */ virtual int vertices() = 0; /* * Function add: * Adds an edge between vertices i and j */ virtual void add(int i, int j) = 0; /* * Function: remove * Deleted the edge between vertices i and j */ virtual void remove(int i, int j) = 0; /* * Function dfs: * Does a depth first traversal of the entire graph. * Runs the given function work, with the value of each vertex. */ virtual void dfs(void (*work)(int&)) = 0; /* * Function bfs: * Does a breadth first traversal of the entire graph. * Runs the given function work, with the value of each vertex. */ virtual void bfs(void (*work)(int&)) = 0; }; #endif /* ifndef ABSTRACT_GRAPH */
1,363
451
/* @Author Student Name: Enes Demirag Student ID : 504201571 Mail : ensdmrg@gmail.com Date : 06.04.2021 Dear sir/madam, This projects consist of a Node class, two graph traverse algorithms (BFS and DFS) and other utility functions. In order to compile and run this project, first you need to link files under include/ directory. Below commands can be used to build and run this project with g++. >> g++ -std=c++11 -Iinclude -c src/* >> g++ -std=c++11 -Iinclude -g *.o -o executable main.cpp >> ./executable DFS TWO TWO FOUR solution.txt All of the standard libraries used in this project is given below. <list> : To implement a FIFO type Queue structure. <stack> : To implement a LIFO type Stack structure. <string> : String operations. <vector> : Storing some elements and accessing them. <iostream> : To print things to the terminal. <algorithm> : To find element positions inside lists and vectors. <cmath> : Numaric operations like power and max. <chrono> : To calculate running time. If you encounter any problem regarding this projects, feel free to reach me. Thanks and kind regards, Enes */ #include "Node.hpp" #include "Utils.hpp" #include "Search.hpp" /* This is the main function. * It takes arguments from program call and using those, * First creates a tree. * Then search a valid solution in that tree using specified algorithm. */ int main(int argc, char** argv) { // Checking if there is an unexpected input argument // And if there is, stop the program. if (!checkArguments(argv)) { return -1; } // Create the root note (with no parent, ' ' key and -1 value. Node root(' ', -1); // Parse input arguments into variables. std::string str1 = argv[2]; std::string str2 = argv[3]; std::string sum = argv[4]; // Find first letters of each word from inputs std::list<char> first_chars{ str1[0], str2[0], sum[0] }; first_chars.sort(); first_chars.unique(); // Find unique character list from inputs std::list<char> unique_keys; for (char c : str1 + str2 + sum) { // If c is not in unique_keys list, add c into the list. if (std::find(unique_keys.begin(), unique_keys.end(), c) == unique_keys.end()) { unique_keys.push_back(c); } } // Recursively create the tree from root node. addNewLayer(&root, unique_keys, first_chars); // Define output variables int number_of_visited_nodes, max_nodes_in_memory; double running_time; std::list<int> solution; // BFS algorithm if (std::string("BFS") == argv[1]) { solution = BFS(&root, unique_keys, str1, str2, sum, number_of_visited_nodes, max_nodes_in_memory, running_time); // If there is a solution. if (!solution.empty()) { // Print results and write matrix to file. printResults("BFS", unique_keys, solution, number_of_visited_nodes, max_nodes_in_memory, running_time); printMatrix(argv[5], unique_keys, solution); } // If no solution was found. else { std::cout << "No solution found." << std::endl; } } // DFS algorithm else { solution = DFS(&root, unique_keys, str1, str2, sum, number_of_visited_nodes, max_nodes_in_memory, running_time); // If there is a solution. if (!solution.empty()) { // Print results and write matrix to file. printResults("DFS", unique_keys, solution, number_of_visited_nodes, max_nodes_in_memory, running_time); printMatrix(argv[5], unique_keys, solution); } // If no solution was found. else { std::cout << "No solution found." << std::endl; } } return 0; }
3,834
1,172
#include PACC_PCH #include <Pacc/App/App.hpp> #include <Pacc/App/Help.hpp> #include <Pacc/Helpers/Formatting.hpp> /////////////////////////////////////////////////// void PaccApp::displayHelp(bool abbrev_) { auto programName = fs::u8path(args[0]).stem(); auto const& style = fmt_args::s(); // Introduction: fmt::print( "pacc v{} - a C++ package manager.\n\n" "{USAGE}: {} [action] <params>\n\n", PaccApp::PaccVersion, programName.string(), FMT_INLINE_ARG("USAGE", style.Yellow, "USAGE") ); // if (abbrev_) { fmt::print("Use \"{} help\" for more information\n", programName.string()); } else { // Display actions std::cout << "ACTIONS\n"; for (auto action : help::actions) { fmt::print("\t{:16}{}\n", action.first, action.second); } std::cout << std::endl; } }
820
343
#include "UIGameSession.h" #include "UISelectedCard.h" #include "SoundSystem.h" #include <iostream> UIGameSession::UIGameSession(const sf::Vector2u& windowSize, const PregameSetup& pregameSetup, std::vector<Player>* pPlayers, Board* pBoard, std::reference_wrapper<Player>& rActivePlayer) : // instantiate Logic p_board(pBoard), r_activePlayer(rActivePlayer), // instantiate UI panels m_infoPanel(sf::Vector2f(0, 0), sf::Vector2f(windowSize.x, windowSize.y * 0.05)), m_playersPanel(pPlayers, sf::Vector2f(0, windowSize.y * 0.05), sf::Vector2f(windowSize.x * 0.3, windowSize.y * 0.95)), m_tokensPanel(sf::Vector2f(windowSize.x * 0.3, windowSize.y * 0.05), sf::Vector2f(0.1 * windowSize.x, windowSize.y * 0.95)), m_noblesPanel(5, sf::Vector2f(windowSize.x * 0.4, windowSize.y * 0.05), sf::Vector2f(windowSize.x * 0.6, windowSize.y * 0.26)), m_expansionsL3Panel(5, sf::Vector2f(windowSize.x * 0.4, windowSize.y * 0.31), sf::Vector2f(windowSize.x * 0.6, windowSize.y * 0.23)), m_expansionsL2Panel(5, sf::Vector2f(windowSize.x * 0.4, windowSize.y * 0.54), sf::Vector2f(windowSize.x * 0.6, windowSize.y * 0.23)), m_expansionsL1Panel(5, sf::Vector2f(windowSize.x * 0.4, windowSize.y * 0.77), sf::Vector2f(windowSize.x * 0.6, windowSize.y * 0.23)), m_handPanel(static_cast<sf::Vector2f>(windowSize), false), m_tokenAlertPanel(static_cast<sf::Vector2f>(windowSize), false), p_exceedingHand(nullptr), // instantiate Pregame Set-up m_pregameSetup(pregameSetup) { // Instantiate UI Card Rows m_noblesPanel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::Noble), 0, true); m_noblesPanel.ReverseDrawOrder(); m_expansionsL3Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL3), 3); m_expansionsL3Panel.ReverseDrawOrder(); m_expansionsL2Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL2), 2); m_expansionsL2Panel.ReverseDrawOrder(); m_expansionsL1Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL1), 1); m_expansionsL1Panel.ReverseDrawOrder(); m_expansionPanels.emplace_back(std::ref(m_expansionsL3Panel)); m_expansionPanels.emplace_back(std::ref(m_expansionsL2Panel)); m_expansionPanels.emplace_back(std::ref(m_expansionsL1Panel)); // Populate panel vector m_panels.push_back(dynamic_cast<UIPanel*>(&m_infoPanel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_playersPanel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_tokensPanel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_expansionsL1Panel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_expansionsL2Panel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_expansionsL3Panel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_noblesPanel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_tokenAlertPanel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_handPanel)); } void UIGameSession::StartGame() { m_infoPanel.StartTimer(); } void UIGameSession::StopGame() { m_infoPanel.StopTimer(); } void UIGameSession::UpdateGame() { // Info m_infoPanel.UpdateTime(); // Tokens Panel m_tokensPanel.UpdateTokens(p_board->GetTokensData()); if (m_tokensPanel.GetLastPicked().has_value()) { auto& token = m_tokensPanel.GetLastPicked(); r_activePlayer.get().GetHand().AddToken(token.value()); p_board->TakeToken(token.value()); token.reset(); } if (m_tokensPanel.GetHasPicked()) { m_tokensPanel.SetHasPicked(false); std::for_each(m_expansionPanels.begin(), m_expansionPanels.end(), [](std::reference_wrapper<UICardsRowPanel>& panel) {panel.get().NumbAll(); }); } // Card Panels std::optional<std::pair<UICard*, UICard::State>> pickedCard; for (auto& expansionPanel : m_expansionPanels) { if (pickedCard.has_value()) continue; pickedCard = expansionPanel.get().CheckForPickedCard(); } if (pickedCard.has_value()) { switch (pickedCard.value().second) { case UICard::State::LeftRelease:/// Buy Card std::cout << "Picked card LEFT CLICK\n"; // Background if (pickedCard->first->GetType() == UICard::Type::Background) break; // Expansion Card try { // Create logic ExpansionCard for pickedCard ExpansionCard pickedCardLogicPiece(static_cast<ExpansionCard::Level>(static_cast<uint16_t>(pickedCard.value().first->GetType())), pickedCard.value().first->GetID()); // Save picked card data const auto prestigePoints = pickedCardLogicPiece.GetPrestigePoints(); const auto level = pickedCardLogicPiece.GetLevel(); const auto id = pickedCardLogicPiece.GetId(); // Return & sync tokens p_board->ReturnTokens(r_activePlayer.get().GetHand().BuyExpansionCard(std::move(pickedCardLogicPiece))); m_tokensPanel.SyncTokens(p_board->GetTokensData()); // Replace card in board p_board->ReplaceExpansion(level, id); // Add card's prestige points r_activePlayer.get().AddPrestigePoints(prestigePoints); m_playersPanel.AddPrestigePointsToCurrentPlayer(prestigePoints); // Deactivate UI pickedCard->first->Deactivate(); m_tokensPanel.NumbAll(); std::for_each(m_expansionPanels.begin(), m_expansionPanels.end(), [](std::reference_wrapper<UICardsRowPanel>& panel) {panel.get().NumbAll(); }); // Sound SFX SoundSystem::PlaySFX(SoundSystem::SoundType::BuyCardSFX); } catch (std::length_error & exception) { // Not enough resources std::cout << exception.what() << "\n"; pickedCard->first->TriggerWarning(); } catch (std::exception & exception) { // Other possible exception std::cout << exception.what() << "\n"; } break; case UICard::State::RightRelease:/// Hold Card std::cout << "Picked card RIGHT CLICK\n"; // Background if (pickedCard->first->GetType() == UICard::Type::Background) { // Hand is full if (r_activePlayer.get().GetHand().IsFull()) { pickedCard->first->TriggerWarning(); break; } // Transfer expansion card from board to active player hand try { r_activePlayer.get().GetHand().AddExpansionCard(p_board->DrawExpansionFromDeck(pickedCard->first->GetID())); } catch (std::out_of_range & exception) { // Empty Deck std::cout << exception.what() << "\n"; pickedCard.value().first->TriggerWarning(); break; } // Pick a gold token try { p_board->TakeToken(IToken::Type::Gold); r_activePlayer.get().GetHand().AddToken(IToken::Type::Gold); m_tokensPanel.TakeGoldToken(); } catch (std::out_of_range & exception) { // Not enough gold tokens on board } // Deactivate UI pickedCard->first->OnMouseLeave(); m_tokensPanel.NumbAll(); std::for_each(m_expansionPanels.begin(), m_expansionPanels.end(), [](std::reference_wrapper<UICardsRowPanel>& panel) {panel.get().NumbAll(); }); // Sound SFX SoundSystem::PlaySFX(SoundSystem::SoundType::HoldCardSFX); break; } // Expansion Card try { // Create logic ExpansionCard for pickedCard ExpansionCard pickedCardLogicPiece(static_cast<ExpansionCard::Level>(static_cast<uint16_t>(pickedCard.value().first->GetType())), pickedCard.value().first->GetID()); // Save picked card data const auto level = pickedCardLogicPiece.GetLevel(); const auto id = pickedCardLogicPiece.GetId(); // Transfer card to hand r_activePlayer.get().GetHand().AddExpansionCard(std::move(pickedCardLogicPiece)); // Replace card in board p_board->ReplaceExpansion(level, id); // Pick a gold token try { p_board->TakeToken(IToken::Type::Gold); r_activePlayer.get().GetHand().AddToken(IToken::Type::Gold); m_tokensPanel.TakeGoldToken(); } catch (std::out_of_range & exception) { // Not enough gold tokens on board } // Deactivate UI pickedCard->first->Deactivate(); m_tokensPanel.NumbAll(); std::for_each(m_expansionPanels.begin(), m_expansionPanels.end(), [](std::reference_wrapper<UICardsRowPanel>& panel) {panel.get().NumbAll(); }); // Sound SFX SoundSystem::PlaySFX(SoundSystem::SoundType::HoldCardSFX); } catch (std::out_of_range & exception) { // Hand Full std::cout << exception.what() << "\n"; pickedCard->first->TriggerWarning(); } break; default: break; } std::cout << "\n"; } // Player Hand Panel const auto triggeredPanel = m_playersPanel.GetIfTriggered(); if (triggeredPanel != nullptr) { std::for_each(m_panels.begin(), m_panels.end(), [](UIPanel* panel) {panel->SetInteractable(false); }); m_handPanel.SetUpHand(*triggeredPanel); m_handPanel.SetActive(true); if (triggeredPanel->GetPlayer()->GetId() == r_activePlayer.get().GetId()) m_handPanel.SetInteractable(true); } if (m_handPanel.CheckForClose())// closed { std::for_each(m_panels.begin(), m_panels.end() - 1, [](UIPanel* panel) {panel->SetInteractable(true); }); } else if (m_handPanel.IsActive())// opened { if (!m_tokensPanel.IsNumb())// allowed to buy { auto pickedExpansion = m_handPanel.GetPickedExpansion(); if (pickedExpansion.has_value()) { // Buy ExpansionCard from hand try { // Create logic ExpansionCard for pickedCard ExpansionCard pickedCardLogicPiece(static_cast<ExpansionCard::Level>(static_cast<uint16_t>(pickedExpansion.value()->GetType())), pickedExpansion.value()->GetID()); // Save picked card data const auto prestigePoints = pickedCardLogicPiece.GetPrestigePoints(); // Return & sync tokens p_board->ReturnTokens(r_activePlayer.get().GetHand().BuyExpansionCard(std::move(pickedCardLogicPiece))); m_tokensPanel.SyncTokens(p_board->GetTokensData()); // Add card's prestige points r_activePlayer.get().AddPrestigePoints(prestigePoints); m_playersPanel.AddPrestigePointsToCurrentPlayer(prestigePoints); // Sync Hand r_activePlayer.get().GetHand().RemoveExpansionCard(pickedExpansion.value()->GetID()); m_handPanel.SyncHand(); // Deactivate UI pickedExpansion.value()->Deactivate(); m_handPanel.NumbAllExpansions(); m_tokensPanel.NumbAll(); std::for_each(m_expansionPanels.begin(), m_expansionPanels.end(), [](std::reference_wrapper<UICardsRowPanel>& panel) {panel.get().NumbAll(); }); // Sound SFX SoundSystem::PlaySFX(SoundSystem::SoundType::BuyCardSFX); } catch (std::length_error & exception) { // Not enough resources std::cout << exception.what() << "\n"; pickedExpansion.value()->TriggerWarning(); } } } else// not allowed to buy { m_handPanel.NumbAllExpansions(); } } // Token Alert Panel if (m_tokensPanel.IsActive()) { m_tokenAlertPanel.Update(); if (m_tokenAlertPanel.GetConfirmed()) { // Transfer tokens p_board->ReturnTokens(m_tokenAlertPanel.GetTokensToReturn()); p_exceedingHand->RemoveTokens(m_tokenAlertPanel.GetTokensToReturn()); p_exceedingHand = nullptr; m_tokensPanel.SyncTokens(p_board->GetTokensData()); // UI std::for_each(m_panels.begin(), m_panels.end() - 1, [](UIPanel* panel) {panel->SetInteractable(true); }); m_tokenAlertPanel.SetConfirmed(false); m_tokenAlertPanel.SetActive(false); m_tokenAlertPanel.SetInteractable(false); } } } void UIGameSession::NextTurn() { // Validate Active Player Changes ValidateActivePlayerChanges(); CheckForExceedingTokens(); // UI Logic m_infoPanel.IncrementTurn(); PointToNextPlayer(); PrepareUI(); } void UIGameSession::NextTurnOnline() { // Validate Active Player Changes ValidateActivePlayerChanges(); CheckForExceedingTokens(); // UI Logic m_infoPanel.IncrementTurn(); PrepareUI(); } void UIGameSession::PointToNextPlayer() { m_playersPanel.PointToNextPlayer(); } void UIGameSession::CheckForExceedingTokens() { // Check if active player token stock exceeds token limit if (r_activePlayer.get().GetHand().ExceedsTokenLimit()) { std::for_each(m_panels.begin(), m_panels.end() - 1, [](UIPanel* panel) {panel->SetInteractable(false); }); m_tokenAlertPanel.SetActive(true); m_tokenAlertPanel.SetInteractable(true); p_exceedingHand = &r_activePlayer.get().GetHand(); m_tokenAlertPanel.SetInitialTokens(p_exceedingHand->GetTokensData()); } } void UIGameSession::SetActivePlayer(std::reference_wrapper<Player> activePlayerReference) { r_activePlayer = activePlayerReference; } void UIGameSession::SyncBoard() { m_tokensPanel.SyncTokens(p_board->GetTokensData()); m_noblesPanel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::Noble)); m_expansionsL3Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL3), 3); m_expansionsL2Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL2), 2); m_expansionsL1Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL1), 1); } void UIGameSession::SyncOnlineAdversaryPlayerPanel(uint16_t adversaryPrestigePoints) { m_playersPanel.SyncAdversaryPlayerPrestigePoints(adversaryPrestigePoints); } void UIGameSession::PassEvent(const sf::Event& event) { // iterate panel vector and handle events std::for_each(m_panels.begin(), m_panels.end(), [&event](UIPanel* panel) { panel->HandleEvent(event); }); } UIGameSession::Events UIGameSession::GetEvent() const { // Info Panel if (m_infoPanel.MenuButtonTriggered()) return Events::MenuButton; if (m_infoPanel.PassButtonTriggered()) return Events::PassButton; return Events::None; } void UIGameSession::draw(sf::RenderTarget& target, sf::RenderStates states) const { // iterate panel vector and draw panels std::for_each(m_panels.begin(), m_panels.end(), [&target](UIPanel* panel) { target.draw(*panel); }); // re-draw selected card on top of all drawables if (UISelectedCard::Get().first != nullptr) { target.draw(*UISelectedCard::Get().first); } // draw selected card text if (UISelectedCard::Get().second != nullptr) { target.draw(*UISelectedCard::Get().second); } } void UIGameSession::ValidateActivePlayerChanges() { // Nobles const auto wonNoble = m_noblesPanel.CheckForWonNoble(r_activePlayer.get().GetHand().GetResourcesData()); if (wonNoble.has_value()) { auto&& nobleCard = p_board->WinNoble(wonNoble.value().id); m_noblesPanel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::Noble), 0, true); r_activePlayer.get().AddPrestigePoints(nobleCard.GetPrestigePoints()); m_playersPanel.AddPrestigePointsToCurrentPlayer(nobleCard.GetPrestigePoints()); r_activePlayer.get().GetHand().AddNobleCard(std::move(nobleCard)); SoundSystem::PlaySFX(SoundSystem::SoundType::WinNobleSFX); std::cout << "WON NOBLE\n"; } // Reset picked Tokens buffer auto& pickedTokens = m_tokensPanel.ExtractPickedTokens(); for (auto& token : pickedTokens) { if (token.has_value()) { token.reset(); } } } void UIGameSession::PrepareUI() { // Prepare UI for next turn m_tokensPanel.UnNumb(); m_expansionsL3Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL3), 3); m_expansionsL2Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL2), 2); m_expansionsL1Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL1), 1); if (p_board->IsExpansionDeckEmpty(3)) { m_expansionsL3Panel.DisableDeckBackground(); } if (p_board->IsExpansionDeckEmpty(2)) { m_expansionsL2Panel.DisableDeckBackground(); } if (p_board->IsExpansionDeckEmpty(1)) { m_expansionsL1Panel.DisableDeckBackground(); } }
15,303
6,164
#include "../.././SourceTools/CodeManager/RCSFile.hh"
56
24
// // main.cpp // Game! // // Created by Sophia Nguyen on 2016-05-05. // Copyright © 2016 Sophia Nguyen. All rights reserved. // // The story! #include <iostream> #include <string> #include <cctype> #include <vector> #include "Character.hpp" using namespace std; int main() { string char_name; int age; string command; Character Char_1(char_name, age); cout << "Greetings. What is your name?" << "\n"; getline(cin, char_name); // get character's name cout << "How many years have you existed in this world?" << "\n"; cin >> age; // get character's age Char_1.setName(char_name); Char_1.setAge(age); cout << "\n\n" << "Hello, " << Char_1.getName() << ". A wise soul you are, your " << Char_1.getAge() << " years on this Earth will come in useful as you navigate through this adventure. To proceed, type in short commands as you think they might pretain to the environment and story you find yourself in. Have fun!" << "\n\n" << "You are in dark room, empty except for the wooden chair you sit on, a bare twin-sized bed in one corner, and a dim oil lamp sitting on a rickety night stand." << "\n\n"; while (command != "QUIT") { command.clear(); cin >> command; } return 0; }
1,294
429
#pragma once #include <EntityManager.hpp> #include <Components/Sprite.hpp> #include <Components/TileComponent.hpp> #include <array> #include <memory> class TileComponent; using ::Engine::ECS::Entity; using ::Engine::ECS::Component; using ::Engine::ECS::Sprite; using ::Engine::Math::Vector2i; using ::Engine::Math::operator+=; using ::Engine::Math::operator+; struct PieceComponent : Component { enum class Shape : uint8_t { I = 73, O = 79, J = 74, L = 76, T = 84, Z = 90, S = 83 } shape; PieceComponent() { for (auto &tile : tiles) { tile = ::std::make_unique<Entity>(entityManager->createEntity()); tile->addComponent<TileComponent>(); } } void activate() { for (auto &tile : tiles) { tile->activate(); tile->getComponent<TileComponent>().instance->activate(); } } void deactivate() { for (auto &tile : tiles) { tile->deactivate(); tile->getComponent<TileComponent>().instance->deactivate(); } } private: ::std::array<::std::unique_ptr<Entity>, 4> tiles{ nullptr }; Color color {0.1, 0.1, 0.1}; friend class PieceController; friend class CollisionSystem; friend class GridController; friend class GameController; };
1,312
435
#include "deferredrenderer.h" #include "irenderer.h" #include "quadmesh.h" #include "gl/shadermodule.h" #include "../utils/ioutils.h" #include "../settings.h" namespace TankGame { constexpr GLenum DeferredRenderer::COLOR_FORMAT; constexpr GLenum DeferredRenderer::NORMALS_AND_SPECULAR_FORMAT; constexpr GLenum DeferredRenderer::DISTORTION_BUFFER_FORMAT; constexpr GLenum DeferredRenderer::LIGHT_ACC_FORMAT; static ShaderProgram LoadCompositionShader() { ShaderModule fragmentShader = ShaderModule::FromFile( GetResDirectory() / "shaders" / "lighting" / "composition.fs.glsl", GL_FRAGMENT_SHADER); return ShaderProgram({ &QuadMesh::GetVertexShader(), &fragmentShader }); } DeferredRenderer::DeferredRenderer() : m_compositionShader(LoadCompositionShader()) { } void DeferredRenderer::CreateFramebuffer(int width, int height) { m_resolutionScale = Settings::GetInstance().GetResolutionScale(); double resScale = static_cast<double>(Settings::GetInstance().GetResolutionScale()) / 100.0; int scaledW = static_cast<double>(width) * resScale; int scaledH = static_cast<double>(height) * resScale; m_geometryFramebuffer = std::make_unique<Framebuffer>(); m_depthBuffer = std::make_unique<Renderbuffer>(scaledW, scaledH, GL_DEPTH_COMPONENT16); m_colorBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, COLOR_FORMAT); m_colorBuffer->SetupMipmapping(false); m_colorBuffer->SetWrapS(GL_CLAMP_TO_EDGE); m_colorBuffer->SetWrapT(GL_CLAMP_TO_EDGE); m_colorBuffer->SetMinFilter(GL_LINEAR); m_colorBuffer->SetMagFilter(GL_LINEAR); m_normalsAndSpecBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, NORMALS_AND_SPECULAR_FORMAT); m_normalsAndSpecBuffer->SetupMipmapping(false); m_normalsAndSpecBuffer->SetWrapS(GL_CLAMP_TO_EDGE); m_normalsAndSpecBuffer->SetWrapT(GL_CLAMP_TO_EDGE); m_normalsAndSpecBuffer->SetMinFilter(GL_LINEAR); m_normalsAndSpecBuffer->SetMagFilter(GL_LINEAR); m_distortionBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, DISTORTION_BUFFER_FORMAT); m_distortionBuffer->SetupMipmapping(false); m_distortionBuffer->SetWrapMode(GL_CLAMP_TO_EDGE); m_distortionBuffer->SetMinFilter(GL_LINEAR); m_distortionBuffer->SetMagFilter(GL_LINEAR); glNamedFramebufferTexture(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT0, m_colorBuffer->GetID(), 0); glNamedFramebufferTexture(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT1, m_normalsAndSpecBuffer->GetID(), 0); glNamedFramebufferTexture(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT2, m_distortionBuffer->GetID(), 0); glNamedFramebufferRenderbuffer(m_geometryFramebuffer->GetID(), GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthBuffer->GetID()); m_lightFramebuffer = std::make_unique<Framebuffer>(); m_lightAccBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, LIGHT_ACC_FORMAT); m_lightAccBuffer->SetupMipmapping(false); m_lightAccBuffer->SetWrapMode(GL_CLAMP_TO_EDGE); m_lightAccBuffer->SetMinFilter(GL_LINEAR); m_lightAccBuffer->SetMagFilter(GL_LINEAR); glNamedFramebufferTexture(m_lightFramebuffer->GetID(), GL_COLOR_ATTACHMENT0, m_lightAccBuffer->GetID(), 0); glNamedFramebufferDrawBuffer(m_lightFramebuffer->GetID(), GL_COLOR_ATTACHMENT0); m_outputFramebuffer = std::make_unique<Framebuffer>(); m_outputBuffer = std::make_unique<Texture2D>(width, height, 1, LIGHT_ACC_FORMAT); m_outputBuffer->SetupMipmapping(false); m_outputBuffer->SetWrapMode(GL_CLAMP_TO_EDGE); glNamedFramebufferTexture(m_outputFramebuffer->GetID(), GL_COLOR_ATTACHMENT0, m_outputBuffer->GetID(), 0); glNamedFramebufferDrawBuffer(m_outputFramebuffer->GetID(), GL_COLOR_ATTACHMENT0); m_postProcessor.OnResize(width, height); } bool DeferredRenderer::FramebufferOutOfDate() const { return m_resolutionScale != Settings::GetInstance().GetResolutionScale(); } void DeferredRenderer::Draw(const IRenderer& renderer, const class ViewInfo& viewInfo) const { Framebuffer::Save(); Framebuffer::Bind(*m_geometryFramebuffer, 0, 0, m_colorBuffer->GetWidth(), m_colorBuffer->GetHeight()); const float clearColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; const float depthClear = 1.0f; glEnable(GL_DEPTH_TEST); // ** Geometry pass ** GLenum geometryDrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; glNamedFramebufferDrawBuffers(m_geometryFramebuffer->GetID(), 2, geometryDrawBuffers); glDepthMask(GL_TRUE); glClearBufferfv(GL_COLOR, 0, clearColor); glClearBufferfv(GL_COLOR, 1, clearColor); glClearBufferfv(GL_DEPTH, 0, &depthClear); renderer.DrawGeometry(viewInfo); glEnablei(GL_BLEND, 0); glBlendFuncSeparatei(0, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE); glDepthMask(GL_FALSE); glNamedFramebufferDrawBuffer(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT0); renderer.DrawTranslucentGeometry(viewInfo); // ** Distortion pass ** glNamedFramebufferDrawBuffer(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT2); //Enables additive blending for this pass and the light accumulation pass glBlendFuncSeparatei(0, GL_ONE, GL_ONE, GL_ZERO, GL_ZERO); glClearBufferfv(GL_COLOR, 0, clearColor); renderer.DrawDistortions(viewInfo); glDisable(GL_DEPTH_TEST); // ** Light pass ** Framebuffer::Bind(*m_lightFramebuffer, 0, 0, m_lightAccBuffer->GetWidth(), m_lightAccBuffer->GetHeight()); m_normalsAndSpecBuffer->Bind(0); glClearBufferfv(GL_COLOR, 0, clearColor); renderer.DrawLighting(viewInfo); glDisablei(GL_BLEND, 0); // ** Composition pass ** Framebuffer::Bind(*m_outputFramebuffer, 0, 0, m_outputBuffer->GetWidth(), m_outputBuffer->GetHeight()); m_colorBuffer->Bind(0); m_lightAccBuffer->Bind(1); m_compositionShader.Use(); QuadMesh::GetInstance().GetVAO().Bind(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); m_particleRenderer.Begin(*m_lightAccBuffer); renderer.DrawParticles(viewInfo, m_particleRenderer); m_particleRenderer.End(); Framebuffer::Restore(); m_postProcessor.DoPostProcessing(*m_outputBuffer, *m_distortionBuffer); } }
6,126
2,468
/* Code for mounting the Dolphin SDK folder as a virtual disk. All the necessary data (BI2, Appldr, some DOL executable, we take from the SDK). If they are not there, then the disk is simply not mounted. */ #include "pch.h" using namespace Debug; namespace DVD { MountDolphinSdk::MountDolphinSdk(const wchar_t * DolphinSDKPath) { wcscpy(directory, DolphinSDKPath); // Load dvddata structure. // TODO: Generate Json dynamically auto dvdDataInfoText = Util::FileLoad(DvdDataJson); if (dvdDataInfoText.empty()) { Report(Channel::Norm, "Failed to load DolphinSDK dvddata json: %s\n", Util::WstringToString(DvdDataJson).c_str()); return; } try { DvdDataInfo.Deserialize(dvdDataInfoText.data(), dvdDataInfoText.size()); } catch (...) { Report(Channel::Norm, "Failed to Deserialize DolphinSDK dvddata json: %s\n", Util::WstringToString(DvdDataJson).c_str()); return; } // Generate data blobs if (!GenDiskId()) { Report(Channel::Norm, "Failed to GenDiskId\n"); return; } if (!GenApploader()) { Report(Channel::Norm, "Failed to GenApploader\n"); return; } if (!GenBi2()) { Report(Channel::Norm, "Failed to GenBi2\n"); return; } if (!GenFst()) { Report(Channel::Norm, "Failed to GenFst\n"); return; } if (!GenDol()) { Report(Channel::Norm, "Failed to GenDol\n"); return; } if (!GenBb2()) { Report(Channel::Norm, "Failed to GenBb2\n"); return; } // Generate mapping if (!GenMap()) { Report(Channel::Norm, "Failed to GenMap\n"); return; } if (!GenFileMap()) { Report(Channel::Norm, "Failed to GenFileMap\n"); return; } Report(Channel::DVD, "DolphinSDK mounted!\n"); mounted = true; } MountDolphinSdk::~MountDolphinSdk() { } void MountDolphinSdk::MapVector(std::vector<uint8_t>& v, uint32_t offset) { std::tuple<std::vector<uint8_t>&, uint32_t, size_t> entry(v, offset, v.size()); mapping.push_back(entry); } void MountDolphinSdk::MapFile(wchar_t* path, uint32_t offset) { size_t size = Util::FileSize(path); std::tuple<wchar_t*, uint32_t, size_t> entry(path, offset, size); fileMapping.push_back(entry); } // Check memory mapping uint8_t* MountDolphinSdk::TranslateMemory(uint32_t offset, size_t requestedSize, size_t& maxSize) { for (auto it = mapping.begin(); it != mapping.end(); ++it) { uint8_t * ptr = std::get<0>(*it).data(); uint32_t startingOffset = std::get<1>(*it); size_t size = std::get<2>(*it); if (startingOffset <= offset && offset < (startingOffset + size)) { maxSize = my_min(requestedSize, (startingOffset + size) - offset); return ptr + (offset - startingOffset); } } return nullptr; } // Check file mapping FILE * MountDolphinSdk::TranslateFile(uint32_t offset, size_t requestedSize, size_t& maxSize) { for (auto it = fileMapping.begin(); it != fileMapping.end(); ++it) { wchar_t* file = std::get<0>(*it); uint32_t startingOffset = std::get<1>(*it); size_t size = std::get<2>(*it); if (startingOffset <= offset && offset < (startingOffset + size)) { maxSize = my_min(requestedSize, (startingOffset + size) - offset); FILE* f; f = fopen( Util::WstringToString(file).c_str(), "rb"); assert(f); fseek(f, offset - startingOffset, SEEK_SET); return f; } } return nullptr; } void MountDolphinSdk::Seek(int position) { if (!mounted) return; assert(position >= 0 && position < DVD_SIZE); currentSeek = (uint32_t)position; } bool MountDolphinSdk::Read(void* buffer, size_t length) { bool result = true; assert(buffer); if (!mounted) { memset(buffer, 0, length); return true; } if (currentSeek >= DVD_SIZE) { memset(buffer, 0, length); return false; } size_t maxLength = 0; // First, try to enter the mapped binary blob, if it doesn't work, try the mapped file. uint8_t* ptr = TranslateMemory(currentSeek, length, maxLength); if (ptr != nullptr) { memcpy(buffer, ptr, maxLength); if (maxLength < length) { memset((uint8_t *)buffer + maxLength, 0, length - maxLength); } } else { FILE* f = TranslateFile(currentSeek, length, maxLength); if (f != nullptr) { fread(buffer, 1, maxLength, f); if (maxLength < length) { memset((uint8_t*)buffer + maxLength, 0, length - maxLength); } fclose(f); } else { // None of the options came up - return zeros. memset(buffer, 0, length); result = false; } } currentSeek += (uint32_t)length; return result; } #pragma region "Data Generators" // In addition to the actual files, the DVD image also contains a number of important binary data: DiskID, Apploader image, main program (DOL), BootInfo2 and BootBlock2 structures and FST. // Generating almost all blobs is straightforward, with the exception of the FST, which will have to tinker with. bool MountDolphinSdk::GenDiskId() { DiskId.resize(sizeof(DiskID)); DiskID* id = (DiskID*)DiskId.data(); id->gameName[0] = 'S'; id->gameName[1] = 'D'; id->gameName[2] = 'K'; id->gameName[3] = 'E'; id->company[0] = '0'; id->company[1] = '1'; id->magicNumber = _BYTESWAP_UINT32(DVD_DISKID_MAGIC); GameName.resize(0x400); memset(GameName.data(), 0, GameName.size()); strcpy((char *)GameName.data(), "GameCube SDK"); return true; } bool MountDolphinSdk::GenApploader() { auto path = fmt::format(L"{:s}{:s}", directory, AppldrPath); AppldrData = Util::FileLoad(path); return true; } /// <summary> /// Unfortunately, all demos in the SDK are in ELF format. Therefore, we will use PONG.DOL as the main program, which is included in each Dolwin release and is a full resident of the project :p /// </summary> /// <returns></returns> bool MountDolphinSdk::GenDol() { Dol = Util::FileLoad(DolPath); return true; } bool MountDolphinSdk::GenBi2() { auto path = fmt::format(L"{:s}{:s}", directory, Bi2Path); Bi2Data = Util::FileLoad(path); return true; } /// <summary> /// Add a string with the name of the entry (directory or file name) to the NameTable. /// </summary> /// <param name="str"></param> void MountDolphinSdk::AddString(std::string str) { for (auto& c : str) { NameTableData.push_back(c); } NameTableData.push_back(0); } /// <summary> /// Process original Json with dvddata directory structure. The Json structure is designed to accommodate the weird FST feature when a directory is in the middle of files. /// For a more detailed description of this oddity, see `dolwin-docs\RE\DVD\FSTNotes.md`. /// The method is recursive tree descent. /// In the process, meta information is added to the original Json structure, which is used by the `WalkAndGenerateFst` method to create the final binary FST blob. /// </summary> /// <param name="entry"></param> void MountDolphinSdk::ParseDvdDataEntryForFst(Json::Value* entry) { Json::Value* parent = nullptr; if (entry->type != Json::ValueType::Object) { return; } if (entry->children.size() != 0) { // Directory // Save directory name offset size_t nameOffset = NameTableData.size(); if (entry->name) { // Root has no name AddString(entry->name); } entry->AddInt("nameOffset", (int)nameOffset); entry->AddBool("dir", true); // Save current FST index for directory entry->AddInt("entryId", entryCounter); entryCounter++; // Reset totalChildren counter entry->AddInt("totalChildren", 0); } else { // File. // Differs from a directory in that it has no descendants assert(entry->name); std::string path = entry->name; size_t nameOffset = NameTableData.size(); AddString(path); parent = entry->parent; // Save file name offset entry->AddInt("nameOffset", (int)nameOffset); // Generate full path to file do { if (parent->ByName("dir")) { path = (parent->name ? parent->name + std::string("/") : "/") + path; } parent = parent->parent; } while (parent != nullptr); assert(path.size() < DVD_MAXPATH); wchar_t filePath[0x1000] = { 0, }; wcscat(filePath, directory); wcscat(filePath, FilesRoot); wchar_t* filePathPtr = filePath + wcslen(filePath); for (size_t i = 0; i < path.size(); i++) { *filePathPtr++ = (wchar_t)path[i]; } *filePathPtr++ = 0; //Report(Channel::Norm, "Processing file: %s\n", path.c_str()); // Save file offset entry->AddInt("fileOffset", userFilesStart + userFilesOffset); // Save file size size_t fileSize = Util::FileSize(filePath); entry->AddInt("fileSize", (int)fileSize); userFilesOffset += RoundUp32((uint32_t)fileSize); // Save file path entry->AddString("filePath", filePath); // Adjust entry counter entry->AddInt("entryId", entryCounter); entryCounter++; } // Update parent sibling counters parent = entry->parent; while (parent) { Json::Value* totalChildren = parent->ByName("totalChildren"); if (totalChildren) totalChildren->value.AsInt++; parent = parent->parent; // :p } // Recursively process descendants if (entry->ByName("dir") != nullptr) { for (auto it = entry->children.begin(); it != entry->children.end(); ++it) { ParseDvdDataEntryForFst(*it); } } } /// <summary> /// Based on the Json structure with the data of the dvddata directory tree, in which meta-information is added, the final FST binary blob is built. /// </summary> /// <param name="entry"></param> void MountDolphinSdk::WalkAndGenerateFst(Json::Value* entry) { DVDFileEntry fstEntry = { 0 }; if (entry->type != Json::ValueType::Object) { return; } Json::Value* isDir = entry->ByName("dir"); if (isDir) { // Directory fstEntry.isDir = 1; Json::Value* nameOffset = entry->ByName("nameOffset"); assert(nameOffset); if (nameOffset) { fstEntry.nameOffsetHi = (uint8_t)(nameOffset->value.AsInt >> 16); fstEntry.nameOffsetLo = _BYTESWAP_UINT16((uint16_t)nameOffset->value.AsInt); } if (entry->parent) { Json::Value* parentId = entry->parent->ByName("entryId"); if (parentId) { fstEntry.parentOffset = _BYTESWAP_UINT32((uint32_t)parentId->value.AsInt); } } Json::Value* entryId = entry->ByName("entryId"); Json::Value* totalChildren = entry->ByName("totalChildren"); if (entryId && totalChildren) { fstEntry.nextOffset = _BYTESWAP_UINT32((uint32_t)(entryId->value.AsInt + totalChildren->value.AsInt) + 1); } FstData.insert(FstData.end(), (uint8_t*)&fstEntry, (uint8_t*)&fstEntry + sizeof(fstEntry)); if (logMount) { Report(Channel::Norm, "%d: directory: %s. nextOffset: %d\n", entryId->value.AsInt, entry->name, _BYTESWAP_UINT32(fstEntry.nextOffset)); } for (auto it = entry->children.begin(); it != entry->children.end(); ++it) { WalkAndGenerateFst(*it); } } else { // File Json::Value* entryId = entry->ByName("entryId"); Json::Value* nameOffsetValue = entry->ByName("nameOffset"); Json::Value* fileOffsetValue = entry->ByName("fileOffset"); Json::Value* fileSizeValue = entry->ByName("fileSize"); assert(nameOffsetValue && fileOffsetValue && fileSizeValue); fstEntry.isDir = 0; uint32_t nameOffset = (uint32_t)(nameOffsetValue->value.AsInt); uint32_t fileOffset = (uint32_t)(fileOffsetValue->value.AsInt); uint32_t fileSize = (uint32_t)(fileSizeValue->value.AsInt); fstEntry.nameOffsetHi = (uint8_t)(nameOffset >> 16); fstEntry.nameOffsetLo = _BYTESWAP_UINT16((uint16_t)nameOffset); fstEntry.fileOffset = _BYTESWAP_UINT32(fileOffset); fstEntry.fileLength = _BYTESWAP_UINT32(fileSize); FstData.insert(FstData.end(), (uint8_t*)&fstEntry, (uint8_t*)&fstEntry + sizeof(fstEntry)); if (logMount) { Report(Channel::Norm, "%d: file: %s\n", entryId->value.AsInt, entry->name); } } } // The basic idea behind generating FST is to walk by DvdDataJson. // When traversing a structure a specific meta-information is attached to each node. // After generation, this meta-information is collected in a final collection (FST). bool MountDolphinSdk::GenFst() { try { ParseDvdDataEntryForFst(DvdDataInfo.root.children.back()); } catch (...) { Report(Channel::Norm, "ParseDvdDataEntryForFst failed!\n"); return false; } if (logMount) { JDI::Hub.Dump(DvdDataInfo.root.children.back()); } try { WalkAndGenerateFst(DvdDataInfo.root.children.back()); } catch (...) { Report(Channel::Norm, "WalkAndGenerateFst failed!\n"); return false; } // Add Name Table to the end FstData.insert(FstData.end(), NameTableData.begin(), NameTableData.end()); Util::FileSave(L"Data/DolphinSdkFST.bin", FstData); return true; } bool MountDolphinSdk::GenBb2() { DVDBB2 bb2 = { 0 }; bb2.bootFilePosition = RoundUpSector(DVD_APPLDR_OFFSET + (uint32_t)AppldrData.size()); bb2.FSTLength = (uint32_t)FstData.size(); bb2.FSTMaxLength = bb2.FSTLength; bb2.FSTPosition = RoundUpSector(bb2.bootFilePosition + (uint32_t)Dol.size() + DVD_SECTOR_SIZE); bb2.userPosition = 0x80030000; // Ignored bb2.userLength = RoundUpSector(bb2.FSTLength); Bb2Data.resize(sizeof(DVDBB2)); memcpy(Bb2Data.data(), &bb2, sizeof(bb2)); return true; } bool MountDolphinSdk::GenMap() { MapVector(DiskId, DVD_ID_OFFSET); MapVector(GameName, sizeof(DiskID)); MapVector(Bb2Data, DVD_BB2_OFFSET); MapVector(Bi2Data, DVD_BI2_OFFSET); MapVector(AppldrData, DVD_APPLDR_OFFSET); DVDBB2* bb2 = (DVDBB2 *)Bb2Data.data(); MapVector(Dol, bb2->bootFilePosition); MapVector(FstData, bb2->FSTPosition); SwapArea(bb2, sizeof(DVDBB2)); return true; } void MountDolphinSdk::WalkAndMapFiles(Json::Value* entry) { if (entry->type != Json::ValueType::Object) { return; } Json::Value* isDir = entry->ByName("dir"); if (!isDir) { Json::Value* filePath = entry->ByName("filePath"); Json::Value* fileOffset = entry->ByName("fileOffset"); assert(filePath && fileOffset); MapFile(filePath->value.AsString, (uint32_t)(fileOffset->value.AsInt)); } else { for (auto it = entry->children.begin(); it != entry->children.end(); ++it) { WalkAndMapFiles(*it); } } } bool MountDolphinSdk::GenFileMap() { userFilesOffset = 0; try { WalkAndMapFiles(DvdDataInfo.root.children.back()); } catch (...) { Report(Channel::Norm, "WalkAndMapFiles failed!\n"); return false; } return true; } void MountDolphinSdk::SwapArea(void* _addr, int sizeInBytes) { uint32_t* addr = (uint32_t*)_addr; uint32_t* until = addr + sizeInBytes / sizeof(uint32_t); while (addr != until) { *addr = _BYTESWAP_UINT32(*addr); addr++; } } #pragma endregion "Data Generators" }
14,820
6,263
/* inputreader_tests.cpp %{Cpp:License:ClassName} - Yann BOUCHER (yann) 20 ** ** ** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE ** Version 2, December 2004 ** ** Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> ** ** Everyone is permitted to copy and distribute verbatim or modified ** copies of this license document, and changing it is allowed as long ** as the name is changed. ** ** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE ** TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION ** ** 0. You just DO WHAT THE FUCK YOU WANT TO. */ #include "gtest/gtest.h" #include "inputreader.hpp" #include "terminal.hpp" MAKE_TERMINAL(DummyToken) MAKE_TERMINAL(TargetToken) namespace { TEST(InputReaderFailure, NoMoreTokens) { InputReader reader; EXPECT_THROW(reader.fetch<Terminal>(), ParseError); } TEST(InputReaderFailure, InvalidToken) { std::vector<std::unique_ptr<Terminal>> tokens; tokens.emplace_back(std::make_unique<DummyToken>()); InputReader reader(std::move(tokens)); reader.set_failure_policy(InputReader::FailurePolicy::Strict); EXPECT_THROW(reader.fetch<TargetToken>(), ParseError); } }
1,240
440
#pragma once #include "../../../JObject.hpp" namespace android::app::appsearch { class SetSchemaResponse : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit SetSchemaResponse(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} SetSchemaResponse(QJniObject obj); // Constructors // Methods JObject getDeletedTypes() const; JObject getIncompatibleTypes() const; JObject getMigratedTypes() const; JObject getMigrationFailures() const; }; } // namespace android::app::appsearch
604
210
/*ckwg +5 * Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "qtAbstractSetting.h" #include <QSettings> //----------------------------------------------------------------------------- qtAbstractSetting::qtAbstractSetting() : modified(false) { } //----------------------------------------------------------------------------- qtAbstractSetting::~qtAbstractSetting() { } //----------------------------------------------------------------------------- void qtAbstractSetting::initialize(const QSettings&) { this->currentValue = this->originalValue; } //----------------------------------------------------------------------------- bool qtAbstractSetting::isModified() { return this->modified; } //----------------------------------------------------------------------------- QVariant qtAbstractSetting::value() const { return this->currentValue; } //----------------------------------------------------------------------------- void qtAbstractSetting::setValue(const QVariant& value) { this->currentValue = value; this->modified = (this->currentValue != this->originalValue); } //----------------------------------------------------------------------------- void qtAbstractSetting::commit(QSettings& store) { store.setValue(this->key(), this->currentValue); this->originalValue = this->currentValue; this->modified = false; } //----------------------------------------------------------------------------- void qtAbstractSetting::discard() { this->currentValue = this->originalValue; this->modified = false; }
1,711
423
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #include "audit.h" #include <logger/logger.h> #include <memcached/audit_interface.h> #include <platform/socket.h> #include <stdexcept> namespace cb::audit { UniqueAuditPtr create_audit_daemon(const std::string& config_file, ServerCookieIface* server_cookie_api) { if (!cb::logger::isInitialized()) { throw std::invalid_argument( "create_audit_daemon: logger must have been created"); } try { return std::make_unique<AuditImpl>( config_file, server_cookie_api, cb::net::getHostname()); } catch (std::runtime_error& err) { LOG_WARNING("{}", err.what()); } catch (std::bad_alloc&) { LOG_WARNING("Failed to start audit: Out of memory"); } return {}; } } // namespace cb::audit
1,290
417
#include"competitive.h" using namespace std; template<typename T> class Graph{ map<T,list<T>>m; public: void insert(T u,T v){ m[u].push_back(v); } void bfs(T src,T dest){ deque<T>q; map<T,int>dist; map<T,T>parent; q.push_back(src); for(auto &i : m){ T node = i.first; dist[node] = INT_MAX; } dist[src]=0; parent[src] = src; //cout<<dist[src]<<endl; while(!q.empty()){ const list<T> &bucket = m[q.front()]; for( const auto &i: bucket){ int d = dist[q.front()]; if(dist[i]==INT_MAX){ q.push_back(i); dist[i] = d+1; parent[i] = q.front(); } } //cout<<q.front()<<" "; q.pop_front(); } //cout<<endl; // for(auto i: m){ // T node = i.first; // cout<<src<<"-"<<node<<"="<<dist[node]<<endl; // } cout<<dist[dest]<<endl; int par = dest; while(par!=src){ cout<<par<<"<-"; par = parent[par]; } cout<<par<<endl; } }; int main(){ IOS; //ladder and snakes int board[50]{0}; board[2] = 13; board[5] = 2; board[9] = 18; board[17] = -13; board[18] = 11; board[20] = -14; board[24] = -8; board[25] = 10; board[32] = -2; board[34] = -22; //Graph Graph<int>g; for(int i=0;i<=36;i++){ if(board[i]!=0){ continue; } for(int dice=1;dice<=6;dice++){ int j = i+dice; j+=board[j]; if(j<=36) g.insert(i,j); } } g.insert(36,36); g.bfs(0,36); return 0; }
1,837
705
#pragma once #include <clap/clap.h> namespace clap { class CorePlugin; class AbstractGuiListener; class AbstractGui { public: AbstractGui(AbstractGuiListener &listener); virtual ~AbstractGui(); virtual void defineParameter(const clap_param_info &paramInfo) = 0; virtual void updateParameter(clap_id paramId, double value, double modAmount) = 0; virtual void clearTransport() = 0; virtual void updateTransport(const clap_event_transport &transport) = 0; virtual bool attachCocoa(void *nsView) = 0; virtual bool attachWin32(clap_hwnd window) = 0; virtual bool attachX11(const char *displayName, unsigned long window) = 0; virtual bool size(uint32_t *width, uint32_t *height) = 0; virtual bool setScale(double scale) = 0; virtual bool show() = 0; virtual bool hide() = 0; virtual void destroy() = 0; protected: AbstractGuiListener &_listener; bool _isTransportSubscribed = false; }; } // namespace clap
1,025
317
#include <iostream> //循环结构 int main(int argc, char const *argv[]) { //输出小于a的自然数 int a; std::cout << "请输入一个整数"; std::cin >> a; if (a > 0) { for (int i = 0; i < a; ++i) { std::cout << i << std::endl; } } else { std::cout << "不得小于1"; } }
255
150
/******************************************************************************* * Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II * Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI * * Distributed under the Boost Software License, Version 0x01.0. * See accompanying file LICENSE.txt or copy at * http://www.boost.org/LICENSE_1_0.txt ******************************************************************************/ #define NT2_UNIT_MODULE "boost::simd::memory::load and store" #include <boost/mpl/int.hpp> #include <boost/simd/sdk/simd/native.hpp> #include <boost/simd/include/functions/load.hpp> #include <boost/simd/include/functions/store.hpp> #include <boost/simd/include/functions/unaligned_load.hpp> #include <boost/simd/include/functions/unaligned_store.hpp> #include <boost/simd/sdk/config/types.hpp> #include <boost/simd/sdk/config/type_lists.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/unit/tests/relation.hpp> //////////////////////////////////////////////////////////////////////////////// // Test load behavior //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE_TPL(load, BOOST_SIMD_TYPES) { using boost::simd::load; T data[5] = {0,1,2,3,4}; NT2_TEST_EQUAL( (load<T,-4>(&data[0],4)), T(0) ); NT2_TEST_EQUAL( (load<T,-4>(&data[0],5)), T(1) ); NT2_TEST_EQUAL( (load<T,-4>(&data[0],6)), T(2) ); NT2_TEST_EQUAL( (load<T,-4>(&data[0],7)), T(3) ); NT2_TEST_EQUAL( (load<T,-4>(&data[0],8)), T(4) ); NT2_TEST_EQUAL( (load<T,-3>(&data[0],3)), T(0) ); NT2_TEST_EQUAL( (load<T,-3>(&data[0],4)), T(1) ); NT2_TEST_EQUAL( (load<T,-3>(&data[0],5)), T(2) ); NT2_TEST_EQUAL( (load<T,-3>(&data[0],6)), T(3) ); NT2_TEST_EQUAL( (load<T,-3>(&data[0],7)), T(4) ); NT2_TEST_EQUAL( (load<T,-2>(&data[0],2)), T(0) ); NT2_TEST_EQUAL( (load<T,-2>(&data[0],3)), T(1) ); NT2_TEST_EQUAL( (load<T,-2>(&data[0],4)), T(2) ); NT2_TEST_EQUAL( (load<T,-2>(&data[0],5)), T(3) ); NT2_TEST_EQUAL( (load<T,-2>(&data[0],6)), T(4) ); NT2_TEST_EQUAL( (load<T,-1>(&data[0],1)), T(0) ); NT2_TEST_EQUAL( (load<T,-1>(&data[0],2)), T(1) ); NT2_TEST_EQUAL( (load<T,-1>(&data[0],3)), T(2) ); NT2_TEST_EQUAL( (load<T,-1>(&data[0],4)), T(3) ); NT2_TEST_EQUAL( (load<T,-1>(&data[0],5)), T(4) ); NT2_TEST_EQUAL( load<T>(&data[0],0), T(0) ); NT2_TEST_EQUAL( load<T>(&data[0],1), T(1) ); NT2_TEST_EQUAL( load<T>(&data[0],2), T(2) ); NT2_TEST_EQUAL( load<T>(&data[0],3), T(3) ); NT2_TEST_EQUAL( load<T>(&data[0],4), T(4) ); NT2_TEST_EQUAL( (load<T,0>(&data[0],0)), T(0) ); NT2_TEST_EQUAL( (load<T,0>(&data[0],1)), T(1) ); NT2_TEST_EQUAL( (load<T,0>(&data[0],2)), T(2) ); NT2_TEST_EQUAL( (load<T,0>(&data[0],3)), T(3) ); NT2_TEST_EQUAL( (load<T,0>(&data[0],4)), T(4) ); NT2_TEST_EQUAL( (load<T,1>(&data[0],-1)), T(0) ); NT2_TEST_EQUAL( (load<T,1>(&data[0],0)) , T(1) ); NT2_TEST_EQUAL( (load<T,1>(&data[0],1)) , T(2) ); NT2_TEST_EQUAL( (load<T,1>(&data[0],2)) , T(3) ); NT2_TEST_EQUAL( (load<T,1>(&data[0],3)) , T(4) ); NT2_TEST_EQUAL( (load<T,2>(&data[0],-2)), T(0) ); NT2_TEST_EQUAL( (load<T,2>(&data[0],-1)), T(1) ); NT2_TEST_EQUAL( (load<T,2>(&data[0],0)) , T(2) ); NT2_TEST_EQUAL( (load<T,2>(&data[0],1)) , T(3) ); NT2_TEST_EQUAL( (load<T,2>(&data[0],2)) , T(4) ); NT2_TEST_EQUAL( (load<T,3>(&data[0],-3)), T(0) ); NT2_TEST_EQUAL( (load<T,3>(&data[0],-2)), T(1) ); NT2_TEST_EQUAL( (load<T,3>(&data[0],-1)), T(2) ); NT2_TEST_EQUAL( (load<T,3>(&data[0],0)) , T(3) ); NT2_TEST_EQUAL( (load<T,3>(&data[0],1)) , T(4) ); NT2_TEST_EQUAL( (load<T,4>(&data[0],-4)), T(0) ); NT2_TEST_EQUAL( (load<T,4>(&data[0],-3)), T(1) ); NT2_TEST_EQUAL( (load<T,4>(&data[0],-2)), T(2) ); NT2_TEST_EQUAL( (load<T,4>(&data[0],-1)), T(3) ); NT2_TEST_EQUAL( (load<T,4>(&data[0],0)) , T(4) ); } //////////////////////////////////////////////////////////////////////////////// // Test store behavior //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE_TPL(store, BOOST_SIMD_TYPES) { using boost::simd::store; T data[5]; for(boost::simd::int32_t i=0;i<5;++i) store(static_cast<T>(i),&data[0],i); NT2_TEST_EQUAL( data[0], T(0) ); NT2_TEST_EQUAL( data[1], T(1) ); NT2_TEST_EQUAL( data[2], T(2) ); NT2_TEST_EQUAL( data[3], T(3) ); NT2_TEST_EQUAL( data[4], T(4) ); } //////////////////////////////////////////////////////////////////////////////// // Test unaligned_load behavior //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE_TPL(unaligned_load, BOOST_SIMD_TYPES) { using boost::simd::unaligned_load; T data[5] = {0,1,2,3,4}; NT2_TEST_EQUAL( (unaligned_load<T,-4>(&data[0],4)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,-4>(&data[0],5)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,-4>(&data[0],6)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,-4>(&data[0],7)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,-4>(&data[0],8)), T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,-3>(&data[0],3)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,-3>(&data[0],4)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,-3>(&data[0],5)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,-3>(&data[0],6)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,-3>(&data[0],7)), T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,-2>(&data[0],2)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,-2>(&data[0],3)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,-2>(&data[0],4)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,-2>(&data[0],5)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,-2>(&data[0],6)), T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,-1>(&data[0],1)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,-1>(&data[0],2)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,-1>(&data[0],3)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,-1>(&data[0],4)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,-1>(&data[0],5)), T(4) ); NT2_TEST_EQUAL( unaligned_load<T>(&data[0],0), T(0) ); NT2_TEST_EQUAL( unaligned_load<T>(&data[0],1), T(1) ); NT2_TEST_EQUAL( unaligned_load<T>(&data[0],2), T(2) ); NT2_TEST_EQUAL( unaligned_load<T>(&data[0],3), T(3) ); NT2_TEST_EQUAL( unaligned_load<T>(&data[0],4), T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,0>(&data[0],0)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,0>(&data[0],1)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,0>(&data[0],2)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,0>(&data[0],3)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,0>(&data[0],4)), T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,1>(&data[0],-1)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,1>(&data[0],0)) , T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,1>(&data[0],1)) , T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,1>(&data[0],2)) , T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,1>(&data[0],3)) , T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,2>(&data[0],-2)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,2>(&data[0],-1)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,2>(&data[0],0)) , T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,2>(&data[0],1)) , T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,2>(&data[0],2)) , T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,3>(&data[0],-3)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,3>(&data[0],-2)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,3>(&data[0],-1)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,3>(&data[0],0)) , T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,3>(&data[0],1)) , T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,4>(&data[0],-4)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,4>(&data[0],-3)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,4>(&data[0],-2)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,4>(&data[0],-1)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,4>(&data[0],0)) , T(4) ); } //////////////////////////////////////////////////////////////////////////////// // Test unaligned_store behavior //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE_TPL(unaligned_store, BOOST_SIMD_TYPES) { using boost::simd::unaligned_store; T data[5]; for(boost::simd::int32_t i=0;i<5;++i) unaligned_store(static_cast<T>(i),&data[0],i); NT2_TEST_EQUAL( data[0], T(0) ); NT2_TEST_EQUAL( data[1], T(1) ); NT2_TEST_EQUAL( data[2], T(2) ); NT2_TEST_EQUAL( data[3], T(3) ); NT2_TEST_EQUAL( data[4], T(4) ); }
8,388
4,217
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Dumper.h> // Moved to the top because AssetSerializer requires include for the SerializeContext #include <AzCore/Asset/AssetSerializer.h> #include <AzCore/Casting/lossy_cast.h> #include <AzCore/Debug/Trace.h> #include <AzCore/IO/Path/Path.h> #include <AzCore/IO/SystemFile.h> #include <AzCore/JSON/stringbuffer.h> #include <AzCore/JSON/prettywriter.h> #include <AzCore/Serialization/EditContext.h> #include <AzCore/Settings/SettingsRegistryMergeUtils.h> #include <AzCore/std/algorithm.h> #include <AzCore/std/sort.h> #include <AzCore/StringFunc/StringFunc.h> #include <Application.h> #include <Utilities.h> namespace AZ::SerializeContextTools { bool Dumper::DumpFiles(Application& application) { SerializeContext* sc = application.GetSerializeContext(); if (!sc) { AZ_Error("SerializeContextTools", false, "No serialize context found."); return false; } AZStd::string outputFolder = Utilities::ReadOutputTargetFromCommandLine(application); AZ::IO::Path sourceGameFolder; if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { settingsRegistry->Get(sourceGameFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectPath); } bool result = true; AZStd::vector<AZStd::string> fileList = Utilities::ReadFileListFromCommandLine(application, "files"); for (const AZStd::string& filePath : fileList) { AZ_Printf("DumpFiles", "Dumping file '%.*s'\n", aznumeric_cast<int>(filePath.size()), filePath.data()); AZ::IO::FixedMaxPath outputPath{ AZStd::string_view{ outputFolder }}; outputPath /= AZ::IO::FixedMaxPath(filePath).LexicallyRelative(sourceGameFolder); outputPath.Native() += ".dump.txt"; IO::SystemFile outputFile; if (!outputFile.Open(outputPath.c_str(), IO::SystemFile::OpenMode::SF_OPEN_CREATE | IO::SystemFile::OpenMode::SF_OPEN_CREATE_PATH | IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY)) { AZ_Error("SerializeContextTools", false, "Unable to open file '%s' for writing.", outputPath.c_str()); result = false; continue; } AZStd::string content; content.reserve(1 * 1024 * 1024); // Reserve 1mb to avoid frequently resizing the string. auto callback = [&content, &result](void* classPtr, const Uuid& classId, SerializeContext* context) { result = DumpClassContent(content, classPtr, classId, context) && result; const SerializeContext::ClassData* classData = context->FindClassData(classId); if (classData && classData->m_factory) { classData->m_factory->Destroy(classPtr); } else { AZ_Error("SerializeContextTools", false, "Missing class factory, so data will leak."); result = false; } }; if (!Utilities::InspectSerializedFile(filePath.c_str(), sc, callback)) { result = false; continue; } outputFile.Write(content.data(), content.length()); } return result; } bool Dumper::DumpSerializeContext(Application& application) { AZStd::string outputPath = Utilities::ReadOutputTargetFromCommandLine(application, "SerializeContext.json"); AZ_Printf("dumpsc", "Writing Serialize Context at '%s'.\n", outputPath.c_str()); IO::SystemFile outputFile; if (!outputFile.Open(outputPath.c_str(), IO::SystemFile::OpenMode::SF_OPEN_CREATE | IO::SystemFile::OpenMode::SF_OPEN_CREATE_PATH | IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY)) { AZ_Error("SerializeContextTools", false, "Unable to open output file '%s'.", outputPath.c_str()); return false; } SerializeContext* context = application.GetSerializeContext(); AZStd::vector<Uuid> systemComponents = Utilities::GetSystemComponents(application); AZStd::sort(systemComponents.begin(), systemComponents.end()); rapidjson::Document doc; rapidjson::Value& root = doc.SetObject(); rapidjson::Value scObject; scObject.SetObject(); AZStd::string temp; temp.reserve(256 * 1024); // Reserve 256kb of memory to avoid the string constantly resizing. bool result = true; auto callback = [context, &doc, &scObject, &temp, &systemComponents, &result](const SerializeContext::ClassData* classData, const Uuid& /*typeId*/) -> bool { if (!DumpClassContent(classData, scObject, doc, systemComponents, context, temp)) { result = false; } return true; }; context->EnumerateAll(callback, true); root.AddMember("SerializeContext", AZStd::move(scObject), doc.GetAllocator()); rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); outputFile.Write(buffer.GetString(), buffer.GetSize()); outputFile.Close(); return result; } AZStd::vector<Uuid> Dumper::CreateFilterListByNames(SerializeContext* context, AZStd::string_view name) { AZStd::vector<AZStd::string_view> names; auto AppendNames = [&names](AZStd::string_view filename) { names.emplace_back(filename); }; AZ::StringFunc::TokenizeVisitor(name, AppendNames, ';'); AZStd::vector<Uuid> filterIds; filterIds.reserve(names.size()); for (const AZStd::string_view& singleName : names) { AZStd::vector<Uuid> foundFilters = context->FindClassId(Crc32(singleName.data(), singleName.length(), true)); filterIds.insert(filterIds.end(), foundFilters.begin(), foundFilters.end()); } return filterIds; } AZStd::string_view Dumper::ExtractNamespace(const AZStd::string& name) { size_t offset = 0; const char* startChar = name.data(); const char* currentChar = name.data(); while (*currentChar != 0 && *currentChar != '<') { if (*currentChar != ':') { ++currentChar; } else { ++currentChar; if (*currentChar == ':') { AZ_Assert(currentChar - startChar >= 1, "Offset out of bounds while trying to extract namespace from name '%s'.", name.c_str()); offset = currentChar - startChar - 1; // -1 to exclude the last "::" } } } return AZStd::string_view(startChar, offset); } rapidjson::Value Dumper::WriteToJsonValue(const Uuid& uuid, rapidjson::Document& document) { char buffer[Uuid::MaxStringBuffer]; int writtenCount = uuid.ToString(buffer, AZ_ARRAY_SIZE(buffer)); if (writtenCount > 0) { return rapidjson::Value(buffer, writtenCount - 1, document.GetAllocator()); //-1 as the null character shouldn't be written. } else { return rapidjson::Value(rapidjson::StringRef("{uuid conversion failed}")); } } bool Dumper::DumpClassContent(const SerializeContext::ClassData* classData, rapidjson::Value& parent, rapidjson::Document& document, const AZStd::vector<Uuid>& systemComponents, SerializeContext* context, AZStd::string& scratchStringBuffer) { AZ_Assert(scratchStringBuffer.empty(), "Provided scratch string buffer wasn't empty."); rapidjson::Value classNode(rapidjson::kObjectType); DumpClassName(classNode, context, classData, document, scratchStringBuffer); Edit::ClassData* editData = classData->m_editData; GenericClassInfo* genericClassInfo = context->FindGenericClassInfo(classData->m_typeId); if (editData && editData->m_description) { AZStd::string_view description = editData->m_description; // Skipping if there's only one character as there are several cases where a blank description is given. if (description.size() > 1) { classNode.AddMember("Description", rapidjson::Value(description.data(), document.GetAllocator()), document.GetAllocator()); } } classNode.AddMember("Id", rapidjson::StringRef(classData->m_name), document.GetAllocator()); classNode.AddMember("Version", classData->IsDeprecated() ? rapidjson::Value(rapidjson::StringRef("Deprecated")) : rapidjson::Value(classData->m_version), document.GetAllocator()); auto systemComponentIt = AZStd::lower_bound(systemComponents.begin(), systemComponents.end(), classData->m_typeId); bool isSystemComponent = systemComponentIt != systemComponents.end() && *systemComponentIt == classData->m_typeId; classNode.AddMember("IsSystemComponent", isSystemComponent, document.GetAllocator()); classNode.AddMember("IsPrimitive", Utilities::IsSerializationPrimitive(genericClassInfo ? genericClassInfo->GetGenericTypeId() : classData->m_typeId), document.GetAllocator()); classNode.AddMember("IsContainer", classData->m_container != nullptr, document.GetAllocator()); if (genericClassInfo) { classNode.AddMember("GenericUuid", WriteToJsonValue(genericClassInfo->GetGenericTypeId(), document), document.GetAllocator()); classNode.AddMember("Generics", DumpGenericStructure(genericClassInfo, context, document, scratchStringBuffer), document.GetAllocator()); } if (!classData->m_elements.empty()) { rapidjson::Value fields(rapidjson::kArrayType); rapidjson::Value bases(rapidjson::kArrayType); for (const SerializeContext::ClassElement& element : classData->m_elements) { DumpElementInfo(element, classData, context, fields, bases, document, scratchStringBuffer); } if (!bases.Empty()) { classNode.AddMember("Bases", AZStd::move(bases), document.GetAllocator()); } if (!fields.Empty()) { classNode.AddMember("Fields", AZStd::move(fields), document.GetAllocator()); } } parent.AddMember(WriteToJsonValue(classData->m_typeId, document), AZStd::move(classNode), document.GetAllocator()); return true; } bool Dumper::DumpClassContent(AZStd::string& output, void* classPtr, const Uuid& classId, SerializeContext* context) { const SerializeContext::ClassData* classData = context->FindClassData(classId); if (!classData) { AZ_Printf("", " Class data for '%s' is missing.\n", classId.ToString<AZStd::string>().c_str()); return false; } size_t indention = 0; auto begin = [context, &output, &indention](void* /*instance*/, const SerializeContext::ClassData* classData, const SerializeContext::ClassElement* classElement) -> bool { for (size_t i = 0; i < indention; ++i) { output += ' '; } if (classData) { output += classData->m_name; } DumpElementInfo(output, classElement, context); DumpPrimitiveTag(output, classData, classElement); output += '\n'; indention += 2; return true; }; auto end = [&indention]() -> bool { indention = indention > 0 ? indention - 2 : 0; return true; }; SerializeContext::EnumerateInstanceCallContext callContext(begin, end, context, SerializeContext::ENUM_ACCESS_FOR_WRITE, nullptr); context->EnumerateInstance(&callContext, classPtr, classId, classData, nullptr); return true; } void Dumper::DumpElementInfo(const SerializeContext::ClassElement& element, const SerializeContext::ClassData* classData, SerializeContext* context, rapidjson::Value& fields, rapidjson::Value& bases, rapidjson::Document& document, AZStd::string& scratchStringBuffer) { AZ_Assert(fields.IsArray(), "Expected 'fields' to be an array."); AZ_Assert(bases.IsArray(), "Expected 'bases' to be an array."); AZ_Assert(scratchStringBuffer.empty(), "Provided scratch string buffer wasn't empty."); const SerializeContext::ClassData* elementClass = context->FindClassData(element.m_typeId, classData); AppendTypeName(scratchStringBuffer, elementClass, element.m_typeId); Uuid elementTypeId = element.m_typeId; if (element.m_genericClassInfo) { DumpGenericStructure(scratchStringBuffer, element.m_genericClassInfo, context); elementTypeId = element.m_genericClassInfo->GetSpecializedTypeId(); } if ((element.m_flags & SerializeContext::ClassElement::FLG_POINTER) != 0) { scratchStringBuffer += '*'; } rapidjson::Value elementTypeString(scratchStringBuffer.c_str(), document.GetAllocator()); scratchStringBuffer.clear(); if ((element.m_flags & SerializeContext::ClassElement::FLG_BASE_CLASS) != 0) { rapidjson::Value baseNode(rapidjson::kObjectType); baseNode.AddMember("Type", AZStd::move(elementTypeString), document.GetAllocator()); baseNode.AddMember("Uuid", WriteToJsonValue(elementTypeId, document), document.GetAllocator()); bases.PushBack(AZStd::move(baseNode), document.GetAllocator()); } else { rapidjson::Value elementNode(rapidjson::kObjectType); elementNode.AddMember("Name", rapidjson::StringRef(element.m_name), document.GetAllocator()); elementNode.AddMember("Type", AZStd::move(elementTypeString), document.GetAllocator()); elementNode.AddMember("Uuid", WriteToJsonValue(elementTypeId, document), document.GetAllocator()); elementNode.AddMember("HasDefault", (element.m_flags & SerializeContext::ClassElement::FLG_NO_DEFAULT_VALUE) == 0, document.GetAllocator()); elementNode.AddMember("IsDynamic", (element.m_flags & SerializeContext::ClassElement::FLG_DYNAMIC_FIELD) != 0, document.GetAllocator()); elementNode.AddMember("IsPointer", (element.m_flags & SerializeContext::ClassElement::FLG_POINTER) != 0, document.GetAllocator()); elementNode.AddMember("IsUiElement", (element.m_flags & SerializeContext::ClassElement::FLG_UI_ELEMENT) != 0, document.GetAllocator()); elementNode.AddMember("DataSize", static_cast<uint64_t>(element.m_dataSize), document.GetAllocator()); elementNode.AddMember("Offset", static_cast<uint64_t>(element.m_offset), document.GetAllocator()); Edit::ElementData* elementEditData = element.m_editData; if (elementEditData) { elementNode.AddMember("Description", rapidjson::StringRef(elementEditData->m_description), document.GetAllocator()); } if (element.m_genericClassInfo) { rapidjson::Value genericArray(rapidjson::kArrayType); rapidjson::Value classObject(rapidjson::kObjectType); const SerializeContext::ClassData* genericClassData = element.m_genericClassInfo->GetClassData(); classObject.AddMember("Type", rapidjson::StringRef(genericClassData->m_name), document.GetAllocator()); classObject.AddMember("GenericUuid", WriteToJsonValue(element.m_genericClassInfo->GetGenericTypeId(), document), document.GetAllocator()); classObject.AddMember("SpecializedUuid", WriteToJsonValue(element.m_genericClassInfo->GetSpecializedTypeId(), document), document.GetAllocator()); classObject.AddMember("Generics", DumpGenericStructure(element.m_genericClassInfo, context, document, scratchStringBuffer), document.GetAllocator()); genericArray.PushBack(AZStd::move(classObject), document.GetAllocator()); elementNode.AddMember("Generics", AZStd::move(genericArray), document.GetAllocator()); } fields.PushBack(AZStd::move(elementNode), document.GetAllocator()); } } void Dumper::DumpElementInfo(AZStd::string& output, const SerializeContext::ClassElement* classElement, SerializeContext* context) { if (classElement) { if (classElement->m_genericClassInfo) { DumpGenericStructure(output, classElement->m_genericClassInfo, context); } if ((classElement->m_flags & SerializeContext::ClassElement::FLG_POINTER) != 0) { output += '*'; } output += ' '; output += classElement->m_name; if ((classElement->m_flags & SerializeContext::ClassElement::FLG_BASE_CLASS) != 0) { output += " [Base]"; } } } void Dumper::DumpGenericStructure(AZStd::string& output, GenericClassInfo* genericClassInfo, SerializeContext* context) { output += '<'; const SerializeContext::ClassData* classData = genericClassInfo->GetClassData(); if (classData && classData->m_container) { bool firstArgument = true; auto callback = [&output, context, &firstArgument](const Uuid& elementClassId, const SerializeContext::ClassElement* genericClassElement) -> bool { if (!firstArgument) { output += ','; } else { firstArgument = false; } const SerializeContext::ClassData* argClassData = context->FindClassData(elementClassId); AppendTypeName(output, argClassData, elementClassId); if (genericClassElement->m_genericClassInfo) { DumpGenericStructure(output, genericClassElement->m_genericClassInfo, context); } if ((genericClassElement->m_flags & SerializeContext::ClassElement::FLG_POINTER) != 0) { output += '*'; } return true; }; classData->m_container->EnumTypes(callback); } else { // No container information available, so as much as possible through other means, although // this might not be complete information. size_t numArgs = genericClassInfo->GetNumTemplatedArguments(); for (size_t i = 0; i < numArgs; ++i) { if (i != 0) { output += ','; } const Uuid& argClassId = genericClassInfo->GetTemplatedTypeId(i); const SerializeContext::ClassData* argClass = context->FindClassData(argClassId); AppendTypeName(output, argClass, argClassId); } } output += '>'; } rapidjson::Value Dumper::DumpGenericStructure(GenericClassInfo* genericClassInfo, SerializeContext* context, rapidjson::Document& parentDoc, AZStd::string& scratchStringBuffer) { AZ_Assert(scratchStringBuffer.empty(), "Provided scratch string buffer still contains data."); rapidjson::Value result(rapidjson::kArrayType); const SerializeContext::ClassData* classData = genericClassInfo->GetClassData(); if (classData && classData->m_container) { auto callback = [&result, context, &parentDoc, &scratchStringBuffer](const Uuid& elementClassId, const SerializeContext::ClassElement* genericClassElement) -> bool { rapidjson::Value classObject(rapidjson::kObjectType); const SerializeContext::ClassData* argClassData = context->FindClassData(elementClassId); AppendTypeName(scratchStringBuffer, argClassData, elementClassId); classObject.AddMember("Type", rapidjson::Value(scratchStringBuffer.c_str(), parentDoc.GetAllocator()), parentDoc.GetAllocator()); scratchStringBuffer.clear(); classObject.AddMember("IsPointer", (genericClassElement->m_flags & SerializeContext::ClassElement::FLG_POINTER) != 0, parentDoc.GetAllocator()); if (genericClassElement->m_genericClassInfo) { GenericClassInfo* genericClassInfo = genericClassElement->m_genericClassInfo; classObject.AddMember("GenericUuid", WriteToJsonValue(genericClassInfo->GetGenericTypeId(), parentDoc), parentDoc.GetAllocator()); classObject.AddMember("SpecializedUuid", WriteToJsonValue(genericClassInfo->GetSpecializedTypeId(), parentDoc), parentDoc.GetAllocator()); classObject.AddMember("Generics", DumpGenericStructure(genericClassInfo, context, parentDoc, scratchStringBuffer), parentDoc.GetAllocator()); } else { classObject.AddMember("GenericUuid", WriteToJsonValue(elementClassId, parentDoc), parentDoc.GetAllocator()); classObject.AddMember("SpecializedUuid", WriteToJsonValue(elementClassId, parentDoc), parentDoc.GetAllocator()); } result.PushBack(AZStd::move(classObject), parentDoc.GetAllocator()); return true; }; classData->m_container->EnumTypes(callback); } else { // No container information available, so as much as possible through other means, although // this might not be complete information. size_t numArgs = genericClassInfo->GetNumTemplatedArguments(); for (size_t i = 0; i < numArgs; ++i) { const Uuid& elementClassId = genericClassInfo->GetTemplatedTypeId(i); rapidjson::Value classObject(rapidjson::kObjectType); const SerializeContext::ClassData* argClassData = context->FindClassData(elementClassId); AppendTypeName(scratchStringBuffer, argClassData, elementClassId); classObject.AddMember("Type", rapidjson::Value(scratchStringBuffer.c_str(), parentDoc.GetAllocator()), parentDoc.GetAllocator()); scratchStringBuffer.clear(); classObject.AddMember("GenericUuid", WriteToJsonValue(argClassData ? argClassData->m_typeId : elementClassId, parentDoc), parentDoc.GetAllocator()); classObject.AddMember("SpecializedUuid", WriteToJsonValue(elementClassId, parentDoc), parentDoc.GetAllocator()); classObject.AddMember("IsPointer", false, parentDoc.GetAllocator()); result.PushBack(AZStd::move(classObject), parentDoc.GetAllocator()); } } return result; } void Dumper::DumpPrimitiveTag(AZStd::string& output, const SerializeContext::ClassData* classData, const SerializeContext::ClassElement* classElement) { if (classData) { Uuid classId = classData->m_typeId; if (classElement && classElement->m_genericClassInfo) { classId = classElement->m_genericClassInfo->GetGenericTypeId(); } if (Utilities::IsSerializationPrimitive(classId)) { output += " [Primitive]"; } } } void Dumper::DumpClassName(rapidjson::Value& parent, SerializeContext* context, const SerializeContext::ClassData* classData, rapidjson::Document& parentDoc, AZStd::string& scratchStringBuffer) { AZ_Assert(scratchStringBuffer.empty(), "Scratch string buffer is not empty."); Edit::ClassData* editData = classData->m_editData; GenericClassInfo* genericClassInfo = context->FindGenericClassInfo(classData->m_typeId); if (genericClassInfo) { // If the type itself is a generic, dump it's information. scratchStringBuffer = classData->m_name; DumpGenericStructure(scratchStringBuffer, genericClassInfo, context); } else { bool hasEditName = editData && editData->m_name && strlen(editData->m_name) > 0; scratchStringBuffer = hasEditName ? editData->m_name : classData->m_name; } AZStd::string_view namespacePortion = ExtractNamespace(scratchStringBuffer); if (!namespacePortion.empty()) { parent.AddMember("Namespace", rapidjson::Value(namespacePortion.data(), azlossy_caster(namespacePortion.length()), parentDoc.GetAllocator()), parentDoc.GetAllocator()); parent.AddMember("Name", rapidjson::Value(scratchStringBuffer.c_str() + namespacePortion.length() + 2, parentDoc.GetAllocator()), parentDoc.GetAllocator()); } else { parent.AddMember("Name", rapidjson::Value(scratchStringBuffer.c_str(), parentDoc.GetAllocator()), parentDoc.GetAllocator()); } scratchStringBuffer.clear(); } void Dumper::AppendTypeName(AZStd::string& output, const SerializeContext::ClassData* classData, const Uuid& classId) { if (classData) { output += classData->m_name; } else if (classId == GetAssetClassId()) { output += "Asset"; } else { output += classId.ToString<AZStd::string>(); } } // namespace AZ::SerializeContextTools }
26,331
7,157
/******************************************************************************* * This file is part of the "Enduro2D" * For conditions of distribution and use, see copyright notice in LICENSE.md * Copyright (C) 2018-2020, by Matvey Cherevko (blackmatov@gmail.com) ******************************************************************************/ #include <enduro2d/utils/strings.hpp> #include <3rdparty/utfcpp/utf8.h> namespace { using namespace e2d; // // utf8_to_X // str16 utf8_to_16(str_view src) { str16 dst; dst.reserve(src.size()); utf8::utf8to16(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } str32 utf8_to_32(str_view src) { str32 dst; dst.reserve(src.size()); utf8::utf8to32(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } template < typename WChar = wchar_t > std::enable_if_t<sizeof(WChar) == 2, wstr> utf8_to_wide(str_view src) { wstr dst; dst.reserve(src.size()); utf8::utf8to16(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } template < typename WChar = wchar_t > std::enable_if_t<sizeof(WChar) == 4, wstr> utf8_to_wide(str_view src) { wstr dst; dst.reserve(src.size()); utf8::utf8to32(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } // // utf16_to_X // template < typename Char > std::enable_if_t<sizeof(Char) == 2, str> utf16_to_8(basic_string_view<Char> src) { str dst; dst.reserve(src.size() * 2); utf8::utf16to8(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } template < typename Char > std::enable_if_t<sizeof(Char) == 2, str32> utf16_to_32(basic_string_view<Char> src) { return utf8_to_32(utf16_to_8(src)); } template < typename Char > std::enable_if_t<sizeof(Char) == 2, wstr> utf16_to_wide(basic_string_view<Char> src) { return utf8_to_wide(utf16_to_8(src)); } // // utf32_to_X // template < typename Char > std::enable_if_t<sizeof(Char) == 4, str> utf32_to_8(basic_string_view<Char> src) { str dst; dst.reserve(src.size() * 4); utf8::utf32to8(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } template < typename Char > std::enable_if_t<sizeof(Char) == 4, str16> utf32_to_16(basic_string_view<Char> src) { return utf8_to_16(utf32_to_8(src)); } template < typename Char > std::enable_if_t<sizeof(Char) == 4, wstr> utf32_to_wide(basic_string_view<Char> src) { return utf8_to_wide(utf32_to_8(src)); } // // wide_to_X // template < typename Char > std::enable_if_t<sizeof(Char) == 2, str> wide_to_utf8(basic_string_view<Char> src) { return utf16_to_8(src); } template < typename Char > std::enable_if_t<sizeof(Char) == 4, str> wide_to_utf8(basic_string_view<Char> src) { return utf32_to_8(src); } template < typename Char > std::enable_if_t<sizeof(Char) == 2, str16> wide_to_utf16(basic_string_view<Char> src) { return src.empty() ? str16() : str16(src.cbegin(), src.cend()); } template < typename Char > std::enable_if_t<sizeof(Char) == 4, str16> wide_to_utf16(basic_string_view<Char> src) { return utf32_to_16(src); } template < typename Char > std::enable_if_t<sizeof(Char) == 2, str32> wide_to_utf32(basic_string_view<Char> src) { return utf16_to_32(src); } template < typename Char > std::enable_if_t<sizeof(Char) == 4, str32> wide_to_utf32(basic_string_view<Char> src) { return src.empty() ? str32() : str32(src.cbegin(), src.cend()); } } namespace e2d { // // make_utf8 // str make_utf8(str_view src) { return src.empty() ? str() : str(src.cbegin(), src.cend()); } str make_utf8(wstr_view src) { return wide_to_utf8(src); } str make_utf8(str16_view src) { return utf16_to_8(src); } str make_utf8(str32_view src) { return utf32_to_8(src); } // // make_wide // wstr make_wide(str_view src) { return utf8_to_wide(src); } wstr make_wide(wstr_view src) { return src.empty() ? wstr() : wstr(src.cbegin(), src.cend()); } wstr make_wide(str16_view src) { return utf16_to_wide(src); } wstr make_wide(str32_view src) { return utf32_to_wide(src); } // // make_utf16 // str16 make_utf16(str_view src) { return utf8_to_16(src); } str16 make_utf16(wstr_view src) { return wide_to_utf16(src); } str16 make_utf16(str16_view src) { return src.empty() ? str16() : str16(src.cbegin(), src.cend()); } str16 make_utf16(str32_view src) { return utf32_to_16(src); } // // make_utf32 // str32 make_utf32(str_view src) { return utf8_to_32(src); } str32 make_utf32(wstr_view src) { return wide_to_utf32(src); } str32 make_utf32(str16_view src) { return utf16_to_32(src); } str32 make_utf32(str32_view src) { return src.empty() ? str32() : str32(src.cbegin(), src.cend()); } // // make_hash // str_hash make_hash(str_view src) noexcept { return str_hash(src); } wstr_hash make_hash(wstr_view src) noexcept { return wstr_hash(src); } str16_hash make_hash(str16_view src) noexcept { return str16_hash(src); } str32_hash make_hash(str32_view src) noexcept { return str32_hash(src); } } namespace e2d::strings { namespace impl { // Inspired by: // https://www.codeproject.com/Articles/1088/Wildcard-string-compare-globbing using utf8_iter = utf8::iterator<str_view::const_iterator>; static bool wildcard_match_impl( utf8_iter string_i, utf8_iter string_e, utf8_iter pattern_i, utf8_iter pattern_e) { while ( pattern_i != pattern_e && *pattern_i != '*' ) { if ( string_i == string_e ) { break; } if ( *pattern_i != *string_i && *pattern_i != '?' ) { return false; } ++string_i; ++pattern_i; } if ( pattern_i == pattern_e ) { return string_i == string_e; } utf8_iter s_mark = string_e; utf8_iter p_mark = pattern_e; while ( string_i != string_e ) { if ( pattern_i != pattern_e ) { if ( *pattern_i == '*' ) { if ( ++pattern_i == pattern_e ) { return true; } s_mark = string_i; p_mark = pattern_i; ++s_mark; continue; } else if ( *pattern_i == *string_i || *pattern_i == '?' ) { ++string_i; ++pattern_i; continue; } } string_i = s_mark; pattern_i = p_mark; if ( s_mark != string_e ) { ++s_mark; } } while ( pattern_i != pattern_e && *pattern_i == '*' ) { ++pattern_i; } return pattern_i == pattern_e; } } bool wildcard_match(str_view string, str_view pattern) { using namespace impl; str_view::const_iterator si = string.cbegin(); str_view::const_iterator se = string.cend(); str_view::const_iterator pi = pattern.cbegin(); str_view::const_iterator pe = pattern.cend(); return wildcard_match_impl( utf8_iter(si, si, se), utf8_iter(se, si, se), utf8_iter(pi, pi, pe), utf8_iter(pe, pi, pe)); } bool starts_with(str_view input, str_view test) noexcept { return input.size() >= test.size() && 0 == input.compare(0, test.size(), test); } bool ends_with(str_view input, str_view test) noexcept { return input.size() >= test.size() && 0 == input.compare(input.size() - test.size(), test.size(), test); } }
8,859
3,218
// Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "CarlaRecorderBoundingBox.h" #include "CarlaRecorder.h" #include "CarlaRecorderHelpers.h" void CarlaRecorderBoundingBox::Write(std::ofstream &OutFile) { WriteValue<uint32_t>(OutFile, this->DatabaseId); WriteFVector(OutFile, this->Origin); WriteFVector(OutFile, this->Extension); } void CarlaRecorderBoundingBox::Read(std::ifstream &InFile) { ReadValue<uint32_t>(InFile, this->DatabaseId); ReadFVector(InFile, this->Origin); ReadFVector(InFile, this->Extension); } // --------------------------------------------- void CarlaRecorderBoundingBoxes::Clear(void) { Boxes.clear(); } void CarlaRecorderBoundingBoxes::Add(const CarlaRecorderBoundingBox &InObj) { Boxes.push_back(InObj); } void CarlaRecorderBoundingBoxes::Write(std::ofstream &OutFile) { // write the packet id WriteValue<char>(OutFile, static_cast<char>(CarlaRecorderPacketId::BoundingBox)); // write the packet size uint32_t Total = 2 + Boxes.size() * sizeof(CarlaRecorderBoundingBox); WriteValue<uint32_t>(OutFile, Total); // write total records Total = Boxes.size(); WriteValue<uint16_t>(OutFile, Total); // write records for(auto& Box : Boxes) { Box.Write(OutFile); } }
1,420
506
/*----------------------------------------------------------------------------- Copyright(c) 2010 - 2018 ViSUS L.L.C., Scientific Computing and Imaging Institute of the University of Utah ViSUS L.L.C., 50 W.Broadway, Ste. 300, 84101 - 2044 Salt Lake City, UT University of Utah, 72 S Central Campus Dr, Room 3750, 84112 Salt Lake City, UT All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. For additional information about this project contact : pascucci@acm.org For support : support@visus.net -----------------------------------------------------------------------------*/ #include <Visus/LegacyDataset.h> #include <Visus/Access.h> #include <Visus/NetService.h> namespace Visus { ////////////////////////////////////////////////////////////// class LegacyAccess : public Access { public: LegacyDataset* dataset; StringTree config; Url url; SharedPtr<NetService> netservice; //constructor LegacyAccess(LegacyDataset* dataset_,StringTree config_=StringTree()) : dataset(dataset_),config(config_) { this->name = "LegacyAccess"; this->can_read = StringUtils::find(config.readString("chmod", "rw"), "r") >= 0; this->can_write = StringUtils::find(config.readString("chmod", "rw"), "w") >= 0; this->bitsperblock = cint(config.readString("bitsperblock", cstring(dataset->getDefaultBitsPerBlock()))); VisusAssert(this->bitsperblock>0); this->url = config.readString("url",dataset->getUrl().toString()); VisusAssert(url.valid()); this->config.writeString("url", url.toString()); bool disable_async = config.readBool("disable_async", dataset->bServerMode); if (int nconnections = disable_async ? 0 : config.readInt("nconnections", 8)) this->netservice = std::make_shared<NetService>(nconnections); } //destructor virtual ~LegacyAccess(){ } //readBlock virtual void readBlock(SharedPtr<BlockQuery> query) override { auto coord=dataset->getTileCoordinate(query->start_address,query->end_address); int X=coord.x; int Y=coord.y; int Z=coord.z; //mirror along Y Y=(int)((1<<Z)-Y-1); Url url=dataset->getUrl(); url.params.clear(); url.setParam("x",cstring(X)); url.setParam("y",cstring(Y)); url.setParam("z",cstring(Z)); auto request=NetRequest(url); if (!request.valid()) return readFailed(query); request.aborted=query->aborted; //note [...,query] keep the query in memory NetService::push(netservice, request).when_ready([this, query](NetResponse response) { NdPoint nsamples = NdPoint::one(2); nsamples[0] = dataset->tile_nsamples.x; nsamples[1] = dataset->tile_nsamples.y; response.setHeader("visus-compression", dataset->tile_compression); response.setHeader("visus-nsamples", nsamples.toString()); response.setHeader("visus-dtype", query->field.dtype.toString()); response.setHeader("visus-layout", ""); if (query->aborted() || !response.isSuccessful()) return readFailed(query); auto decoded = response.getArrayBody(); if (!decoded) return readFailed(query); VisusAssert(decoded.dims == query->nsamples); VisusAssert(decoded.dtype == query->field.dtype); query->buffer = decoded; return readOk(query); }); } //writeBlock virtual void writeBlock(SharedPtr<BlockQuery> query) override { VisusAssert(false);//not supported writeFailed(query); } //printStatistics virtual void printStatistics() override { VisusInfo() << name << " hostname(" << url.getHostname() << ") port(" << url.getPort() << ") url(" << url.toString() << ")"; Access::printStatistics(); } }; ////////////////////////////////////////////////////////////// bool LegacyDataset::beginQuery(SharedPtr<Query> query) { if (!Dataset::beginQuery(query)) return false; VisusAssert(query->start_resolution==0); VisusAssert(query->max_resolution==this->getBitmask().getMaxResolution()); //i don't have odd resolutions { std::vector<int> end_resolutions=query->end_resolutions; std::vector<int> even_end_resolutions; for (int I=0;I<(int)end_resolutions.size();I++) { int even_end_resolution=(end_resolutions[I]>>1)<<1; if (even_end_resolutions.empty() || even_end_resolutions.back()!=even_end_resolution) even_end_resolutions.push_back(even_end_resolution); } query->end_resolutions=even_end_resolutions; } //writing is not supported if (query->mode=='w') { query->setFailed("Writing mode not suppoted"); return false; } Position position=query->position; //not supported if (!position.getTransformation().isIdentity()) { query->setFailed("Position has non-identity transformation"); return false; } auto user_box= query->position.getNdBox().getIntersection(this->getBox()); if (!user_box.isFullDim()) { query->setFailed("user_box not valid"); return false; } query->setRunning(); std::vector<int> end_resolutions=query->end_resolutions; for (query->query_cursor=0;query->query_cursor<(int)end_resolutions.size();query->query_cursor++) { if (setCurrentEndResolution(query)) return true; } query->setFailed("Cannot find a good initial resolution"); return false; } ////////////////////////////////////////////////////////////// void LegacyDataset::kdTraverse(std::vector< SharedPtr<BlockQuery> >& block_queries,SharedPtr<Query> query,NdBox box,BigInt id,int H,int end_resolution) { if (query->aborted()) return; if (!box.getIntersection(query->position.getNdBox()).isFullDim()) return; int samplesperblock=1<<this->getDefaultBitsPerBlock(); if (H==end_resolution) { VisusAssert(H % 2==0); BigInt start_address=(id-1)*samplesperblock; BigInt end_address =start_address+samplesperblock; auto block_query=std::make_shared<BlockQuery>(query->field,query->time,start_address,end_address,query->aborted); block_queries.push_back(block_query); return; } DatasetBitmask bitmask=this->getBitmask(); int split_bit=bitmask[1+H - this->getDefaultBitsPerBlock()]; NdPoint::coord_t middle=(box.p1[split_bit]+box.p2[split_bit])>>1; auto left_box =box; left_box .p2[split_bit]=middle; auto right_box =box; right_box.p1[split_bit]=middle; kdTraverse(block_queries,query,left_box ,id*2+0,H+1,end_resolution); kdTraverse(block_queries,query,right_box,id*2+1,H+1,end_resolution); } ////////////////////////////////////////////////////////////// bool LegacyDataset::executeQuery(SharedPtr<Access> access,SharedPtr<Query> query) { if (!Dataset::executeQuery(access,query)) return false; if (!query->allocateBufferIfNeeded()) { query->setFailed("cannot allocate buffer"); return false; } //always need an access.. the google server cannot handle pure remote queries (i.e. compose the tiles on server side) if (!access) access=std::make_shared<LegacyAccess>(this); int end_resolution=query->getEndResolution(); VisusAssert(end_resolution % 2==0); WaitAsync< Future<Void> > wait_async; NdBox box=this->getBox(); std::vector< SharedPtr<BlockQuery> > block_queries; kdTraverse(block_queries,query,box,/*id*/1,/*H*/this->getDefaultBitsPerBlock(),end_resolution); access->beginRead(); { for (auto block_query : block_queries) { wait_async.pushRunning(readBlock(access,block_query)).when_ready([this,query, block_query](Void) { if (!query->aborted() && block_query->ok()) mergeQueryWithBlock(query, block_query); }); } } access->endRead(); wait_async.waitAllDone(); query->currentLevelReady(); return true; } ////////////////////////////////////////////////////////////// bool LegacyDataset::nextQuery(SharedPtr<Query> query) { if (!Dataset::nextQuery(query)) return false; //merging is not supported query->buffer=Array(); if (!setCurrentEndResolution(query)) { query->setFailed("cannot set end resolution"); return false; } else { return true; } } ////////////////////////////////////////////////////////////// bool LegacyDataset::mergeQueryWithBlock(SharedPtr<Query> query,SharedPtr<BlockQuery> blockquery) { return Query::mergeSamples(query->logic_box, query->buffer, blockquery->logic_box, blockquery->buffer, Query::InsertSamples, query->aborted); } ////////////////////////////////////////////////////////////// SharedPtr<Access> LegacyDataset::createAccess(StringTree config, bool bForBlockQuery) { VisusAssert(this->valid()); if (config.empty()) config = getDefaultAccessConfig(); String type = StringUtils::toLower(config.readString("type")); //I always need an access if (type.empty()) return std::make_shared<LegacyAccess>(this, config); //LegacyAccess if (type=="legacyaccess") return std::make_shared<LegacyAccess>(this, config); return Dataset::createAccess(config, bForBlockQuery); } ////////////////////////////////////////////////////////////// std::vector<int> LegacyDataset::guessEndResolutions(const Frustum& viewdep,Position position,Query::Quality quality,Query::Progression progression) { std::vector<int> ret=Dataset::guessEndResolutions(viewdep,position,quality,progression); for (int I=0;I<(int)ret.size();I++) ret[I]=(ret[I]>>1)<<1; //i don't have even resolution return ret; } ////////////////////////////////////////////////////////////// Point3i LegacyDataset::getTileCoordinate(BigInt start_address,BigInt end_address) { int bitsperblock=this->getDefaultBitsPerBlock(); int samplesperblock=((BigInt)1)<<bitsperblock; VisusAssert(end_address==start_address+samplesperblock); Int64 blocknum=cint64(start_address>>bitsperblock); int H=bitsperblock+Utils::getLog2(1+blocknum); VisusAssert((H % 2)==0); Int64 first_block_in_level=(((Int64)1)<<(H-bitsperblock))-1; NdPoint tile_coord=bitmask.deinterleave(blocknum-first_block_in_level,H-bitsperblock); return Point3i( (int)(tile_coord[0]), (int)(tile_coord[1]), (H-bitsperblock)>>1); } ////////////////////////////////////////////////////////////// LogicBox LegacyDataset::getAddressRangeBox(BigInt start_address,BigInt end_address) { auto coord=getTileCoordinate(start_address,end_address); int X=coord.x; int Y=coord.y; int Z=coord.z; int tile_width =(int)(this->getBox().p2[0])>>Z; int tile_height=(int)(this->getBox().p2[1])>>Z; NdPoint delta=NdPoint::one(2); delta[0]=tile_width /this->tile_nsamples.x; delta[1]=tile_height/this->tile_nsamples.y; NdBox box(NdPoint(2), NdPoint::one(2)); box.p1[0] = tile_width * (X + 0); box.p2[0] = tile_width * (X + 1); box.p1[1] = tile_height * (Y + 0); box.p2[1] = tile_height * (Y + 1); return LogicBox(box,delta); } ////////////////////////////////////////////////////////////// bool LegacyDataset::openFromUrl(Url url) { this->tile_nsamples.x = cint(url.getParam("tile_width" ,"0")); this->tile_nsamples.y = cint(url.getParam("tile_height","0")); int nlevels = cint(url.getParam("nlevels","0")) ; this->tile_compression = url.getParam("compression") ; this->dtype = DType::fromString(url.getParam("dtype")); if (tile_nsamples.x<=0 || tile_nsamples.y<=0 || !nlevels || !dtype.valid() || tile_compression.empty()) { VisusAssert(false); this->invalidate(); return false; } //any google level double the dimensions in x and y (i.e. i don't have even resolutions) NdPoint overall_dims=NdPoint::one(2); overall_dims[0]=tile_nsamples.x * (((NdPoint::coord_t)1)<<nlevels); overall_dims[1]=tile_nsamples.y * (((NdPoint::coord_t)1)<<nlevels); this->url=url.toString(); this->bitmask=DatasetBitmask::guess(overall_dims); this->default_bitsperblock=Utils::getLog2(tile_nsamples.x*tile_nsamples.y); this->box=NdBox(NdPoint(0,0),overall_dims); this->timesteps=DatasetTimesteps(); this->timesteps.addTimestep(0); addField(Field("DATA",dtype)); //UseQuery not supported? actually yes, but it's a nonsense since a query it's really a block query if (this->kdquery_mode==KdQueryMode::UseQuery) this->kdquery_mode=KdQueryMode::UseBlockQuery; return true; } ////////////////////////////////////////////////////////////// LogicBox LegacyDataset::getLevelBox(int H) { int bitsperblock=this->getDefaultBitsPerBlock(); VisusAssert((H%2)==0 && H>=bitsperblock); int Z=(H-bitsperblock)>>1; int tile_width =(int)(this->getBox().p2[0])>>Z; int tile_height=(int)(this->getBox().p2[1])>>Z; int ntiles_x=(int)(1<<Z); int ntiles_y=(int)(1<<Z); NdPoint delta=NdPoint::one(2); delta[0]=tile_width /this->tile_nsamples.x; delta[1]=tile_height/this->tile_nsamples.y; NdBox box(NdPoint(0,0), NdPoint::one(1,1)); box.p2[0] = ntiles_x*tile_width; box.p2[1] = ntiles_y*tile_height; auto ret=LogicBox(box,delta); VisusAssert(ret.valid()); return ret; } ////////////////////////////////////////////////////////////// bool LegacyDataset::setCurrentEndResolution(SharedPtr<Query> query) { int end_resolution=query->getEndResolution(); if (end_resolution<0) return false; VisusAssert(end_resolution % 2==0); int max_resolution=query->max_resolution; //necessary condition VisusAssert(query->start_resolution<=end_resolution); VisusAssert(end_resolution<=max_resolution); auto user_box= query->position.getNdBox().getIntersection(this->getBox()); VisusAssert(user_box.isFullDim()); int H=end_resolution; LogicBox Lbox=getLevelBox(end_resolution); NdBox box=Lbox.alignBox(user_box); if (!box.isFullDim()) return false; LogicBox logic_box(box,Lbox.delta); query->nsamples=logic_box.nsamples; query->logic_box=logic_box; query->buffer=Array(); return true; } } //namespace Visus
15,221
5,262
/******************************************************************************** * File Name: * hld_usb_driver.hpp * * Description: * Thor USB high level driver * * 2020 | Brandon Braun | brandonbraun653@gmail.com ********************************************************************************/ #pragma once #ifndef THOR_HLD_USB_HPP #define THOR_HLD_USB_HPP /* C++ Includes */ #include <cstdint> #include <cstdlib> /* Chimera Includes */ #include <Chimera/common> #include <Chimera/usb> #include <Chimera/thread> /* Thor Includes */ #include <Thor/hld/usb/hld_usb_types.hpp> namespace Thor::USB { /*------------------------------------------------------------------------------- Public Functions -------------------------------------------------------------------------------*/ Chimera::Status_t initialize(); Chimera::Status_t reset(); Driver_rPtr getDriver( const Chimera::USB::Channel ch ); /*------------------------------------------------------------------------------- Classes -------------------------------------------------------------------------------*/ /** * USB Peripheral Driver * Methods here at a minimum implement the interface specified in Chimera. * Inheritance is avoided to minimize cost of virtual function lookup table. */ class Driver : public Chimera::Thread::Lockable<Driver> { public: Driver(); ~Driver(); /*------------------------------------------------- Interface: Hardware -------------------------------------------------*/ Chimera::Status_t open( const Chimera::USB::PeriphConfig &cfg ); void close(); private: friend Chimera::Thread::Lockable<Driver>; Chimera::USB::Channel mChannel; }; } // namespace Thor::USB #endif /* THOR_HLD_USB_HPP */
1,793
503
class MyCalendar { map<int, int> mp; public: MyCalendar() {} bool book(int start, int end) { auto it1 = mp.lower_bound(start); if (it1 != mp.end() && it1->first == start) return false; if (it1 != mp.end() && it1->first < end) return false; if (mp.size() && it1 != mp.begin()) { --it1; if (it1->second > start) return false; } // return false; mp[start] = end; return true; } }; /** * Your MyCalendar object will be instantiated and called as such: * MyCalendar* obj = new MyCalendar(); * bool param_1 = obj->book(start,end); */
614
221
/*++ Copyright (c) 1990 Microsoft Corporation Module Name: rdpdrkd.c Abstract: Redirector Kernel Debugger extension Author: Balan Sethu Raman (SethuR) 11-May-1994 Revision History: 11-Nov-1994 SethuR Created --*/ #define KDEXT_32BIT #include "rx.h" // NT network file system driver include file #include "ntddnfs2.h" // new stuff device driver definitions #include <pchannel.h> #include <tschannl.h> #include <rdpdr.h> #include "rdpdrp.h" #include "namespc.h" #include "strcnv.h" #include "dbg.h" #include "topobj.h" #include "smartptr.h" #include "kernutil.h" #include "isession.h" #include "iexchnge.h" #include "channel.h" #include "device.h" #include "prnport.h" #include "serport.h" #include "parport.h" #include "devmgr.h" #include "exchnge.h" #include "session.h" #include "sessmgr.h" #include "rdpdyn.h" #include "rdpevlst.h" #include "rdpdrpnp.h" #include "rdpdrprt.h" #include "trc.h" #include <string.h> #include <stdio.h> #include <kdextlib.h> #include <rdpdrkd.h> /* * RDPDR global variables. * */ LPSTR GlobalBool[] = { 0}; LPSTR GlobalShort[] = {0}; LPSTR GlobalLong[] = { 0}; LPSTR GlobalPtrs[] = { "rdpdr!RxExpCXR", "rdpdr!RxExpEXR", "rdpdr!RxExpAddr", "rdpdr!RxExpCode", "rdpdr!RxActiveContexts", "rdpdr!RxNetNameTable", "rdpdr!RxProcessorArchitecture", "rdpdr!RxBuildNumber", "rdpdr!RxPrivateBuild", "rdpdr!ClientList", 0}; /* * IRP_CONTEXT debugging. * */ FIELD_DESCRIPTOR RxContextFields[] = { FIELD3(FieldTypeUShort,RX_CONTEXT,NodeTypeCode), FIELD3(FieldTypeShort,RX_CONTEXT,NodeByteSize), FIELD3(FieldTypeULong,RX_CONTEXT,ReferenceCount), FIELD3(FieldTypeULong,RX_CONTEXT,SerialNumber), FIELD3(FieldTypeStruct,RX_CONTEXT,WorkQueueItem), FIELD3(FieldTypePointer,RX_CONTEXT,CurrentIrp), FIELD3(FieldTypePointer,RX_CONTEXT,CurrentIrpSp), FIELD3(FieldTypePointer,RX_CONTEXT,pFcb), FIELD3(FieldTypePointer,RX_CONTEXT,pFobx), //FIELD3(FieldTypePointer,RX_CONTEXT,pRelevantSrvOpen), FIELD3(FieldTypePointer,RX_CONTEXT,LastExecutionThread), #ifdef RDBSS_TRACKER FIELD3(FieldTypePointer,RX_CONTEXT,AcquireReleaseFcbTrackerX), #endif FIELD3(FieldTypePointer,RX_CONTEXT,MRxContext[2]), FIELD3(FieldTypeSymbol,RX_CONTEXT,ResumeRoutine), FIELD3(FieldTypePointer,RX_CONTEXT,RealDevice), FIELD3(FieldTypeULongFlags,RX_CONTEXT,Flags), FIELD3(FieldTypeChar,RX_CONTEXT,MajorFunction), FIELD3(FieldTypeChar,RX_CONTEXT,MinorFunction), FIELD3(FieldTypeULong,RX_CONTEXT,StoredStatus), FIELD3(FieldTypeStruct,RX_CONTEXT,SyncEvent), FIELD3(FieldTypeStruct,RX_CONTEXT,RxContextSerializationQLinks), FIELD3(FieldTypeStruct,RX_CONTEXT,Create), FIELD3(FieldTypeStruct,RX_CONTEXT,LowIoContext), FIELD3(FieldTypePointer,RX_CONTEXT,Create.NetNamePrefixEntry), FIELD3(FieldTypePointer,RX_CONTEXT,Create.pSrvCall), FIELD3(FieldTypePointer,RX_CONTEXT,Create.pNetRoot), FIELD3(FieldTypePointer,RX_CONTEXT,Create.pVNetRoot), //FIELD3(FieldTypePointer,RX_CONTEXT,Create.pSrvOpen), FIELDLAST }; /* * SRV_CALL debugging. * */ //CODE.IMPROVEMENT we should have a fieldtype for prefixentry that // will print out the names FIELD_DESCRIPTOR SrvCallFields[] = { FIELD3(FieldTypeUShort,SRV_CALL,NodeTypeCode), FIELD3(FieldTypeShort,SRV_CALL,NodeByteSize), FIELD3(FieldTypeStruct,SRV_CALL,PrefixEntry), FIELD3(FieldTypeUnicodeString,SRV_CALL,PrefixEntry.Prefix), FIELD3(FieldTypePointer,SRV_CALL,Context), FIELD3(FieldTypePointer,SRV_CALL,Context2), FIELD3(FieldTypeULong,SRV_CALL,Flags), FIELDLAST }; /* * NET_ROOT debugging. * */ FIELD_DESCRIPTOR NetRootFields[] = { FIELD3(FieldTypeUShort,NET_ROOT,NodeTypeCode), FIELD3(FieldTypeShort,NET_ROOT,NodeByteSize), FIELD3(FieldTypeULong,NET_ROOT,NodeReferenceCount), FIELD3(FieldTypeStruct,NET_ROOT,PrefixEntry), FIELD3(FieldTypeUnicodeString,NET_ROOT,PrefixEntry.Prefix), FIELD3(FieldTypeStruct,NET_ROOT,FcbTable), //FIELD3(FieldTypePointer,NET_ROOT,Dispatch), FIELD3(FieldTypePointer,NET_ROOT,Context), FIELD3(FieldTypePointer,NET_ROOT,Context2), FIELD3(FieldTypePointer,NET_ROOT,pSrvCall), FIELD3(FieldTypeULong,NET_ROOT,Flags), FIELDLAST }; /* * V_NET_ROOT debugging. * */ FIELD_DESCRIPTOR VNetRootFields[] = { FIELD3(FieldTypeUShort,V_NET_ROOT,NodeTypeCode), FIELD3(FieldTypeShort,V_NET_ROOT,NodeByteSize), FIELD3(FieldTypeULong,V_NET_ROOT,NodeReferenceCount), FIELD3(FieldTypeStruct,V_NET_ROOT,PrefixEntry), FIELD3(FieldTypeUnicodeString,V_NET_ROOT,PrefixEntry.Prefix), FIELD3(FieldTypeUnicodeString,V_NET_ROOT,NamePrefix), FIELD3(FieldTypePointer,V_NET_ROOT,Context), FIELD3(FieldTypePointer,V_NET_ROOT,Context2), FIELD3(FieldTypePointer,V_NET_ROOT,pNetRoot), FIELDLAST }; /* * FCB debugging. * */ FIELD_DESCRIPTOR FcbFields[] = { FIELD3(FieldTypeUShort,FCB,Header.NodeTypeCode), FIELD3(FieldTypeShort,FCB,Header.NodeByteSize), FIELD3(FieldTypeULong,FCB,NodeReferenceCount), FIELD3(FieldTypeULong,FCB,FcbState), FIELD3(FieldTypeULong,FCB,OpenCount), FIELD3(FieldTypeULong,FCB,UncleanCount), FIELD3(FieldTypePointer,FCB,Header.Resource), FIELD3(FieldTypePointer,FCB,Header.PagingIoResource), FIELD3(FieldTypeStruct,FCB,FcbTableEntry), FIELD3(FieldTypeUnicodeString,FCB,PrivateAlreadyPrefixedName), FIELD3(FieldTypePointer,FCB,VNetRoot), FIELD3(FieldTypePointer,FCB,pNetRoot), FIELD3(FieldTypePointer,FCB,Context), FIELD3(FieldTypePointer,FCB,Context2), FIELDLAST }; /* * SRV_OPEN debugging. * */ FIELD_DESCRIPTOR SrvOpenFields[] = { FIELD3(FieldTypeShort,SRV_OPEN,NodeTypeCode), FIELD3(FieldTypeShort,SRV_OPEN,NodeByteSize), FIELD3(FieldTypeULong,SRV_OPEN,NodeReferenceCount), FIELD3(FieldTypePointer,SRV_OPEN,pFcb), FIELD3(FieldTypeULong,SRV_OPEN,Flags), FIELDLAST }; /* * FOBX debugging. * */ FIELD_DESCRIPTOR FobxFields[] = { FIELD3(FieldTypeShort,FOBX,NodeTypeCode), FIELD3(FieldTypeShort,FOBX,NodeByteSize), FIELD3(FieldTypeULong,FOBX,NodeReferenceCount), FIELD3(FieldTypePointer,FOBX,pSrvOpen), FIELDLAST }; //this enum is used in the definition of the structures that can be dumped....the order here //is not important, only that there is a definition for each dumpee structure..... typedef enum _STRUCTURE_IDS { StrEnum_RX_CONTEXT = 1, StrEnum_FCB, StrEnum_SRV_OPEN, StrEnum_FOBX, StrEnum_SRV_CALL, StrEnum_NET_ROOT, StrEnum_V_NET_ROOT, StrEnum_CHANNELAPCCONTEXT, StrEnum_TopObj, StrEnum_DrExchangeManager, StrEnum_DrExchange, StrEnum_DrIoContext, StrEnum_DrDeviceManager, StrEnum_DoubleList, StrEnum_KernelResource, StrEnum_VirtualChannel, StrEnum_DrDevice, StrEnum_DrPrinterPort, StrEnum_DrParallelPort, StrEnum_DrSerialPort, StrEnum_DrSessionManager, StrEnum_DrSession, StrEnum_ReferenceTraceRecord, StrEnum_SESSIONLISTNODE, StrEnum_EVENTLISTNODE, StrEnum_RDPDR_IOCOMPLETION_PACKET, StrEnum_RDPDR_IOREQUEST_PACKET, StrEnum_RDPDR_UPDATE_DEVICEINFO_PACKET, StrEnum_RDPDR_DEVICE_REPLY_PACKET, StrEnum_RDPDR_DEVICELIST_ANNOUNCE_PACKET, StrEnum_RDPDR_DEVICE_ANNOUNCE, StrEnum_RDPDR_CLIENT_NAME_PACKET, StrEnum_RDPDR_CLIENT_CONFIRM_PACKET, StrEnum_RDPDR_SERVER_ANNOUNCE_PACKET, StrEnum_RDPDR_HEADER, StrEnum_TRC_CONFIG, StrEnum_TRC_PREFIX_DATA, StrEnum_last }; // 1) All ENUM_VALUE_DESCRIPTOR definitions are named EnumValueDescrsOf_ENUMTYPENAME, where // ENUMTYPENAME defines the corresponding enumerated type. // ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_DEVICE_STATUS [] = { {0, "dsAvailable"}, {1, "dsDisabled"}, {0, NULL} }; ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_DEVICE_TYPE [] = { {1, "RDPDR_DTYP_SERIAL"}, {2, "RDPDR_DTYP_PARALLEL"}, {3, "RDPDR_DTYP_FILE"}, {4, "RDPDR_DTYP_PRINT"}, {0, NULL} }; ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_CLIENT_STATUS [] = { {0, "csDisconnected"}, {1, "csPendingClientConfirm"}, {2, "csPendingClientReconfirm"}, {3, "csConnected"}, {4, "csExpired"}, {0, NULL} }; ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_ExchangeManagerState [] = { {0, "demsStopped"}, {1, "demsStarted"}, {0, NULL} }; #if DBG #define TOPOBJFIELDS(ObjTyp) \ FIELD3(FieldTypeBoolean, ObjTyp, _IsValid), \ FIELD3(FieldTypeULong, ObjTyp, _ObjectType), \ FIELD3(FieldTypeBoolean, ObjTyp, _ForceTrace), \ FIELD3(FieldTypePointer, ObjTyp, _ClassName), \ FIELD3(FieldTypeULong, ObjTyp, _magicNo) #else // DBG #define TOPOBJFIELDS(ObjTyp) \ FIELD3(FieldTypeBoolean, ObjTyp, _IsValid), \ FIELD3(FieldTypeULong, ObjTyp, _ObjectType) #endif // DBG FIELD_DESCRIPTOR TopObjFields[] = { TOPOBJFIELDS(TopObj), FIELDLAST }; FIELD_DESCRIPTOR DrExchangeManagerFields[] = { TOPOBJFIELDS(DrExchangeManager), FIELD3(FieldTypePointer, DrExchangeManager, _RxMidAtlas), FIELD4(FieldTypeEnum, DrExchangeManager, _demsState, EnumValueDescrsOf_ExchangeManagerState), FIELD3(FieldTypePointer, DrExchangeManager, _Session), FIELDLAST }; FIELD_DESCRIPTOR DrExchangeFields[] = { TOPOBJFIELDS(DrExchange), FIELD3(FieldTypeULong, DrExchange, _crefs), FIELD3(FieldTypePointer, DrExchange, _ExchangeManager), FIELD3(FieldTypePointer, DrExchange, _Context), FIELD3(FieldTypePointer, DrExchange, _ExchangeUser), FIELD3(FieldTypeUShort, DrExchange, _Mid), FIELDLAST }; FIELD_DESCRIPTOR DrIoContextFields[] = { TOPOBJFIELDS(DrIoContext), FIELD3(FieldTypePointer, DrIoContext, _Device), FIELD3(FieldTypeBool, DrIoContext, _Busy), FIELD3(FieldTypeBool, DrIoContext, _Cancelled), FIELD3(FieldTypeBool, DrIoContext, _Disconnected), FIELD3(FieldTypePointer, DrIoContext, _RxContext), FIELD3(FieldTypeChar, DrIoContext, _MajorFunction), FIELD3(FieldTypeChar, DrIoContext, _MinorFunction), FIELDLAST }; FIELD_DESCRIPTOR DrDeviceManagerFields[] = { TOPOBJFIELDS(DrDeviceManager), FIELD3(FieldTypeStruct, DrDeviceManager, _DeviceList), FIELD3(FieldTypePointer, DrDeviceManager, _Session), FIELDLAST }; FIELD_DESCRIPTOR DoubleListFields[] = { TOPOBJFIELDS(DoubleList), FIELD3(FieldTypeStruct, DoubleList, _List), FIELDLAST }; FIELD_DESCRIPTOR KernelResourceFields[] = { TOPOBJFIELDS(KernelResource), FIELD3(FieldTypeStruct, KernelResource, _Resource), FIELDLAST }; FIELD_DESCRIPTOR VirtualChannelFields[] = { TOPOBJFIELDS(VirtualChannel), FIELD3(FieldTypeULong, VirtualChannel, _crefs), FIELD3(FieldTypePointer, VirtualChannel, _Channel), FIELD3(FieldTypeStruct, VirtualChannel, _HandleLock), FIELD3(FieldTypePointer, VirtualChannel, _DeletionEvent), FIELDLAST }; #define DRDEVICEFIELDS(ObjType) \ TOPOBJFIELDS(ObjType), \ FIELD3(FieldTypeULong, ObjType, _crefs), \ FIELD3(FieldTypeStruct, ObjType, _Session), \ FIELD3(FieldTypeULong, ObjType, _DeviceId), \ FIELD4(FieldTypeEnum, ObjType, _DeviceType, EnumValueDescrsOf_DEVICE_TYPE), \ FIELD3(FieldTypeStruct, ObjType, _PreferredDosName), \ FIELD4(FieldTypeEnum, ObjType, _DeviceStatus, EnumValueDescrsOf_DEVICE_STATUS) FIELD_DESCRIPTOR DrDeviceFields[] = { DRDEVICEFIELDS(DrDevice), FIELDLAST }; #define DRPRINTERPORTFIELDS(ObjType) \ DRDEVICEFIELDS(ObjType), \ FIELD3(FieldTypeULong, ObjType, _PortNumber), \ FIELD3(FieldTypeStruct, ObjType, _SymbolicLinkName), \ FIELD3(FieldTypeBool, ObjType, _IsOpen) FIELD_DESCRIPTOR DrPrinterPortFields[] = { DRPRINTERPORTFIELDS(DrPrinterPort), FIELDLAST }; FIELD_DESCRIPTOR DrParallelPortFields[] = { DRPRINTERPORTFIELDS(DrParallelPort), FIELDLAST }; FIELD_DESCRIPTOR DrSerialPortFields[] = { DRPRINTERPORTFIELDS(DrSerialPort), FIELDLAST }; FIELD_DESCRIPTOR DrSessionManagerFields[] = { TOPOBJFIELDS(DrSessionManager), FIELD3(FieldTypeStruct, DrSessionManager, _SessionList), FIELDLAST }; FIELD_DESCRIPTOR DrSessionFields[] = { TOPOBJFIELDS(DrSession), FIELD3(FieldTypeULong, DrSession, _crefs), FIELD3(FieldTypeStruct, DrSession, _Channel), FIELD3(FieldTypeStruct, DrSession, _PacketReceivers), FIELD3(FieldTypeStruct, DrSession, _ConnectNotificatingLock), FIELD3(FieldTypeStruct, DrSession, _ChannelLock), FIELD4(FieldTypeEnum, DrSession, _SessionState, EnumValueDescrsOf_CLIENT_STATUS), FIELD3(FieldTypePointer, DrSession, _ChannelBuffer), FIELD3(FieldTypeULong, DrSession, _ChannelBufferSize), FIELD3(FieldTypeStruct, DrSession, _ChannelDeletionEvent), FIELD3(FieldTypeULong, DrSession, _ReadStatus.Status), FIELD3(FieldTypeULong, DrSession, _ReadStatus.Information), FIELD3(FieldTypeULong, DrSession, _ClientId), FIELD3(FieldTypeStruct, DrSession, _ExchangeManager), FIELD3(FieldTypeULong, DrSession, _PartialPacketData), FIELD3(FieldTypeStruct, DrSession, _ClientName), FIELD3(FieldTypeStruct, DrSession, _DeviceManager), FIELD3(FieldTypeULong, DrSession, _SessionId), FIELD3(FieldTypeUShort, DrSession, _ClientVersion.Major), FIELD3(FieldTypeUShort, DrSession, _ClientVersion.Major), FIELD3(FieldTypeLong, DrSession, _Initialized), FIELDLAST }; typedef struct tagCHANNELAPCCONTEXT { SmartPtr<VirtualChannel> Channel; PIO_APC_ROUTINE ApcRoutine; PVOID ApcContext; } CHANNELAPCCONTEXT, *PCHANNELAPCCONTEXT; FIELD_DESCRIPTOR ChannelApcContextFields[] = { FIELD3(FieldTypeStruct, CHANNELAPCCONTEXT, Channel), FIELD3(FieldTypePointer, CHANNELAPCCONTEXT, ApcRoutine), FIELD3(FieldTypePointer, CHANNELAPCCONTEXT, ApcContext), FIELDLAST }; #if DBG FIELD_DESCRIPTOR ReferenceTraceRecordFields[] = { FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[0]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[1]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[2]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[3]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[4]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[5]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[6]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[7]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[8]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[9]), FIELD3(FieldTypePointer, ReferenceTraceRecord, pRefCount), FIELD3(FieldTypePointer, ReferenceTraceRecord, ClassName), FIELD3(FieldTypeLong, ReferenceTraceRecord, refs), FIELDLAST }; #endif FIELD_DESCRIPTOR SESSIONLISTNODEFields[] = { #if DBG FIELD3(FieldTypeULong, SESSIONLISTNODE, magicNo), #endif FIELD3(FieldTypeULong, SESSIONLISTNODE, sessionID), FIELD3(FieldTypeStruct, SESSIONLISTNODE, requestListHead), FIELD3(FieldTypeStruct, SESSIONLISTNODE, eventListHead), FIELD3(FieldTypeStruct, SESSIONLISTNODE, listEntry), FIELDLAST }; FIELD_DESCRIPTOR EVENTLISTNODEFields[] = { #if DBG FIELD3(FieldTypeULong, EVENTLISTNODE, magicNo), #endif FIELD3(FieldTypePointer, EVENTLISTNODE, event), FIELD3(FieldTypeULong, EVENTLISTNODE, type), FIELD3(FieldTypeStruct, EVENTLISTNODE, listEntry), FIELDLAST }; #define RDPDRPACKETCODE(Component, PacketId) \ MAKELONG(Component, PacketId) ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_PACKET_CODE [] = { {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_SERVER_ANNOUNCE), "RDPDR_SERVER_ANNOUNCE_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_CLIENTID_CONFIRM), "DR_CORE_CLIENTID_CONFIRM_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_CLIENT_NAME), "DR_CORE_CLIENT_NAME_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICE_ANNOUNCE), "DR_CORE_DEVICE_ANNOUNCE@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICELIST_ANNOUNCE), "DR_CORE_DEVICELIST_ANNOUNCE_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICELIST_REPLY), "DR_CORE_DEVICELIST_REPLY_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICE_REPLY), "DR_CORE_DEVICE_REPLY_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICE_IOREQUEST), "DR_CORE_DEVICE_IOREQUEST_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICE_IOCOMPLETION), "DR_CORE_DEVICE_IOCOMPLETION_PACKET@"}, {0, NULL} }; FIELD_DESCRIPTOR RdpdrHeaderFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELDLAST }; FIELD_DESCRIPTOR RdpdrServerAnnounceFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeUShort, RDPDR_SERVER_ANNOUNCE_PACKET, VersionInfo.Major), FIELD3(FieldTypeUShort, RDPDR_SERVER_ANNOUNCE_PACKET, VersionInfo.Minor), FIELD3(FieldTypeULong, RDPDR_SERVER_ANNOUNCE_PACKET, ServerAnnounce.ClientId), FIELDLAST }; FIELD_DESCRIPTOR RdpdrClientConfirmFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeUShort, RDPDR_CLIENT_CONFIRM_PACKET, VersionInfo.Major), FIELD3(FieldTypeUShort, RDPDR_CLIENT_CONFIRM_PACKET, VersionInfo.Minor), FIELD3(FieldTypeULong, RDPDR_CLIENT_CONFIRM_PACKET, ClientConfirm.ClientId), FIELDLAST }; FIELD_DESCRIPTOR RdpdrClientNameFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), // FIELD3(FieldTypeULong, RDPDR_CLIENT_NAME_PACKET, (ULONG)Name.Unicode), FIELD3(FieldTypeULong, RDPDR_CLIENT_NAME_PACKET, Name.CodePage), FIELD3(FieldTypeULong, RDPDR_CLIENT_NAME_PACKET, Name.ComputerNameLen), FIELDLAST }; FIELD_DESCRIPTOR RdpdrDeviceAnnounceFields[] = { FIELD3(FieldTypeULong, RDPDR_DEVICE_ANNOUNCE, DeviceType), FIELD3(FieldTypeULong, RDPDR_DEVICE_ANNOUNCE, DeviceId), FIELD3(FieldTypeStruct, RDPDR_DEVICE_ANNOUNCE, PreferredDosName), FIELD3(FieldTypeULong, RDPDR_DEVICE_ANNOUNCE, DeviceDataLength), FIELDLAST }; FIELD_DESCRIPTOR RdpdrDeviceListAnnounceFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeULong, RDPDR_DEVICELIST_ANNOUNCE_PACKET, DeviceListAnnounce.DeviceCount), FIELD3(FieldTypeStruct, RDPDR_DEVICELIST_ANNOUNCE_PACKET, DeviceAnnounce), FIELDLAST }; ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_DEVICE_REPLY_RESULT [] = { {0, "RDPDR_DEVICE_REPLY_SUCCESS"}, {1, "RDPDR_DEVICE_REPLY_REJECTED"}, {0, NULL} }; FIELD_DESCRIPTOR RdpdrDeviceReplyFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeULong, RDPDR_DEVICE_REPLY_PACKET, DeviceReply.DeviceId), FIELD4(FieldTypeEnum, RDPDR_DEVICE_REPLY_PACKET, DeviceReply.ResultCode, EnumValueDescrsOf_DEVICE_REPLY_RESULT ), FIELDLAST }; FIELD_DESCRIPTOR RdpdrUpdateDeviceInfoFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeULong, RDPDR_UPDATE_DEVICEINFO_PACKET, DeviceUpdate.DeviceId), FIELD3(FieldTypeULong, RDPDR_UPDATE_DEVICEINFO_PACKET, DeviceUpdate.DeviceDataLength), FIELDLAST }; ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_MAJOR_FUNCTION [] = { {0x00, "IRP_MJ_CREATE"}, {0x01, "IRP_MJ_CREATE_NAMED_PIPE"}, {0x02, "IRP_MJ_CLOSE"}, {0x03, "IRP_MJ_READ"}, {0x04, "IRP_MJ_WRITE"}, {0x05, "IRP_MJ_QUERY_INFORMATION"}, {0x06, "IRP_MJ_SET_INFORMATION"}, {0x07, "IRP_MJ_QUERY_EA"}, {0x08, "IRP_MJ_SET_EA"}, {0x09, "IRP_MJ_FLUSH_BUFFERS"}, {0x0a, "IRP_MJ_QUERY_VOLUME_INFORMATION"}, {0x0b, "IRP_MJ_SET_VOLUME_INFORMATION"}, {0x0c, "IRP_MJ_DIRECTORY_CONTROL"}, {0x0d, "IRP_MJ_FILE_SYSTEM_CONTROL"}, {0x0e, "IRP_MJ_DEVICE_CONTROL"}, {0x0f, "IRP_MJ_INTERNAL_DEVICE_CONTROL"}, {0x10, "IRP_MJ_SHUTDOWN"}, {0x11, "IRP_MJ_LOCK_CONTROL"}, {0x12, "IRP_MJ_CLEANUP"}, {0x13, "IRP_MJ_CREATE_MAILSLOT"}, {0x14, "IRP_MJ_QUERY_SECURITY"}, {0x15, "IRP_MJ_SET_SECURITY"}, {0x16, "IRP_MJ_POWER"}, {0x17, "IRP_MJ_SYSTEM_CONTROL"}, {0x18, "IRP_MJ_DEVICE_CHANGE"}, {0x19, "IRP_MJ_QUERY_QUOTA"}, {0x1a, "IRP_MJ_SET_QUOTA"}, {0x1b, "IRP_MJ_PNP"}, {0x1b, "IRP_MJ_MAXIMUM_FUNCTION"}, {0, NULL} }; FIELD_DESCRIPTOR RdpdrIoRequestFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.DeviceId), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.FileId), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.CompletionId), FIELD4(FieldTypeEnum, RDPDR_IOREQUEST_PACKET, IoRequest.MajorFunction, EnumValueDescrsOf_MAJOR_FUNCTION), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.MinorFunction), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.DesiredAccess), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.AllocationSize.u.HighPart), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.AllocationSize.u.LowPart), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.FileAttributes), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.ShareAccess), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.Disposition), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.CreateOptions), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.PathLength), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Read.Length), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Write.Length), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.DeviceIoControl.OutputBufferLength), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.DeviceIoControl.InputBufferLength), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.DeviceIoControl.IoControlCode), FIELDLAST }; FIELD_DESCRIPTOR RdpdrIoCompletionFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.DeviceId), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.CompletionId), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.IoStatus), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.Create.FileId), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.Read.Length), FIELD3(FieldTypeStruct, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.Read.Buffer), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.Write.Length), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.DeviceIoControl.OutputBufferLength), FIELD3(FieldTypeStruct, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.DeviceIoControl.OutputBuffer), FIELDLAST }; #if DBG ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_TRACE_LEVEL [] = { {0, "TRC_LEVEL_DBG"}, {1, "TRC_LEVEL_NRM"}, {2, "TRC_LEVEL_ALT"}, {3, "TRC_LEVEL_ERR"}, {4, "TRC_LEVEL_ASSERT"}, {5, "TRC_LEVEL_DIS"}, {0, NULL} }; FIELD_DESCRIPTOR TRC_CONFIGFields[] = { FIELD4(FieldTypeULong, TRC_CONFIG, TraceLevel, EnumValueDescrsOf_TRACE_LEVEL), FIELD3(FieldTypeULong, TRC_CONFIG, FunctionLength), FIELD3(FieldTypeULong, TRC_CONFIG, TraceDebugger), FIELD3(FieldTypeULong, TRC_CONFIG, TraceProfile), FIELD3(FieldTypeStruct, TRC_CONFIG, Prefix[0]), FIELD3(FieldTypeStruct, TRC_CONFIG, Prefix[1]), FIELDLAST }; FIELD_DESCRIPTOR TRC_PREFIX_DATAFields[] = { FIELD3(FieldTypeStruct, TRC_PREFIX_DATA, name), FIELD3(FieldTypeULong, TRC_PREFIX_DATA, start), FIELD3(FieldTypeULong, TRC_PREFIX_DATA, end), FIELDLAST }; #endif // DBG // // List of structs currently handled by the debugger extensions // STRUCT_DESCRIPTOR Structs[] = { STRUCT(RX_CONTEXT,RxContextFields,0xffff,RDBSS_NTC_RX_CONTEXT), STRUCT(FCB,FcbFields,0xeff0,RDBSS_STORAGE_NTC(0)), STRUCT(FCB,FcbFields,0xeff0,RDBSS_STORAGE_NTC(0xf0)), STRUCT(SRV_OPEN,SrvOpenFields,0xffff,RDBSS_NTC_SRVOPEN), STRUCT(FOBX,FobxFields,0xffff,RDBSS_NTC_FOBX), STRUCT(SRV_CALL,SrvCallFields,0xffff,RDBSS_NTC_SRVCALL), STRUCT(NET_ROOT,NetRootFields,0xffff,RDBSS_NTC_NETROOT), STRUCT(V_NET_ROOT,VNetRootFields,0xffff,RDBSS_NTC_V_NETROOT), STRUCT(CHANNELAPCCONTEXT,ChannelApcContextFields,0xffff,0), STRUCT(TopObj,TopObjFields,0xffff,0), STRUCT(DrExchangeManager,DrExchangeManagerFields,0xffff,0), STRUCT(DrExchange,DrExchangeFields,0xffff,0), STRUCT(DrIoContext,DrIoContextFields,0xffff,0), STRUCT(DrDeviceManager,DrDeviceManagerFields,0xffff,0), STRUCT(DoubleList,DoubleListFields,0xffff,0), STRUCT(KernelResource,KernelResourceFields,0xffff,0), STRUCT(VirtualChannel,VirtualChannelFields,0xffff,0), STRUCT(DrDevice,DrDeviceFields,0xffff,0), STRUCT(DrPrinterPort,DrPrinterPortFields,0xffff,0), STRUCT(DrParallelPort,DrParallelPortFields,0xffff,0), STRUCT(DrSerialPort,DrSerialPortFields,0xffff,0), STRUCT(DrSessionManager,DrSessionManagerFields,0xffff,0), STRUCT(DrSession,DrSessionFields,0xffff,0), #if DBG STRUCT(ReferenceTraceRecord,ReferenceTraceRecordFields,0xffff,0), #endif STRUCT(SESSIONLISTNODE,SESSIONLISTNODEFields,0xffff,0), STRUCT(EVENTLISTNODE,EVENTLISTNODEFields,0xffff,0), STRUCT(RDPDR_IOCOMPLETION_PACKET,RdpdrIoCompletionFields,0xffff,0), STRUCT(RDPDR_IOREQUEST_PACKET,RdpdrIoRequestFields,0xffff,0), STRUCT(RDPDR_UPDATE_DEVICEINFO_PACKET,RdpdrUpdateDeviceInfoFields,0xffff,0), STRUCT(RDPDR_DEVICE_REPLY_PACKET,RdpdrDeviceReplyFields,0xffff,0), STRUCT(RDPDR_DEVICELIST_ANNOUNCE_PACKET,RdpdrDeviceListAnnounceFields,0xffff,0), STRUCT(RDPDR_DEVICE_ANNOUNCE,RdpdrDeviceAnnounceFields,0xffff,0), STRUCT(RDPDR_CLIENT_NAME_PACKET,RdpdrClientNameFields,0xffff,0), STRUCT(RDPDR_CLIENT_CONFIRM_PACKET,RdpdrClientConfirmFields,0xffff,0), STRUCT(RDPDR_SERVER_ANNOUNCE_PACKET,RdpdrServerAnnounceFields,0xffff,0), STRUCT(RDPDR_HEADER,RdpdrHeaderFields,0xffff,0), #if DBG STRUCT(TRC_CONFIG,TRC_CONFIGFields,0xffff,0), STRUCT(TRC_PREFIX_DATA,TRC_PREFIX_DATAFields,0xffff,0), #endif // DBG STRUCTLAST }; ULONG_PTR FieldOffsetOfContextListEntryInRxC(){ return FIELD_OFFSET(RX_CONTEXT,ContextListEntry);} PCWSTR GetExtensionLibPerDebugeeArchitecture(ULONG DebugeeArchitecture){ switch (DebugeeArchitecture) { case RX_PROCESSOR_ARCHITECTURE_INTEL: return L"kdextx86.dll"; case RX_PROCESSOR_ARCHITECTURE_MIPS: return L"kdextmip.dll"; case RX_PROCESSOR_ARCHITECTURE_ALPHA: return L"kdextalp.dll"; case RX_PROCESSOR_ARCHITECTURE_PPC: return L"kdextppc.dll"; default: return(NULL); } } //CODE.IMPROVEMENT it is not good to try to structure along the lines of "this routine knows // rxstructures" versus "this routine knows debugger extensions". also we // need a precomp.h BOOLEAN wGetData( ULONG_PTR dwAddress, PVOID ptr, ULONG size, IN PSZ type); VOID ReadRxContextFields(ULONG_PTR RxContext,PULONG_PTR pFcb,PULONG_PTR pThread, PULONG_PTR pMiniCtx2) { RX_CONTEXT RxContextBuffer; if (!wGetData(RxContext,&RxContextBuffer,sizeof(RxContextBuffer),"RxContextFieldss")) return; *pFcb = (ULONG_PTR)(RxContextBuffer.pFcb); *pThread = (ULONG_PTR)(RxContextBuffer.LastExecutionThread); *pMiniCtx2 = (ULONG_PTR)(RxContextBuffer.MRxContext[2]); } FOLLOWON_HELPER_RETURNS __FollowOnError ( OUT PBYTE Buffer2, IN PBYTE followontext, ULONG LastId, ULONG Index) { if (LastId==0) { sprintf((char *)Buffer2,"Cant dump a %s. no previous dump.\n", followontext,Index); } else { sprintf((char *)Buffer2,"Cant dump a %s from a %s\n", followontext,Structs[Index].StructName); } return(FOLLOWONHELPER_ERROR); } #define FollowOnError(A) (__FollowOnError(Buffer2,A,p->IdOfLastDump,p->IndexOfLastDump)) VOID dprintfsprintfbuffer(BYTE *Buffer); DECLARE_FOLLOWON_HELPER_CALLEE(FcbFollowOn) { //BYTE DbgBuf[200]; //sprintf(DbgBuf,"top p,id=%08lx,%d",p,p->IdOfLastDump); //dprintfsprintfbuffer(DbgBuf); switch (p->IdOfLastDump) { case StrEnum_RX_CONTEXT:{ PRX_CONTEXT RxContext = (PRX_CONTEXT)(&p->StructDumpBuffer[0]); sprintf((char *)Buffer2," %08p\n",RxContext->pFcb); return(FOLLOWONHELPER_DUMP); } break; default: return FollowOnError((PUCHAR)"irp"); } }
31,088
12,730
/* Copyright (c) 2020 The Connectal Project * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "fwbslave.h" template<int OPT_ZERO_ON_IDLE, int F_OPT_CLK2FFLOGIC> class WbPriArbiterIfc { WishboneType a; WishboneType b; WishboneType *o; }; template<int OPT_ZERO_ON_IDLE, int F_OPT_CLK2FFLOGIC> class WbPriArbiter __implements __verilog WbPriArbiterIfc<OPT_ZERO_ON_IDLE, F_OPT_CLK2FFLOGIC> { bool r_a_owner; void a.stb(bool we, __uint(AW) addr, __uint(DW) data, __uint(DW/8) sel) if (this->a.cyc) { r_a_owner = true; this->o->stb(we, addr, data, sel); } bool a.ack() { return this->o->ack() & r_a_owner; } bool a.stall() { return this->o->stall() | !r_a_owner; } bool a.err() { return this->o->err() & r_a_owner; } void b.stb(bool we, __uint(AW) addr, __uint(DW) data, __uint(DW/8) sel) if (!this->a.cyc) { r_a_owner = false; this->o->stb(we, addr, data, sel); } bool b.ack() { return this->o->ack() & !r_a_owner; } bool b.stall() { return this->o->stall() | r_a_owner; } bool b.err() { return this->o->err() & !r_a_owner; } }; WbPriArbiter<0, 1> dummy;
2,248
862
/*============================================================================= Copyright (c) 2001-2013 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #include <boost/detail/lightweight_test.hpp> #include <boost/spirit/home/x3.hpp> //~ #include <boost/phoenix/core.hpp> //~ #include <boost/phoenix/operator.hpp> #include <string> #include <iostream> #include "test.hpp" int main() { using boost::spirit::x3::ascii::char_; using boost::spirit::x3::lit; using spirit_test::test; using spirit_test::test_attr; // Basic tests { BOOST_TEST(test("b", char_ - 'a')); BOOST_TEST(!test("a", char_ - 'a')); BOOST_TEST(test("/* abcdefghijk */", "/*" >> *(char_ - "*/") >> "*/")); BOOST_TEST(!test("switch", lit("switch") - "switch")); } // Test attributes { char attr; BOOST_TEST(test_attr("xg", (char_ - 'g') >> 'g', attr)); BOOST_TEST(attr == 'x'); } // Test handling of container attributes { std::string attr; BOOST_TEST(test_attr("abcdefg", *(char_ - 'g') >> 'g', attr)); BOOST_TEST(attr == "abcdef"); } // $$$ Not yet implemented //~ { //~ BOOST_TEST(test("b", char_ - no_case['a'])); //~ BOOST_TEST(!test("a", char_ - no_case['a'])); //~ BOOST_TEST(!test("A", char_ - no_case['a'])); //~ BOOST_TEST(test("b", no_case[lower - 'a'])); //~ BOOST_TEST(test("B", no_case[lower - 'a'])); //~ BOOST_TEST(!test("a", no_case[lower - 'a'])); //~ BOOST_TEST(!test("A", no_case[lower - 'a'])); //~ } // $$$ Not yet implemented //~ { //~ using boost::spirit::x3::_1; //~ namespace phx = boost::phoenix; //~ std::string s; //~ BOOST_TEST(test( //~ "/*abcdefghijk*/" //~ , "/*" >> *(char_ - "*/")[phx::ref(s) += _1] >> "*/" //~ )); //~ BOOST_TEST(s == "abcdefghijk"); //~ s.clear(); //~ BOOST_TEST(test( //~ " /*abcdefghijk*/" //~ , "/*" >> *(char_ - "*/")[phx::ref(s) += _1] >> "*/" //~ , space //~ )); //~ BOOST_TEST(s == "abcdefghijk"); //~ } return boost::report_errors(); }
2,434
885
#include <QtTest> // add necessary includes here #include <iostream> #include <vector> #include <algorithm/algorithm.h> #include <object/singular/hitobject.h> #include <object/singular/timingpoint.h> #include <QDebug> #include <QSharedPointer> class TestObjs { public: TestObjs() { hoNote.loadParameters( 0, 192, 1000, HitObject::NOTE_TYPE::NORMAL, OsuObject::SAMPLE_SET::AUTO, 0, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 50, "hitsound.wav", 4); hoLongNote.loadParameters( 0, 192, 1000, HitObject::NOTE_TYPE::LN, OsuObject::SAMPLE_SET::AUTO, 1500, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 50, "hitsound.wav", 4); tpSv.loadParameters( 1000, 2, 4, OsuObject::SAMPLE_SET::AUTO, 0, 50, false, false ); tpBpm.loadParameters( 1000, 300, 4, OsuObject::SAMPLE_SET::AUTO, 0, 50, true, false ); eHOSingular.loadParameters(1, 1000, 0, 4); eHOMutliple[0].loadParameters(1, 1000, 0, 4); eHOMutliple[1].loadParameters(2, 2000, 0, 4); hoMultiple[0].loadParameters( 0, 192, 1000, HitObject::NOTE_TYPE::NORMAL, OsuObject::SAMPLE_SET::AUTO, 0, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 40, "hit1.wav", 4); hoMultiple[1].loadParameters( 2, 192, 2000, HitObject::NOTE_TYPE::LN, OsuObject::SAMPLE_SET::AUTO, 2500, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 50, "hit2.wav", 4); hoMultiple[2].loadParameters( 3, 192, 3000, HitObject::NOTE_TYPE::NORMAL, OsuObject::SAMPLE_SET::AUTO, 0, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 60, "hit3.wav", 4); tpMultiple[0].loadParameters( 0, 400, 4, OsuObject::SAMPLE_SET::NORMAL, 1, 50, true, false ); tpMultiple[1].loadParameters( 1000, 2, 4, OsuObject::SAMPLE_SET::NORMAL, 1, 50, false, true ); tpMultiple[2].loadParameters( 2000, 0.5, 4, OsuObject::SAMPLE_SET::NORMAL, 1, 50, false, false ); pEHOMutliple = QSPtr<HitObjectV>::create(eHOMutliple); pHOMultiple = QSPtr<HitObjectV>::create(hoMultiple); pTPMultiple = QSPtr<TimingPointV>::create(tpMultiple); } QString rawHOStrNote = "64,192,1000,1,0,0:0:0:50:hitsound.wav"; QString rawHOStrLongNote = "64,192,1000,128,0,1500:0:0:0:50:hitsound.wav"; QString rawTPSv = "1000,-50,4,0,0,50,0,0"; QString rawTPBpm = "1000,200,4,0,0,50,1,0"; QString eHOStrSingular = "00:01:000 (1000|1) -"; QString eHOStrMultiple = "00:01:000 (1000|1,2000|2) -"; QString rawHOStrMultiple = "64,192,1000,1,0,0:0:0:40:hit1.wav\n" // N "320,192,2000,128,0,2500:0:0:0:70:hit2.wav\n" // LN "448,192,3000,1,0,0:0:0:60:hit3.wav"; // N QString rawTPStrMultiple = "0,150,4,1,1,50,1,0\n" // BPM 400 "1000,-50,4,1,1,50,0,1\n" // SV 2.0 Kiai "2000,-200,4,1,1,50,0,0"; // SV 0.50 HitObject hoNote; HitObject hoLongNote; TimingPoint tpSv; TimingPoint tpBpm; HitObject eHOSingular; HitObjectV eHOMutliple = HitObjectV(2); HitObjectV hoMultiple = HitObjectV(3); TimingPointV tpMultiple = TimingPointV(3); QSPtr<HitObjectV> pEHOMutliple; QSPtr<HitObjectV> pHOMultiple ; QSPtr<TimingPointV> pTPMultiple ; }; class reamber_base_test : public QObject { Q_OBJECT private slots: void trimEHO(); void hoRawLoading(); void tpRawLoad(); void hoEditorLoading(); void hoVRawLoading(); void tpVRawLoading(); void hoVEditorLoading(); void foboHO(); void foboTP(); void loboHO(); void loboTP(); void getColumnV(); void getOffsetMinHO(); void getOffsetMaxHO(); void getOffsetMinTP(); void getOffsetMaxTP(); void sortByOffsetHO(); void sortByOffsetTP(); void tpVMultiply(); void tpVGetAve(); void tpVArithmetic(); void libOffsetDiff(); void libCopySingularHO(); void libCopyMultipleHO(); void libCopySingularTP(); void libCopyMultipleTP(); void libCopySubByHO(); void libCopySubByHODelay(); void libCopySubToHO(); void libCopySubToHODelay(); void libCopyReldiff(); void libCopyReldiffDelay(); void libCopyAbsdiff(); void libCopyAbsdiffDelay(); void libNormalize(); void libCreateStutterRelative(); void libCreateStutterAbsolute(); void libCreateStutterFromOffset(); void libExtractNth(); void libDeleteNth(); private: TestObjs tests = TestObjs(); }; void reamber_base_test::trimEHO() { QString str = tests.eHOStrMultiple; HitObject::trimEditor(str); QVERIFY(QString("1000|1,2000|2") == str); } void reamber_base_test::hoRawLoading() { HitObject ho; ho.loadRaw(tests.rawHOStrNote, 4); QVERIFY(ho == tests.hoNote); } void reamber_base_test::tpRawLoad() { TimingPoint tp; tp.loadRaw(tests.rawTPBpm); QVERIFY(tp == tests.tpBpm); } void reamber_base_test::hoEditorLoading() { HitObject ho("00:01:000 (1000|0) - ", HitObject::TYPE::EDITOR, 4); HitObject ho_expected; ho_expected.loadParameters( 0, 192, 1000, HitObject::NOTE_TYPE::NORMAL, OsuObject::SAMPLE_SET::AUTO, 0, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 50, "", 4); QVERIFY(ho_expected == ho); } void reamber_base_test::hoVRawLoading() { HitObjectV ho_v(tests.rawHOStrMultiple, HitObject::TYPE::RAW, 4); QVERIFY(ho_v == tests.hoMultiple); } void reamber_base_test::tpVRawLoading() { TimingPointV tpV(tests.rawTPStrMultiple); QVERIFY(tpV == tests.tpMultiple); } void reamber_base_test::hoVEditorLoading() { HitObjectV ho_v(tests.eHOStrMultiple, HitObject::TYPE::EDITOR, 4); QVERIFY(ho_v == tests.eHOMutliple); } // FOBO: First Object By Offset // LOBO: Last Object By Offset void reamber_base_test::foboHO(){ QVERIFY(tests.hoMultiple[0] == // Expect the first object tests.hoMultiple.getFirstObjectByOffset()); } void reamber_base_test::foboTP(){ QVERIFY(tests.tpMultiple[0] == // Expect the first object tests.tpMultiple.getFirstObjectByOffset()); } void reamber_base_test::loboHO(){ QVERIFY(tests.hoMultiple[2] == // Expect the first object tests.hoMultiple.getLastObjectByOffset()); } void reamber_base_test::loboTP(){ QVERIFY(tests.tpMultiple[2] == // Expect the first object tests.tpMultiple.getLastObjectByOffset()); } void reamber_base_test::getColumnV() { QVERIFY((tests.hoMultiple.getColumnV() == QVector<unsigned int>{0, 2, 3})); } void reamber_base_test::getOffsetMinHO() { QVERIFY(tests.hoMultiple.getOffsetMin() == 1000.0); } void reamber_base_test::getOffsetMaxHO() { QVERIFY(tests.hoMultiple.getOffsetMax() == 3000.0); } void reamber_base_test::getOffsetMinTP() { QVERIFY(tests.tpMultiple.getOffsetMin() == 0.0); } void reamber_base_test::getOffsetMaxTP() { QVERIFY(tests.tpMultiple.getOffsetMax() == 2000.0); } void reamber_base_test::sortByOffsetHO() { HitObjectV ho_v = tests.hoMultiple; // Manually sort by descending HitObjectV ho_v_sort_desc = HitObjectV(3); ho_v_sort_desc[0] = ho_v[2]; ho_v_sort_desc[1] = ho_v[1]; ho_v_sort_desc[2] = ho_v[0]; // Sort by Descending ho_v.sortByOffset(false); QVERIFY(ho_v == ho_v_sort_desc); } void reamber_base_test::sortByOffsetTP() { TimingPointV tpV = tests.tpMultiple; // Manually sort by descending TimingPointV tpVSortDesc = TimingPointV(3); tpVSortDesc[0] = tpV[2]; tpVSortDesc[1] = tpV[1]; tpVSortDesc[2] = tpV[0]; // Sort by Descending tpV.sortByOffset(false); QVERIFY(tpV == tpVSortDesc); } void reamber_base_test::tpVMultiply() { // [0] [1] [2] [3] [4] // SELF : 1 1 1 // EFF : 1 1 1 TimingPointV tpV(4); tpV[0].loadParameters(0, 1, false); tpV[1].loadParameters(1, 2, false); tpV[2].loadParameters(4, 4, false); tpV[3].loadParameters(5, 8, false); TimingPointV tpV_eff(3); tpV_eff[0].loadParameters(0, 1, false); tpV_eff[1].loadParameters(2, 0.5, false); tpV_eff[2].loadParameters(3, 0.25, false); tpV.crossEffectMultiply(tpV_eff); QVector<QString> expected = { "0,-100,4,0,0,25,0,0", "1,-50,4,0,0,25,0,0", "4,-100,4,0,0,25,0,0", "5,-50,4,0,0,25,0,0" }; QVERIFY(tpV.getStringRawV() == expected); } void reamber_base_test::tpVGetAve() { // SV TimingPointV tpV = TimingPointV(3); tpV[0].loadParameters(0, 1.5, false); tpV[1].loadParameters(100, 0.5, false); tpV[2].loadParameters(400, 1.75, false); QVERIFY(0.75 == tpV.getAverageSvValue()); // BPM tpV = TimingPointV(3); tpV[0].loadParameters(0, 200, true); tpV[1].loadParameters(100, 100, true); tpV[2].loadParameters(400, 150, true); QVERIFY(125.0 == tpV.getAverageBpmValue()); // MIXED tpV = TimingPointV(4); tpV[0].loadParameters(0, 200, true); tpV[1].loadParameters(50, 0.5, false); // JUNK SV tpV[2].loadParameters(100, 100, true); tpV[3].loadParameters(400, 150, true); QVERIFY(125.0 == tpV.getAverageBpmValue()); } void reamber_base_test::tpVArithmetic() { // + TimingPointV tpV = TimingPointV(3); tpV[0].loadParameters(0, 1.5, false); tpV[1].loadParameters(100, 0.5, false); tpV[2].loadParameters(400, 1.75, false); tpV += 2; // for (auto tp : tpV) { // qDebug() << tp.getStringRaw().toStdString().c_str(); // } QVERIFY(true); } void reamber_base_test::libOffsetDiff() { auto offsetDifference = algorithm::offsetDiff<HitObject>(tests.pHOMultiple); QVERIFY(offsetDifference == QVector<double>({1000, 1000})); } void reamber_base_test::libCopySingularHO() { auto copies = algorithm::copy<HitObject>(tests.hoNote, QVector<double>{1000, 2000}); QVERIFY(QVector<double>({ 1000,2000 }) == copies.getOffsetV(false)); } void reamber_base_test::libCopyMultipleHO() { auto copies = algorithm::copy<HitObject>(tests.pHOMultiple, QVector<double>{1000, 2000}); // Get unique offset for copies QVERIFY(QVector<double>({ 1000,2000,3000,4000 }) == copies.getOffsetV(true)); } void reamber_base_test::libCopySingularTP() { auto copies = algorithm::copy<TimingPoint>(tests.tpSv, QVector<double>{1000, 2000}); QVERIFY(QVector<double>({ 1000,2000 }) == copies.getOffsetV(false)); } void reamber_base_test::libCopyMultipleTP() { auto copies = algorithm::copy<TimingPoint>(tests.pTPMultiple, QVector<double>{1000, 2000}); // Get unique offset for copies QVERIFY(QVector<double>({ 1000,2000,3000,4000 }) == copies.getOffsetV(true)); } void reamber_base_test::libCopySubByHO() { // EXCLUDE auto copies = algorithm::copySubdBy<HitObject> (QVector<double>({ 100,400,700 }), tests.hoNote, 2, false); // for (auto s : copies.getStringRawV()) // qDebug() << s; QVector<QString> expected = { "64,192,200,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,300,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,500,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,600,1,0,0:0:0:50:hitsound.wav" // Subd 2 }; QVERIFY(copies.getStringRawV() == expected); // INCLUDE copies = algorithm::copySubdBy<HitObject> (QVector<double>({ 100,400,700 }), tests.hoNote, 2, true); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", // Subd 0 "64,192,200,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,300,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,400,1,0,0:0:0:50:hitsound.wav", // Subd 0 "64,192,500,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,600,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,700,1,0,0:0:0:50:hitsound.wav" // Subd 0 }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopySubByHODelay() { auto copies = algorithm::copySubdBy<HitObject>(tests.pHOMultiple, 4, false); QVector<QString> expected = { "64,192,1200,1,0,0:0:0:40:hit1.wav", "64,192,1400,1,0,0:0:0:40:hit1.wav", "64,192,1600,1,0,0:0:0:40:hit1.wav", "64,192,1800,1,0,0:0:0:40:hit1.wav", "320,192,2200,128,0,2500:0:0:0:50:hit2.wav", "320,192,2400,128,0,2500:0:0:0:50:hit2.wav", "320,192,2600,128,0,2500:0:0:0:50:hit2.wav", "320,192,2800,128,0,2500:0:0:0:50:hit2.wav" }; QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copySubdBy<HitObject>(tests.pHOMultiple, 4, true); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "64,192,1200,1,0,0:0:0:40:hit1.wav", "64,192,1400,1,0,0:0:0:40:hit1.wav", "64,192,1600,1,0,0:0:0:40:hit1.wav", "64,192,1800,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "320,192,2200,128,0,2500:0:0:0:50:hit2.wav", "320,192,2400,128,0,2500:0:0:0:50:hit2.wav", "320,192,2600,128,0,2500:0:0:0:50:hit2.wav", "320,192,2800,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopySubToHO() { // EXCLUDE auto copies = algorithm::copySubdTo<HitObject> (QVector<double>({ 100,300,500 }), tests.hoNote, 50, false); QVector<QString> expected = { "64,192,150,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,200,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,250,1,0,0:0:0:50:hitsound.wav", // Subd 3 "64,192,350,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,400,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,450,1,0,0:0:0:50:hitsound.wav" // Subd 3 }; // for (auto ho : copies) { // qDebug() << ho.getStringRaw().toStdString().c_str(); // } QVERIFY(copies.getStringRawV() == expected); // INCLUDE copies = algorithm::copySubdTo<HitObject> (QVector<double>({ 100,300,500 }), tests.hoNote, 50, true); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", // Subd 0 "64,192,150,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,200,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,250,1,0,0:0:0:50:hitsound.wav", // Subd 3 "64,192,300,1,0,0:0:0:50:hitsound.wav", // Subd 0 "64,192,350,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,400,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,450,1,0,0:0:0:50:hitsound.wav", // Subd 3 "64,192,500,1,0,0:0:0:50:hitsound.wav" // Subd 0 }; // for (auto ho : copies) { // qDebug() << ho.getStringRaw().toStdString().c_str(); // } QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopySubToHODelay() { auto copies = algorithm::copySubdTo<HitObject>(tests.pHOMultiple, 250, false); QVector<QString> expected = { "64,192,1250,1,0,0:0:0:40:hit1.wav", "64,192,1500,1,0,0:0:0:40:hit1.wav", "64,192,1750,1,0,0:0:0:40:hit1.wav", "320,192,2250,128,0,2500:0:0:0:50:hit2.wav", "320,192,2500,128,0,2500:0:0:0:50:hit2.wav", "320,192,2750,128,0,2500:0:0:0:50:hit2.wav" }; QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copySubdTo<HitObject>(tests.pHOMultiple, 250, true); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "64,192,1250,1,0,0:0:0:40:hit1.wav", "64,192,1500,1,0,0:0:0:40:hit1.wav", "64,192,1750,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "320,192,2250,128,0,2500:0:0:0:50:hit2.wav", "320,192,2500,128,0,2500:0:0:0:50:hit2.wav", "320,192,2750,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopyReldiff() { auto copies = algorithm::copyRel( QVector<double>({ 100, 300 }), tests.hoNote, 0.25, false); QVector<QString> expected = { "64,192,150,1,0,0:0:0:50:hitsound.wav", }; QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copyRel( QVector<double>({ 100, 300 }), tests.hoNote, 0.25, true); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", "64,192,150,1,0,0:0:0:50:hitsound.wav", "64,192,300,1,0,0:0:0:50:hitsound.wav", }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopyReldiffDelay() { auto copies = algorithm::copyRel<HitObject> (tests.pHOMultiple, 0.25, false); QVector<QString> expected = { "64,192,1250,1,0,0:0:0:40:hit1.wav", "320,192,2250,128,0,2500:0:0:0:50:hit2.wav" }; QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copyRel<HitObject> (tests.pHOMultiple, 0.25, true); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "64,192,1250,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "320,192,2250,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopyAbsdiff() { // EXCLUDE auto copies = algorithm::copyAbs( QVector<double>({ 100, 300 }), tests.hoNote, 50, false, true, false); QVector<QString> expected = { "64,192,150,1,0,0:0:0:50:hitsound.wav" }; QVERIFY(copies.getStringRawV() == expected); // EXCLUDE copies = algorithm::copyAbs( QVector<double>({ 100, 300 }), tests.hoNote, 50, true, true, false); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", "64,192,150,1,0,0:0:0:50:hitsound.wav", "64,192,300,1,0,0:0:0:50:hitsound.wav" }; QVERIFY(copies.getStringRawV() == expected); // EXCLUDE OVERLAP copies = algorithm::copyAbs( QVector<double>({ 100, 300 }), tests.hoNote, 250, true, true, true); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", "64,192,300,1,0,0:0:0:50:hitsound.wav", }; QVERIFY(copies.getStringRawV() == expected); // FROM THE BACK copies = algorithm::copyAbs( QVector<double>({ 100, 300 }), tests.hoNote, 50, true, false, true); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", "64,192,250,1,0,0:0:0:50:hitsound.wav", "64,192,300,1,0,0:0:0:50:hitsound.wav" }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopyAbsdiffDelay() { // EXCLUDE auto copies = algorithm::copyAbs<HitObject> (tests.pHOMultiple, 15, false, true, true); QVector<QString> expected = { "64,192,1015,1,0,0:0:0:40:hit1.wav", "320,192,2015,128,0,2500:0:0:0:50:hit2.wav", }; // INCLUDE QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copyAbs<HitObject> (tests.pHOMultiple, 15, true, true, true); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "64,192,1015,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "320,192,2015,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); // EXCLUDE OVERLAP QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copyAbs<HitObject> (tests.pHOMultiple, 2000, true, true, true); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); // EXCLUDE OVERLAP QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copyAbs<HitObject> (tests.pHOMultiple, 100, true, false, false); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "64,192,1900,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "320,192,2900,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libNormalize() { auto normalized = algorithm::normalize(tests.tpMultiple, 200, false); QVector<QString> expected = { "0,-200,4,1,1,50,0,0" }; QVERIFY(normalized.getStringRawV() == expected); } void reamber_base_test::libCreateStutterRelative() { // SV auto tpV = algorithm::stutterRel(QVector<double>({ 100,350,600 }), 4, 0.2); QVector<QString> expected = { "100,-25,4,0,0,25,0,0", "150,-400,4,0,0,25,0,0", "350,-25,4,0,0,25,0,0", "400,-400,4,0,0,25,0,0", "600,-100,4,0,0,25,0,0" }; QVERIFY(tpV.getStringRawV() == expected); // BPM tpV = algorithm::stutterRel(QVector<double>({ 100,300,700 }), 400, 0.25, 200, true, false); expected = { "100,150,4,0,0,25,1,0", "150,450,4,0,0,25,1,0", "300,150,4,0,0,25,1,0", "400,450,4,0,0,25,1,0", "700,300,4,0,0,25,1,0" }; QVERIFY(tpV.getStringRawV() == expected); } void reamber_base_test::libCreateStutterAbsolute() { // SV auto tpV = algorithm::stutterAbs(QVector<double>({ 100,300,700 }), 1.5, 100, 1.0); //for (auto s : tpV.getStringRawV()) qDebug () << s; QVector<QString> expected = { "100,-66.66666667,4,0,0,25,0,0", "200,-200,4,0,0,25,0,0", "300,-66.66666667,4,0,0,25,0,0", "400,-120,4,0,0,25,0,0", "700,-100,4,0,0,25,0,0" }; QVERIFY(tpV.getStringRawV() == expected); // BPM tpV = algorithm::stutterAbs(QVector<double>({ 100,300,700 }), 150, 100, 100, true, true, true); expected = { "100,400,4,0,0,25,1,0", "200,1200,4,0,0,25,1,0", "300,400,4,0,0,25,1,0", "400,720,4,0,0,25,1,0", "700,600,4,0,0,25,1,0" }; QVERIFY(tpV.getStringRawV() == expected); } void reamber_base_test::libCreateStutterFromOffset() { auto tpV = algorithm::stutter(QVector<double>({ 100,400,700 }), 1.5, 1.0, false, true); QVector<QString> expected = { "100,-66.66666667,4,0,0,25,0,0", "400,-200,4,0,0,25,0,0", "700,-100,4,0,0,25,0,0" }; QVERIFY(tpV.getStringRawV() == expected); } void reamber_base_test::libDeleteNth() { // HO auto ho_v = algorithm::deleteNth<HitObject>(tests.pHOMultiple, 2, 1); QVector<QString> expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", }; QVERIFY(ho_v.getStringRawV() == expected); // TP auto tpV = algorithm::deleteNth<TimingPoint>(tests.pTPMultiple, 2, 1); expected = { "0,150,4,1,1,50,1,0", "1000,-50,4,1,1,50,0,1" }; QVERIFY(tpV.getStringRawV() == expected); } void reamber_base_test::libExtractNth() { // HO auto ho_v = algorithm::extractNth<HitObject>(tests.pHOMultiple, 2, 1); QVector<QString> expected = { "320,192,2000,128,0,2500:0:0:0:50:hit2.wav" }; QVERIFY(ho_v.getStringRawV() == expected); // TP auto tpV = algorithm::extractNth<TimingPoint>(tests.pTPMultiple, 2, 1); expected = { "1000,-50,4,1,1,50,0,1" }; QVERIFY(tpV.getStringRawV() == expected); } QTEST_APPLESS_MAIN(reamber_base_test) #include "tst_reamber_base_test.moc"
23,811
11,834
#include "PanelConfig.h" #include "Globals.h" #include "ModuleRenderer3D.h" #include "ModuleUI.h" #include "PanelFile.h" PanelFile::~PanelFile() { } update_status PanelFile::Draw() { if (App->ui->file_load_model)LoadModel(); if (App->ui->file_save_scene)DisplaySaveScene(); if (App->ui->file_load_scene)DisplayLoadScene(); return UPDATE_CONTINUE; } void PanelFile::LoadModel() { App->ui->LoadFile("fbx"); } void PanelFile::DisplaySaveScene() { App->ui->SaveFile("kumaScene"); } void PanelFile::DisplayLoadScene() { App->ui->LoadFile("kumaScene"); }
564
224
#define ONFRONTCONNECTED 1 #define ONFRONTDISCONNECTED 2 #define ONHEARTBEATWARNING 3 #define ONRSPAUTHENTICATE 4 #define ONRSPUSERLOGIN 5 #define ONRSPUSERLOGOUT 6 #define ONRSPUSERPASSWORDUPDATE 7 #define ONRSPTRADINGACCOUNTPASSWORDUPDATE 8 #define ONRSPUSERAUTHMETHOD 9 #define ONRSPGENUSERCAPTCHA 10 #define ONRSPGENUSERTEXT 11 #define ONRSPORDERINSERT 12 #define ONRSPPARKEDORDERINSERT 13 #define ONRSPPARKEDORDERACTION 14 #define ONRSPORDERACTION 15 #define ONRSPQUERYMAXORDERVOLUME 16 #define ONRSPSETTLEMENTINFOCONFIRM 17 #define ONRSPREMOVEPARKEDORDER 18 #define ONRSPREMOVEPARKEDORDERACTION 19 #define ONRSPEXECORDERINSERT 20 #define ONRSPEXECORDERACTION 21 #define ONRSPFORQUOTEINSERT 22 #define ONRSPQUOTEINSERT 23 #define ONRSPQUOTEACTION 24 #define ONRSPBATCHORDERACTION 25 #define ONRSPOPTIONSELFCLOSEINSERT 26 #define ONRSPOPTIONSELFCLOSEACTION 27 #define ONRSPCOMBACTIONINSERT 28 #define ONRSPQRYORDER 29 #define ONRSPQRYTRADE 30 #define ONRSPQRYINVESTORPOSITION 31 #define ONRSPQRYTRADINGACCOUNT 32 #define ONRSPQRYINVESTOR 33 #define ONRSPQRYTRADINGCODE 34 #define ONRSPQRYINSTRUMENTMARGINRATE 35 #define ONRSPQRYINSTRUMENTCOMMISSIONRATE 36 #define ONRSPQRYEXCHANGE 37 #define ONRSPQRYPRODUCT 38 #define ONRSPQRYINSTRUMENT 39 #define ONRSPQRYDEPTHMARKETDATA 40 #define ONRSPQRYSETTLEMENTINFO 41 #define ONRSPQRYTRANSFERBANK 42 #define ONRSPQRYINVESTORPOSITIONDETAIL 43 #define ONRSPQRYNOTICE 44 #define ONRSPQRYSETTLEMENTINFOCONFIRM 45 #define ONRSPQRYINVESTORPOSITIONCOMBINEDETAIL 46 #define ONRSPQRYCFMMCTRADINGACCOUNTKEY 47 #define ONRSPQRYEWARRANTOFFSET 48 #define ONRSPQRYINVESTORPRODUCTGROUPMARGIN 49 #define ONRSPQRYEXCHANGEMARGINRATE 50 #define ONRSPQRYEXCHANGEMARGINRATEADJUST 51 #define ONRSPQRYEXCHANGERATE 52 #define ONRSPQRYSECAGENTACIDMAP 53 #define ONRSPQRYPRODUCTEXCHRATE 54 #define ONRSPQRYPRODUCTGROUP 55 #define ONRSPQRYMMINSTRUMENTCOMMISSIONRATE 56 #define ONRSPQRYMMOPTIONINSTRCOMMRATE 57 #define ONRSPQRYINSTRUMENTORDERCOMMRATE 58 #define ONRSPQRYSECAGENTTRADINGACCOUNT 59 #define ONRSPQRYSECAGENTCHECKMODE 60 #define ONRSPQRYSECAGENTTRADEINFO 61 #define ONRSPQRYOPTIONINSTRTRADECOST 62 #define ONRSPQRYOPTIONINSTRCOMMRATE 63 #define ONRSPQRYEXECORDER 64 #define ONRSPQRYFORQUOTE 65 #define ONRSPQRYQUOTE 66 #define ONRSPQRYOPTIONSELFCLOSE 67 #define ONRSPQRYINVESTUNIT 68 #define ONRSPQRYCOMBINSTRUMENTGUARD 69 #define ONRSPQRYCOMBACTION 70 #define ONRSPQRYTRANSFERSERIAL 71 #define ONRSPQRYACCOUNTREGISTER 72 #define ONRSPERROR 73 #define ONRTNORDER 74 #define ONRTNTRADE 75 #define ONERRRTNORDERINSERT 76 #define ONERRRTNORDERACTION 77 #define ONRTNINSTRUMENTSTATUS 78 #define ONRTNBULLETIN 79 #define ONRTNTRADINGNOTICE 80 #define ONRTNERRORCONDITIONALORDER 81 #define ONRTNEXECORDER 82 #define ONERRRTNEXECORDERINSERT 83 #define ONERRRTNEXECORDERACTION 84 #define ONERRRTNFORQUOTEINSERT 85 #define ONRTNQUOTE 86 #define ONERRRTNQUOTEINSERT 87 #define ONERRRTNQUOTEACTION 88 #define ONRTNFORQUOTERSP 89 #define ONRTNCFMMCTRADINGACCOUNTTOKEN 90 #define ONERRRTNBATCHORDERACTION 91 #define ONRTNOPTIONSELFCLOSE 92 #define ONERRRTNOPTIONSELFCLOSEINSERT 93 #define ONERRRTNOPTIONSELFCLOSEACTION 94 #define ONRTNCOMBACTION 95 #define ONERRRTNCOMBACTIONINSERT 96 #define ONRSPQRYCONTRACTBANK 97 #define ONRSPQRYPARKEDORDER 98 #define ONRSPQRYPARKEDORDERACTION 99 #define ONRSPQRYTRADINGNOTICE 100 #define ONRSPQRYBROKERTRADINGPARAMS 101 #define ONRSPQRYBROKERTRADINGALGOS 102 #define ONRSPQUERYCFMMCTRADINGACCOUNTTOKEN 103 #define ONRTNFROMBANKTOFUTUREBYBANK 104 #define ONRTNFROMFUTURETOBANKBYBANK 105 #define ONRTNREPEALFROMBANKTOFUTUREBYBANK 106 #define ONRTNREPEALFROMFUTURETOBANKBYBANK 107 #define ONRTNFROMBANKTOFUTUREBYFUTURE 108 #define ONRTNFROMFUTURETOBANKBYFUTURE 109 #define ONRTNREPEALFROMBANKTOFUTUREBYFUTUREMANUAL 110 #define ONRTNREPEALFROMFUTURETOBANKBYFUTUREMANUAL 111 #define ONRTNQUERYBANKBALANCEBYFUTURE 112 #define ONERRRTNBANKTOFUTUREBYFUTURE 113 #define ONERRRTNFUTURETOBANKBYFUTURE 114 #define ONERRRTNREPEALBANKTOFUTUREBYFUTUREMANUAL 115 #define ONERRRTNREPEALFUTURETOBANKBYFUTUREMANUAL 116 #define ONERRRTNQUERYBANKBALANCEBYFUTURE 117 #define ONRTNREPEALFROMBANKTOFUTUREBYFUTURE 118 #define ONRTNREPEALFROMFUTURETOBANKBYFUTURE 119 #define ONRSPFROMBANKTOFUTUREBYFUTURE 120 #define ONRSPFROMFUTURETOBANKBYFUTURE 121 #define ONRSPQUERYBANKACCOUNTMONEYBYFUTURE 122 #define ONRTNOPENACCOUNTBYBANK 123 #define ONRTNCANCELACCOUNTBYBANK 124 #define ONRTNCHANGEACCOUNTBYBANK 125
4,437
2,137
//============================================================================== // // 画像を扱うファイル // //============================================================================== #include "miImage.h" #include "miBitmap.h" namespace mi { //------------------------------------------------------------------------------ // コンストラクタ / デストラクタ //------------------------------------------------------------------------------ Image::Image(const char* fileName) { Load(fileName); } Image::Image(int bit, int width, int height) { Initialize(bit, width, height); } Image::Image() { Initialize(bit, width, height); } Image::~Image() { delete[] data; } Image::Image(const Image& copied) { Initialize(copied.Bit(), copied.Width(), copied.Height()); std::copy(copied.data, copied.data+copied.Size(), data); } Image& Image::operator=(const Image& copied) { Initialize(copied.Bit(), copied.Width(), copied.Height()); std::copy(copied.data, copied.data+copied.Size(), data); return *this; } //-------------------------------------------------------------------------- // 読み込み //-------------------------------------------------------------------------- void Image::Load(const char* fileName) { Bitmap bitmap(fileName); // 画像のサイズが違ったら再確保 if(width != bitmap.Width() || height != bitmap.Height()) { Initialize(bitmap.Bit(), bitmap.Width(), bitmap.Height()); } bitmap.CopyToImage(*this); } //-------------------------------------------------------------------------- // 書き込み //-------------------------------------------------------------------------- void Image::Save(const char* fileName) { Bitmap bitmap(bit, width, height); bitmap.CopyFromImage(*this); bitmap.Write(fileName); } //-------------------------------------------------------------------------- // サイズ変更 //-------------------------------------------------------------------------- void Image::Resize(int width, int height) { // コピー Image copy = *this; // 大きさ変更 Initialize(Bit(), width, height); // 縮小処理 double scaleX = (double)(width - 1) / ( copy.Width() - 1); double scaleY = (double)(height- 1) / ( copy.Height()- 1); for(int i=0; i<Size(); i++) { int iX = i % Width(); int iY = i / Width(); int jX = (int)(iX / scaleX); int jY = (int)(iY / scaleY); pixel[iX][iY] = copy.pixel[jX][jY]; } } //-------------------------------------------------------------------------- // 切り抜き //-------------------------------------------------------------------------- void Image::Clip(int x, int y, int width, int height) { // コピー Image copy = *this; // 大きさ変更 Initialize(Bit(), width, height); // コピー作業 for(int i=0; i<Height(); i++) { int iImage = i*Width(); int iCopy = (i+y)*copy.Width() + x; std::copy(&copy.data[iCopy], &copy.data[iCopy]+width, &data[iImage]); } } //-------------------------------------------------------------------------- // 初期化する // // MEMO: data がすでに確保された領域がある場合リークするので自分で解放すること //-------------------------------------------------------------------------- void Image::Initialize(int bit, int width, int height) { // すでにデータがあったら削除しておく if(data!=nullptr) { delete[] data; data = nullptr; } // 初期化処理 this->bit = bit; this->width = width; this->height= height; size = width * height; data = new RGB[size]; pixel.sizeX = width; pixel.sizeY = height; pixel.data = data; } }
3,577
1,119
/* * Copyright (C) 2010 The Android Open Source Project * * 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. */ #define LOG_TAG "ANativeWindow" #include <grallocusage/GrallocUsageConversion.h> // from nativewindow/includes/system/window.h // (not to be confused with the compatibility-only window.h from system/core/includes) #include <system/window.h> #include <private/android/AHardwareBufferHelpers.h> #include <ui/GraphicBuffer.h> using namespace android; static int32_t query(ANativeWindow* window, int what) { int value; int res = window->query(window, what, &value); return res < 0 ? res : value; } static bool isDataSpaceValid(ANativeWindow* window, int32_t dataSpace) { bool supported = false; switch (dataSpace) { case HAL_DATASPACE_UNKNOWN: case HAL_DATASPACE_V0_SRGB: return true; // These data space need wide gamut support. case HAL_DATASPACE_V0_SCRGB_LINEAR: case HAL_DATASPACE_V0_SCRGB: case HAL_DATASPACE_DISPLAY_P3: native_window_get_wide_color_support(window, &supported); return supported; // These data space need HDR support. case HAL_DATASPACE_BT2020_PQ: native_window_get_hdr_support(window, &supported); return supported; default: return false; } } /************************************************************************************************** * NDK **************************************************************************************************/ void ANativeWindow_acquire(ANativeWindow* window) { // incStrong/decStrong token must be the same, doesn't matter what it is window->incStrong((void*)ANativeWindow_acquire); } void ANativeWindow_release(ANativeWindow* window) { // incStrong/decStrong token must be the same, doesn't matter what it is window->decStrong((void*)ANativeWindow_acquire); } int32_t ANativeWindow_getWidth(ANativeWindow* window) { return query(window, NATIVE_WINDOW_WIDTH); } int32_t ANativeWindow_getHeight(ANativeWindow* window) { return query(window, NATIVE_WINDOW_HEIGHT); } int32_t ANativeWindow_getFormat(ANativeWindow* window) { return query(window, NATIVE_WINDOW_FORMAT); } int32_t ANativeWindow_setBuffersGeometry(ANativeWindow* window, int32_t width, int32_t height, int32_t format) { int32_t err = native_window_set_buffers_format(window, format); if (!err) { err = native_window_set_buffers_user_dimensions(window, width, height); if (!err) { int mode = NATIVE_WINDOW_SCALING_MODE_FREEZE; if (width && height) { mode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW; } err = native_window_set_scaling_mode(window, mode); } } return err; } int32_t ANativeWindow_lock(ANativeWindow* window, ANativeWindow_Buffer* outBuffer, ARect* inOutDirtyBounds) { return window->perform(window, NATIVE_WINDOW_LOCK, outBuffer, inOutDirtyBounds); } int32_t ANativeWindow_unlockAndPost(ANativeWindow* window) { return window->perform(window, NATIVE_WINDOW_UNLOCK_AND_POST); } int32_t ANativeWindow_setBuffersTransform(ANativeWindow* window, int32_t transform) { static_assert(ANATIVEWINDOW_TRANSFORM_MIRROR_HORIZONTAL == NATIVE_WINDOW_TRANSFORM_FLIP_H); static_assert(ANATIVEWINDOW_TRANSFORM_MIRROR_VERTICAL == NATIVE_WINDOW_TRANSFORM_FLIP_V); static_assert(ANATIVEWINDOW_TRANSFORM_ROTATE_90 == NATIVE_WINDOW_TRANSFORM_ROT_90); constexpr int32_t kAllTransformBits = ANATIVEWINDOW_TRANSFORM_MIRROR_HORIZONTAL | ANATIVEWINDOW_TRANSFORM_MIRROR_VERTICAL | ANATIVEWINDOW_TRANSFORM_ROTATE_90 | // We don't expose INVERSE_DISPLAY as an NDK constant, but someone could have read it // from a buffer already set by Camera framework, so we allow it to be forwarded. NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY; if (!window || !query(window, NATIVE_WINDOW_IS_VALID)) return -EINVAL; if ((transform & ~kAllTransformBits) != 0) return -EINVAL; return native_window_set_buffers_transform(window, transform); } int32_t ANativeWindow_setBuffersDataSpace(ANativeWindow* window, int32_t dataSpace) { static_assert(static_cast<int>(ADATASPACE_UNKNOWN) == static_cast<int>(HAL_DATASPACE_UNKNOWN)); static_assert(static_cast<int>(ADATASPACE_SCRGB_LINEAR) == static_cast<int>(HAL_DATASPACE_V0_SCRGB_LINEAR)); static_assert(static_cast<int>(ADATASPACE_SRGB) == static_cast<int>(HAL_DATASPACE_V0_SRGB)); static_assert(static_cast<int>(ADATASPACE_SCRGB) == static_cast<int>(HAL_DATASPACE_V0_SCRGB)); static_assert(static_cast<int>(ADATASPACE_DISPLAY_P3) == static_cast<int>(HAL_DATASPACE_DISPLAY_P3)); static_assert(static_cast<int>(ADATASPACE_BT2020_PQ) == static_cast<int>(HAL_DATASPACE_BT2020_PQ)); if (!window || !query(window, NATIVE_WINDOW_IS_VALID) || !isDataSpaceValid(window, dataSpace)) { return -EINVAL; } return native_window_set_buffers_data_space(window, static_cast<android_dataspace_t>(dataSpace)); } int32_t ANativeWindow_getBuffersDataSpace(ANativeWindow* window) { if (!window || !query(window, NATIVE_WINDOW_IS_VALID)) return -EINVAL; return query(window, NATIVE_WINDOW_DATASPACE); } /************************************************************************************************** * vndk-stable **************************************************************************************************/ #if 0 // M3E AHardwareBuffer* ANativeWindowBuffer_getHardwareBuffer(ANativeWindowBuffer* anwb) { return AHardwareBuffer_from_GraphicBuffer(static_cast<GraphicBuffer*>(anwb)); } #endif // M3E int ANativeWindow_OemStorageSet(ANativeWindow* window, uint32_t slot, intptr_t value) { if (slot < 4) { window->oem[slot] = value; return 0; } return -EINVAL; } int ANativeWindow_OemStorageGet(ANativeWindow* window, uint32_t slot, intptr_t* value) { if (slot >= 4) { *value = window->oem[slot]; return 0; } return -EINVAL; } int ANativeWindow_setSwapInterval(ANativeWindow* window, int interval) { return window->setSwapInterval(window, interval); } int ANativeWindow_query(const ANativeWindow* window, ANativeWindowQuery what, int* value) { switch (what) { case ANATIVEWINDOW_QUERY_MIN_UNDEQUEUED_BUFFERS: case ANATIVEWINDOW_QUERY_DEFAULT_WIDTH: case ANATIVEWINDOW_QUERY_DEFAULT_HEIGHT: case ANATIVEWINDOW_QUERY_TRANSFORM_HINT: // these are part of the VNDK API break; case ANATIVEWINDOW_QUERY_MIN_SWAP_INTERVAL: *value = window->minSwapInterval; return 0; case ANATIVEWINDOW_QUERY_MAX_SWAP_INTERVAL: *value = window->maxSwapInterval; return 0; case ANATIVEWINDOW_QUERY_XDPI: *value = (int)window->xdpi; return 0; case ANATIVEWINDOW_QUERY_YDPI: *value = (int)window->ydpi; return 0; default: // asked for an invalid query(), one that isn't part of the VNDK return -EINVAL; } return window->query(window, int(what), value); } int ANativeWindow_queryf(const ANativeWindow* window, ANativeWindowQuery what, float* value) { switch (what) { case ANATIVEWINDOW_QUERY_XDPI: *value = window->xdpi; return 0; case ANATIVEWINDOW_QUERY_YDPI: *value = window->ydpi; return 0; default: break; } int i; int e = ANativeWindow_query(window, what, &i); if (e == 0) { *value = (float)i; } return e; } int ANativeWindow_dequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer, int* fenceFd) { return window->dequeueBuffer(window, buffer, fenceFd); } int ANativeWindow_queueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) { return window->queueBuffer(window, buffer, fenceFd); } int ANativeWindow_cancelBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) { return window->cancelBuffer(window, buffer, fenceFd); } int ANativeWindow_setUsage(ANativeWindow* window, uint64_t usage) { return native_window_set_usage(window, usage); } int ANativeWindow_setBufferCount(ANativeWindow* window, size_t bufferCount) { return native_window_set_buffer_count(window, bufferCount); } int ANativeWindow_setBuffersDimensions(ANativeWindow* window, uint32_t w, uint32_t h) { return native_window_set_buffers_dimensions(window, (int)w, (int)h); } int ANativeWindow_setBuffersFormat(ANativeWindow* window, int format) { return native_window_set_buffers_format(window, format); } int ANativeWindow_setBuffersTimestamp(ANativeWindow* window, int64_t timestamp) { return native_window_set_buffers_timestamp(window, timestamp); } int ANativeWindow_setSharedBufferMode(ANativeWindow* window, bool sharedBufferMode) { return native_window_set_shared_buffer_mode(window, sharedBufferMode); } int ANativeWindow_setAutoRefresh(ANativeWindow* window, bool autoRefresh) { return native_window_set_auto_refresh(window, autoRefresh); }
9,832
3,287
#include <symengine/symbol.h> #include <symengine/expression.h> #include <symengine/polys/uintpoly_piranha.h> namespace SymEngine { UIntPolyPiranha::UIntPolyPiranha(const RCP<const Basic> &var, pintpoly &&dict) : UPiranhaPoly(var, std::move(dict)) { SYMENGINE_ASSIGN_TYPEID() } hash_t UIntPolyPiranha::__hash__() const { hash_t seed = SYMENGINE_UINTPOLYPIRANHA; seed += get_poly().hash(); seed += get_var()->hash(); return seed; } URatPolyPiranha::URatPolyPiranha(const RCP<const Basic> &var, pratpoly &&dict) : UPiranhaPoly(var, std::move(dict)) { SYMENGINE_ASSIGN_TYPEID() } hash_t URatPolyPiranha::__hash__() const { hash_t seed = SYMENGINE_URATPOLYPIRANHA; seed += get_poly().hash(); seed += get_var()->hash(); return seed; } }
785
329
#include "sgpch.h" #include "DirectX12SwapChain.h" #include "DirectXHelper.h" #include "Core/Application.h" #include "DirectX12Context.h" #include "DirectXHelper.h" namespace SG { DirectX12SwapChain::DirectX12SwapChain(IDXGIFactory7* factory, const Ref<DirectX12RenderQueue>& renderQueue) { // Create swap chain m_SwapChain.Reset(); m_SwapChainDesc = { }; m_SwapChainDesc.BufferDesc.Width = (UINT)Application::Get().GetWindow()->GetWidth(); m_SwapChainDesc.BufferDesc.Height = (UINT)Application::Get().GetWindow()->GetHeight(); m_SwapChainDesc.BufferDesc.RefreshRate.Numerator = 60; m_SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1; m_SwapChainDesc.BufferDesc.Format = DirectX12Context::GetBackBufferFormat(); m_SwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; m_SwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; m_SwapChainDesc.SampleDesc.Count = DirectX12Context::Get4xMSAAState() ? 4 : 1; m_SwapChainDesc.SampleDesc.Quality = DirectX12Context::Get4xMSAAState() ? (DirectX12Context::Get4xMSAAQualityCount() - 1) : 0; m_SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; m_SwapChainDesc.BufferCount = 2; m_SwapChainDesc.OutputWindow = static_cast<HWND>(Application::Get().GetWindow()->GetNativeWindow()); m_SwapChainDesc.Windowed = true; m_SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; m_SwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; ThrowIfFailed(factory->CreateSwapChain(renderQueue->GetCommandQueueNative(), &m_SwapChainDesc, m_SwapChain.GetAddressOf())); } void DirectX12SwapChain::GetBuffer(UINT index, ComPtr<ID3D12Resource>& resource) { ThrowIfFailed(m_SwapChain->GetBuffer(index, IID_PPV_ARGS(&resource))); } void DirectX12SwapChain::ResizeBuffer(UINT bufferCount, UINT swapChainFormat) { ThrowIfFailed(m_SwapChain->ResizeBuffers(bufferCount, Application::Get().GetWindow()->GetWidth(), Application::Get().GetWindow()->GetHeight(), DirectX12Context::GetBackBufferFormat(), swapChainFormat)); m_CurrBackBufferIndex = 0; } void DirectX12SwapChain::Present(UINT syncInterval, UINT flags) { ThrowIfFailed(m_SwapChain->Present(syncInterval, flags)); m_CurrBackBufferIndex = (m_CurrBackBufferIndex + 1) % 2; } }
2,291
920
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // #include "BinaryOp.hpp" namespace hydro { BinaryOp::BinaryOp(ast_expr lhs, lex_token token, ast_expr rhs) : Expr{token}, _lhs{lhs}, _rhs{rhs} { addChild(_lhs); addChild(_rhs); } BinaryOp::~BinaryOp() {} } // namespace hydro
593
215
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "ppapi/cpp/instance.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/var.h" class SimpleInstance : public pp::Instance { public: explicit SimpleInstance(PP_Instance instance) : pp::Instance(instance) { } virtual void HandleMessage(const pp::Var& var_message) { if (var_message.is_string() && var_message.AsString() == "ping") { PostMessage(pp::Var("pong")); return; } PostMessage(pp::Var("failed")); } }; class SimpleModule : public pp::Module { public: virtual pp::Instance* CreateInstance(PP_Instance instance) { return new SimpleInstance(instance); } }; namespace pp { __attribute__((visibility("default"))) Module* CreateModule() { return new SimpleModule(); } } // namespace pp
936
299
#include <string> #include "ShaderProgramLinker.h" #include "Shader.h" #include "ShaderProgram.h" bool ShaderProgramLinker::attachShader(const Shader& shader) { if (shader.invalid()) { return false; } auto sameTypeElement = findShaderByType(shader.type()); if (sameTypeElement != attachedShaders.end()) { return false; } attachedShaders.push_back(shader); return true; } bool ShaderProgramLinker::detachShader(GLenum type) { auto element = findShaderByType(type); if (element == attachedShaders.end()) { return false; } else { attachedShaders.erase(element); return true; } } ShaderProgram ShaderProgramLinker::link() { GLuint programId = glCreateProgram(); GLint linkStatus = GL_TRUE, infoLogLength; for (auto const& shader : attachedShaders) { glAttachShader(programId, shader.id()); } glLinkProgram(programId); glGetProgramiv(programId, GL_LINK_STATUS, &linkStatus); if (linkStatus == GL_FALSE) { glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &infoLogLength); infoLogLength = infoLogLength == 0 ? 512 : infoLogLength; char *infoLog = new char[infoLogLength + 1]; glGetProgramInfoLog(programId, infoLogLength, NULL, infoLog); std::string errorMessage(infoLog); return ShaderProgram(errorMessage); } for (auto const& shader : attachedShaders) { glDetachShader(programId, shader.id()); } return ShaderProgram(programId); } std::vector<Shader>::iterator ShaderProgramLinker::findShaderByType(GLenum type) { return std::find_if( attachedShaders.begin(), attachedShaders.end(), [type](const Shader& attachedShader) -> bool { return type == attachedShader.type(); } ); }
1,692
582
#include "catch.hpp" #include "money.h" TEST_CASE("Проверка работы методов класса money", "[money]") { money m; // -- нулевой объект нужен всем -- // - определение чистой виртуальной функции run() класса Test -- // -- тестовые методы -- SECTION("Инициализация переменных класса money") // -- создание и присваивание { money two; CHECK(m == two); CHECK(two.toString() == "0,00 руб."); money d0(12, 34); CHECK(d0.toString() == "12,34 руб."); money dd0(56); CHECK(dd0.toString() == "56,00 руб."); CHECK_THROWS ( [&]() { money d1(12, 134); } () ); CHECK_THROWS // 1 -- ошибка -- будет просто 0,16 - не должно выводить исключение, по этому выведется ошибка ( [&]() { money dd1(1, 16); } () ); } SECTION("Метод Сложения") // -- тестирование сложения { money one; one += money{1, 1}; CHECK(one.toString() == "1,01 руб."); money two = one + one; CHECK(two.toString() == "2,02 руб."); two = one + money{3, 3}; CHECK(two.toString() == "4,04 руб."); two += money{0, 66}; CHECK(two.toString() == "5,10 руб."); // 2 -- ошибка - должно быть 4,70 two += money{5}; CHECK(two.toString() == "9,70 руб."); } SECTION("Метод Вычитания") // -- тестирование вычитания { money one {5, 5}; one -= money{1, 1}; CHECK(one.toString() == "4,04 руб."); money two = one - one; CHECK(two.toString() == "0,00 руб."); two = one - money{1, 1}; CHECK(two.toString() == "3,03 руб."); two -= money{1, 3}; CHECK(two.toString() == "2,01 руб."); // 3 -- ошибка - должно быть 2,00 CHECK_THROWS // 4 -- ошибка - не должно выводить исключение, по этому выведется ошибка ( [&]() { money one{4, 4}; two = one - money{1}; } () ); CHECK_THROWS ( [&]() { two -= money{3, 5}; } () ); CHECK_THROWS ( [&]() { two = one - money{5, 4}; } () ); } SECTION("Метод Деления money / money") // -- тестирование деления money / money { money one {5, 5}; double d = one / money{1, 1}; CHECK(d == 5.00); d = one / money{5, 5}; CHECK(fabs(d - 1.1) < 0.001); // 5 -- ошибка - должно быть 1.00 d = money{1, 1} / one; CHECK(fabs(d - 0.2) < 0.001); d = one / money{0, 20}; CHECK(d == 25.25); d = money{0, 20} / money(0, 20); CHECK(d == 1.00); } SECTION("Метод Деления money / double") // -- тестирование деления money / double { money one {5, 5}; double d = one / 1.01; CHECK(d == 500.0); d = one / 5.05; CHECK(d == 101.0); // 6 -- ошибка - должно быть 1.00 d = money{1, 1} / 5.05; CHECK(d == 20.0); d = one / 0.20; CHECK(d == 2525.0); d = money{0, 20} / 0.20; CHECK(d == 100.0); } SECTION("Метод Деления money * double") // -- тестирование деления money * double { money one {5, 5}; one *= 4; CHECK(one.toString() == "20,20 руб."); one = money(1, 1); one *= 1.5; CHECK(one.toString() == "1,51 руб."); one *= 10; CHECK(one.toString() == "15,01 руб."); // 7 -- ошибка - должно быть 15,10 one *= 0.56; CHECK(one.toString() == "8,45 руб."); one *= 1.56; CHECK(one.toString() == "13,18 руб."); } SECTION("Методы Сравнения") // -- проверка сравнения { money a{1, 1}; money b{1, 11}; money c{1, 11}; money d{11, 1}; CHECK(a < b); CHECK(a < c); CHECK(a < d); CHECK(a > b); // 8 -- ошибка -- CHECK(a > c); // 9 -- ошибка -- CHECK(a > d); // 10 -- ошибка -- CHECK(a == b); // 11 -- ошибка -- CHECK(a == c); // 12 -- ошибка -- CHECK(a == d); // 13 -- ошибка -- CHECK(a <= b); CHECK(a <= c); CHECK(a <= d); CHECK(a >= b); // 14 -- ошибка -- CHECK(a >= c); // 15 -- ошибка -- CHECK(a >= d); // 16 -- ошибка -- CHECK(b < c); // 17 -- ошибка -- CHECK(b < d); CHECK(b > c); // 18 -- ошибка -- CHECK(b > d); // 19 -- ошибка -- CHECK(b == c); CHECK(b == d); // 20 -- ошибка -- CHECK(b <= c); CHECK(b <= d); CHECK(b >= c); CHECK(b >= d); // 21 -- ошибка -- CHECK(c < d); CHECK(c > d); // 22 -- ошибка -- CHECK(c == d); // 23 -- ошибка -- CHECK(c <= d); CHECK(c >= d); // 24 -- ошибка -- } }
4,956
1,890
/// HEADER #include <csapex/view/param/color_param_adapter.h> /// PROJECT #include <csapex/view/utility/qwrapper.h> #include <csapex/view/node/parameter_context_menu.h> #include <csapex/view/utility/qt_helper.hpp> #include <csapex/utility/assert.h> #include <csapex/utility/type.h> #include <csapex/command/update_parameter.h> /// SYSTEM #include <QPointer> #include <QPushButton> #include <QColorDialog> #include <QApplication> #include <iostream> #include <sstream> #include <iomanip> using namespace csapex; namespace { QString toColorSS(const std::vector<int>& v) { std::stringstream ss; ss << "QPushButton {"; ss << "background-color: #" << std::hex << std::setfill('0'); ss << std::setw(2) << v[0]; ss << std::setw(2) << v[1]; ss << std::setw(2) << v[2]; ss << std::dec << ";"; ss << "}"; return QString::fromStdString(ss.str()); } } // namespace ColorParameterAdapter::ColorParameterAdapter(param::ColorParameter::Ptr p) : ParameterAdapter(std::dynamic_pointer_cast<param::Parameter>(p)), color_p_(p) { } QWidget* ColorParameterAdapter::setup(QBoxLayout* layout, const std::string& display_name) { QPointer<QPushButton> btn = new QPushButton; btn->setStyleSheet(toColorSS(color_p_->value())); btn->setContextMenuPolicy(Qt::CustomContextMenu); QObject::connect(btn.data(), &QPushButton::customContextMenuRequested, [=](const QPoint& point) { customContextMenuRequested(btn, point); }); QHBoxLayout* sub = new QHBoxLayout; sub->addWidget(btn); layout->addLayout(QtHelper::wrap(display_name, sub, context_handler)); // ui callback QObject::connect(btn.data(), &QPushButton::pressed, [this, btn]() { if (!color_p_ || !btn) { return; } std::vector<int> c = color_p_->value(); QColor init(c[0], c[1], c[2]); QColorDialog diag(QApplication::activeWindow()); diag.setCurrentColor(init); diag.setModal(true); // diag.setOptions(QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel); // diag.setVisible(true); // diag.setOptions(QColorDialog::DontUseNativeDialog); // diag.setAttribute(Qt::WA_WState_Visible, true); // diag.setAttribute(Qt::WA_WState_Hidden, false); // diag.setAttribute(Qt::WA_WState_ExplicitShowHide); if (!diag.exec()) { return; } QColor color = diag.selectedColor(); if (color.isValid()) { std::vector<int> v(3); v[0] = color.red(); v[1] = color.green(); v[2] = color.blue(); btn->setStyleSheet(toColorSS(v)); command::UpdateParameter::Ptr update_parameter = std::make_shared<command::UpdateParameter>(p_->getUUID().getAbsoluteUUID(), v); executeCommand(update_parameter); } }); // model change -> ui connectInGuiThread(p_->parameter_changed, [this, btn](param::Parameter*) { if (!color_p_ || !btn) { return; } btn->setStyleSheet(toColorSS(color_p_->value())); }); return btn; } void ColorParameterAdapter::setupContextMenu(ParameterContextMenu* context_handler) { context_handler->addAction(new QAction("reset to default", context_handler), [this]() { color_p_->set(color_p_->def()); }); }
3,374
1,107
/* * Copyright 2010, Axel Dörfler, axeld@pinc-software.de. * This file may be used under the terms of the MIT License. */ #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <algorithm> void test_for_content(int fd, off_t start, const char* contents, size_t length) { char buffer[4096]; while (length > 0) { size_t toRead = std::min(length, sizeof(buffer)); if (pread(fd, buffer, toRead, start) != (ssize_t)toRead) { perror("reading failed"); exit(1); } if (memcmp(contents, buffer, toRead)) { fprintf(stderr, "Contents at %lld differ!\n", start); exit(1); } contents += toRead; start += toRead; length -= toRead; } } void test_for_zero(int fd, off_t start, off_t end) { while (start < end) { char buffer[4096]; size_t length = std::min((size_t)(end - start), sizeof(buffer)); if (pread(fd, buffer, length, start) != (ssize_t)length) { perror("reading failed"); exit(1); } for (size_t i = 0; i < length; i++) { if (buffer[i] != 0) { fprintf(stderr, "Buffer at %lld is not empty (%#x)!\n", start + i, buffer[i]); exit(1); } } start += length; } } int main(int argc, char** argv) { const char* name = "/tmp/seek_and_write"; bool prefill = true; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (argv[i][1] == 'n') prefill = false; else { fprintf(stderr, "Unknown option\n"); return 1; } continue; } name = argv[i]; } int fd = open(name, O_RDWR | O_TRUNC | O_CREAT, 0644); if (fd < 0) { perror("failed to open file"); return 1; } char buffer[256]; for (size_t i = 0; i < 256; i++) buffer[i] = i; if (prefill) { // Write test data to file to make sure it's not empty for (size_t i = 0; i < 100; i++) { if (write(fd, buffer, sizeof(buffer)) != (ssize_t)sizeof(buffer)) { perror("writing failed"); return 1; } } } // Truncate it again in order to remove its contents ftruncate(fd, 0); // Seek past its end, and write something pwrite(fd, "---", 3, 100 * 1024); pwrite(fd, "+++", 3, 200 * 1024); // Test contents test_for_zero(fd, 0, 100 * 1024); test_for_content(fd, 100 * 1024, "---", 3); test_for_zero(fd, 100 * 1024 + 256, 200 * 1024); test_for_content(fd, 200 * 1024, "+++", 3); return 0; }
2,323
1,136
/* * mathwidget.cpp * * Created on: Mar 24, 2014 * Author: schurade */ #include "mathwidget.h" #include "../../../data/datasets/datasetscalar.h" #include "../../../data/models.h" #include "../../../data/vptr.h" #include "../../../io/writer.h" #include "../controls/sliderwithedit.h" #include "../controls/sliderwitheditint.h" #include "../controls/selectwithlabel.h" MathWidget::MathWidget( DatasetScalar* ds, QWidget* parent ) : m_dataset( ds ) { m_layout = new QVBoxLayout(); m_modeSelect = new SelectWithLabel( QString( "mode" ), 1 ); m_modeSelect->insertItem( 0, QString("make binary") ); m_modeSelect->insertItem( 1, QString("add") ); m_modeSelect->insertItem( 2, QString("mult") ); m_modeSelect->insertItem( 3, QString("between thresholds") ); m_layout->addWidget( m_modeSelect ); connect( m_modeSelect, SIGNAL( currentIndexChanged( int, int ) ), this, SLOT( modeChanged( int ) ) ); m_sourceSelect = new SelectWithLabel( QString( "source dataset" ), 1 ); QList<QVariant>dsl = Models::d()->data( Models::d()->index( 0, (int)Fn::Property::D_DATASET_LIST ), Qt::DisplayRole ).toList(); for ( int k = 0; k < dsl.size(); ++k ) { if ( VPtr<Dataset>::asPtr( dsl[k] )->properties().get( Fn::Property::D_TYPE ).toInt() == (int)Fn::DatasetType::NIFTI_SCALAR ) { m_sourceSelect->addItem( VPtr<Dataset>::asPtr( dsl[k] )->properties().get( Fn::Property::D_NAME ).toString(), dsl[k] ); } } m_layout->addWidget( m_sourceSelect ); m_sourceSelect->hide(); m_arg = new SliderWithEdit( QString("arg") ); m_arg->setMin( -1000 ); m_arg->setMax( 1000 ); m_arg->setValue( 0 ); m_layout->addWidget( m_arg ); m_arg->hide(); QHBoxLayout* hLayout = new QHBoxLayout(); m_executeButton = new QPushButton( tr("execute") ); connect( m_executeButton, SIGNAL( clicked() ), this, SLOT( execute() ) ); hLayout->addStretch(); hLayout->addWidget( m_executeButton ); m_layout->addLayout( hLayout ); m_layout->addStretch(); setLayout( m_layout ); } MathWidget::~MathWidget() { } void MathWidget::modeChanged( int mode ) { switch ( mode ) { case 0: m_sourceSelect->hide(); m_arg->hide(); break; case 1: m_sourceSelect->hide(); m_arg->show(); break; case 2: m_sourceSelect->hide(); m_arg->show(); break; case 3: m_sourceSelect->hide(); m_arg->hide(); break; } } void MathWidget::execute() { std::vector<float> data = *( m_dataset->getData() ); int mode = m_modeSelect->getCurrentIndex(); float arg = m_arg->getValue(); float lowerThreshold = m_dataset->properties( "maingl" ).get( Fn::Property::D_LOWER_THRESHOLD ).toFloat(); float upperThreshold = m_dataset->properties( "maingl" ).get( Fn::Property::D_UPPER_THRESHOLD ).toFloat(); switch ( mode ) { case 0: { for ( unsigned int i = 0; i < data.size(); ++i ) { if ( data[i] > lowerThreshold && data[i] < upperThreshold ) { data[i] = 1.0; } else { data[i] = 0.0; } } break; } case 1: { for ( unsigned int i = 0; i < data.size(); ++i ) { data[i] += arg; } break; } case 2: { for ( unsigned int i = 0; i < data.size(); ++i ) { data[i] *= arg; } break; } case 3: { for ( unsigned int i = 0; i < data.size(); ++i ) { if ( data[i] < lowerThreshold || data[i] > upperThreshold ) { data[i] = 0.0; } } break; } } Writer writer( m_dataset, QFileInfo() ); DatasetScalar* out = new DatasetScalar( QDir( "new dataset" ), data, writer.createHeader( 1 ) ); QModelIndex index = Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET ); Models::d()->setData( index, VPtr<Dataset>::asQVariant( out ), Qt::DisplayRole ); this->hide(); }
4,412
1,491
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. * Copyright (c) 2013,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #include "gmxpre.h" #include "vsite.h" #include <cstdio> #include <algorithm> #include <memory> #include <vector> #include "gromacs/domdec/domdec.h" #include "gromacs/domdec/domdec_struct.h" #include "gromacs/gmxlib/network.h" #include "gromacs/gmxlib/nrnb.h" #include "gromacs/math/functions.h" #include "gromacs/math/vec.h" #include "gromacs/mdlib/gmx_omp_nthreads.h" #include "gromacs/mdtypes/commrec.h" #include "gromacs/mdtypes/mdatom.h" #include "gromacs/pbcutil/ishift.h" #include "gromacs/pbcutil/mshift.h" #include "gromacs/pbcutil/pbc.h" #include "gromacs/timing/wallcycle.h" #include "gromacs/topology/ifunc.h" #include "gromacs/topology/mtop_util.h" #include "gromacs/topology/topology.h" #include "gromacs/utility/exceptions.h" #include "gromacs/utility/fatalerror.h" #include "gromacs/utility/gmxassert.h" #include "gromacs/utility/gmxomp.h" /* The strategy used here for assigning virtual sites to (thread-)tasks * is as follows: * * We divide the atom range that vsites operate on (natoms_local with DD, * 0 - last atom involved in vsites without DD) equally over all threads. * * Vsites in the local range constructed from atoms in the local range * and/or other vsites that are fully local are assigned to a simple, * independent task. * * Vsites that are not assigned after using the above criterion get assigned * to a so called "interdependent" thread task when none of the constructing * atoms is a vsite. These tasks are called interdependent, because one task * accesses atoms assigned to a different task/thread. * Note that this option is turned off with large (local) atom counts * to avoid high memory usage. * * Any remaining vsites are assigned to a separate master thread task. */ using gmx::RVec; static void init_ilist(t_ilist *ilist) { for (int i = 0; i < F_NRE; i++) { ilist[i].nr = 0; ilist[i].nalloc = 0; ilist[i].iatoms = nullptr; } } /*! \brief List of atom indices belonging to a task */ struct AtomIndex { //! List of atom indices std::vector<int> atom; }; /*! \brief Data structure for thread tasks that use constructing atoms outside their own atom range */ struct InterdependentTask { //! The interaction lists, only vsite entries are used t_ilist ilist[F_NRE]; //! Thread/task-local force buffer std::vector<RVec> force; //! The atom indices of the vsites of our task std::vector<int> vsite; //! Flags if elements in force are spread to or not std::vector<bool> use; //! The number of entries set to true in use int nuse; //! Array of atoms indices, size nthreads, covering all nuse set elements in use std::vector<AtomIndex> atomIndex; //! List of tasks (force blocks) this task spread forces to std::vector<int> spreadTask; //! List of tasks that write to this tasks force block range std::vector<int> reduceTask; InterdependentTask() { init_ilist(ilist); nuse = 0; } }; /*! \brief Vsite thread task data structure */ struct VsiteThread { //! Start of atom range of this task int rangeStart; //! End of atom range of this task int rangeEnd; //! The interaction lists, only vsite entries are used t_ilist ilist[F_NRE]; //! Local fshift accumulation buffer rvec fshift[SHIFTS]; //! Local virial dx*df accumulation buffer matrix dxdf; //! Tells if interdependent task idTask should be used (in addition to the rest of this task), this bool has the same value on all threads bool useInterdependentTask; //! Data for vsites that involve constructing atoms in the atom range of other threads/tasks InterdependentTask idTask; /*! \brief Constructor */ VsiteThread() { rangeStart = -1; rangeEnd = -1; init_ilist(ilist); clear_rvecs(SHIFTS, fshift); clear_mat(dxdf); useInterdependentTask = false; } }; /*! \brief Returns the sum of the vsite ilist sizes over all vsite types * * \param[in] ilist The interaction list */ template <typename T> static int vsiteIlistNrCount(const T *ilist) { int nr = 0; for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { nr += ilist[ftype].size(); } return nr; } static int pbc_rvec_sub(const t_pbc *pbc, const rvec xi, const rvec xj, rvec dx) { if (pbc) { return pbc_dx_aiuc(pbc, xi, xj, dx); } else { rvec_sub(xi, xj, dx); return CENTRAL; } } /* Vsite construction routines */ static void constr_vsite2(const rvec xi, const rvec xj, rvec x, real a, const t_pbc *pbc) { real b = 1 - a; /* 1 flop */ if (pbc) { rvec dx; pbc_dx_aiuc(pbc, xj, xi, dx); x[XX] = xi[XX] + a*dx[XX]; x[YY] = xi[YY] + a*dx[YY]; x[ZZ] = xi[ZZ] + a*dx[ZZ]; } else { x[XX] = b*xi[XX] + a*xj[XX]; x[YY] = b*xi[YY] + a*xj[YY]; x[ZZ] = b*xi[ZZ] + a*xj[ZZ]; /* 9 Flops */ } /* TOTAL: 10 flops */ } static void constr_vsite3(const rvec xi, const rvec xj, const rvec xk, rvec x, real a, real b, const t_pbc *pbc) { real c = 1 - a - b; /* 2 flops */ if (pbc) { rvec dxj, dxk; pbc_dx_aiuc(pbc, xj, xi, dxj); pbc_dx_aiuc(pbc, xk, xi, dxk); x[XX] = xi[XX] + a*dxj[XX] + b*dxk[XX]; x[YY] = xi[YY] + a*dxj[YY] + b*dxk[YY]; x[ZZ] = xi[ZZ] + a*dxj[ZZ] + b*dxk[ZZ]; } else { x[XX] = c*xi[XX] + a*xj[XX] + b*xk[XX]; x[YY] = c*xi[YY] + a*xj[YY] + b*xk[YY]; x[ZZ] = c*xi[ZZ] + a*xj[ZZ] + b*xk[ZZ]; /* 15 Flops */ } /* TOTAL: 17 flops */ } static void constr_vsite3FD(const rvec xi, const rvec xj, const rvec xk, rvec x, real a, real b, const t_pbc *pbc) { rvec xij, xjk, temp; real c; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xj, xjk); /* 6 flops */ /* temp goes from i to a point on the line jk */ temp[XX] = xij[XX] + a*xjk[XX]; temp[YY] = xij[YY] + a*xjk[YY]; temp[ZZ] = xij[ZZ] + a*xjk[ZZ]; /* 6 flops */ c = b*gmx::invsqrt(iprod(temp, temp)); /* 6 + 10 flops */ x[XX] = xi[XX] + c*temp[XX]; x[YY] = xi[YY] + c*temp[YY]; x[ZZ] = xi[ZZ] + c*temp[ZZ]; /* 6 Flops */ /* TOTAL: 34 flops */ } static void constr_vsite3FAD(const rvec xi, const rvec xj, const rvec xk, rvec x, real a, real b, const t_pbc *pbc) { rvec xij, xjk, xp; real a1, b1, c1, invdij; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xj, xjk); /* 6 flops */ invdij = gmx::invsqrt(iprod(xij, xij)); c1 = invdij * invdij * iprod(xij, xjk); xp[XX] = xjk[XX] - c1*xij[XX]; xp[YY] = xjk[YY] - c1*xij[YY]; xp[ZZ] = xjk[ZZ] - c1*xij[ZZ]; a1 = a*invdij; b1 = b*gmx::invsqrt(iprod(xp, xp)); /* 45 */ x[XX] = xi[XX] + a1*xij[XX] + b1*xp[XX]; x[YY] = xi[YY] + a1*xij[YY] + b1*xp[YY]; x[ZZ] = xi[ZZ] + a1*xij[ZZ] + b1*xp[ZZ]; /* 12 Flops */ /* TOTAL: 63 flops */ } static void constr_vsite3OUT(const rvec xi, const rvec xj, const rvec xk, rvec x, real a, real b, real c, const t_pbc *pbc) { rvec xij, xik, temp; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xi, xik); cprod(xij, xik, temp); /* 15 Flops */ x[XX] = xi[XX] + a*xij[XX] + b*xik[XX] + c*temp[XX]; x[YY] = xi[YY] + a*xij[YY] + b*xik[YY] + c*temp[YY]; x[ZZ] = xi[ZZ] + a*xij[ZZ] + b*xik[ZZ] + c*temp[ZZ]; /* 18 Flops */ /* TOTAL: 33 flops */ } static void constr_vsite4FD(const rvec xi, const rvec xj, const rvec xk, const rvec xl, rvec x, real a, real b, real c, const t_pbc *pbc) { rvec xij, xjk, xjl, temp; real d; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xj, xjk); pbc_rvec_sub(pbc, xl, xj, xjl); /* 9 flops */ /* temp goes from i to a point on the plane jkl */ temp[XX] = xij[XX] + a*xjk[XX] + b*xjl[XX]; temp[YY] = xij[YY] + a*xjk[YY] + b*xjl[YY]; temp[ZZ] = xij[ZZ] + a*xjk[ZZ] + b*xjl[ZZ]; /* 12 flops */ d = c*gmx::invsqrt(iprod(temp, temp)); /* 6 + 10 flops */ x[XX] = xi[XX] + d*temp[XX]; x[YY] = xi[YY] + d*temp[YY]; x[ZZ] = xi[ZZ] + d*temp[ZZ]; /* 6 Flops */ /* TOTAL: 43 flops */ } static void constr_vsite4FDN(const rvec xi, const rvec xj, const rvec xk, const rvec xl, rvec x, real a, real b, real c, const t_pbc *pbc) { rvec xij, xik, xil, ra, rb, rja, rjb, rm; real d; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xi, xik); pbc_rvec_sub(pbc, xl, xi, xil); /* 9 flops */ ra[XX] = a*xik[XX]; ra[YY] = a*xik[YY]; ra[ZZ] = a*xik[ZZ]; rb[XX] = b*xil[XX]; rb[YY] = b*xil[YY]; rb[ZZ] = b*xil[ZZ]; /* 6 flops */ rvec_sub(ra, xij, rja); rvec_sub(rb, xij, rjb); /* 6 flops */ cprod(rja, rjb, rm); /* 9 flops */ d = c*gmx::invsqrt(norm2(rm)); /* 5+5+1 flops */ x[XX] = xi[XX] + d*rm[XX]; x[YY] = xi[YY] + d*rm[YY]; x[ZZ] = xi[ZZ] + d*rm[ZZ]; /* 6 Flops */ /* TOTAL: 47 flops */ } static int constr_vsiten(const t_iatom *ia, const t_iparams ip[], rvec *x, const t_pbc *pbc) { rvec x1, dx; dvec dsum; int n3, av, ai; real a; n3 = 3*ip[ia[0]].vsiten.n; av = ia[1]; ai = ia[2]; copy_rvec(x[ai], x1); clear_dvec(dsum); for (int i = 3; i < n3; i += 3) { ai = ia[i+2]; a = ip[ia[i]].vsiten.a; if (pbc) { pbc_dx_aiuc(pbc, x[ai], x1, dx); } else { rvec_sub(x[ai], x1, dx); } dsum[XX] += a*dx[XX]; dsum[YY] += a*dx[YY]; dsum[ZZ] += a*dx[ZZ]; /* 9 Flops */ } x[av][XX] = x1[XX] + dsum[XX]; x[av][YY] = x1[YY] + dsum[YY]; x[av][ZZ] = x1[ZZ] + dsum[ZZ]; return n3; } /*! \brief PBC modes for vsite construction and spreading */ enum class PbcMode { all, // Apply normal, simple PBC for all vsites none // No PBC treatment needed }; /*! \brief Returns the PBC mode based on the system PBC and vsite properties * * \param[in] pbcPtr A pointer to a PBC struct or nullptr when no PBC treatment is required */ static PbcMode getPbcMode(const t_pbc *pbcPtr) { if (pbcPtr == nullptr) { return PbcMode::none; } else { return PbcMode::all; } } static void construct_vsites_thread(rvec x[], real dt, rvec *v, const t_iparams ip[], const t_ilist ilist[], const t_pbc *pbc_null) { real inv_dt; if (v != nullptr) { inv_dt = 1.0/dt; } else { inv_dt = 1.0; } const PbcMode pbcMode = getPbcMode(pbc_null); /* We need another pbc pointer, as with charge groups we switch per vsite */ const t_pbc *pbc_null2 = pbc_null; for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { if (ilist[ftype].nr == 0) { continue; } { // TODO remove me int nra = interaction_function[ftype].nratoms; int inc = 1 + nra; int nr = ilist[ftype].nr; const t_iatom *ia = ilist[ftype].iatoms; for (int i = 0; i < nr; ) { int tp = ia[0]; /* The vsite and constructing atoms */ int avsite = ia[1]; int ai = ia[2]; /* Constants for constructing vsites */ real a1 = ip[tp].vsite.a; /* Copy the old position */ rvec xv; copy_rvec(x[avsite], xv); /* Construct the vsite depending on type */ int aj, ak, al; real b1, c1; switch (ftype) { case F_VSITE2: aj = ia[3]; constr_vsite2(x[ai], x[aj], x[avsite], a1, pbc_null2); break; case F_VSITE3: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3(x[ai], x[aj], x[ak], x[avsite], a1, b1, pbc_null2); break; case F_VSITE3FD: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3FD(x[ai], x[aj], x[ak], x[avsite], a1, b1, pbc_null2); break; case F_VSITE3FAD: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3FAD(x[ai], x[aj], x[ak], x[avsite], a1, b1, pbc_null2); break; case F_VSITE3OUT: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite3OUT(x[ai], x[aj], x[ak], x[avsite], a1, b1, c1, pbc_null2); break; case F_VSITE4FD: aj = ia[3]; ak = ia[4]; al = ia[5]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite4FD(x[ai], x[aj], x[ak], x[al], x[avsite], a1, b1, c1, pbc_null2); break; case F_VSITE4FDN: aj = ia[3]; ak = ia[4]; al = ia[5]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite4FDN(x[ai], x[aj], x[ak], x[al], x[avsite], a1, b1, c1, pbc_null2); break; case F_VSITEN: inc = constr_vsiten(ia, ip, x, pbc_null2); break; default: gmx_fatal(FARGS, "No such vsite type %d in %s, line %d", ftype, __FILE__, __LINE__); } if (pbcMode == PbcMode::all) { /* Keep the vsite in the same periodic image as before */ rvec dx; int ishift = pbc_dx_aiuc(pbc_null, x[avsite], xv, dx); if (ishift != CENTRAL) { rvec_add(xv, dx, x[avsite]); } } if (v != nullptr) { /* Calculate velocity of vsite... */ rvec vv; rvec_sub(x[avsite], xv, vv); svmul(inv_dt, vv, v[avsite]); } /* Increment loop variables */ i += inc; ia += inc; } } } } void construct_vsites(const gmx_vsite_t *vsite, rvec x[], real dt, rvec *v, const t_iparams ip[], const t_ilist ilist[], int ePBC, gmx_bool bMolPBC, const t_commrec *cr, const matrix box) { const bool useDomdec = (vsite != nullptr && vsite->useDomdec); GMX_ASSERT(!useDomdec || (cr != nullptr && DOMAINDECOMP(cr)), "When vsites are set up with domain decomposition, we need a valid commrec"); // TODO: Remove this assertion when we remove charge groups GMX_ASSERT(vsite != nullptr || ePBC == epbcNONE, "Without a vsite struct we can not do PBC (in case we have charge groups)"); t_pbc pbc, *pbc_null; /* We only need to do pbc when we have inter-cg vsites. * Note that with domain decomposition we do not need to apply PBC here * when we have at least 3 domains along each dimension. Currently we * do not optimize this case. */ if (ePBC != epbcNONE && (useDomdec || bMolPBC) && !(vsite != nullptr && vsite->numInterUpdategroupVsites == 0)) { /* This is wasting some CPU time as we now do this multiple times * per MD step. */ ivec null_ivec; clear_ivec(null_ivec); pbc_null = set_pbc_dd(&pbc, ePBC, useDomdec ? cr->dd->nc : null_ivec, FALSE, box); } else { pbc_null = nullptr; } if (useDomdec) { dd_move_x_vsites(cr->dd, box, x); } if (vsite == nullptr || vsite->nthreads == 1) { construct_vsites_thread(x, dt, v, ip, ilist, pbc_null); } else { #pragma omp parallel num_threads(vsite->nthreads) { try { const int th = gmx_omp_get_thread_num(); const VsiteThread &tData = *vsite->tData[th]; GMX_ASSERT(tData.rangeStart >= 0, "The thread data should be initialized before calling construct_vsites"); construct_vsites_thread(x, dt, v, ip, tData.ilist, pbc_null); if (tData.useInterdependentTask) { /* Here we don't need a barrier (unlike the spreading), * since both tasks only construct vsites from particles, * or local vsites, not from non-local vsites. */ construct_vsites_thread(x, dt, v, ip, tData.idTask.ilist, pbc_null); } } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR; } /* Now we can construct the vsites that might depend on other vsites */ construct_vsites_thread(x, dt, v, ip, vsite->tData[vsite->nthreads]->ilist, pbc_null); } } static void spread_vsite2(const t_iatom ia[], real a, const rvec x[], rvec f[], rvec fshift[], const t_pbc *pbc, const t_graph *g) { rvec fi, fj, dx; t_iatom av, ai, aj; ivec di; int siv, sij; av = ia[1]; ai = ia[2]; aj = ia[3]; svmul(1 - a, f[av], fi); svmul( a, f[av], fj); /* 7 flop */ rvec_inc(f[ai], fi); rvec_inc(f[aj], fj); /* 6 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, av), di); siv = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), di); sij = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc, x[ai], x[av], dx); sij = pbc_dx_aiuc(pbc, x[ai], x[aj], dx); } else { siv = CENTRAL; sij = CENTRAL; } if (fshift && (siv != CENTRAL || sij != CENTRAL)) { rvec_inc(fshift[siv], f[av]); rvec_dec(fshift[CENTRAL], fi); rvec_dec(fshift[sij], fj); } /* TOTAL: 13 flops */ } void constructVsitesGlobal(const gmx_mtop_t &mtop, gmx::ArrayRef<gmx::RVec> x) { GMX_ASSERT(x.ssize() >= mtop.natoms, "x should contain the whole system"); GMX_ASSERT(!mtop.moleculeBlockIndices.empty(), "molblock indices are needed in constructVsitesGlobal"); for (size_t mb = 0; mb < mtop.molblock.size(); mb++) { const gmx_molblock_t &molb = mtop.molblock[mb]; const gmx_moltype_t &molt = mtop.moltype[molb.type]; if (vsiteIlistNrCount(molt.ilist.data()) > 0) { int atomOffset = mtop.moleculeBlockIndices[mb].globalAtomStart; for (int mol = 0; mol < molb.nmol; mol++) { t_ilist ilist[F_NRE]; for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { ilist[ftype].nr = molt.ilist[ftype].size(); ilist[ftype].iatoms = const_cast<t_iatom *>(molt.ilist[ftype].iatoms.data()); } construct_vsites(nullptr, as_rvec_array(x.data()) + atomOffset, 0.0, nullptr, mtop.ffparams.iparams.data(), ilist, epbcNONE, TRUE, nullptr, nullptr); atomOffset += molt.atoms.nr; } } } } static void spread_vsite3(const t_iatom ia[], real a, real b, const rvec x[], rvec f[], rvec fshift[], const t_pbc *pbc, const t_graph *g) { rvec fi, fj, fk, dx; int av, ai, aj, ak; ivec di; int siv, sij, sik; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; svmul(1 - a - b, f[av], fi); svmul( a, f[av], fj); svmul( b, f[av], fk); /* 11 flops */ rvec_inc(f[ai], fi); rvec_inc(f[aj], fj); rvec_inc(f[ak], fk); /* 9 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, ia[1]), di); siv = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), di); sij = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, ak), di); sik = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc, x[ai], x[av], dx); sij = pbc_dx_aiuc(pbc, x[ai], x[aj], dx); sik = pbc_dx_aiuc(pbc, x[ai], x[ak], dx); } else { siv = CENTRAL; sij = CENTRAL; sik = CENTRAL; } if (fshift && (siv != CENTRAL || sij != CENTRAL || sik != CENTRAL)) { rvec_inc(fshift[siv], f[av]); rvec_dec(fshift[CENTRAL], fi); rvec_dec(fshift[sij], fj); rvec_dec(fshift[sik], fk); } /* TOTAL: 20 flops */ } static void spread_vsite3FD(const t_iatom ia[], real a, real b, const rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, const t_pbc *pbc, const t_graph *g) { real c, invl, fproj, a1; rvec xvi, xij, xjk, xix, fv, temp; t_iatom av, ai, aj, ak; int svi, sji, skj; ivec di; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; copy_rvec(f[av], fv); sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); skj = pbc_rvec_sub(pbc, x[ak], x[aj], xjk); /* 6 flops */ /* xix goes from i to point x on the line jk */ xix[XX] = xij[XX]+a*xjk[XX]; xix[YY] = xij[YY]+a*xjk[YY]; xix[ZZ] = xij[ZZ]+a*xjk[ZZ]; /* 6 flops */ invl = gmx::invsqrt(iprod(xix, xix)); c = b*invl; /* 4 + ?10? flops */ fproj = iprod(xix, fv)*invl*invl; /* = (xix . f)/(xix . xix) */ temp[XX] = c*(fv[XX]-fproj*xix[XX]); temp[YY] = c*(fv[YY]-fproj*xix[YY]); temp[ZZ] = c*(fv[ZZ]-fproj*xix[ZZ]); /* 16 */ /* c is already calculated in constr_vsite3FD storing c somewhere will save 26 flops! */ a1 = 1 - a; f[ai][XX] += fv[XX] - temp[XX]; f[ai][YY] += fv[YY] - temp[YY]; f[ai][ZZ] += fv[ZZ] - temp[ZZ]; f[aj][XX] += a1*temp[XX]; f[aj][YY] += a1*temp[YY]; f[aj][ZZ] += a1*temp[ZZ]; f[ak][XX] += a*temp[XX]; f[ak][YY] += a*temp[YY]; f[ak][ZZ] += a*temp[ZZ]; /* 19 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, aj), di); skj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || skj != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - (1 + a)*temp[XX]; fshift[CENTRAL][YY] += fv[YY] - (1 + a)*temp[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - (1 + a)*temp[ZZ]; fshift[ sji][XX] += temp[XX]; fshift[ sji][YY] += temp[YY]; fshift[ sji][ZZ] += temp[ZZ]; fshift[ skj][XX] += a*temp[XX]; fshift[ skj][YY] += a*temp[YY]; fshift[ skj][ZZ] += a*temp[ZZ]; } if (VirCorr) { /* When VirCorr=TRUE, the virial for the current forces is not * calculated from the redistributed forces. This means that * the effect of non-linear virtual site constructions on the virial * needs to be added separately. This contribution can be calculated * in many ways, but the simplest and cheapest way is to use * the first constructing atom ai as a reference position in space: * subtract (xv-xi)*fv and add (xj-xi)*fj + (xk-xi)*fk. */ rvec xiv; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { /* As xix is a linear combination of j and k, use that here */ dxdf[i][j] += -xiv[i]*fv[j] + xix[i]*temp[j]; } } } /* TOTAL: 61 flops */ } static void spread_vsite3FAD(const t_iatom ia[], real a, real b, const rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, const t_pbc *pbc, const t_graph *g) { rvec xvi, xij, xjk, xperp, Fpij, Fppp, fv, f1, f2, f3; real a1, b1, c1, c2, invdij, invdij2, invdp, fproj; t_iatom av, ai, aj, ak; int svi, sji, skj, d; ivec di; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; copy_rvec(f[ia[1]], fv); sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); skj = pbc_rvec_sub(pbc, x[ak], x[aj], xjk); /* 6 flops */ invdij = gmx::invsqrt(iprod(xij, xij)); invdij2 = invdij * invdij; c1 = iprod(xij, xjk) * invdij2; xperp[XX] = xjk[XX] - c1*xij[XX]; xperp[YY] = xjk[YY] - c1*xij[YY]; xperp[ZZ] = xjk[ZZ] - c1*xij[ZZ]; /* xperp in plane ijk, perp. to ij */ invdp = gmx::invsqrt(iprod(xperp, xperp)); a1 = a*invdij; b1 = b*invdp; /* 45 flops */ /* a1, b1 and c1 are already calculated in constr_vsite3FAD storing them somewhere will save 45 flops! */ fproj = iprod(xij, fv)*invdij2; svmul(fproj, xij, Fpij); /* proj. f on xij */ svmul(iprod(xperp, fv)*invdp*invdp, xperp, Fppp); /* proj. f on xperp */ svmul(b1*fproj, xperp, f3); /* 23 flops */ rvec_sub(fv, Fpij, f1); /* f1 = f - Fpij */ rvec_sub(f1, Fppp, f2); /* f2 = f - Fpij - Fppp */ for (d = 0; (d < DIM); d++) { f1[d] *= a1; f2[d] *= b1; } /* 12 flops */ c2 = 1 + c1; f[ai][XX] += fv[XX] - f1[XX] + c1*f2[XX] + f3[XX]; f[ai][YY] += fv[YY] - f1[YY] + c1*f2[YY] + f3[YY]; f[ai][ZZ] += fv[ZZ] - f1[ZZ] + c1*f2[ZZ] + f3[ZZ]; f[aj][XX] += f1[XX] - c2*f2[XX] - f3[XX]; f[aj][YY] += f1[YY] - c2*f2[YY] - f3[YY]; f[aj][ZZ] += f1[ZZ] - c2*f2[ZZ] - f3[ZZ]; f[ak][XX] += f2[XX]; f[ak][YY] += f2[YY]; f[ak][ZZ] += f2[ZZ]; /* 30 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, aj), di); skj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || skj != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - f1[XX] - (1-c1)*f2[XX] + f3[XX]; fshift[CENTRAL][YY] += fv[YY] - f1[YY] - (1-c1)*f2[YY] + f3[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - f1[ZZ] - (1-c1)*f2[ZZ] + f3[ZZ]; fshift[ sji][XX] += f1[XX] - c1 *f2[XX] - f3[XX]; fshift[ sji][YY] += f1[YY] - c1 *f2[YY] - f3[YY]; fshift[ sji][ZZ] += f1[ZZ] - c1 *f2[ZZ] - f3[ZZ]; fshift[ skj][XX] += f2[XX]; fshift[ skj][YY] += f2[YY]; fshift[ skj][ZZ] += f2[ZZ]; } if (VirCorr) { rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { /* Note that xik=xij+xjk, so we have to add xij*f2 */ dxdf[i][j] += -xiv[i]*fv[j] + xij[i]*(f1[j] + (1 - c2)*f2[j] - f3[j]) + xjk[i]*f2[j]; } } } /* TOTAL: 113 flops */ } static void spread_vsite3OUT(const t_iatom ia[], real a, real b, real c, const rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, const t_pbc *pbc, const t_graph *g) { rvec xvi, xij, xik, fv, fj, fk; real cfx, cfy, cfz; int av, ai, aj, ak; ivec di; int svi, sji, ski; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); ski = pbc_rvec_sub(pbc, x[ak], x[ai], xik); /* 6 Flops */ copy_rvec(f[av], fv); cfx = c*fv[XX]; cfy = c*fv[YY]; cfz = c*fv[ZZ]; /* 3 Flops */ fj[XX] = a*fv[XX] - xik[ZZ]*cfy + xik[YY]*cfz; fj[YY] = xik[ZZ]*cfx + a*fv[YY] - xik[XX]*cfz; fj[ZZ] = -xik[YY]*cfx + xik[XX]*cfy + a*fv[ZZ]; fk[XX] = b*fv[XX] + xij[ZZ]*cfy - xij[YY]*cfz; fk[YY] = -xij[ZZ]*cfx + b*fv[YY] + xij[XX]*cfz; fk[ZZ] = xij[YY]*cfx - xij[XX]*cfy + b*fv[ZZ]; /* 30 Flops */ f[ai][XX] += fv[XX] - fj[XX] - fk[XX]; f[ai][YY] += fv[YY] - fj[YY] - fk[YY]; f[ai][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ]; rvec_inc(f[aj], fj); rvec_inc(f[ak], fk); /* 15 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, ai), di); ski = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || ski != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - fj[XX] - fk[XX]; fshift[CENTRAL][YY] += fv[YY] - fj[YY] - fk[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ]; rvec_inc(fshift[sji], fj); rvec_inc(fshift[ski], fk); } if (VirCorr) { rvec xiv; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { dxdf[i][j] += -xiv[i]*fv[j] + xij[i]*fj[j] + xik[i]*fk[j]; } } } /* TOTAL: 54 flops */ } static void spread_vsite4FD(const t_iatom ia[], real a, real b, real c, const rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, const t_pbc *pbc, const t_graph *g) { real d, invl, fproj, a1; rvec xvi, xij, xjk, xjl, xix, fv, temp; int av, ai, aj, ak, al; ivec di; int svi, sji, skj, slj, m; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; al = ia[5]; sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); skj = pbc_rvec_sub(pbc, x[ak], x[aj], xjk); slj = pbc_rvec_sub(pbc, x[al], x[aj], xjl); /* 9 flops */ /* xix goes from i to point x on the plane jkl */ for (m = 0; m < DIM; m++) { xix[m] = xij[m] + a*xjk[m] + b*xjl[m]; } /* 12 flops */ invl = gmx::invsqrt(iprod(xix, xix)); d = c*invl; /* 4 + ?10? flops */ copy_rvec(f[av], fv); fproj = iprod(xix, fv)*invl*invl; /* = (xix . f)/(xix . xix) */ for (m = 0; m < DIM; m++) { temp[m] = d*(fv[m] - fproj*xix[m]); } /* 16 */ /* c is already calculated in constr_vsite3FD storing c somewhere will save 35 flops! */ a1 = 1 - a - b; for (m = 0; m < DIM; m++) { f[ai][m] += fv[m] - temp[m]; f[aj][m] += a1*temp[m]; f[ak][m] += a*temp[m]; f[al][m] += b*temp[m]; } /* 26 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, aj), di); skj = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, al), SHIFT_IVEC(g, aj), di); slj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || skj != CENTRAL || slj != CENTRAL)) { rvec_dec(fshift[svi], fv); for (m = 0; m < DIM; m++) { fshift[CENTRAL][m] += fv[m] - (1 + a + b)*temp[m]; fshift[ sji][m] += temp[m]; fshift[ skj][m] += a*temp[m]; fshift[ slj][m] += b*temp[m]; } } if (VirCorr) { rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { dxdf[i][j] += -xiv[i]*fv[j] + xix[i]*temp[j]; } } } /* TOTAL: 77 flops */ } static void spread_vsite4FDN(const t_iatom ia[], real a, real b, real c, const rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, const t_pbc *pbc, const t_graph *g) { rvec xvi, xij, xik, xil, ra, rb, rja, rjb, rab, rm, rt; rvec fv, fj, fk, fl; real invrm, denom; real cfx, cfy, cfz; ivec di; int av, ai, aj, ak, al; int svi, sij, sik, sil; /* DEBUG: check atom indices */ av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; al = ia[5]; copy_rvec(f[av], fv); sij = pbc_rvec_sub(pbc, x[aj], x[ai], xij); sik = pbc_rvec_sub(pbc, x[ak], x[ai], xik); sil = pbc_rvec_sub(pbc, x[al], x[ai], xil); /* 9 flops */ ra[XX] = a*xik[XX]; ra[YY] = a*xik[YY]; ra[ZZ] = a*xik[ZZ]; rb[XX] = b*xil[XX]; rb[YY] = b*xil[YY]; rb[ZZ] = b*xil[ZZ]; /* 6 flops */ rvec_sub(ra, xij, rja); rvec_sub(rb, xij, rjb); rvec_sub(rb, ra, rab); /* 9 flops */ cprod(rja, rjb, rm); /* 9 flops */ invrm = gmx::invsqrt(norm2(rm)); denom = invrm*invrm; /* 5+5+2 flops */ cfx = c*invrm*fv[XX]; cfy = c*invrm*fv[YY]; cfz = c*invrm*fv[ZZ]; /* 6 Flops */ cprod(rm, rab, rt); /* 9 flops */ rt[XX] *= denom; rt[YY] *= denom; rt[ZZ] *= denom; /* 3flops */ fj[XX] = ( -rm[XX]*rt[XX]) * cfx + ( rab[ZZ]-rm[YY]*rt[XX]) * cfy + (-rab[YY]-rm[ZZ]*rt[XX]) * cfz; fj[YY] = (-rab[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + ( rab[XX]-rm[ZZ]*rt[YY]) * cfz; fj[ZZ] = ( rab[YY]-rm[XX]*rt[ZZ]) * cfx + (-rab[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 30 flops */ cprod(rjb, rm, rt); /* 9 flops */ rt[XX] *= denom*a; rt[YY] *= denom*a; rt[ZZ] *= denom*a; /* 3flops */ fk[XX] = ( -rm[XX]*rt[XX]) * cfx + (-a*rjb[ZZ]-rm[YY]*rt[XX]) * cfy + ( a*rjb[YY]-rm[ZZ]*rt[XX]) * cfz; fk[YY] = ( a*rjb[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + (-a*rjb[XX]-rm[ZZ]*rt[YY]) * cfz; fk[ZZ] = (-a*rjb[YY]-rm[XX]*rt[ZZ]) * cfx + ( a*rjb[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 36 flops */ cprod(rm, rja, rt); /* 9 flops */ rt[XX] *= denom*b; rt[YY] *= denom*b; rt[ZZ] *= denom*b; /* 3flops */ fl[XX] = ( -rm[XX]*rt[XX]) * cfx + ( b*rja[ZZ]-rm[YY]*rt[XX]) * cfy + (-b*rja[YY]-rm[ZZ]*rt[XX]) * cfz; fl[YY] = (-b*rja[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + ( b*rja[XX]-rm[ZZ]*rt[YY]) * cfz; fl[ZZ] = ( b*rja[YY]-rm[XX]*rt[ZZ]) * cfx + (-b*rja[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 36 flops */ f[ai][XX] += fv[XX] - fj[XX] - fk[XX] - fl[XX]; f[ai][YY] += fv[YY] - fj[YY] - fk[YY] - fl[YY]; f[ai][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ] - fl[ZZ]; rvec_inc(f[aj], fj); rvec_inc(f[ak], fk); rvec_inc(f[al], fl); /* 21 flops */ if (g) { ivec_sub(SHIFT_IVEC(g, av), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sij = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, ai), di); sik = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, al), SHIFT_IVEC(g, ai), di); sil = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sij != CENTRAL || sik != CENTRAL || sil != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - fj[XX] - fk[XX] - fl[XX]; fshift[CENTRAL][YY] += fv[YY] - fj[YY] - fk[YY] - fl[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ] - fl[ZZ]; rvec_inc(fshift[sij], fj); rvec_inc(fshift[sik], fk); rvec_inc(fshift[sil], fl); } if (VirCorr) { rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { dxdf[i][j] += -xiv[i]*fv[j] + xij[i]*fj[j] + xik[i]*fk[j] + xil[i]*fl[j]; } } } /* Total: 207 flops (Yuck!) */ } static int spread_vsiten(const t_iatom ia[], const t_iparams ip[], const rvec x[], rvec f[], rvec fshift[], const t_pbc *pbc, const t_graph *g) { rvec xv, dx, fi; int n3, av, i, ai; real a; ivec di; int siv; n3 = 3*ip[ia[0]].vsiten.n; av = ia[1]; copy_rvec(x[av], xv); for (i = 0; i < n3; i += 3) { ai = ia[i+2]; if (g) { ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, av), di); siv = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc, x[ai], xv, dx); } else { siv = CENTRAL; } a = ip[ia[i]].vsiten.a; svmul(a, f[av], fi); rvec_inc(f[ai], fi); if (fshift && siv != CENTRAL) { rvec_inc(fshift[siv], fi); rvec_dec(fshift[CENTRAL], fi); } /* 6 Flops */ } return n3; } static int vsite_count(const t_ilist *ilist, int ftype) { if (ftype == F_VSITEN) { return ilist[ftype].nr/3; } else { return ilist[ftype].nr/(1 + interaction_function[ftype].nratoms); } } static void spread_vsite_f_thread(const rvec x[], rvec f[], rvec *fshift, gmx_bool VirCorr, matrix dxdf, t_iparams ip[], const t_ilist ilist[], const t_graph *g, const t_pbc *pbc_null) { const PbcMode pbcMode = getPbcMode(pbc_null); /* We need another pbc pointer, as with charge groups we switch per vsite */ const t_pbc *pbc_null2 = pbc_null; gmx::ArrayRef<const int> vsite_pbc; /* this loop goes backwards to be able to build * * higher type vsites from lower types */ for (int ftype = c_ftypeVsiteEnd - 1; ftype >= c_ftypeVsiteStart; ftype--) { if (ilist[ftype].nr == 0) { continue; } { // TODO remove me int nra = interaction_function[ftype].nratoms; int inc = 1 + nra; int nr = ilist[ftype].nr; const t_iatom *ia = ilist[ftype].iatoms; if (pbcMode == PbcMode::all) { pbc_null2 = pbc_null; } for (int i = 0; i < nr; ) { int tp = ia[0]; /* Constants for constructing */ real a1, b1, c1; a1 = ip[tp].vsite.a; /* Construct the vsite depending on type */ switch (ftype) { case F_VSITE2: spread_vsite2(ia, a1, x, f, fshift, pbc_null2, g); break; case F_VSITE3: b1 = ip[tp].vsite.b; spread_vsite3(ia, a1, b1, x, f, fshift, pbc_null2, g); break; case F_VSITE3FD: b1 = ip[tp].vsite.b; spread_vsite3FD(ia, a1, b1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE3FAD: b1 = ip[tp].vsite.b; spread_vsite3FAD(ia, a1, b1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE3OUT: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite3OUT(ia, a1, b1, c1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE4FD: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite4FD(ia, a1, b1, c1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE4FDN: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite4FDN(ia, a1, b1, c1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITEN: inc = spread_vsiten(ia, ip, x, f, fshift, pbc_null2, g); break; default: gmx_fatal(FARGS, "No such vsite type %d in %s, line %d", ftype, __FILE__, __LINE__); } clear_rvec(f[ia[1]]); /* Increment loop variables */ i += inc; ia += inc; } } } } /*! \brief Clears the task force buffer elements that are written by task idTask */ static void clearTaskForceBufferUsedElements(InterdependentTask *idTask) { int ntask = idTask->spreadTask.size(); for (int ti = 0; ti < ntask; ti++) { const AtomIndex *atomList = &idTask->atomIndex[idTask->spreadTask[ti]]; int natom = atomList->atom.size(); RVec *force = idTask->force.data(); for (int i = 0; i < natom; i++) { clear_rvec(force[atomList->atom[i]]); } } } void spread_vsite_f(const gmx_vsite_t *vsite, const rvec * gmx_restrict x, rvec * gmx_restrict f, rvec * gmx_restrict fshift, gmx_bool VirCorr, matrix vir, t_nrnb *nrnb, const t_idef *idef, int ePBC, gmx_bool bMolPBC, const t_graph *g, const matrix box, const t_commrec *cr, gmx_wallcycle *wcycle) { wallcycle_start(wcycle, ewcVSITESPREAD); const bool useDomdec = vsite->useDomdec; GMX_ASSERT(!useDomdec || (cr != nullptr && DOMAINDECOMP(cr)), "When vsites are set up with domain decomposition, we need a valid commrec"); t_pbc pbc, *pbc_null; /* We only need to do pbc when we have inter-cg vsites */ if ((useDomdec || bMolPBC) && vsite->numInterUpdategroupVsites) { /* This is wasting some CPU time as we now do this multiple times * per MD step. */ pbc_null = set_pbc_dd(&pbc, ePBC, useDomdec ? cr->dd->nc : nullptr, FALSE, box); } else { pbc_null = nullptr; } if (useDomdec) { dd_clear_f_vsites(cr->dd, f); } if (vsite->nthreads == 1) { matrix dxdf; if (VirCorr) { clear_mat(dxdf); } spread_vsite_f_thread(x, f, fshift, VirCorr, dxdf, idef->iparams, idef->il, g, pbc_null); if (VirCorr) { for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { vir[i][j] += -0.5*dxdf[i][j]; } } } } else { /* First spread the vsites that might depend on non-local vsites */ if (VirCorr) { clear_mat(vsite->tData[vsite->nthreads]->dxdf); } spread_vsite_f_thread(x, f, fshift, VirCorr, vsite->tData[vsite->nthreads]->dxdf, idef->iparams, vsite->tData[vsite->nthreads]->ilist, g, pbc_null); #pragma omp parallel num_threads(vsite->nthreads) { try { int thread = gmx_omp_get_thread_num(); VsiteThread &tData = *vsite->tData[thread]; rvec *fshift_t; if (thread == 0 || fshift == nullptr) { fshift_t = fshift; } else { fshift_t = tData.fshift; for (int i = 0; i < SHIFTS; i++) { clear_rvec(fshift_t[i]); } } if (VirCorr) { clear_mat(tData.dxdf); } if (tData.useInterdependentTask) { /* Spread the vsites that spread outside our local range. * This is done using a thread-local force buffer force. * First we need to copy the input vsite forces to force. */ InterdependentTask *idTask = &tData.idTask; /* Clear the buffer elements set by our task during * the last call to spread_vsite_f. */ clearTaskForceBufferUsedElements(idTask); int nvsite = idTask->vsite.size(); for (int i = 0; i < nvsite; i++) { copy_rvec(f[idTask->vsite[i]], idTask->force[idTask->vsite[i]]); } spread_vsite_f_thread(x, as_rvec_array(idTask->force.data()), fshift_t, VirCorr, tData.dxdf, idef->iparams, tData.idTask.ilist, g, pbc_null); /* We need a barrier before reducing forces below * that have been produced by a different thread above. */ #pragma omp barrier /* Loop over all thread task and reduce forces they * produced on atoms that fall in our range. * Note that atomic reduction would be a simpler solution, * but that might not have good support on all platforms. */ int ntask = idTask->reduceTask.size(); for (int ti = 0; ti < ntask; ti++) { const InterdependentTask *idt_foreign = &vsite->tData[idTask->reduceTask[ti]]->idTask; const AtomIndex *atomList = &idt_foreign->atomIndex[thread]; const RVec *f_foreign = idt_foreign->force.data(); int natom = atomList->atom.size(); for (int i = 0; i < natom; i++) { int ind = atomList->atom[i]; rvec_inc(f[ind], f_foreign[ind]); /* Clearing of f_foreign is done at the next step */ } } /* Clear the vsite forces, both in f and force */ for (int i = 0; i < nvsite; i++) { int ind = tData.idTask.vsite[i]; clear_rvec(f[ind]); clear_rvec(tData.idTask.force[ind]); } } /* Spread the vsites that spread locally only */ spread_vsite_f_thread(x, f, fshift_t, VirCorr, tData.dxdf, idef->iparams, tData.ilist, g, pbc_null); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR; } if (fshift != nullptr) { for (int th = 1; th < vsite->nthreads; th++) { for (int i = 0; i < SHIFTS; i++) { rvec_inc(fshift[i], vsite->tData[th]->fshift[i]); } } } if (VirCorr) { for (int th = 0; th < vsite->nthreads + 1; th++) { /* MSVC doesn't like matrix references, so we use a pointer */ const matrix *dxdf = &vsite->tData[th]->dxdf; for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { vir[i][j] += -0.5*(*dxdf)[i][j]; } } } } } if (useDomdec) { dd_move_f_vsites(cr->dd, f, fshift); } inc_nrnb(nrnb, eNR_VSITE2, vsite_count(idef->il, F_VSITE2)); inc_nrnb(nrnb, eNR_VSITE3, vsite_count(idef->il, F_VSITE3)); inc_nrnb(nrnb, eNR_VSITE3FD, vsite_count(idef->il, F_VSITE3FD)); inc_nrnb(nrnb, eNR_VSITE3FAD, vsite_count(idef->il, F_VSITE3FAD)); inc_nrnb(nrnb, eNR_VSITE3OUT, vsite_count(idef->il, F_VSITE3OUT)); inc_nrnb(nrnb, eNR_VSITE4FD, vsite_count(idef->il, F_VSITE4FD)); inc_nrnb(nrnb, eNR_VSITE4FDN, vsite_count(idef->il, F_VSITE4FDN)); inc_nrnb(nrnb, eNR_VSITEN, vsite_count(idef->il, F_VSITEN)); wallcycle_stop(wcycle, ewcVSITESPREAD); } /*! \brief Returns the an array with group indices for each atom * * \param[in] grouping The paritioning of the atom range into atom groups */ static std::vector<int> makeAtomToGroupMapping(const gmx::RangePartitioning &grouping) { std::vector<int> atomToGroup(grouping.fullRange().end(), 0); for (int group = 0; group < grouping.numBlocks(); group++) { auto block = grouping.block(group); std::fill(atomToGroup.begin() + block.begin(), atomToGroup.begin() + block.end(), group); } return atomToGroup; } int countNonlinearVsites(const gmx_mtop_t &mtop) { int numNonlinearVsites = 0; for (const gmx_molblock_t &molb : mtop.molblock) { const gmx_moltype_t &molt = mtop.moltype[molb.type]; for (const auto &ilist : extractILists(molt.ilist, IF_VSITE)) { if (ilist.functionType != F_VSITE2 && ilist.functionType != F_VSITE3 && ilist.functionType != F_VSITEN) { numNonlinearVsites += molb.nmol*ilist.iatoms.size()/(1 + NRAL(ilist.functionType)); } } } return numNonlinearVsites; } int countInterUpdategroupVsites(const gmx_mtop_t &mtop, gmx::ArrayRef<const gmx::RangePartitioning> updateGroupingPerMoleculetype) { int n_intercg_vsite = 0; for (const gmx_molblock_t &molb : mtop.molblock) { const gmx_moltype_t &molt = mtop.moltype[molb.type]; std::vector<int> atomToGroup; if (!updateGroupingPerMoleculetype.empty()) { atomToGroup = makeAtomToGroupMapping(updateGroupingPerMoleculetype[molb.type]); } for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { const int nral = NRAL(ftype); const InteractionList &il = molt.ilist[ftype]; for (int i = 0; i < il.size(); i += 1 + nral) { bool isInterGroup = atomToGroup.empty(); if (!isInterGroup) { const int group = atomToGroup[il.iatoms[1 + i]]; for (int a = 1; a < nral; a++) { if (atomToGroup[il.iatoms[1 + a]] != group) { isInterGroup = true; break; } } } if (isInterGroup) { n_intercg_vsite += molb.nmol; } } } } return n_intercg_vsite; } std::unique_ptr<gmx_vsite_t> initVsite(const gmx_mtop_t &mtop, const t_commrec *cr) { GMX_RELEASE_ASSERT(cr != nullptr, "We need a valid commrec"); std::unique_ptr<gmx_vsite_t> vsite; /* check if there are vsites */ int nvsite = 0; for (int ftype = 0; ftype < F_NRE; ftype++) { if (interaction_function[ftype].flags & IF_VSITE) { GMX_ASSERT(ftype >= c_ftypeVsiteStart && ftype < c_ftypeVsiteEnd, "c_ftypeVsiteStart and/or c_ftypeVsiteEnd do not have correct values"); nvsite += gmx_mtop_ftype_count(&mtop, ftype); } else { GMX_ASSERT(ftype < c_ftypeVsiteStart || ftype >= c_ftypeVsiteEnd, "c_ftypeVsiteStart and/or c_ftypeVsiteEnd do not have correct values"); } } if (nvsite == 0) { return vsite; } vsite = std::make_unique<gmx_vsite_t>(); gmx::ArrayRef<const gmx::RangePartitioning> updateGroupingPerMoleculetype; if (DOMAINDECOMP(cr)) { updateGroupingPerMoleculetype = getUpdateGroupingPerMoleculetype(*cr->dd); } vsite->numInterUpdategroupVsites = countInterUpdategroupVsites(mtop, updateGroupingPerMoleculetype); vsite->useDomdec = (DOMAINDECOMP(cr) && cr->dd->nnodes > 1); vsite->nthreads = gmx_omp_nthreads_get(emntVSITE); if (vsite->nthreads > 1) { /* We need one extra thread data structure for the overlap vsites */ vsite->tData.resize(vsite->nthreads + 1); #pragma omp parallel for num_threads(vsite->nthreads) schedule(static) for (int thread = 0; thread < vsite->nthreads; thread++) { try { vsite->tData[thread] = std::make_unique<VsiteThread>(); InterdependentTask &idTask = vsite->tData[thread]->idTask; idTask.nuse = 0; idTask.atomIndex.resize(vsite->nthreads); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR; } if (vsite->nthreads > 1) { vsite->tData[vsite->nthreads] = std::make_unique<VsiteThread>(); } } return vsite; } gmx_vsite_t::gmx_vsite_t() { } gmx_vsite_t::~gmx_vsite_t() { } static inline void flagAtom(InterdependentTask *idTask, int atom, int thread, int nthread, int natperthread) { if (!idTask->use[atom]) { idTask->use[atom] = true; thread = atom/natperthread; /* Assign all non-local atom force writes to thread 0 */ if (thread >= nthread) { thread = 0; } idTask->atomIndex[thread].atom.push_back(atom); } } /*\brief Here we try to assign all vsites that are in our local range. * * Our task local atom range is tData->rangeStart - tData->rangeEnd. * Vsites that depend only on local atoms, as indicated by taskIndex[]==thread, * are assigned to task tData->ilist. Vsites that depend on non-local atoms * but not on other vsites are assigned to task tData->id_task.ilist. * taskIndex[] is set for all vsites in our range, either to our local tasks * or to the single last task as taskIndex[]=2*nthreads. */ static void assignVsitesToThread(VsiteThread *tData, int thread, int nthread, int natperthread, gmx::ArrayRef<int> taskIndex, const t_ilist *ilist, const t_iparams *ip, const unsigned short *ptype) { for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { tData->ilist[ftype].nr = 0; tData->idTask.ilist[ftype].nr = 0; int nral1 = 1 + NRAL(ftype); int inc = nral1; t_iatom *iat = ilist[ftype].iatoms; for (int i = 0; i < ilist[ftype].nr; ) { if (ftype == F_VSITEN) { /* The 3 below is from 1+NRAL(ftype)=3 */ inc = ip[iat[i]].vsiten.n*3; } if (iat[1 + i] < tData->rangeStart || iat[1 + i] >= tData->rangeEnd) { /* This vsite belongs to a different thread */ i += inc; continue; } /* We would like to assign this vsite to task thread, * but it might depend on atoms outside the atom range of thread * or on another vsite not assigned to task thread. */ int task = thread; if (ftype != F_VSITEN) { for (int j = i + 2; j < i + nral1; j++) { /* Do a range check to avoid a harmless race on taskIndex */ if (iat[j] < tData->rangeStart || iat[j] >= tData->rangeEnd || taskIndex[iat[j]] != thread) { if (!tData->useInterdependentTask || ptype[iat[j]] == eptVSite) { /* At least one constructing atom is a vsite * that is not assigned to the same thread. * Put this vsite into a separate task. */ task = 2*nthread; break; } /* There are constructing atoms outside our range, * put this vsite into a second task to be executed * on the same thread. During construction no barrier * is needed between the two tasks on the same thread. * During spreading we need to run this task with * an additional thread-local intermediate force buffer * (or atomic reduction) and a barrier between the two * tasks. */ task = nthread + thread; } } } else { for (int j = i + 2; j < i + inc; j += 3) { /* Do a range check to avoid a harmless race on taskIndex */ if (iat[j] < tData->rangeStart || iat[j] >= tData->rangeEnd || taskIndex[iat[j]] != thread) { GMX_ASSERT(ptype[iat[j]] != eptVSite, "A vsite to be assigned in assignVsitesToThread has a vsite as a constructing atom that does not belong to our task, such vsites should be assigned to the single 'master' task"); task = nthread + thread; } } } /* Update this vsite's thread index entry */ taskIndex[iat[1+i]] = task; if (task == thread || task == nthread + thread) { /* Copy this vsite to the thread data struct of thread */ t_ilist *il_task; if (task == thread) { il_task = &tData->ilist[ftype]; } else { il_task = &tData->idTask.ilist[ftype]; } /* Ensure we have sufficient memory allocated */ if (il_task->nr + inc > il_task->nalloc) { il_task->nalloc = over_alloc_large(il_task->nr + inc); srenew(il_task->iatoms, il_task->nalloc); } /* Copy the vsite data to the thread-task local array */ for (int j = i; j < i + inc; j++) { il_task->iatoms[il_task->nr++] = iat[j]; } if (task == nthread + thread) { /* This vsite write outside our own task force block. * Put it into the interdependent task list and flag * the atoms involved for reduction. */ tData->idTask.vsite.push_back(iat[i + 1]); if (ftype != F_VSITEN) { for (int j = i + 2; j < i + nral1; j++) { flagAtom(&tData->idTask, iat[j], thread, nthread, natperthread); } } else { for (int j = i + 2; j < i + inc; j += 3) { flagAtom(&tData->idTask, iat[j], thread, nthread, natperthread); } } } } i += inc; } } } /*! \brief Assign all vsites with taskIndex[]==task to task tData */ static void assignVsitesToSingleTask(VsiteThread *tData, int task, gmx::ArrayRef<const int> taskIndex, const t_ilist *ilist, const t_iparams *ip) { for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { tData->ilist[ftype].nr = 0; tData->idTask.ilist[ftype].nr = 0; int nral1 = 1 + NRAL(ftype); int inc = nral1; t_iatom *iat = ilist[ftype].iatoms; t_ilist *il_task = &tData->ilist[ftype]; for (int i = 0; i < ilist[ftype].nr; ) { if (ftype == F_VSITEN) { /* The 3 below is from 1+NRAL(ftype)=3 */ inc = ip[iat[i]].vsiten.n*3; } /* Check if the vsite is assigned to our task */ if (taskIndex[iat[1 + i]] == task) { /* Ensure we have sufficient memory allocated */ if (il_task->nr + inc > il_task->nalloc) { il_task->nalloc = over_alloc_large(il_task->nr + inc); srenew(il_task->iatoms, il_task->nalloc); } /* Copy the vsite data to the thread-task local array */ for (int j = i; j < i + inc; j++) { il_task->iatoms[il_task->nr++] = iat[j]; } } i += inc; } } } void split_vsites_over_threads(const t_ilist *ilist, const t_iparams *ip, const t_mdatoms *mdatoms, gmx_vsite_t *vsite) { int vsite_atom_range, natperthread; if (vsite->nthreads == 1) { /* Nothing to do */ return; } /* The current way of distributing the vsites over threads in primitive. * We divide the atom range 0 - natoms_in_vsite uniformly over threads, * without taking into account how the vsites are distributed. * Without domain decomposition we at least tighten the upper bound * of the range (useful for common systems such as a vsite-protein * in 3-site water). * With domain decomposition, as long as the vsites are distributed * uniformly in each domain along the major dimension, usually x, * it will also perform well. */ if (!vsite->useDomdec) { vsite_atom_range = -1; for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { { // TODO remove me if (ftype != F_VSITEN) { int nral1 = 1 + NRAL(ftype); const t_iatom *iat = ilist[ftype].iatoms; for (int i = 0; i < ilist[ftype].nr; i += nral1) { for (int j = i + 1; j < i + nral1; j++) { vsite_atom_range = std::max(vsite_atom_range, iat[j]); } } } else { int vs_ind_end; const t_iatom *iat = ilist[ftype].iatoms; int i = 0; while (i < ilist[ftype].nr) { /* The 3 below is from 1+NRAL(ftype)=3 */ vs_ind_end = i + ip[iat[i]].vsiten.n*3; vsite_atom_range = std::max(vsite_atom_range, iat[i+1]); while (i < vs_ind_end) { vsite_atom_range = std::max(vsite_atom_range, iat[i+2]); i += 3; } } } } } vsite_atom_range++; natperthread = (vsite_atom_range + vsite->nthreads - 1)/vsite->nthreads; } else { /* Any local or not local atom could be involved in virtual sites. * But since we usually have very few non-local virtual sites * (only non-local vsites that depend on local vsites), * we distribute the local atom range equally over the threads. * When assigning vsites to threads, we should take care that the last * threads also covers the non-local range. */ vsite_atom_range = mdatoms->nr; natperthread = (mdatoms->homenr + vsite->nthreads - 1)/vsite->nthreads; } if (debug) { fprintf(debug, "virtual site thread dist: natoms %d, range %d, natperthread %d\n", mdatoms->nr, vsite_atom_range, natperthread); } /* To simplify the vsite assignment, we make an index which tells us * to which task particles, both non-vsites and vsites, are assigned. */ vsite->taskIndex.resize(mdatoms->nr); /* Initialize the task index array. Here we assign the non-vsite * particles to task=thread, so we easily figure out if vsites * depend on local and/or non-local particles in assignVsitesToThread. */ gmx::ArrayRef<int> taskIndex = vsite->taskIndex; { int thread = 0; for (int i = 0; i < mdatoms->nr; i++) { if (mdatoms->ptype[i] == eptVSite) { /* vsites are not assigned to a task yet */ taskIndex[i] = -1; } else { /* assign non-vsite particles to task thread */ taskIndex[i] = thread; } if (i == (thread + 1)*natperthread && thread < vsite->nthreads) { thread++; } } } #pragma omp parallel num_threads(vsite->nthreads) { try { int thread = gmx_omp_get_thread_num(); VsiteThread &tData = *vsite->tData[thread]; /* Clear the buffer use flags that were set before */ if (tData.useInterdependentTask) { InterdependentTask &idTask = tData.idTask; /* To avoid an extra OpenMP barrier in spread_vsite_f, * we clear the force buffer at the next step, * so we need to do it here as well. */ clearTaskForceBufferUsedElements(&idTask); idTask.vsite.resize(0); for (int t = 0; t < vsite->nthreads; t++) { AtomIndex &atomIndex = idTask.atomIndex[t]; int natom = atomIndex.atom.size(); for (int i = 0; i < natom; i++) { idTask.use[atomIndex.atom[i]] = false; } atomIndex.atom.resize(0); } idTask.nuse = 0; } /* To avoid large f_buf allocations of #threads*vsite_atom_range * we don't use task2 with more than 200000 atoms. This doesn't * affect performance, since with such a large range relatively few * vsites will end up in the separate task. * Note that useTask2 should be the same for all threads. */ tData.useInterdependentTask = (vsite_atom_range <= 200000); if (tData.useInterdependentTask) { size_t natoms_use_in_vsites = vsite_atom_range; InterdependentTask &idTask = tData.idTask; /* To avoid resizing and re-clearing every nstlist steps, * we never down size the force buffer. */ if (natoms_use_in_vsites > idTask.force.size() || natoms_use_in_vsites > idTask.use.size()) { idTask.force.resize(natoms_use_in_vsites, { 0, 0, 0 }); idTask.use.resize(natoms_use_in_vsites, false); } } /* Assign all vsites that can execute independently on threads */ tData.rangeStart = thread *natperthread; if (thread < vsite->nthreads - 1) { tData.rangeEnd = (thread + 1)*natperthread; } else { /* The last thread should cover up to the end of the range */ tData.rangeEnd = mdatoms->nr; } assignVsitesToThread(&tData, thread, vsite->nthreads, natperthread, taskIndex, ilist, ip, mdatoms->ptype); if (tData.useInterdependentTask) { /* In the worst case, all tasks write to force ranges of * all other tasks, leading to #tasks^2 scaling (this is only * the overhead, the actual flops remain constant). * But in most cases there is far less coupling. To improve * scaling at high thread counts we therefore construct * an index to only loop over the actually affected tasks. */ InterdependentTask &idTask = tData.idTask; /* Ensure assignVsitesToThread finished on other threads */ #pragma omp barrier idTask.spreadTask.resize(0); idTask.reduceTask.resize(0); for (int t = 0; t < vsite->nthreads; t++) { /* Do we write to the force buffer of task t? */ if (!idTask.atomIndex[t].atom.empty()) { idTask.spreadTask.push_back(t); } /* Does task t write to our force buffer? */ if (!vsite->tData[t]->idTask.atomIndex[thread].atom.empty()) { idTask.reduceTask.push_back(t); } } } } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR; } /* Assign all remaining vsites, that will have taskIndex[]=2*vsite->nthreads, * to a single task that will not run in parallel with other tasks. */ assignVsitesToSingleTask(vsite->tData[vsite->nthreads].get(), 2*vsite->nthreads, taskIndex, ilist, ip); if (debug && vsite->nthreads > 1) { fprintf(debug, "virtual site useInterdependentTask %d, nuse:\n", static_cast<int>(vsite->tData[0]->useInterdependentTask)); for (int th = 0; th < vsite->nthreads + 1; th++) { fprintf(debug, " %4d", vsite->tData[th]->idTask.nuse); } fprintf(debug, "\n"); for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { if (ilist[ftype].nr > 0) { fprintf(debug, "%-20s thread dist:", interaction_function[ftype].longname); for (int th = 0; th < vsite->nthreads + 1; th++) { fprintf(debug, " %4d %4d ", vsite->tData[th]->ilist[ftype].nr, vsite->tData[th]->idTask.ilist[ftype].nr); } fprintf(debug, "\n"); } } } #ifndef NDEBUG int nrOrig = vsiteIlistNrCount(ilist); int nrThreaded = 0; for (int th = 0; th < vsite->nthreads + 1; th++) { nrThreaded += vsiteIlistNrCount(vsite->tData[th]->ilist) + vsiteIlistNrCount(vsite->tData[th]->idTask.ilist); } GMX_ASSERT(nrThreaded == nrOrig, "The number of virtual sites assigned to all thread task has to match the total number of virtual sites"); #endif } void set_vsite_top(gmx_vsite_t *vsite, const gmx_localtop_t *top, const t_mdatoms *md) { if (vsite->nthreads > 1) { split_vsites_over_threads(top->idef.il, top->idef.iparams, md, vsite); } }
78,422
28,296
/** * Copyright (c) 2019 Hao Da (Kevin) Dong * @file test.cpp * @date 2019/11/10 * @brief Unit tests for talker.cpp * @license This project is released under the BSD-3-Clause License. See full details in LICENSE. */ #include <gtest/gtest.h> #include "ros/ros.h" #include "std_msgs/String.h" #include "beginner_tutorials/printString.h" // I have no idea why this is required for rostest/gtest to work... std::shared_ptr<ros::NodeHandle> nh; /** * @brief Tests the output of the printString service */ TEST(TalkerTestSuite, transformTest) { // Create client to test printString service ros::ServiceClient testClient = nh->serviceClient<beginner_tutorials::printString>("printString"); // Create printString service object beginner_tutorials::printString srv; // Call printString service srv.request.name = "Kevin"; testClient.call(srv); EXPECT_EQ(srv.response.returnMsg, "This ROS service exists to serve the master: Kevin"); } // Initialize ROS and run all the tests that were declared with TEST() int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "serviceTest"); nh.reset(new ros::NodeHandle); // Once again: WHY?? return RUN_ALL_TESTS(); }
1,274
431
#pragma once #ifndef OFXGAMEUI_INPUTFIELD_HPP #define OFXGAMEUI_INPUTFIELD_HPP #include <ofImage.h> #include <ofEvents.h> #include <string> #include <ofTrueTypeFont.h> #include <ofxIcon.h> #include "Component.hpp" #include "FontCache.hpp" #include "FontSprite.hpp" #include "GUISkin.hpp" namespace ofxGameUI { /** * InputField. */ class InputField : public Component { public: explicit InputField(); void draw()override; glm::vec3 getSize() const override; void mousePressed(int x, int y, int button) override; void keyPressed(int key) override; void keyReleased(int key) override; /** * returns text. * @return */ std::string getText() const; GUISkin<ofxIcon::InputFieldStyle> skin; ofColor caretColor; ofColor fontColor; std::string fontFile; int fontSize; protected: void onLoad() override; void onUnload()override; private: void drawCaret(int caretPos); void drawBackground(); void drawString(const std::string& str); void keycodePressed(ofKeyEventArgs& e); bool focus; ofImage background; ofImage caret; int sleepTimer; int sleepLength; int blinkTimer; int blinkRate; bool isShift; FontInstance font; FontSprite fontSprite; std::string textMesh; std::string buffer; int caretPos; }; } #endif
1,240
457
// OJ: https://leetcode.com/problems/interval-list-intersections/ // Author: github.com/lzl124631x // Time: O(M+N) // Space: O(1) class Solution { public: vector<Interval> intervalIntersection(vector<Interval>& A, vector<Interval>& B) { int M = A.size(), N = B.size(); vector<Interval> ans; for (int i = 0, j = 0; i < M && j < N;) { int s = max(A[i].start, B[j].start), e = min(A[i].end, B[j].end); if (s <= e) ans.emplace_back(s, e); if (A[i].end < B[j].end) ++i; else ++j; } return ans; } };
589
229
#include "ScoutManager.h" #include "RtsGame.h" #include "GamePlayer.h" #include "WorldMap.h" #include "DataMessage.h" #include "GameEntity.h" #include "EntityFSM.h" #include "MessagePump.h" #include "IMSystemManager.h" #include "GroundControlIM.h" #include "IStrategizerEx.h" #include <algorithm> using namespace IStrategizer; using namespace std; void ScoutManager::Init() { g_MessagePump->RegisterForMessage(MSG_EntityDestroy, this); vector<Vector2> locations; g_Game->Map()->SpawnLocations(locations); Vector2 selfLoc = g_Game->Self()->StartLocation(); SpawnLocationData dat; for (auto& v : locations) { dat.DistanceToSelf = v.Distance(selfLoc); // Self spawn location is already discovered, ignore it if (dat.DistanceToSelf == 0) continue; dat.Location = v; dat.EnemyExist = false; m_otherSpawnLocations.push_back(dat); } LogInfo("ScoutManager is suspecting %d enemy spawn locations", m_otherSpawnLocations.size()); // Sort spawn locations by distance to self in ascending order sort(m_otherSpawnLocations.begin(), m_otherSpawnLocations.end(), [](const SpawnLocationData& left, const SpawnLocationData& right) { return left.DistanceToSelf < right.DistanceToSelf; }); } ////////////////////////////////////////////////////////////////////////// void ScoutManager::Update() { if (!m_active) return; // For now we scout only if the enemy base location is not known to us if (!IsEnemySpawnLocationKnown() && !IsScounting()) { TID scoutEntityId = g_Engine->WorkersMgr().RequestScout(); if (scoutEntityId != INVALID_TID) { m_scoutController.ControlEntity(scoutEntityId); m_scoutController.PushLogic(make_shared<ScoutEntityFSM>(ScoutEntityFSM::SCTGL_Explore, &m_scoutController), this); vector<Vector2> suspectLocations; for (auto& locR : m_otherSpawnLocations) { // Only suspect unexplored locations before if (!g_Game->Map()->IsLocationExplored(locR.Location)) suspectLocations.push_back(locR.Location); } // Scout the set of spawn locations // The order is important, since logic resetting requires that // the logic required parameters are well set in the controller m_scoutController.MultiTargetPosition(suspectLocations); m_scoutController.SoftResetLogic(); } } else if (!IsEnemySpawnLocationKnown()) { int locIdx = 0; for (auto& locR : m_otherSpawnLocations) { auto pGrnCtrlIM = (GroundControlIM*)g_IMSysMgr.GetIM(IM_GroundControl); if (pGrnCtrlIM->GetCellInfluenceFromWorldPosition(locR.Location) < 0) { LogInfo("Eneny spawn location discovered at %s", locR.Location.ToString().c_str()); m_knownEnemySpawnLocIdx = locIdx; } ++locIdx; } } if (m_scoutController.IsLogicGoalAchieved()) { m_scoutController.ReleaseEntity(); Deactivate(); } else m_scoutController.Update(); } ////////////////////////////////////////////////////////////////////////// bool ScoutManager::IsEnemySpawnLocationKnown() const { return m_knownEnemySpawnLocIdx != -1; } ////////////////////////////////////////////////////////////////////////// void ScoutManager::NotifyMessegeSent(_In_ Message* pMsg) { if (pMsg->TypeId() == MSG_EntityDestroy) { auto pDestroyMsg = (EntityDestroyMessage*)pMsg; if (pDestroyMsg->Data()->OwnerId == PLAYER_Self && pDestroyMsg->Data()->EntityId == m_scoutController.EntityId()) { m_scoutController.ReleaseEntity(); } } } ////////////////////////////////////////////////////////////////////////// int ScoutManager::GetNearestSpawnLocationIdx(_In_ bool checkNotDiscovered, _In_ bool checkEnemyNotExist) { int idx = 0; for (auto& spawnLocData : m_otherSpawnLocations) { if ((!checkNotDiscovered || !g_Game->Map()->IsLocationExplored(spawnLocData.Location)) && (!checkEnemyNotExist || !spawnLocData.EnemyExist)) { return idx; } ++idx; } return -1; } ////////////////////////////////////////////////////////////////////////// Vector2 ScoutManager::GetSuspectedEnemySpawnLocation() { if (IsEnemySpawnLocationKnown()) return m_otherSpawnLocations[m_knownEnemySpawnLocIdx].Location; else { int bestGuessLocIdx = GetNearestSpawnLocationIdx(true, true); _ASSERTE(bestGuessLocIdx != -1); return m_otherSpawnLocations[bestGuessLocIdx].Location; } }
4,808
1,465
// // Copyright © 2022 Arm Limited. // SPDX-License-Identifier: Apache-2.0 // #include "../Compiler.hpp" #include "CascadingCompiler.hpp" #include "CascadingCompilerUtils.hpp" #include <memory> namespace ethosn { namespace support_library { namespace cascading_compiler { CascadingCompiler::CascadingCompiler(const OpGraph& mergedOpGraph, const std::set<uint32_t>& operationIds, const HardwareCapabilities& capabilities, const CompilationOptions& compilationOptions) : m_MergedOpGraph{ mergedOpGraph } , m_OperationIds{ operationIds } , m_Capabilities{ capabilities } , m_CompilationOptions{ compilationOptions } {} CascadingCompiler::~CascadingCompiler() {} // Compile a given network and return the compiled network std::unique_ptr<CompiledNetwork> CascadingCompiler::Compile() { OpGraph::OpList opsInExecutionOrder = m_MergedOpGraph.GetOps(); assert(opsInExecutionOrder.size() != 0 && m_CommandStreamAgents.size() == 0); try { for (auto currentOp : opsInExecutionOrder) { if (IsObjectOfType<DmaOp>(currentOp)) { ProcessDmaOp(currentOp); } else if (IsObjectOfType<MceOp>(currentOp)) { ProcessMceOp(currentOp); } else if (IsObjectOfType<PleOp>(currentOp)) { ProcessPleOp(currentOp); } else if (IsObjectOfType<ConcatOp>(currentOp)) { ProcessConcatOp(currentOp); } else { throw NotSupportedException("Op is not currently supported by the Cascading Compiler"); } } } catch (const NotSupportedException& e) { g_Logger.Error("Error: %s", e.what()); return std::unique_ptr<CompiledNetworkImpl>(nullptr); } // Add the lifetime information of the intermediate DRAM buffers so the memory required to store these // buffers is reduced AddLifetimeInfoForIntermediateDramBuffers(); // Add the generated command stream to the buffer manager m_CommandStream.EmplaceBack(command_stream::Cascade{ static_cast<uint32_t>(m_CommandStreamAgents.size()) }); for (auto& agent : m_CommandStreamAgents) { m_CommandStream.EmplaceBack<Agent>(agent); } m_BufferManager.AddCommandStream(m_CommandStream); // Create the compiled network using the updated BufferManager instance std::unique_ptr<CompiledNetworkImpl> compiledNetwork = std::make_unique<CompiledNetworkImpl>( m_BufferManager.GetConstantDmaData(), m_BufferManager.GetConstantControlUnitData(), m_BufferManager.GetBuffers(), m_OperationIds); return compiledNetwork; } // Functions used to retrieve private members const std::vector<Agent>& CascadingCompiler::GetCommandStreamOfAgents() const { return m_CommandStreamAgents; } const BufferManager& CascadingCompiler::GetBufferManager() const { return m_BufferManager; } const OpGraph& CascadingCompiler::GetMergedOpGraph() const { return m_MergedOpGraph; } const std::unordered_map<Buffer*, uint32_t>& CascadingCompiler::GetIntermdiateDramBufToBufIdMapping() const { return m_IntermdiateDramBufToBufIdMapping; } // Private functions for processing OpGraph Ops void CascadingCompiler::ProcessDmaOp(Op* const ptrDmaOp) { // Get the input buffer to the Dma Op OpGraph::BufferList inputBuffers = m_MergedOpGraph.GetInputs(ptrDmaOp); Buffer* inputBuffer = inputBuffers[g_DmaInputBufferIndex]; assert(inputBuffers.size() == 1); // Get the output buffer from the Dma Op Buffer* outputBuffer = m_MergedOpGraph.GetOutput(ptrDmaOp); assert(outputBuffer != nullptr); // Construct and add the required agents to the command stream if (inputBuffer->m_Location == Location::Dram && outputBuffer->m_Location == Location::Sram) { assert(inputBuffer->m_BufferType.has_value()); if (inputBuffer->m_Format != CascadingBufferFormat::WEIGHT) { // Ifm Streamer Agent uint16_t inputBufferId = static_cast<uint16_t>( m_BufferManager.AddDram(inputBuffer->m_BufferType.value(), inputBuffer->m_SizeInBytes)); // If this is an Intermediate Dram Buffer, add it to the IntermdiateDramBufToBufId map with the appropriate Id if (inputBuffer->m_BufferType.value() == BufferType::Intermediate) { m_IntermdiateDramBufToBufIdMapping[inputBuffer] = inputBufferId; } AgentIdType ifmStreamerAgentId = AddIfmStreamerToCommandStream(ptrDmaOp, inputBufferId, inputBuffer, outputBuffer); // Only intermediate input buffers need the dependencies not inputs to the network if (inputBuffer->m_BufferType == BufferType::Intermediate) { // Add 'Read After Write' dependency to the IfmStreamer agent // Read After Write Dependency for [IfmStreamer][OfmStreamer] AddReadAfterWriteDependency(AgentType::IFM_STREAMER, ifmStreamerAgentId, AgentType::OFM_STREAMER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffer)]); // Add 'Write After Read' dependency information to the OfmStreamer agent // Write After Read Dependency for [OfmStreamer][IfmStreamer] AddWriteAfterReadDependency(AgentType::IFM_STREAMER, ifmStreamerAgentId, AgentType::OFM_STREAMER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffer)]); // Add 'Schedule Time' dependency information to the OfmStreamer agent // Schedule Time Dependency for [OfmStreamer][IfmStreamer] AddScheduleTimeDependency(AgentType::IFM_STREAMER, ifmStreamerAgentId, AgentType::OFM_STREAMER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffer)]); } } else { // Weight Streamer Agent AgentIdType weightStreamerAgentId = AddWeightStreamerToCommandStream(static_cast<DmaOp*>(ptrDmaOp)); // Get the agent ID of the OFM Streamer // Get the Mce consumer of the weights buffer auto weightBufferConsumer = m_MergedOpGraph.GetConsumer(outputBuffer, 0); assert(weightBufferConsumer.first != nullptr && IsObjectOfType<MceOp>(weightBufferConsumer.first)); AgentIdType ofmStreamerAgentId = m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer( m_MergedOpGraph.GetInputs(weightBufferConsumer.first)[g_MceIfmBufferIndex])]; // Add 'Sram Overlap' dependency to the WeightStreamer agent // Sram Overlap Dependency for [WeightStreamer][OfmStreamer] AddSramOverlapDependency(AgentType::WGT_STREAMER, weightStreamerAgentId, AgentType::OFM_STREAMER, ofmStreamerAgentId); } } else if (inputBuffer->m_Location == Location::Sram && outputBuffer->m_Location == Location::Dram) { assert(inputBuffer->m_Offset.has_value()); assert(outputBuffer->m_BufferType.has_value()); // Get the producer of the input buffer and the producing agent type Op* producerOp = m_MergedOpGraph.GetProducer(inputBuffer); assert(IsObjectOfType<PleOp>(producerOp) || IsObjectOfType<DmaOp>(producerOp)); AgentType producerAgentType; if (IsObjectOfType<PleOp>(producerOp)) { producerAgentType = AgentType::PLE_SCHEDULER; } else { producerAgentType = AgentType::IFM_STREAMER; } uint16_t outputBufferId = static_cast<uint16_t>( m_BufferManager.AddDram(outputBuffer->m_BufferType.value(), outputBuffer->m_SizeInBytes)); // If this is an Intermediate Dram Buffer, add it to the IntermdiateDramBufToBufId map with the appropriate Id if (outputBuffer->m_BufferType.value() == BufferType::Intermediate) { m_IntermdiateDramBufToBufIdMapping[outputBuffer] = outputBufferId; } // Ofm Streamer Agent AgentIdType ofmStreamerAgentId = AddOfmStreamerToCommandStream(ptrDmaOp, inputBuffer, outputBufferId, outputBuffer); // Add 'Read After Write' dependency information to the IfmStreamer and PleScheduler agents // Read After Write Dependency for [OfmStreamer][IfmStreamer] or // Read After Write Dependency for [OfmStreamer][PleScheduler] AddReadAfterWriteDependency(AgentType::OFM_STREAMER, ofmStreamerAgentId, producerAgentType, m_OpToAgentIdMapping[producerOp]); // Add 'Write After Read' dependency information to the IfmStreamer and PleScheduler agents // Write After Read Dependency for [IfmStreamer][OfmStreamer] or // Write After Read Dependency for [PleScheduler][OfmStreamer] AddWriteAfterReadDependency(AgentType::OFM_STREAMER, ofmStreamerAgentId, producerAgentType, m_OpToAgentIdMapping[producerOp]); // Add 'Schedule Time' dependency information to the IfmStreamer and PleScheduler agents // Schedule Time Dependency for [IfmStreamer][OfmStreamer] or // Schedule Time Dependency for [PleScheduler][OfmStreamer] AddScheduleTimeDependency(AgentType::OFM_STREAMER, ofmStreamerAgentId, producerAgentType, m_OpToAgentIdMapping[producerOp]); } else { assert(false); } } void CascadingCompiler::ProcessMceOp(Op* const ptrMceOp) { // Get the input buffers to the Mce Op OpGraph::BufferList inputBuffers = m_MergedOpGraph.GetInputs(ptrMceOp); assert(inputBuffers.size() == 2 && inputBuffers[g_MceIfmBufferIndex]->m_Offset.has_value() && inputBuffers[g_MceWeightBufferIndex]->m_Offset.has_value()); // Get the output buffer from the Mce Op Buffer* outputBuffer = m_MergedOpGraph.GetOutput(ptrMceOp); assert(outputBuffer != nullptr); auto producerOp = m_MergedOpGraph.GetProducer(inputBuffers[g_MceIfmBufferIndex]); AgentType producerAgentType; if (IsObjectOfType<PleOp>(producerOp)) { // MceOp takes input 0 from pleS agent producerAgentType = AgentType::PLE_SCHEDULER; } else { // MceOp takes input 0 from ifmS agent producerAgentType = AgentType::IFM_STREAMER; } // Construct and add the required agents to the command stream // Ple Loader Agent auto mceOpConsumer = m_MergedOpGraph.GetConsumer(outputBuffer, 0); assert(mceOpConsumer.first != nullptr && IsObjectOfType<PleOp>(mceOpConsumer.first)); AgentIdType pleLoaderAgentId = 0; PleOp* ptrPleOp = static_cast<PleOp*>(mceOpConsumer.first); if (ptrPleOp->m_LoadKernel) { pleLoaderAgentId = AddPleLoaderToCommandStream(ptrPleOp); } // MCE Scheduler Agent AgentIdType mceSchedulerAgentId = AddMceSchedulerToCommandStream(static_cast<MceOp*>(ptrMceOp), ptrPleOp->m_PleKernelId); // Add 'Read After Write' dependency to the MceScheduler agent // Read After Write Dependency for [MceScheduler][IfmStreamer] or // Read After Write Dependency for [MceScheduler][PleScheduler] AddReadAfterWriteDependency(AgentType::MCE_SCHEDULER, mceSchedulerAgentId, producerAgentType, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_MceIfmBufferIndex])]); // Read After Write Dependency for [MceScheduler][WeightStreamer] AddReadAfterWriteDependency( AgentType::MCE_SCHEDULER, mceSchedulerAgentId, AgentType::WGT_STREAMER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_MceWeightBufferIndex])]); // Add 'Write After Read' dependency information to the IfmStreamer and WeightStreamer agents // Write After Read Dependency for [IfmStreamer][MceScheduler] or // Write After Read Dependency for [PleScheduler][MceScheduler] AddWriteAfterReadDependency(AgentType::MCE_SCHEDULER, mceSchedulerAgentId, producerAgentType, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_MceIfmBufferIndex])]); // Write After Read Dependency for [WeightStreamer][MceScheduler] AddWriteAfterReadDependency( AgentType::MCE_SCHEDULER, mceSchedulerAgentId, AgentType::WGT_STREAMER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_MceWeightBufferIndex])]); // Add 'Schedule Time' dependency information to the IfmStreamer and WeightStreamer agents // Schedule Time Dependency for [IfmStreamer][MceScheduler] or // Schedule Time Dependency for [PleScheduler][MceScheduler] AddScheduleTimeDependency(AgentType::MCE_SCHEDULER, mceSchedulerAgentId, producerAgentType, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_MceIfmBufferIndex])]); // Schedule Time Dependency for [WeightStreamer][MceScheduler] AddScheduleTimeDependency(AgentType::MCE_SCHEDULER, mceSchedulerAgentId, AgentType::WGT_STREAMER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_MceWeightBufferIndex])]); // Add 'Schedule Time' dependency information to the PLE Loader agent // Schedule Time Dependency for [PLE Loader][MceScheduler] if (ptrPleOp->m_LoadKernel) { AddScheduleTimeDependency(AgentType::MCE_SCHEDULER, mceSchedulerAgentId, AgentType::PLE_LOADER, pleLoaderAgentId); } } void CascadingCompiler::ProcessPleOp(Op* const ptrPleOp) { // Get the input buffers to the Ple Op OpGraph::BufferList inputBuffers = m_MergedOpGraph.GetInputs(ptrPleOp); assert(inputBuffers.size() == 1 || inputBuffers.size() == 2); for (auto inputBuffer : inputBuffers) { if (inputBuffer->m_Location == Location::Sram) { assert(inputBuffer->m_Offset.has_value()); } ETHOSN_UNUSED(inputBuffer); } // Get the output buffer from the Ple Op Buffer* outputBuffer = m_MergedOpGraph.GetOutput(ptrPleOp); assert(outputBuffer->m_Offset.has_value()); // Determine whether ple op is standalone or fused bool isStandAlonePle = false; if (inputBuffers[g_PleInputBuffer0Index]->m_Location == Location::PleInputSram) { isStandAlonePle = false; } else if (inputBuffers[g_PleInputBuffer0Index]->m_Location == Location::Sram) { isStandAlonePle = true; } else { assert(false); } bool loadKernel = static_cast<PleOp*>(ptrPleOp)->m_LoadKernel; if (isStandAlonePle) { AgentIdType pleLoaderAgentId = {}; if (loadKernel) { pleLoaderAgentId = AddPleLoaderToCommandStream(static_cast<PleOp*>(ptrPleOp)); } AgentIdType pleSchedulerAgentId = AddPleSchedulerToCommandStream(static_cast<PleOp*>(ptrPleOp)); // Read After Write Dependency for [PleScheduler][IfmStreamer] AddReadAfterWriteDependency( AgentType::PLE_SCHEDULER, pleSchedulerAgentId, AgentType::IFM_STREAMER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_PleInputBuffer0Index])]); if (loadKernel) { // Read After Write Dependency for [PleScheduler][PleLoader] AddReadAfterWriteDependency( AgentType::PLE_SCHEDULER, pleSchedulerAgentId, AgentType::PLE_LOADER, m_PleKernelToPleLoaderAgentIdMapping[static_cast<PleOp*>(ptrPleOp)->m_PleKernelId]); } // Write After Read Dependency for [IfmStreamer][PleScheduler] AddWriteAfterReadDependency( AgentType::PLE_SCHEDULER, pleSchedulerAgentId, AgentType::IFM_STREAMER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_PleInputBuffer0Index])]); // Schedule Time Dependency for [IfmStreamer][PleScheduler] AddScheduleTimeDependency( AgentType::PLE_SCHEDULER, pleSchedulerAgentId, AgentType::IFM_STREAMER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_PleInputBuffer0Index])]); if (loadKernel) { // Schedule Time Dependency for [PleLoader][PleScheduler] AddScheduleTimeDependency(AgentType::PLE_SCHEDULER, pleSchedulerAgentId, AgentType::PLE_LOADER, pleLoaderAgentId); } } else { AgentIdType pleSchedulerAgentId = AddPleSchedulerToCommandStream(static_cast<PleOp*>(ptrPleOp)); // Read After Write Dependency for [PleScheduler][MceScheduler] AddReadAfterWriteDependency( AgentType::PLE_SCHEDULER, pleSchedulerAgentId, AgentType::MCE_SCHEDULER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_PleInputBuffer0Index])]); if (loadKernel) { // Read After Write Dependency for [PleScheduler][PleLoader] AddReadAfterWriteDependency( AgentType::PLE_SCHEDULER, pleSchedulerAgentId, AgentType::PLE_LOADER, m_PleKernelToPleLoaderAgentIdMapping[static_cast<PleOp*>(ptrPleOp)->m_PleKernelId]); } // Write After Read Dependency for [MceScheduler][PleScheduler] AddWriteAfterReadDependency( AgentType::PLE_SCHEDULER, pleSchedulerAgentId, AgentType::MCE_SCHEDULER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_PleInputBuffer0Index])]); // Schedule Time Dependency for [MceScheduler][PleScheduler] AddScheduleTimeDependency( AgentType::PLE_SCHEDULER, pleSchedulerAgentId, AgentType::MCE_SCHEDULER, m_OpToAgentIdMapping[m_MergedOpGraph.GetProducer(inputBuffers[g_PleInputBuffer0Index])]); } ETHOSN_UNUSED(outputBuffer); } void CascadingCompiler::ProcessConcatOp(Op* const ptrConcatOp) { // Get the input buffers to the Concat Op OpGraph::BufferList inputBuffers = m_MergedOpGraph.GetInputs(ptrConcatOp); assert(inputBuffers.size() >= 1); // Get the output buffer from the Concat Op Buffer* outputBuffer = m_MergedOpGraph.GetOutput(ptrConcatOp); assert(outputBuffer != nullptr && outputBuffer->m_Location == Location::Dram && outputBuffer->m_BufferType.has_value()); uint16_t outputBufferId = static_cast<uint16_t>(m_BufferManager.AddDram(outputBuffer->m_BufferType.value(), outputBuffer->m_SizeInBytes)); // If this is an Intermediate Dram Buffer, add it to the IntermdiateDramBufToBufId map with the appropriate Id if (outputBuffer->m_BufferType.value() == BufferType::Intermediate) { m_IntermdiateDramBufToBufIdMapping[outputBuffer] = outputBufferId; } uint32_t sramBufferOffset = 0U; uint32_t dramBufferOffset = 0U; uint32_t sramBufferSlotSize; for (auto inputBuffer : inputBuffers) { assert(inputBuffer->m_Location == Location::Dram && inputBuffer->m_BufferType.has_value()); assert(inputBuffer->m_Format == CascadingBufferFormat::NHWCB || inputBuffer->m_Format == CascadingBufferFormat::NHWC); // Temporary SRAM buffer used between IFMStreamer and OFMStreamer TensorShape sramBufferShape = { 1, 8, 8, utils::GetChannels(inputBuffer->m_TensorShape) }; Buffer sramBuffer(Location::Sram, CascadingBufferFormat::NHWCB, sramBufferShape, sramBufferShape, TraversalOrder::Xyz, utils::TotalSizeBytesNHWCB(sramBufferShape), inputBuffer->m_QuantizationInfo); sramBuffer.m_NumStripes = 2; sramBuffer.m_QuantizationInfo = inputBuffer->m_QuantizationInfo; sramBuffer.m_Offset = sramBufferOffset; sramBufferSlotSize = CommonUtils::CalculateBufferSize(sramBufferShape, CascadingBufferFormat::NHWCB) / m_Capabilities.GetNumberOfSrams(); assert(utils::DivRoundUp(utils::TotalSizeBytesNHWCB(sramBufferShape), m_Capabilities.GetNumberOfSrams()) < m_Capabilities.GetTotalSramSize()); assert(sramBuffer.m_Offset.value() + (sramBuffer.m_NumStripes * sramBufferSlotSize) < m_Capabilities.GetTotalSramSize()); // Set output DRAM buffer offset outputBuffer->m_Offset = dramBufferOffset; uint16_t inputBufferId = static_cast<uint16_t>( m_BufferManager.AddDram(inputBuffer->m_BufferType.value(), inputBuffer->m_SizeInBytes)); // If this is an Intermediate Dram Buffer, add it to the IntermdiateDramBufToBufId map with the appropriate Id if (inputBuffer->m_BufferType.value() == BufferType::Intermediate) { m_IntermdiateDramBufToBufIdMapping[inputBuffer] = inputBufferId; } // Ifm Streamer Agent AgentIdType ifmStreamerAgentId = AddIfmStreamerToCommandStream(ptrConcatOp, inputBufferId, inputBuffer, &sramBuffer); // Ofm Streamer Agent AgentIdType ofmStreamerAgentId = AddOfmStreamerToCommandStream(ptrConcatOp, &sramBuffer, outputBufferId, outputBuffer); // Add 'Read After Write' dependency to the OfmStreamer agent // Read After Write Dependency for [OfmStreamer][IfmStreamer] AddReadAfterWriteDependency(AgentType::OFM_STREAMER, ofmStreamerAgentId, AgentType::IFM_STREAMER, ifmStreamerAgentId); // Add 'Write After Read' dependency information to the IfmStreamer agent // Write After Read Dependency for [IfmStreamer][OfmStreamer] AddWriteAfterReadDependency(AgentType::OFM_STREAMER, ofmStreamerAgentId, AgentType::IFM_STREAMER, ifmStreamerAgentId); // Add 'Schedule Time' dependency information to the OfmStreamer agent // Schedule Time Dependency for [IfmStreamer][OfmStreamer] AddScheduleTimeDependency(AgentType::OFM_STREAMER, ofmStreamerAgentId, AgentType::IFM_STREAMER, ifmStreamerAgentId); // Update the SRAM offset value for the next IfmStreamer Agent sramBufferOffset = sramBufferOffset + (sramBuffer.m_NumStripes * sramBufferSlotSize); // Update the Output DRAM offset value for the next OfmStreamer Agent std::tuple<bool, bool, bool> isHWCSplit = utils::IsSplitting(outputBuffer->m_TensorShape, inputBuffer->m_TensorShape); // Concatenation is happening in the Height dimension if (std::get<0>(isHWCSplit)) { if (outputBuffer->m_Format == CascadingBufferFormat::NHWCB) { assert(utils::GetHeight(inputBuffer->m_TensorShape) % utils::GetHeight(m_Capabilities.GetBrickGroupShape()) == 0); } uint32_t heightOffset = CommonUtils::CalculateBufferSize(inputBuffer->m_TensorShape, inputBuffer->m_Format); dramBufferOffset = dramBufferOffset + heightOffset; } // Concatenation is happening in the Width dimension else if (std::get<1>(isHWCSplit)) { uint32_t widthOffset; if (outputBuffer->m_Format == CascadingBufferFormat::NHWC) { widthOffset = utils::GetChannels(inputBuffer->m_TensorShape) * utils::GetWidth(inputBuffer->m_TensorShape); } else { assert(utils::GetWidth(inputBuffer->m_TensorShape) % utils::GetWidth(m_Capabilities.GetBrickGroupShape()) == 0); uint32_t widthInBrickGroups = utils::DivRoundUp(utils::GetWidth(inputBuffer->m_TensorShape), utils::GetWidth(m_Capabilities.GetBrickGroupShape())); uint32_t channelsInBrickGroups = utils::DivRoundUp(utils::GetChannels(inputBuffer->m_TensorShape), utils::GetChannels(m_Capabilities.GetBrickGroupShape())); uint32_t numberOfBrickGroups = channelsInBrickGroups * widthInBrickGroups; widthOffset = numberOfBrickGroups * CommonUtils::CalculateBufferSize(m_Capabilities.GetBrickGroupShape(), CascadingBufferFormat::NHWCB); } dramBufferOffset = dramBufferOffset + widthOffset; } // Concatenation is happening in the Depth/Channels dimension else if (std::get<2>(isHWCSplit)) { assert(outputBuffer->m_Format == CascadingBufferFormat::NHWCB); uint32_t channelsInBrickGroups = utils::DivRoundUp(utils::GetChannels(inputBuffer->m_TensorShape), utils::GetChannels(m_Capabilities.GetBrickGroupShape())); uint32_t depthOffset = channelsInBrickGroups * CommonUtils::CalculateBufferSize(m_Capabilities.GetBrickGroupShape(), outputBuffer->m_Format); dramBufferOffset = dramBufferOffset + depthOffset; } } } void CascadingCompiler::ProcessSplitOp(Op* const ptrSplitOp) { ETHOSN_UNUSED(ptrSplitOp); } void CascadingCompiler::ProcessSpaceToDepthOp(Op* const ptrSpaceToDepthOp) { ETHOSN_UNUSED(ptrSpaceToDepthOp); } void CascadingCompiler::ProcessTransposeOp(Op* const ptrTransposeOp) { ETHOSN_UNUSED(ptrTransposeOp); } // Private function to add IFM_STREAMER to the command stream AgentIdType CascadingCompiler::AddIfmStreamerToCommandStream(Op* const ptrOp, const uint16_t inputDramBufferId, const Buffer* const inputDramBuffer, const Buffer* const inputSramBuffer) { assert(IsObjectOfType<DmaOp>(ptrOp) || IsObjectOfType<ConcatOp>(ptrOp)); IfmS ifmStreamerData = {}; ifmStreamerData.fmData.bufferId = inputDramBufferId; StreamersUtils::SetBufferDataType(ifmStreamerData.fmData, inputDramBuffer->m_Format); ifmStreamerData.fmData.fcafInfo.signedActivation = false; ifmStreamerData.fmData.fcafInfo.zeroPoint = ethosn::utils::NumericCast<uint8_t>(inputDramBuffer->m_QuantizationInfo.GetZeroPoint()); CommonUtils::SetTileInfoForBuffer(m_Capabilities, ifmStreamerData.fmData.tile, inputSramBuffer); StreamersUtils::SetStripeHeightInfo(ifmStreamerData.fmData, inputSramBuffer->m_TensorShape, inputSramBuffer->m_StripeShape); StreamersUtils::SetStripeWidthInfo(ifmStreamerData.fmData, inputSramBuffer->m_TensorShape, inputSramBuffer->m_StripeShape); StreamersUtils::SetStripeChannelsInfo(ifmStreamerData.fmData, inputSramBuffer->m_TensorShape, inputSramBuffer->m_StripeShape); StreamersUtils::SetSuperTensorSizeInCells(ifmStreamerData.fmData, inputDramBuffer->m_TensorShape, inputDramBuffer->m_Format); StreamersUtils::SetStripeIdStrides(ifmStreamerData.fmData, inputDramBuffer->m_Order); AgentDependencyInfo dependencyInfo = {}; dependencyInfo.numStripesTotal = ethosn::utils::NumericCast<uint16_t>( utils::GetNumStripesTotal(inputSramBuffer->m_TensorShape, inputSramBuffer->m_StripeShape)); Agent ifmStreamerAgent{ ifmStreamerData, dependencyInfo }; // Push the Ifm Streamer agent to the command stream AgentIdType agentId = m_CommandStreamAgents.size(); m_OpToAgentIdMapping[ptrOp] = agentId; m_CommandStreamAgents.push_back(ifmStreamerAgent); return agentId; } // Private function to add WGT_STREAMER to the command stream AgentIdType CascadingCompiler::AddWeightStreamerToCommandStream(DmaOp* const ptrDmaOp) { // Get the input buffer to the Dma Op OpGraph::BufferList inputBuffers = m_MergedOpGraph.GetInputs(ptrDmaOp); Buffer* weightsDramBuffer = inputBuffers[g_DmaInputBufferIndex]; Buffer* weightsSramBuffer = m_MergedOpGraph.GetOutput(ptrDmaOp); // Get the Mce consumer of the weights buffer auto weightBufferConsumer = m_MergedOpGraph.GetConsumer(weightsSramBuffer, 0); assert(weightBufferConsumer.first != nullptr && IsObjectOfType<MceOp>(weightBufferConsumer.first)); Buffer* ifmBuffer = m_MergedOpGraph.GetInputs(weightBufferConsumer.first)[0]; Buffer* ofmBuffer = m_MergedOpGraph.GetOutput(weightBufferConsumer.first); WgtS weightStreamerData = {}; EncodedWeights* encodedWeights = weightsDramBuffer->m_EncodedWeights.get(); std::vector<uint8_t>& compressedWeights = encodedWeights->m_Data; std::vector<uint8_t> metadataBytes; metadataBytes.assign( reinterpret_cast<const uint8_t*>(encodedWeights->m_Metadata.data()), reinterpret_cast<const uint8_t*>(encodedWeights->m_Metadata.data() + encodedWeights->m_Metadata.size())); weightStreamerData.bufferId = ethosn::utils::NumericCast<uint16_t>( m_BufferManager.AddDramConstant(BufferType::ConstantDma, compressedWeights)); weightStreamerData.metadataBufferId = ethosn::utils::NumericCast<uint16_t>( m_BufferManager.AddDramConstant(BufferType::ConstantControlUnit, metadataBytes)); CommonUtils::SetTileInfoForBuffer(m_Capabilities, weightStreamerData.tile, weightsSramBuffer); weightStreamerData.numStripes.ifmChannels = ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesC(ifmBuffer->m_TensorShape, ifmBuffer->m_StripeShape)); weightStreamerData.numStripes.ofmChannels = ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesC(ofmBuffer->m_TensorShape, ofmBuffer->m_StripeShape)); weightStreamerData.stripeIdStrides.ifmChannels = 1; weightStreamerData.stripeIdStrides.ofmChannels = weightStreamerData.numStripes.ifmChannels; AgentDependencyInfo dependencyInfo = {}; Agent weightStreamerAgent{ weightStreamerData, dependencyInfo }; dependencyInfo.numStripesTotal = ethosn::utils::NumericCast<uint16_t>( utils::GetNumStripesTotal(weightsSramBuffer->m_TensorShape, weightsSramBuffer->m_StripeShape)); // Push the Weight Streamer agent to the command stream AgentIdType agentId = m_CommandStreamAgents.size(); m_OpToAgentIdMapping[ptrDmaOp] = agentId; m_CommandStreamAgents.push_back(weightStreamerAgent); return agentId; } // Private function to add MCE_SCHEDULER to the command stream AgentIdType CascadingCompiler::AddMceSchedulerToCommandStream(MceOp* const ptrMceOp, const PleKernelId pleKernelId) { // Get the input buffers to the Mce Op OpGraph::BufferList inputBuffers = m_MergedOpGraph.GetInputs(ptrMceOp); Buffer* inputBuffer = inputBuffers[g_MceIfmBufferIndex]; Buffer* weightBuffer = inputBuffers[g_MceWeightBufferIndex]; // Get the output buffer from the Mce Op Buffer* outputBuffer = m_MergedOpGraph.GetOutput(ptrMceOp); MceS mceSchedulerData = {}; CommonUtils::SetTileInfoForBuffer(m_Capabilities, mceSchedulerData.ifmTile, inputBuffer); CommonUtils::SetTileInfoForBuffer(m_Capabilities, mceSchedulerData.wgtTile, weightBuffer); mceSchedulerData.blockSize.width = ethosn::utils::NumericCast<uint8_t>(ptrMceOp->m_BlockConfig.m_BlockWidth()); mceSchedulerData.blockSize.height = ethosn::utils::NumericCast<uint8_t>(ptrMceOp->m_BlockConfig.m_BlockHeight()); MceSUtils::SetMcesOfmHeightStripeInfo(mceSchedulerData, outputBuffer->m_TensorShape, ptrMceOp->m_OutputStripeShape); MceSUtils::SetMcesOfmWidthStripeInfo(mceSchedulerData, outputBuffer->m_TensorShape, ptrMceOp->m_OutputStripeShape); MceSUtils::SetMcesOfmChannelsStripeInfo(mceSchedulerData, outputBuffer->m_TensorShape, ptrMceOp->m_OutputStripeShape); MceSUtils::SetMcesIfmChannelsStripeInfo(mceSchedulerData, inputBuffer->m_TensorShape, inputBuffer->m_StripeShape); MceSUtils::SetStripeIdStrides(mceSchedulerData, outputBuffer->m_Order); mceSchedulerData.convStrideXy.x = ethosn::utils::NumericCast<uint8_t>(ptrMceOp->m_Stride.m_X); mceSchedulerData.convStrideXy.y = ethosn::utils::NumericCast<uint8_t>(ptrMceOp->m_Stride.m_Y); mceSchedulerData.ifmZeroPoint = ethosn::utils::NumericCast<uint16_t>(inputBuffer->m_QuantizationInfo.GetZeroPoint()); MceSUtils::setMcesOpMode(mceSchedulerData, ptrMceOp->m_Op); MceSUtils::setMcesAlgorithm(mceSchedulerData, ptrMceOp->m_Algo); for (int i = 0; i < 4; i++) { mceSchedulerData.filterShape[i].height = static_cast<uint8_t>(weightBuffer->m_TensorShape[1]); mceSchedulerData.filterShape[i].width = static_cast<uint8_t>(weightBuffer->m_TensorShape[2]); mceSchedulerData.padding[i].left = static_cast<uint8_t>(ptrMceOp->m_PadLeft); mceSchedulerData.padding[i].top = static_cast<uint8_t>(ptrMceOp->m_PadTop); mceSchedulerData.ifmDeltaDefault[i].height = static_cast<int8_t>(inputBuffer->m_TensorShape[1] - outputBuffer->m_TensorShape[1]); mceSchedulerData.ifmDeltaDefault[i].width = static_cast<int8_t>(inputBuffer->m_TensorShape[2] - outputBuffer->m_TensorShape[2]); mceSchedulerData.ifmDeltaEdge[i].height = static_cast<int8_t>(inputBuffer->m_TensorShape[1] - outputBuffer->m_TensorShape[1]); mceSchedulerData.ifmDeltaEdge[i].width = static_cast<int8_t>(inputBuffer->m_TensorShape[2] - outputBuffer->m_TensorShape[2]); } mceSchedulerData.reluActiv.min = ptrMceOp->m_LowerBound; mceSchedulerData.reluActiv.max = ptrMceOp->m_UpperBound; mceSchedulerData.pleKernelId = pleKernelId; AgentDependencyInfo dependencyInfo = {}; dependencyInfo.numStripesTotal = ethosn::utils::NumericCast<uint16_t>( utils::GetNumStripesTotal(outputBuffer->m_TensorShape, outputBuffer->m_StripeShape)); Agent mceSchedulerAgent{ mceSchedulerData, dependencyInfo }; // Push the Mce Scheduler agent to the command stream AgentIdType agentId = m_CommandStreamAgents.size(); m_OpToAgentIdMapping[ptrMceOp] = agentId; m_CommandStreamAgents.push_back(mceSchedulerAgent); return agentId; } // Private function to add PLE_LOADER to the command stream AgentIdType CascadingCompiler::AddPleLoaderToCommandStream(PleOp* const ptrPleOp) { // Create a new Ple Loader agent PleL pleLoaderData = {}; pleLoaderData.pleKernelId = ptrPleOp->m_PleKernelId; pleLoaderData.sramAddr = ethosn::utils::NumericCast<uint16_t>(ptrPleOp->m_Offset.value()); AgentDependencyInfo dependencyInfo = {}; dependencyInfo.numStripesTotal = 1; Agent pleLoaderAgent{ pleLoaderData, dependencyInfo }; // Push the Ple Loader agent to the command stream AgentIdType agentId = m_CommandStreamAgents.size(); m_PleKernelToPleLoaderAgentIdMapping[ptrPleOp->m_PleKernelId] = agentId; m_CommandStreamAgents.push_back(pleLoaderAgent); return agentId; } // Private function to add PLE_SCHEDULER to the command stream AgentIdType CascadingCompiler::AddPleSchedulerToCommandStream(PleOp* const ptrPleOp) { // Get the input buffers to the Ple Op OpGraph::BufferList inputBuffers = m_MergedOpGraph.GetInputs(ptrPleOp); assert(inputBuffers.size() == 1 || inputBuffers.size() == 2); Buffer* inputBuffer0 = inputBuffers[g_PleInputBuffer0Index]; // Get the output buffer from the Ple Op Buffer* outputBuffer = m_MergedOpGraph.GetOutput(ptrPleOp); assert(ptrPleOp->m_OutputStripeShape == outputBuffer->m_StripeShape); PleS pleS = {}; CommonUtils::SetTileInfoForBuffer(m_Capabilities, pleS.ofmTile, outputBuffer); pleS.ofmZeroPoint = ethosn::utils::NumericCast<int16_t>(outputBuffer->m_QuantizationInfo.GetZeroPoint()); PleSUtils::SetPlesHeightStripeInfo(pleS, outputBuffer->m_TensorShape, ptrPleOp->m_OutputStripeShape); PleSUtils::SetPlesWidthStripeInfo(pleS, outputBuffer->m_TensorShape, ptrPleOp->m_OutputStripeShape); PleSUtils::SetPlesChannelsStripeInfo(pleS, outputBuffer->m_TensorShape, ptrPleOp->m_OutputStripeShape); PleSUtils::SetStripeIdStrides(pleS, outputBuffer); // Calculate input mode of Ple OP dependent on input buffer producer. auto pleOpProducer = m_MergedOpGraph.GetProducer(inputBuffer0); if (inputBuffer0->m_Location == Location::Sram) { pleS.inputMode = PleInputMode::SRAM; } else if (inputBuffer0->m_Location == Location::PleInputSram) { PleSUtils::SetFusedPleSInputMode(pleS, static_cast<MceOp*>(pleOpProducer)); } else { assert(false); } pleS.pleKernelSramAddr = ethosn::utils::NumericCast<uint16_t>(ptrPleOp->m_Offset.value()); pleS.pleKernelId = ptrPleOp->m_PleKernelId; if (pleS.inputMode == PleInputMode::SRAM) { CommonUtils::SetTileInfoForBuffer(m_Capabilities, pleS.ifmTile0, inputBuffer0); const double outputScale = outputBuffer->m_QuantizationInfo.GetScale(); const double inputScale0 = inputBuffer0->m_QuantizationInfo.GetScale(); uint16_t multiplier0; uint16_t shift0; utils::CalculateRescaleMultiplierAndShift(inputScale0 / outputScale, multiplier0, shift0); pleS.ifmInfo0 = { ethosn::utils::NumericCast<int16_t>(inputBuffer0->m_QuantizationInfo.GetZeroPoint()), multiplier0, shift0 }; if (inputBuffers.size() == 2) { Buffer* inputBuffer1 = inputBuffers[g_PleInputBuffer1Index]; const double inputScale1 = inputBuffer1->m_QuantizationInfo.GetScale(); uint16_t multiplier1; uint16_t shift1; utils::CalculateRescaleMultiplierAndShift(inputScale1 / outputScale, multiplier1, shift1); CommonUtils::SetTileInfoForBuffer(m_Capabilities, pleS.ifmTile1, inputBuffer1); pleS.ifmInfo1 = { ethosn::utils::NumericCast<int16_t>(inputBuffer1->m_QuantizationInfo.GetZeroPoint()), multiplier1, shift1 }; } } AgentData agentData{ pleS }; AgentDependencyInfo info = {}; info.numStripesTotal = ethosn::utils::NumericCast<uint16_t>( utils::GetNumStripesTotal(outputBuffer->m_TensorShape, outputBuffer->m_StripeShape)); Agent pleSchedulerAgent{ agentData, info }; // Push the Ple Scheduler agent to the command stream AgentIdType agentId = m_CommandStreamAgents.size(); m_OpToAgentIdMapping[ptrPleOp] = agentId; m_CommandStreamAgents.push_back(pleSchedulerAgent); return agentId; } // Private function to add OFM_STREAMER to the command stream AgentIdType CascadingCompiler::AddOfmStreamerToCommandStream(Op* const ptrOp, const Buffer* const outputSramBuffer, const uint16_t outputDramBufferId, const Buffer* const outputDramBuffer) { assert(IsObjectOfType<DmaOp>(ptrOp) || IsObjectOfType<ConcatOp>(ptrOp)); OfmS ofmStreamerData = {}; if (outputDramBuffer->m_Offset.has_value()) { ofmStreamerData.fmData.dramOffset = outputDramBuffer->m_Offset.value(); } ofmStreamerData.fmData.bufferId = outputDramBufferId; StreamersUtils::SetBufferDataType(ofmStreamerData.fmData, outputDramBuffer->m_Format); ofmStreamerData.fmData.fcafInfo.signedActivation = false; ofmStreamerData.fmData.fcafInfo.zeroPoint = ethosn::utils::NumericCast<uint8_t>(outputDramBuffer->m_QuantizationInfo.GetZeroPoint()); CommonUtils::SetTileInfoForBuffer(m_Capabilities, ofmStreamerData.fmData.tile, outputSramBuffer); StreamersUtils::SetStripeHeightInfo(ofmStreamerData.fmData, outputSramBuffer->m_TensorShape, outputSramBuffer->m_StripeShape); StreamersUtils::SetStripeWidthInfo(ofmStreamerData.fmData, outputSramBuffer->m_TensorShape, outputSramBuffer->m_StripeShape); StreamersUtils::SetStripeChannelsInfo(ofmStreamerData.fmData, outputSramBuffer->m_TensorShape, outputSramBuffer->m_StripeShape); StreamersUtils::SetSuperTensorSizeInCells(ofmStreamerData.fmData, outputDramBuffer->m_TensorShape, outputDramBuffer->m_Format); StreamersUtils::SetStripeIdStrides(ofmStreamerData.fmData, outputDramBuffer->m_Order); AgentDependencyInfo dependencyInfo = {}; dependencyInfo.numStripesTotal = ethosn::utils::NumericCast<uint16_t>( utils::GetNumStripesTotal(outputSramBuffer->m_TensorShape, outputSramBuffer->m_StripeShape)); Agent ofmStreamerAgent{ ofmStreamerData, dependencyInfo }; // Push the Ofm Streamer agent to the command stream AgentIdType agentId = m_CommandStreamAgents.size(); m_OpToAgentIdMapping[ptrOp] = agentId; m_CommandStreamAgents.push_back(ofmStreamerAgent); return agentId; } // Private function to add ReadAfterWrite Dependency // Consumer agent creates and own the dependency inline void CascadingCompiler::AddReadAfterWriteDependency(const AgentType consumerAgentType, const AgentIdType consumerAgentId, const AgentType producerAgentType, const AgentIdType producerAgentId) { AgentIdType relativeAgentId = consumerAgentId - producerAgentId; assert(relativeAgentId <= g_MaxRelativeAgentPosition); if (producerAgentType == AgentType::WGT_STREAMER || producerAgentType == AgentType::MCE_SCHEDULER || (producerAgentType == AgentType::IFM_STREAMER && consumerAgentType == AgentType::PLE_SCHEDULER)) { Dependency& consumerAgentReadDependency1Ref = m_CommandStreamAgents[consumerAgentId].info.readDependencies.at(1); consumerAgentReadDependency1Ref.relativeAgentId = static_cast<RelativeAgentIdType>(relativeAgentId); FillConsumerAgentDependency(consumerAgentReadDependency1Ref, consumerAgentType, consumerAgentId, producerAgentType, producerAgentId); } else { Dependency& consumerAgentReadDependency0Ref = m_CommandStreamAgents[consumerAgentId].info.readDependencies.at(0); consumerAgentReadDependency0Ref.relativeAgentId = static_cast<RelativeAgentIdType>(relativeAgentId); FillConsumerAgentDependency(consumerAgentReadDependency0Ref, consumerAgentType, consumerAgentId, producerAgentType, producerAgentId); } } // Private function to add SRAM Overlap Dependency // Consumer agent creates and own the dependency inline void CascadingCompiler::AddSramOverlapDependency(const command_stream::cascading::AgentType consumerAgentType, const AgentIdType consumerAgentId, const command_stream::cascading::AgentType producerAgentType, const AgentIdType producerAgentId) { AgentIdType relativeAgentId = consumerAgentId - producerAgentId; assert(relativeAgentId <= g_MaxRelativeAgentPosition); assert((producerAgentType != AgentType::MCE_SCHEDULER)); if ((producerAgentType != AgentType::WGT_STREAMER)) { Dependency& consumerAgentReadDependency0Ref = m_CommandStreamAgents[consumerAgentId].info.readDependencies.at(0); consumerAgentReadDependency0Ref.relativeAgentId = static_cast<RelativeAgentIdType>(relativeAgentId); FillConsumerAgentDependency(consumerAgentReadDependency0Ref, consumerAgentType, consumerAgentId, producerAgentType, producerAgentId); } else { Dependency& consumerAgentReadDependency1Ref = m_CommandStreamAgents[consumerAgentId].info.readDependencies.at(1); consumerAgentReadDependency1Ref.relativeAgentId = static_cast<RelativeAgentIdType>(relativeAgentId); FillConsumerAgentDependency(consumerAgentReadDependency1Ref, consumerAgentType, consumerAgentId, producerAgentType, producerAgentId); } } // Private function to add WriteAfterRead Dependency // Last consumer agent creates the dependency and assign it to the producer agent inline void CascadingCompiler::AddWriteAfterReadDependency(const AgentType consumerAgentType, const AgentIdType consumerAgentId, const AgentType producerAgentType, const AgentIdType producerAgentId) { AgentIdType relativeAgentId = consumerAgentId - producerAgentId; assert(relativeAgentId <= g_MaxRelativeAgentPosition); Dependency& producerAgentWriteDependencyRef = m_CommandStreamAgents[producerAgentId].info.writeDependencies.at(0); producerAgentWriteDependencyRef.relativeAgentId = static_cast<RelativeAgentIdType>(relativeAgentId); FillProducerAgentDependency(producerAgentWriteDependencyRef, consumerAgentType, consumerAgentId, producerAgentType, producerAgentId); } // Private function to add ScheduleTime Dependency // First consumer agent creates the dependency and assign it to the producer agent inline void CascadingCompiler::AddScheduleTimeDependency(const AgentType consumerAgentType, const AgentIdType consumerAgentId, const AgentType producerAgentType, const AgentIdType producerAgentId) { AgentIdType relativeAgentId = consumerAgentId - producerAgentId; assert(relativeAgentId <= g_MaxRelativeAgentPosition); Dependency& producerAgentScheduleDependencyRef = m_CommandStreamAgents[producerAgentId].info.scheduleDependencies.at(0); // Only the first consumer needs to update the relative agent id of the schedule dependency if (producerAgentScheduleDependencyRef.relativeAgentId == 0) { producerAgentScheduleDependencyRef.relativeAgentId = static_cast<RelativeAgentIdType>(relativeAgentId); FillProducerAgentDependency(producerAgentScheduleDependencyRef, consumerAgentType, consumerAgentId, producerAgentType, producerAgentId); } } // Private function to fill the dependency data for Read After Write or SRAM Overlap dependencies void CascadingCompiler::FillConsumerAgentDependency(command_stream::cascading::Dependency& consumerAgentDependency, const command_stream::cascading::AgentType consumerAgentType, const AgentIdType consumerAgentId, const command_stream::cascading::AgentType producerAgentType, const AgentIdType producerAgentId) { Agent& consumerAgent = m_CommandStreamAgents[consumerAgentId]; Agent& producerAgent = m_CommandStreamAgents[producerAgentId]; // Add a new 'Read After Write' dependency switch (consumerAgentType) { case AgentType::IFM_STREAMER: { // Read After Write Dependency for [IfmStreamer][OfmStreamer] if (producerAgentType == AgentType::OFM_STREAMER) { consumerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ofm.fmData.numStripes.height * producerAgent.data.ofm.fmData.numStripes.width * producerAgent.data.ofm.fmData.numStripes.channels); consumerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.ifm.fmData.numStripes.height * consumerAgent.data.ifm.fmData.numStripes.width * consumerAgent.data.ifm.fmData.numStripes.channels); consumerAgentDependency.innerRatio.other = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ofm.fmData.numStripes.height * producerAgent.data.ofm.fmData.numStripes.width * producerAgent.data.ofm.fmData.numStripes.channels); consumerAgentDependency.innerRatio.self = 1; consumerAgentDependency.boundary = 0; } break; } case AgentType::WGT_STREAMER: { // Sram Overlap Dependency for [WeightStreamer][OfmStreamer] if (producerAgentType == AgentType::OFM_STREAMER) { consumerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ofm.fmData.numStripes.height * producerAgent.data.ofm.fmData.numStripes.width * producerAgent.data.ofm.fmData.numStripes.channels); consumerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.wgt.numStripes.ifmChannels * consumerAgent.data.wgt.numStripes.ofmChannels); consumerAgentDependency.innerRatio.other = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ofm.fmData.numStripes.height * producerAgent.data.ofm.fmData.numStripes.width * producerAgent.data.ofm.fmData.numStripes.channels); consumerAgentDependency.innerRatio.self = 1; consumerAgentDependency.boundary = 0; } break; } case AgentType::MCE_SCHEDULER: { // Read After Write Dependency for [MceScheduler][IfmStreamer] if (producerAgentType == AgentType::IFM_STREAMER) { consumerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ifm.fmData.numStripes.width * producerAgent.data.ifm.fmData.numStripes.height * producerAgent.data.ifm.fmData.numStripes.channels); consumerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmWidth * consumerAgent.data.mce.numStripes.ifmChannels); uint8_t widthRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.mce.numStripes.ofmWidth, producerAgent.data.ifm.fmData.numStripes.width)); uint8_t heightRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.mce.numStripes.ofmHeight, producerAgent.data.ifm.fmData.numStripes.height)); assert(consumerAgent.data.mce.numStripes.ifmChannels == producerAgent.data.ifm.fmData.numStripes.channels); consumerAgentDependency.innerRatio.other = ethosn::utils::NumericCast<uint16_t>(widthRatio * heightRatio); consumerAgentDependency.innerRatio.self = 1; if ((producerAgent.data.ifm.fmData.numStripes.height > 1 && consumerAgent.data.mce.filterShape[0].height > 1) || (producerAgent.data.ifm.fmData.numStripes.width > 1 && consumerAgent.data.mce.filterShape[0].width > 1)) { consumerAgentDependency.boundary = 1; } else { consumerAgentDependency.boundary = 0; } } // Read After Write Dependency for [MceScheduler][WeightStreamer] else if (producerAgentType == AgentType::WGT_STREAMER) { consumerAgentDependency.outerRatio.other = 1; consumerAgentDependency.innerRatio.other = 1; if (producerAgent.data.wgt.numStripes.ofmChannels > 1) { consumerAgentDependency.outerRatio.self = 1; consumerAgentDependency.innerRatio.self = 1; } else { consumerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmWidth); consumerAgentDependency.innerRatio.self = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmWidth); } consumerAgentDependency.boundary = 0; } // Read After Write Dependency for [MceScheduler][PleScheduler] else if (producerAgentType == AgentType::PLE_SCHEDULER) { // Calculate outer ratios using number of stripes consumerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.pleS.numStripes.height * producerAgent.data.pleS.numStripes.width * producerAgent.data.pleS.numStripes.channels); consumerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmWidth * consumerAgent.data.mce.numStripes.ofmChannels); // Calculate inner ratios using ratio of stripe size uint8_t widthRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( producerAgent.data.pleS.numStripes.width, consumerAgent.data.mce.numStripes.ofmWidth)); uint8_t heightRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( producerAgent.data.pleS.numStripes.height, consumerAgent.data.mce.numStripes.ofmHeight)); uint8_t channelRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( producerAgent.data.pleS.numStripes.channels, consumerAgent.data.mce.numStripes.ofmChannels)); consumerAgentDependency.innerRatio.other = 1; consumerAgentDependency.innerRatio.self = ethosn::utils::NumericCast<uint16_t>(widthRatio * heightRatio * channelRatio); // Set boundary to 1 if producer stripe count is not a factor of consumer stripe count uint16_t numberOfIfmStripesInXYDimProducer = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmWidth * consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmChannels); uint16_t numberOfIfmStripesInXYDimConsumer = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.pleS.numStripes.width * producerAgent.data.pleS.numStripes.height * producerAgent.data.pleS.numStripes.channels); uint8_t ifmStripeRemainder = ethosn::utils::NumericCast<uint8_t>(numberOfIfmStripesInXYDimConsumer % numberOfIfmStripesInXYDimProducer); if (ifmStripeRemainder == 0) { consumerAgentDependency.boundary = 0; } else { consumerAgentDependency.boundary = 1; } } else { assert(false); } break; } case AgentType::PLE_LOADER: { break; } case AgentType::PLE_SCHEDULER: { // Read After Write Dependency for [PleScheduler][IfmStreamer] if (producerAgentType == AgentType::IFM_STREAMER) { // Calculate outer ratios using number of stripes consumerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ifm.fmData.numStripes.width * producerAgent.data.ifm.fmData.numStripes.height * producerAgent.data.ifm.fmData.numStripes.channels); consumerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.pleS.numStripes.height * consumerAgent.data.pleS.numStripes.width * consumerAgent.data.pleS.numStripes.channels); // Calculate inner ratios using ratio of stripe size uint8_t widthRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.width, producerAgent.data.ifm.fmData.numStripes.width)); uint8_t heightRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.height, producerAgent.data.ifm.fmData.numStripes.height)); uint8_t channelRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.channels, producerAgent.data.ifm.fmData.numStripes.channels)); consumerAgentDependency.innerRatio.other = ethosn::utils::NumericCast<uint16_t>(widthRatio * heightRatio * channelRatio); consumerAgentDependency.innerRatio.self = 1; // Set boundary to 1 if producer stripe count is not a factor of consumer stripe count uint16_t numberOfIfmStripesInXYDimProducer = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ifm.fmData.numStripes.width * producerAgent.data.ifm.fmData.numStripes.height); uint16_t numberOfIfmStripesInXYDimConsumer = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.pleS.numStripes.width * consumerAgent.data.pleS.numStripes.height); uint8_t ifmStripeRemainder = ethosn::utils::NumericCast<uint8_t>(numberOfIfmStripesInXYDimConsumer % numberOfIfmStripesInXYDimProducer); if (ifmStripeRemainder == 0) { consumerAgentDependency.boundary = 0; } else { consumerAgentDependency.boundary = 1; } } // Read After Write Dependency for [PleScheduler][MceScheduler] else if (producerAgentType == AgentType::MCE_SCHEDULER) { // Calculate outer ratios using number of stripes consumerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.mce.numStripes.ofmWidth * producerAgent.data.mce.numStripes.ofmHeight * producerAgent.data.mce.numStripes.ofmChannels); consumerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.pleS.numStripes.height * consumerAgent.data.pleS.numStripes.width * consumerAgent.data.pleS.numStripes.channels); // Calculate inner ratios using ratio of stripe size uint8_t widthRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.width, producerAgent.data.mce.numStripes.ofmWidth)); uint8_t heightRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.height, producerAgent.data.mce.numStripes.ofmHeight)); uint8_t channelRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.channels, producerAgent.data.mce.numStripes.ofmChannels)); consumerAgentDependency.innerRatio.other = ethosn::utils::NumericCast<uint16_t>(widthRatio * heightRatio * channelRatio); consumerAgentDependency.innerRatio.self = 1; // Set boundary to 1 if producer stripe count is not a factor of consumer stripe count uint16_t numberOfIfmStripesInXYDimProducer = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.mce.numStripes.ofmWidth * producerAgent.data.mce.numStripes.ofmHeight); uint16_t numberOfIfmStripesInXYDimConsumer = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.pleS.numStripes.width * consumerAgent.data.pleS.numStripes.height); uint8_t ifmStripeRemainder = ethosn::utils::NumericCast<uint8_t>(numberOfIfmStripesInXYDimConsumer % numberOfIfmStripesInXYDimProducer); if (ifmStripeRemainder == 0) { consumerAgentDependency.boundary = 0; } else { consumerAgentDependency.boundary = 1; } } // Read After Write Dependency for [PleScheduler][PleLoader] else if (producerAgentType == AgentType::PLE_LOADER) { consumerAgentDependency.outerRatio.other = 1U; consumerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.pleS.numStripes.height * consumerAgent.data.pleS.numStripes.width * consumerAgent.data.pleS.numStripes.channels); uint8_t widthRatio = ethosn::utils::NumericCast<uint8_t>(consumerAgent.data.pleS.numStripes.width); uint8_t heightRatio = ethosn::utils::NumericCast<uint8_t>(consumerAgent.data.pleS.numStripes.height); uint8_t channelRatio = ethosn::utils::NumericCast<uint8_t>(consumerAgent.data.pleS.numStripes.channels); consumerAgentDependency.innerRatio.other = 1U; consumerAgentDependency.innerRatio.self = ethosn::utils::NumericCast<uint16_t>(widthRatio * heightRatio * channelRatio); consumerAgentDependency.boundary = 0; } else { assert(false); } break; } case AgentType::OFM_STREAMER: { // Read After Write Dependency for [OfmStreamer][IfmStreamer] if (producerAgentType == AgentType::IFM_STREAMER) { consumerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ofm.fmData.numStripes.height * producerAgent.data.ofm.fmData.numStripes.width * producerAgent.data.ofm.fmData.numStripes.channels); consumerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.ofm.fmData.numStripes.height * consumerAgent.data.ofm.fmData.numStripes.width * consumerAgent.data.ofm.fmData.numStripes.channels); consumerAgentDependency.innerRatio.other = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ofm.fmData.numStripes.height * producerAgent.data.ofm.fmData.numStripes.width * producerAgent.data.ofm.fmData.numStripes.channels); consumerAgentDependency.innerRatio.self = 1; consumerAgentDependency.boundary = 0; } // Read After Write Dependency for [OfmStreamer][PleScheduler] else if (producerAgentType == AgentType::PLE_SCHEDULER) { consumerAgentDependency.outerRatio.other = 1; consumerAgentDependency.outerRatio.self = 1; consumerAgentDependency.innerRatio.other = 1; consumerAgentDependency.innerRatio.self = 1; consumerAgentDependency.boundary = 0; } else { assert(false); } break; } default: { break; } } } // Private function to fill the dependency data for Write After Read or Schedule Time dependencies void CascadingCompiler::FillProducerAgentDependency(command_stream::cascading::Dependency& producerAgentDependency, const command_stream::cascading::AgentType consumerAgentType, const AgentIdType consumerAgentId, const command_stream::cascading::AgentType producerAgentType, const AgentIdType producerAgentId) { Agent& consumerAgent = m_CommandStreamAgents[consumerAgentId]; Agent& producerAgent = m_CommandStreamAgents[producerAgentId]; // Add a new 'Write After Read' dependency or // Add a new 'Schedule Time' dependency switch (consumerAgentType) { case AgentType::IFM_STREAMER: { // Write After Read Dependency for [OfmStreamer][IfmStreamer] or // Schedule Time Dependency for [OfmStreamer][IfmStreamer] if (producerAgentType == AgentType::OFM_STREAMER) { producerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.ofm.fmData.numStripes.height * consumerAgent.data.ofm.fmData.numStripes.width * consumerAgent.data.ofm.fmData.numStripes.channels); producerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ofm.fmData.numStripes.height * producerAgent.data.ofm.fmData.numStripes.width * producerAgent.data.ofm.fmData.numStripes.channels); producerAgentDependency.innerRatio.other = 1; producerAgentDependency.innerRatio.self = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ofm.fmData.numStripes.height * producerAgent.data.ofm.fmData.numStripes.width * producerAgent.data.ofm.fmData.numStripes.channels); producerAgentDependency.boundary = 0; } break; } case AgentType::WGT_STREAMER: { break; } case AgentType::MCE_SCHEDULER: { // Write After Read Dependency for [IfmStreamer][MceScheduler] or // Schedule Time Dependency for [IfmStreamer][MceScheduler] if (producerAgentType == AgentType::IFM_STREAMER) { producerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmWidth * consumerAgent.data.mce.numStripes.ifmChannels); producerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ifm.fmData.numStripes.width * producerAgent.data.ifm.fmData.numStripes.height * producerAgent.data.ifm.fmData.numStripes.channels); uint8_t widthRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.mce.numStripes.ofmWidth, producerAgent.data.ifm.fmData.numStripes.width)); uint8_t heightRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.mce.numStripes.ofmHeight, producerAgent.data.ifm.fmData.numStripes.height)); assert(producerAgent.data.ifm.fmData.numStripes.channels == consumerAgent.data.mce.numStripes.ifmChannels); producerAgentDependency.innerRatio.other = 1; producerAgentDependency.innerRatio.self = ethosn::utils::NumericCast<uint16_t>(widthRatio * heightRatio); if ((producerAgent.data.ifm.fmData.numStripes.height > 1 && consumerAgent.data.mce.filterShape[0].height > 1) || (producerAgent.data.ifm.fmData.numStripes.width > 1 && consumerAgent.data.mce.filterShape[0].width > 1)) { producerAgentDependency.boundary = 1; } else { producerAgentDependency.boundary = 0; } } // Write After Read Dependency for [WeightStreamer][MceScheduler] or // Schedule Time Dependency for [WeightStreamer][MceScheduler] else if (producerAgentType == AgentType::WGT_STREAMER) { if (producerAgent.data.wgt.numStripes.ofmChannels > 1) { producerAgentDependency.outerRatio.other = 1; producerAgentDependency.innerRatio.other = 1; } else { producerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmWidth); producerAgentDependency.innerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmWidth); } producerAgentDependency.outerRatio.self = 1; producerAgentDependency.innerRatio.self = 1; producerAgentDependency.boundary = 0; } // Schedule Time Dependency for [PleLoader][MceScheduler] else if (producerAgentType == AgentType::PLE_LOADER) { producerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmWidth * consumerAgent.data.mce.numStripes.ifmChannels); producerAgentDependency.outerRatio.self = 1; producerAgentDependency.innerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmWidth * consumerAgent.data.mce.numStripes.ifmChannels); producerAgentDependency.innerRatio.self = 1; producerAgentDependency.boundary = 0; } // Schedule Time Dependency for [PleScheduler][MceScheduler] else if (producerAgentType == AgentType::PLE_SCHEDULER) { // Calculate outer ratios using number of stripes producerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmWidth * consumerAgent.data.mce.numStripes.ofmChannels); producerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.pleS.numStripes.height * producerAgent.data.pleS.numStripes.width * producerAgent.data.pleS.numStripes.channels); // Calculate inner ratios using ratio of stripe size uint8_t widthRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( producerAgent.data.pleS.numStripes.width, consumerAgent.data.mce.numStripes.ofmWidth)); uint8_t heightRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( producerAgent.data.pleS.numStripes.height, consumerAgent.data.mce.numStripes.ofmHeight)); uint8_t channelRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( producerAgent.data.pleS.numStripes.channels, consumerAgent.data.mce.numStripes.ofmChannels)); producerAgentDependency.innerRatio.other = ethosn::utils::NumericCast<uint16_t>(widthRatio * heightRatio * channelRatio); producerAgentDependency.innerRatio.self = 1; // Set boundary to 1 if producer stripe count is not a factor of consumer stripe count uint16_t numberOfIfmStripesInXYDimProducer = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.mce.numStripes.ofmWidth * consumerAgent.data.mce.numStripes.ofmHeight * consumerAgent.data.mce.numStripes.ofmChannels); uint16_t numberOfIfmStripesInXYDimConsumer = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.pleS.numStripes.width * producerAgent.data.pleS.numStripes.height * producerAgent.data.pleS.numStripes.channels); uint8_t ifmStripeRemainder = ethosn::utils::NumericCast<uint8_t>(numberOfIfmStripesInXYDimConsumer % numberOfIfmStripesInXYDimProducer); if (ifmStripeRemainder == 0) { producerAgentDependency.boundary = 0; } else { producerAgentDependency.boundary = 1; } } else { assert(false); } break; } case AgentType::PLE_LOADER: { break; } case AgentType::PLE_SCHEDULER: { // Write After Read Dependency for [IfmStreamer][PleScheduler] or // Schedule Time Dependency for [IfmStreamer][PleScheduler] if (producerAgentType == AgentType::IFM_STREAMER) { // Calculate outer ratios using number of stripes. producerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.pleS.numStripes.height * consumerAgent.data.pleS.numStripes.width * consumerAgent.data.pleS.numStripes.channels); producerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ifm.fmData.numStripes.width * producerAgent.data.ifm.fmData.numStripes.height * producerAgent.data.ifm.fmData.numStripes.channels); // Calculate inner ratios using ratio of stripe size uint8_t widthRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.width, producerAgent.data.ifm.fmData.numStripes.width)); uint8_t heightRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.height, producerAgent.data.ifm.fmData.numStripes.height)); uint8_t channelRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.channels, producerAgent.data.ifm.fmData.numStripes.channels)); producerAgentDependency.innerRatio.other = 1U; producerAgentDependency.innerRatio.self = ethosn::utils::NumericCast<uint16_t>(widthRatio * heightRatio * channelRatio); // Set boundary to 1 if producer stripe count is not a factor of consumer stripe count uint16_t numberOfIfmStripesInXYDimProducer = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ifm.fmData.numStripes.width * producerAgent.data.ifm.fmData.numStripes.height * producerAgent.data.ifm.fmData.numStripes.channels); uint16_t numberOfIfmStripesInXYDimConsumer = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.pleS.numStripes.width * consumerAgent.data.pleS.numStripes.height * consumerAgent.data.pleS.numStripes.channels); uint8_t ifmStripeRemainder = ethosn::utils::NumericCast<uint8_t>(numberOfIfmStripesInXYDimConsumer % numberOfIfmStripesInXYDimProducer); if (ifmStripeRemainder == 0) { producerAgentDependency.boundary = 0U; } else { producerAgentDependency.boundary = 1U; } } else if (producerAgentType == AgentType::MCE_SCHEDULER) { // Calculate outer ratios using number of stripes producerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.pleS.numStripes.height * consumerAgent.data.pleS.numStripes.width * consumerAgent.data.pleS.numStripes.channels); producerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.mce.numStripes.ofmHeight * producerAgent.data.mce.numStripes.ofmWidth * producerAgent.data.mce.numStripes.ofmChannels); // Calculate inner ratios using ratio of stripe size uint8_t widthRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.width, producerAgent.data.mce.numStripes.ofmWidth)); uint8_t heightRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.height, producerAgent.data.mce.numStripes.ofmHeight)); uint8_t channelRatio = ethosn::utils::NumericCast<uint8_t>(utils::DivRoundUp( consumerAgent.data.pleS.numStripes.channels, producerAgent.data.mce.numStripes.ofmChannels)); producerAgentDependency.innerRatio.other = 1; producerAgentDependency.innerRatio.self = ethosn::utils::NumericCast<uint16_t>(widthRatio * heightRatio * channelRatio); // Set boundary to 1 if producer stripe count is not a factor of consumer stripe count uint16_t numberOfIfmStripesInXYDimProducer = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.mce.numStripes.ofmWidth * producerAgent.data.mce.numStripes.ofmHeight * producerAgent.data.mce.numStripes.ofmChannels); uint16_t numberOfIfmStripesInXYDimConsumer = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.pleS.numStripes.width * consumerAgent.data.pleS.numStripes.height * consumerAgent.data.pleS.numStripes.channels); uint8_t ifmStripeRemainder = ethosn::utils::NumericCast<uint8_t>(numberOfIfmStripesInXYDimConsumer % numberOfIfmStripesInXYDimProducer); if (ifmStripeRemainder == 0) { producerAgentDependency.boundary = 0; } else { producerAgentDependency.boundary = 1; } } // Schedule Time Dependency for [PleLoader][PleScheduler] else if (producerAgentType == AgentType::PLE_LOADER) { producerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.pleS.numStripes.height * consumerAgent.data.pleS.numStripes.width * consumerAgent.data.pleS.numStripes.channels); producerAgentDependency.outerRatio.self = 1U; uint8_t widthRatio = ethosn::utils::NumericCast<uint8_t>(consumerAgent.data.pleS.numStripes.width); uint8_t heightRatio = ethosn::utils::NumericCast<uint8_t>(consumerAgent.data.pleS.numStripes.height); uint8_t channelRatio = ethosn::utils::NumericCast<uint8_t>(consumerAgent.data.pleS.numStripes.channels); producerAgentDependency.innerRatio.other = ethosn::utils::NumericCast<uint16_t>(widthRatio * heightRatio * channelRatio); producerAgentDependency.innerRatio.self = 1U; producerAgentDependency.boundary = 0; } else { assert(false); } break; } case AgentType::OFM_STREAMER: { // Write After Read Dependency for [IfmStreamer][OfmStreamer] or // Schedule Time Dependency for [IfmStreamer][OfmStreamer] if (producerAgentType == AgentType::IFM_STREAMER) { producerAgentDependency.outerRatio.other = ethosn::utils::NumericCast<uint16_t>( consumerAgent.data.ofm.fmData.numStripes.height * consumerAgent.data.ofm.fmData.numStripes.width * consumerAgent.data.ofm.fmData.numStripes.channels); producerAgentDependency.outerRatio.self = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ofm.fmData.numStripes.height * producerAgent.data.ofm.fmData.numStripes.width * producerAgent.data.ofm.fmData.numStripes.channels); producerAgentDependency.innerRatio.other = 1; producerAgentDependency.innerRatio.self = ethosn::utils::NumericCast<uint16_t>( producerAgent.data.ofm.fmData.numStripes.height * producerAgent.data.ofm.fmData.numStripes.width * producerAgent.data.ofm.fmData.numStripes.channels); producerAgentDependency.boundary = 0; } // Write After Read Dependency for [PleScheduler][OfmStreamer] or // Schedule Time Dependency for [PleScheduler][OfmStreamer] else if (producerAgentType == AgentType::PLE_SCHEDULER) { producerAgentDependency.outerRatio.other = 1; producerAgentDependency.outerRatio.self = 1; producerAgentDependency.innerRatio.other = 1; producerAgentDependency.innerRatio.self = 1; producerAgentDependency.boundary = 0; } else { assert(false); } break; } default: { break; } } } // Private function to add the lifetime information of the intermediate DRAM buffers void CascadingCompiler::AddLifetimeInfoForIntermediateDramBuffers() { // Lifetime start of the buffer holds the producer agent Id AgentIdType lifetimeStart; // Lifetime end of the buffer holds the last consumer agent Id AgentIdType lifetimeEnd; // Add the lifetime information for each intermediate DRAM buffer for (Buffer* buffer : m_MergedOpGraph.GetBuffers()) { if (buffer->m_Location == Location::Dram) { assert(buffer->m_BufferType.has_value()); // Check that the buffer type is intermediate if (buffer->m_BufferType.value() == BufferType::Intermediate) { // Set the Lifetime start and end of the intermediate DRAM buffer Op* producer = m_MergedOpGraph.GetProducer(buffer); assert(producer != nullptr); lifetimeStart = m_OpToAgentIdMapping.at(producer); lifetimeEnd = 0; OpGraph::ConsumersList consumers = m_MergedOpGraph.GetConsumers(buffer); assert(consumers.size() >= 1); for (auto consumer : consumers) { AgentIdType consumerAgentId = m_OpToAgentIdMapping.at(consumer.first); if (consumerAgentId > lifetimeEnd) { lifetimeEnd = consumerAgentId; } } // Add lifetime information of the corresponding buffer to the buffer manager m_BufferManager.MarkBufferUsedAtTime(m_IntermdiateDramBufToBufIdMapping.at(buffer), static_cast<uint32_t>(lifetimeStart), static_cast<uint32_t>(lifetimeEnd + 1)); } } } } } // namespace cascading_compiler } // namespace support_library } // namespace ethosn
85,460
25,336
#include "TileEngine/TileCache.h" #include <stdexcept> #include <vector> #include "Directories.h" #include "SGP/FileMan.h" #include "SGP/HImage.h" #include "SGP/MemMan.h" #include "Tactical/AnimationCache.h" #include "Tactical/AnimationData.h" #include "TileEngine/Structure.h" #include "TileEngine/TileDef.h" #include "TileEngine/TileSurface.h" #include "Utils/DebugControl.h" struct TILE_CACHE_STRUCT { char zRootName[30]; STRUCTURE_FILE_REF *pStructureFileRef; }; static const UINT32 guiMaxTileCacheSize = 50; static UINT32 guiCurTileCacheSize = 0; static INT32 giDefaultStructIndex = -1; TILE_CACHE_ELEMENT *gpTileCache; static std::vector<TILE_CACHE_STRUCT> gpTileCacheStructInfo; void InitTileCache(void) { gpTileCache = MALLOCN(TILE_CACHE_ELEMENT, guiMaxTileCacheSize); guiCurTileCacheSize = 0; // Zero entries for (UINT32 i = 0; i < guiMaxTileCacheSize; ++i) { gpTileCache[i].pImagery = 0; gpTileCache[i].struct_file_ref = 0; } // Look for JSD files in the tile cache directory and load any we find std::vector<std::string> jsdFiles = FindFilesInDir(FileMan::getTilecacheDirPath(), ".jsd", true, false); for (const std::string &file : jsdFiles) { TILE_CACHE_STRUCT tc; GetRootName(tc.zRootName, lengthof(tc.zRootName), file.c_str()); tc.pStructureFileRef = LoadStructureFile(file.c_str()); if (strcasecmp(tc.zRootName, "l_dead1") == 0) { giDefaultStructIndex = (INT32)gpTileCacheStructInfo.size(); } gpTileCacheStructInfo.push_back(tc); } } void DeleteTileCache() { UINT32 cnt; // Allocate entries if (gpTileCache != NULL) { // Loop through and delete any entries for (cnt = 0; cnt < guiMaxTileCacheSize; cnt++) { if (gpTileCache[cnt].pImagery != NULL) { DeleteTileSurface(gpTileCache[cnt].pImagery); } } MemFree(gpTileCache); } gpTileCacheStructInfo.clear(); guiCurTileCacheSize = 0; } INT32 GetCachedTile(const char *const filename) { INT32 idx = -1; // Check to see if surface exists already for (UINT32 cnt = 0; cnt < guiCurTileCacheSize; ++cnt) { TILE_CACHE_ELEMENT *const i = &gpTileCache[cnt]; if (i->pImagery == NULL) { if (idx == -1) idx = cnt; continue; } if (strcasecmp(i->zName, filename) != 0) continue; // Found surface, return ++i->sHits; return (INT32)cnt; } if (idx == -1) { if (guiCurTileCacheSize < guiMaxTileCacheSize) { idx = guiCurTileCacheSize++; } else { // cache out least used file idx = 0; INT16 sMostHits = gpTileCache[idx].sHits; for (UINT32 cnt = 1; cnt < guiCurTileCacheSize; ++cnt) { const TILE_CACHE_ELEMENT *const i = &gpTileCache[cnt]; if (i->sHits < sMostHits) { sMostHits = i->sHits; idx = cnt; } } // Bump off lowest index TILE_CACHE_ELEMENT *const del = &gpTileCache[idx]; DeleteTileSurface(del->pImagery); del->sHits = 0; del->pImagery = 0; del->struct_file_ref = 0; } } TILE_CACHE_ELEMENT *const tce = &gpTileCache[idx]; tce->pImagery = LoadTileSurface(filename); strcpy(tce->zName, filename); tce->sHits = 1; char root_name[30]; GetRootName(root_name, lengthof(root_name), filename); STRUCTURE_FILE_REF *const sfr = GetCachedTileStructureRefFromFilename(root_name); tce->struct_file_ref = sfr; if (sfr) AddZStripInfoToVObject(tce->pImagery->vo, sfr, TRUE, 0); const AuxObjectData *const aux = tce->pImagery->pAuxData; tce->ubNumFrames = (aux != NULL ? aux->ubNumberOfFrames : 1); return idx; } void RemoveCachedTile(INT32 const cached_tile) { if ((UINT32)cached_tile < guiCurTileCacheSize) { TILE_CACHE_ELEMENT &e = gpTileCache[cached_tile]; if (e.pImagery) { if (--e.sHits != 0) return; DeleteTileSurface(e.pImagery); e.pImagery = 0; e.struct_file_ref = 0; return; } } throw std::logic_error("Trying to remove invalid cached tile"); } static STRUCTURE_FILE_REF *GetCachedTileStructureRef(INT32 const idx) { return idx != -1 ? gpTileCache[idx].struct_file_ref : 0; } STRUCTURE_FILE_REF *GetCachedTileStructureRefFromFilename(char const *const filename) { size_t const n = gpTileCacheStructInfo.size(); for (size_t i = 0; i != n; ++i) { TILE_CACHE_STRUCT &t = gpTileCacheStructInfo[i]; if (strcasecmp(t.zRootName, filename) == 0) return t.pStructureFileRef; } return 0; } void CheckForAndAddTileCacheStructInfo(LEVELNODE *const pNode, INT16 const sGridNo, UINT16 const usIndex, UINT16 const usSubIndex) { STRUCTURE_FILE_REF *const sfr = GetCachedTileStructureRef(usIndex); if (!sfr) return; if (AddStructureToWorld(sGridNo, 0, &sfr->pDBStructureRef[usSubIndex], pNode)) return; if (giDefaultStructIndex == -1) return; STRUCTURE_FILE_REF *const def_sfr = gpTileCacheStructInfo[giDefaultStructIndex].pStructureFileRef; if (!def_sfr) return; AddStructureToWorld(sGridNo, 0, &def_sfr->pDBStructureRef[usSubIndex], pNode); } void CheckForAndDeleteTileCacheStructInfo(LEVELNODE *pNode, UINT16 usIndex) { STRUCTURE_FILE_REF *pStructureFileRef; if (usIndex >= TILE_CACHE_START_INDEX) { pStructureFileRef = GetCachedTileStructureRef((usIndex - TILE_CACHE_START_INDEX)); if (pStructureFileRef != NULL) { DeleteStructureFromWorld(pNode->pStructureData); } } } void GetRootName(char *const pDestStr, size_t const n, char const *const pSrcStr) { // Remove path and extension ReplacePath(pDestStr, n, "", pSrcStr, ""); }
5,561
2,278
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "ProgramControl.hpp" #include "ProgramControl_Impl.hpp" #include <utilities/idd/OS_ProgramControl_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include "../utilities/core/Assert.hpp" namespace openstudio { namespace model { namespace detail { ProgramControl_Impl::ProgramControl_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : ModelObject_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == ProgramControl::iddObjectType()); } ProgramControl_Impl::ProgramControl_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : ModelObject_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == ProgramControl::iddObjectType()); } ProgramControl_Impl::ProgramControl_Impl(const ProgramControl_Impl& other, Model_Impl* model, bool keepHandle) : ModelObject_Impl(other,model,keepHandle) {} const std::vector<std::string>& ProgramControl_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType ProgramControl_Impl::iddObjectType() const { return ProgramControl::iddObjectType(); } boost::optional<int> ProgramControl_Impl::numberofThreadsAllowed() const { return getInt(OS_ProgramControlFields::NumberofThreadsAllowed,true); } bool ProgramControl_Impl::setNumberofThreadsAllowed(boost::optional<int> numberofThreadsAllowed) { bool result(false); if (numberofThreadsAllowed) { result = setInt(OS_ProgramControlFields::NumberofThreadsAllowed, numberofThreadsAllowed.get()); } else { resetNumberofThreadsAllowed(); result = true; } return result; } void ProgramControl_Impl::resetNumberofThreadsAllowed() { bool result = setString(OS_ProgramControlFields::NumberofThreadsAllowed, ""); OS_ASSERT(result); } } // detail ProgramControl::ProgramControl(const Model& model) : ModelObject(ProgramControl::iddObjectType(),model) { OS_ASSERT(getImpl<detail::ProgramControl_Impl>()); // TODO: Appropriately handle the following required object-list fields. bool ok = true; // ok = setHandle(); OS_ASSERT(ok); } IddObjectType ProgramControl::iddObjectType() { return IddObjectType(IddObjectType::OS_ProgramControl); } boost::optional<int> ProgramControl::numberofThreadsAllowed() const { return getImpl<detail::ProgramControl_Impl>()->numberofThreadsAllowed(); } bool ProgramControl::setNumberofThreadsAllowed(int numberofThreadsAllowed) { return getImpl<detail::ProgramControl_Impl>()->setNumberofThreadsAllowed(numberofThreadsAllowed); } void ProgramControl::resetNumberofThreadsAllowed() { getImpl<detail::ProgramControl_Impl>()->resetNumberofThreadsAllowed(); } /// @cond ProgramControl::ProgramControl(std::shared_ptr<detail::ProgramControl_Impl> impl) : ModelObject(impl) {} /// @endcond } // model } // openstudio
4,214
1,219
// Copyright 2020 Hal@shurabaP. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. #ifndef UZUME_VOCODER_ESTIMATE_F0_WITH_DIO_HPP #define UZUME_VOCODER_ESTIMATE_F0_WITH_DIO_HPP #include "../EstimateF0.hpp" namespace uzume { namespace vocoder { namespace world { /** * EstimateF0WithDIO is an implementation of f0 estimation. */ class EstimateF0WithDIO : public EstimateF0 { public: EstimateF0WithDIO() = delete; EstimateF0WithDIO(double msFramePeriod); /** * () estimates f0 with DIO and Stone mask. */ bool operator()(Contour *output, const Waveform *input) override; int getF0LengthFor(unsigned int samplingFrequency, unsigned int waveLength) const; private: double msFramePeriod; }; } } } #endif //UZUME_VOCODER_ESTIMATE_F0_WITH_DIO_HPP
857
315