hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
9841cde6783d99abd6b8d06c2e011ba28dc3f152
5,127
cpp
C++
ogldev-source/tutorial38/tutorial38.cpp
maodougansidui/ucsb_cmpsc180
2a207838ce269c27fa0f9a601b5633e4327a6e3b
[ "MIT" ]
null
null
null
ogldev-source/tutorial38/tutorial38.cpp
maodougansidui/ucsb_cmpsc180
2a207838ce269c27fa0f9a601b5633e4327a6e3b
[ "MIT" ]
null
null
null
ogldev-source/tutorial38/tutorial38.cpp
maodougansidui/ucsb_cmpsc180
2a207838ce269c27fa0f9a601b5633e4327a6e3b
[ "MIT" ]
null
null
null
/* Copyright 2011 Etay Meiri This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Tutorial 38 - Skinning */ #include <math.h> #include <GL/glew.h> #include <GL/freeglut.h> #include <string> #ifndef WIN32 #include <sys/time.h> #include <unistd.h> #endif #include <sys/types.h> #include "ogldev_engine_common.h" #include "ogldev_app.h" #include "ogldev_camera.h" #include "ogldev_util.h" #include "ogldev_pipeline.h" #include "ogldev_camera.h" #include "texture.h" #include "skinning_technique.h" #include "ogldev_glut_backend.h" #include "ogldev_skinned_mesh.h" using namespace std; #define WINDOW_WIDTH 1280 #define WINDOW_HEIGHT 1024 class Tutorial38 : public ICallbacks, public OgldevApp { public: Tutorial38() { m_pGameCamera = NULL; m_pEffect = NULL; m_directionalLight.Color = Vector3f(1.0f, 1.0f, 1.0f); m_directionalLight.AmbientIntensity = 0.55f; m_directionalLight.DiffuseIntensity = 0.9f; m_directionalLight.Direction = Vector3f(1.0f, 0.0, 0.0); m_persProjInfo.FOV = 60.0f; m_persProjInfo.Height = WINDOW_HEIGHT; m_persProjInfo.Width = WINDOW_WIDTH; m_persProjInfo.zNear = 1.0f; m_persProjInfo.zFar = 100.0f; m_position = Vector3f(0.0f, 0.0f, 6.0f); } ~Tutorial38() { SAFE_DELETE(m_pEffect); SAFE_DELETE(m_pGameCamera); } bool Init() { Vector3f Pos(0.0f, 3.0f, -1.0f); Vector3f Target(0.0f, 0.0f, 1.0f); Vector3f Up(0.0, 1.0f, 0.0f); m_pGameCamera = new Camera(WINDOW_WIDTH, WINDOW_HEIGHT, Pos, Target, Up); m_pEffect = new SkinningTechnique(); if (!m_pEffect->Init()) { printf("Error initializing the lighting technique\n"); return false; } m_pEffect->Enable(); m_pEffect->SetColorTextureUnit(COLOR_TEXTURE_UNIT_INDEX); m_pEffect->SetDirectionalLight(m_directionalLight); m_pEffect->SetMatSpecularIntensity(0.0f); m_pEffect->SetMatSpecularPower(0); if (!m_mesh.LoadMesh("../Content/boblampclean.md5mesh")) { printf("Mesh load failed\n"); return false; } #ifndef WIN32 if (!m_fontRenderer.InitFontRenderer()) { return false; } #endif return true; } void Run() { GLUTBackendRun(this); } virtual void RenderSceneCB() { CalcFPS(); m_pGameCamera->OnRender(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_pEffect->Enable(); vector<Matrix4f> Transforms; float RunningTime = GetRunningTime(); m_mesh.BoneTransform(RunningTime, Transforms); for (uint i = 0 ; i < Transforms.size() ; i++) { m_pEffect->SetBoneTransform(i, Transforms[i]); } m_pEffect->SetEyeWorldPos(m_pGameCamera->GetPos()); Pipeline p; p.SetCamera(m_pGameCamera->GetPos(), m_pGameCamera->GetTarget(), m_pGameCamera->GetUp()); p.SetPerspectiveProj(m_persProjInfo); p.Scale(0.1f, 0.1f, 0.1f); Vector3f Pos(m_position); p.WorldPos(Pos); p.Rotate(270.0f, 180.0f, 0.0f); m_pEffect->SetWVP(p.GetWVPTrans()); m_pEffect->SetWorldMatrix(p.GetWorldTrans()); m_mesh.Render(); RenderFPS(); glutSwapBuffers(); } virtual void KeyboardCB(OGLDEV_KEY OgldevKey, OGLDEV_KEY_STATE State) { switch (OgldevKey) { case OGLDEV_KEY_ESCAPE: case OGLDEV_KEY_q: GLUTBackendLeaveMainLoop(); break; default: m_pGameCamera->OnKeyboard(OgldevKey); } } virtual void PassiveMouseCB(int x, int y) { m_pGameCamera->OnMouse(x, y); } private: SkinningTechnique* m_pEffect; Camera* m_pGameCamera; DirectionalLight m_directionalLight; SkinnedMesh m_mesh; Vector3f m_position; PersProjInfo m_persProjInfo; }; int main(int argc, char** argv) { GLUTBackendInit(argc, argv, true, false); if (!GLUTBackendCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, false, "Tutorial 38")) { return 1; } SRANDOM; Tutorial38* pApp = new Tutorial38(); if (!pApp->Init()) { return 1; } pApp->Run(); delete pApp; return 0; }
24.649038
97
0.611469
[ "mesh", "render", "vector" ]
984c7bcb5ee5c5eb18bef276dd89ab9b541b845d
1,783
cpp
C++
src/main/cpp/hanal/MorphDic.cpp
krikit/hanal
e99a3632c244444bec52478fb836590570c409f3
[ "Unlicense" ]
25
2015-01-26T01:08:26.000Z
2021-07-27T08:07:48.000Z
src/main/cpp/hanal/MorphDic.cpp
krikit/hanal
e99a3632c244444bec52478fb836590570c409f3
[ "Unlicense" ]
null
null
null
src/main/cpp/hanal/MorphDic.cpp
krikit/hanal
e99a3632c244444bec52478fb836590570c409f3
[ "Unlicense" ]
5
2016-06-19T06:45:13.000Z
2019-02-17T10:59:48.000Z
/** * @author krikit(krikit@naver.com) * @copyright Copyright (C) 2014-2015, krikit. All rights reserved. BSD 2-Clause License */ #include "hanal/MorphDic.hpp" ////////////// // includes // ////////////// #include <list> #include <string> #include <vector> #include "boost/log/trivial.hpp" namespace hanal { MorphDic::~MorphDic() { close(); } void MorphDic::open(std::string rsc_dir) { close(); _trie.open(rsc_dir + "/morph.trie"); _value.open(rsc_dir + "/morph.val", true); // private mode open auto val_data = _value.data(); MappedDic<int16_t> len; // this contains length of each value text len.open(rsc_dir + "/morph.val.len"); auto len_data = len.const_data(); int size = len.size(); _val_idx.reserve(size); _val_idx.emplace_back(val_data); int len_sum = len_data[0]; for (int i = 1; i < size; ++i) { _val_idx.emplace_back(val_data + len_sum); len_sum += len_data[i]; // add each length (length already includes zero termination) } HANAL_ASSERT(_value.size() == len_sum, "Invalid morpheme dic at resource dir: " + rsc_dir); BOOST_LOG_TRIVIAL(info) << "Morpheme dictionary loaded"; } void MorphDic::close() { _trie.close(); _value.close(); _val_idx.clear(); _val_cache.clear(); } std::list<Trie::match_t> MorphDic::lookup(const wchar_t* text) const { return _trie.search_common_prefix_matches(text); } const std::vector<SHDPTRVEC(Morph)>& MorphDic::value(int idx) { HANAL_ASSERT(0 <= idx && idx < _val_idx.size(), "Invalid value index: " + boost::lexical_cast<std::string>(idx)); if (_val_cache.empty()) _val_cache.resize(_val_idx.size()); if (_val_cache[idx].empty()) _val_cache[idx] = Morph::parse_anal_result_vec(_val_idx[idx]); return _val_cache[idx]; } } // namespace hanal
24.094595
115
0.667975
[ "vector" ]
984c99747a66ce467c56188cfa58346c5b7d7d12
514
cpp
C++
source/Ch18/drill/drill_18V.cpp
Broxigar11/UDProg-Introduction
f7edc7a8c9fd31ba00f666a34173eba1fe274655
[ "CC0-1.0" ]
null
null
null
source/Ch18/drill/drill_18V.cpp
Broxigar11/UDProg-Introduction
f7edc7a8c9fd31ba00f666a34173eba1fe274655
[ "CC0-1.0" ]
null
null
null
source/Ch18/drill/drill_18V.cpp
Broxigar11/UDProg-Introduction
f7edc7a8c9fd31ba00f666a34173eba1fe274655
[ "CC0-1.0" ]
null
null
null
#include "../../std_lib_facilities.h" int fact(int n){ int a=1; for(int i=2; i<=n; i++){ a*=i; } return a; } vector<int> gv{1,2,4,8,16,32,64,128,512,1024}; void f(vector<int> av){ vector<int> lv(av.size(), 0); for(int i=0; i<gv.size(); i++){ lv[i]=gv[i]; cout << lv[i] << " "; } cout << endl; vector<int> lv2(av); for(int elem: av){ cout << elem << " "; } cout << endl; } int main(){ f(gv); vector<int> vv; for(int i=0; i<10; i++){ vv.push_back(fact(i+1)); } f(vv); return 0; }
13.891892
46
0.51751
[ "vector" ]
984d3aaefab0a49d1c784bace5dae8e529930192
15,623
cpp
C++
tools/rdf3xembedded/rdf3xembedded.cpp
gh-rdf3x/gh-rdf3x
4184d355b922d9d2f1aa63a36461bf889617928c
[ "Xnet", "X11" ]
40
2015-02-17T03:27:19.000Z
2022-03-24T15:17:38.000Z
tools/rdf3xembedded/rdf3xembedded.cpp
gh-rdf3x/gh-rdf3x
4184d355b922d9d2f1aa63a36461bf889617928c
[ "Xnet", "X11" ]
3
2016-02-22T17:36:59.000Z
2020-04-09T14:45:15.000Z
tools/rdf3xembedded/rdf3xembedded.cpp
gh-rdf3x/gh-rdf3x
4184d355b922d9d2f1aa63a36461bf889617928c
[ "Xnet", "X11" ]
15
2015-01-15T20:39:48.000Z
2020-11-11T03:07:11.000Z
#include "cts/codegen/CodeGen.hpp" #include "cts/infra/QueryGraph.hpp" #include "cts/parser/SPARQLLexer.hpp" #include "cts/parser/SPARQLParser.hpp" #include "cts/parser/TurtleParser.hpp" #include "cts/plangen/PlanGen.hpp" #include "cts/semana/SemanticAnalysis.hpp" #include "infra/osdep/Timestamp.hpp" #include "rts/database/Database.hpp" #include "rts/operator/Operator.hpp" #include "rts/operator/PlanPrinter.hpp" #include "rts/operator/ResultsPrinter.hpp" #include "rts/runtime/BulkOperation.hpp" #include "rts/runtime/DifferentialIndex.hpp" #include "rts/runtime/Runtime.hpp" #include "rts/runtime/TemporaryDictionary.hpp" #include "rts/segment/DictionarySegment.hpp" #include <iostream> #include <fstream> #include <sstream> #include <cstdlib> //--------------------------------------------------------------------------- // RDF-3X // (c) 2008 Thomas Neumann. Web site: http://www.mpi-inf.mpg.de/~neumann/rdf3x // // This work is licensed under the Creative Commons // Attribution-Noncommercial-Share Alike 3.0 Unported License. To view a copy // of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ // or send a letter to Creative Commons, 171 Second Street, Suite 300, // San Francisco, California, 94105, USA. //--------------------------------------------------------------------------- using namespace std; //--------------------------------------------------------------------------- bool smallAddressSpace() // Is the address space too small? { return sizeof(void*)<8; } //--------------------------------------------------------------------------- namespace { //--------------------------------------------------------------------------- /// Query types enum QueryType { RegularQuery, ExplainQuery, InsertQuery, RollbackQuery, UnknownQueryType }; //--------------------------------------------------------------------------- static QueryType classifyQuery(const string& s) // Classify a query { SPARQLLexer lexer(s); if (lexer.getNext()!=SPARQLLexer::Identifier) return UnknownQueryType; if (lexer.isKeyword("select")) return RegularQuery; if (lexer.isKeyword("explain")) return ExplainQuery; if (lexer.isKeyword("insert")) return InsertQuery; if (lexer.isKeyword("rollback")) return RollbackQuery; return UnknownQueryType; } //--------------------------------------------------------------------------- static void writeHeader(const QueryGraph& graph,const SPARQLParser& parser) // Write the query header { bool first=true; for (QueryGraph::projection_iterator iter=graph.projectionBegin(),limit=graph.projectionEnd();iter!=limit;++iter) { string name=parser.getVariableName(*iter); if (first) first=false; else cout << ' '; for (string::const_iterator iter2=name.begin(),limit2=name.end();iter2!=limit2;++iter2) { char c=(*iter2); if ((c==' ')||(c=='\n')||(c=='\\')) cout << '\\'; cout << c; } } if ((graph.getDuplicateHandling()==QueryGraph::CountDuplicates)||(graph.getDuplicateHandling()==QueryGraph::ShowDuplicates)) cout << " count"; cout << endl; } //--------------------------------------------------------------------------- static void runQuery(DifferentialIndex& diffIndex,const string& query) // Evaluate a query { QueryGraph queryGraph; // Parse the query SPARQLLexer lexer(query); SPARQLParser parser(lexer); try { parser.parse(); } catch (const SPARQLParser::ParserException& e) { cout << "parse error: " << e.message << endl; return; } // And perform the semantic anaylsis try { SemanticAnalysis semana(diffIndex); semana.transform(parser,queryGraph); } catch (const SemanticAnalysis::SemanticException& e) { cout << "semantic error: " << e.message << endl; return; } if (queryGraph.knownEmpty()) { cout << "ok" << endl; writeHeader(queryGraph,parser); cout << "\\." << endl; cout.flush(); return; } // Run the optimizer PlanGen plangen; Plan* plan=plangen.translate(diffIndex.getDatabase(),queryGraph); if (!plan) { cout << "internal error plan generation failed" << endl; return; } // Build a physical plan TemporaryDictionary tempDict(diffIndex); Runtime runtime(diffIndex.getDatabase(),&diffIndex,&tempDict); Operator* operatorTree=CodeGen().translate(runtime,queryGraph,plan,false); dynamic_cast<ResultsPrinter*>(operatorTree)->setOutputMode(ResultsPrinter::Embedded); // Execute it cout << "ok" << endl; writeHeader(queryGraph,parser); if (operatorTree->first()) { while (operatorTree->next()) ; } cout << "\\." << endl; cout.flush(); delete operatorTree; } //--------------------------------------------------------------------------- /// Output for the explain command class ExplainPrinter : public PlanPrinter { private: /// The runtime Runtime& runtime; /// The indentation level unsigned indent; /// The operator data string operatorName,operatorArguments; /// Cardinalities double expectedOutputCardinality; /// Cardinalities unsigned observedOutputCardinality; /// Currently in an operator? bool inOp; /// Write the current operator if any void flushOperator(); public: /// Constructor explicit ExplainPrinter(Runtime& runtime); /// Destructor ~ExplainPrinter(); /// Begin a new operator void beginOperator(const std::string& name,double expectedOutputCardinality,unsigned observedOutputCardinality); /// Add an operator argument annotation void addArgumentAnnotation(const std::string& argument); /// Add a scan annotation void addScanAnnotation(const Register* reg,bool bound); /// Add a predicate annotate void addEqualPredicateAnnotation(const Register* reg1,const Register* reg2); /// Add a materialization annotation void addMaterializationAnnotation(const std::vector<Register*>& regs); /// Add a generic annotation void addGenericAnnotation(const std::string& text); /// Close the current operator void endOperator(); /// Format a register (for generic annotations) std::string formatRegister(const Register* reg); /// Format a constant value (for generic annotations) std::string formatValue(unsigned value); }; //--------------------------------------------------------------------------- ExplainPrinter::ExplainPrinter(Runtime& runtime) : runtime(runtime),indent(0),inOp(false) // Constructor { } //--------------------------------------------------------------------------- ExplainPrinter::~ExplainPrinter() // Destructor { } //--------------------------------------------------------------------------- template <class T> void escapeOutput(T start,T stop) // Write a string { for (T iter=start;iter!=stop;++iter) { char c=*iter; if ((c=='\\')||(c==' ')||(c=='\n')||(c=='\r')) cout << "\\"; cout << c; } } //--------------------------------------------------------------------------- void ExplainPrinter::flushOperator() // Write the current operator if any { if (inOp) { inOp=false; cout << indent << " \""; escapeOutput(operatorName.begin(),operatorName.end()); cout << "\" \""; escapeOutput(operatorArguments.begin(),operatorArguments.end()); cout << "\" " << expectedOutputCardinality << endl; inOp=false; } } //--------------------------------------------------------------------------- void ExplainPrinter::beginOperator(const std::string& name,double expectedOutputCardinality,unsigned observedOutputCardinality) // Begin a new operator { flushOperator(); operatorName=name; operatorArguments=""; this->expectedOutputCardinality=expectedOutputCardinality; this->observedOutputCardinality=observedOutputCardinality; inOp=true; ++indent; } //--------------------------------------------------------------------------- void ExplainPrinter::addArgumentAnnotation(const std::string& argument) // Add an operator argument annotation { if (operatorArguments.length()) operatorArguments+=" "; operatorArguments+=argument; } //--------------------------------------------------------------------------- void ExplainPrinter::addScanAnnotation(const Register* reg,bool bound) // Add a scan annotation { if (operatorArguments.length()) operatorArguments+=" "; if (bound) operatorArguments+=formatValue(reg->value); else operatorArguments+=formatRegister(reg); } //--------------------------------------------------------------------------- void ExplainPrinter::addEqualPredicateAnnotation(const Register* reg1,const Register* reg2) // Add a predicate annotate { if (operatorArguments.length()) operatorArguments+=" "; operatorArguments+=formatRegister(reg1); operatorArguments+="="; operatorArguments+=formatRegister(reg2); } //--------------------------------------------------------------------------- void ExplainPrinter::addMaterializationAnnotation(const std::vector<Register*>& /*regs*/) // Add a materialization annotation { } //--------------------------------------------------------------------------- void ExplainPrinter::addGenericAnnotation(const std::string& /*text*/) // Add a generic annotation { } //--------------------------------------------------------------------------- void ExplainPrinter::endOperator() // Close the current operator { flushOperator(); --indent; } //--------------------------------------------------------------------------- string ExplainPrinter::formatRegister(const Register* reg) // Format a register (for generic annotations) { stringstream result; // Regular register? if (runtime.getRegisterCount()&&(reg>=runtime.getRegister(0))&&(reg<=runtime.getRegister(runtime.getRegisterCount()-1))) { result << "?" << (reg-runtime.getRegister(0)); } else { // Arbitrary register outside the runtime system. Should not occur except for debugging! result << "@0x" << hex << reinterpret_cast<uintptr_t>(reg); } return result.str(); } //--------------------------------------------------------------------------- string ExplainPrinter::formatValue(unsigned value) // Format a constant value (for generic annotations) { stringstream result; if (~value) { const char* start,*stop; Type::ID type; unsigned subType; if (runtime.getDatabase().getDictionary().lookupById(value,start,stop,type,subType)) { result << '\"'; for (const char* iter=start;iter!=stop;++iter) result << *iter; result << '\"'; } else result << "@?" << value; } else { result << "NULL"; } return result.str(); } //--------------------------------------------------------------------------- static void explainQuery(DifferentialIndex& diffIndex,const string& query) // Explain a query { QueryGraph queryGraph; // Parse the query SPARQLLexer lexer(query); if ((lexer.getNext()!=SPARQLLexer::Identifier)||(!lexer.isKeyword("explain"))) { cout << "internal error: explain expected" << endl; return; } SPARQLParser parser(lexer); try { parser.parse(); } catch (const SPARQLParser::ParserException& e) { cout << "parse error: " << e.message << endl; return; } // And perform the semantic anaylsis try { SemanticAnalysis semana(diffIndex); semana.transform(parser,queryGraph); } catch (const SemanticAnalysis::SemanticException& e) { cout << "semantic error: " << e.message << endl; return; } if (queryGraph.knownEmpty()) { cout << "ok" << endl << "indent operator arguments expectedcardinality" << endl << "1 \"EmptyScan\" \"\" 0" << endl << "\\." << endl; cout.flush(); return; } // Run the optimizer PlanGen plangen; Plan* plan=plangen.translate(diffIndex.getDatabase(),queryGraph); if (!plan) { cout << "internal error plan generation failed" << endl; return; } // Print the plan cout << "ok" << endl << "indent operator arguments expectedcardinality" << endl; Runtime runtime(diffIndex.getDatabase(),&diffIndex); ExplainPrinter out(runtime); Operator* operatorTree=CodeGen().translate(runtime,queryGraph,plan,false); dynamic_cast<ResultsPrinter*>(operatorTree)->getInput()->print(out); cout << "\\." << endl; cout.flush(); delete operatorTree; } //--------------------------------------------------------------------------- static void insertQuery(DifferentialIndex& diffIndex,const string& query) // Insert new triples { // Find the boundaries of the new triples string::const_iterator start,stop; SPARQLLexer lexer(query); if ((lexer.getNext()!=SPARQLLexer::Identifier)||(!lexer.isKeyword("insert"))) { cout << "'insert' expected" << endl; return; } if ((lexer.getNext()!=SPARQLLexer::Identifier)||(!lexer.isKeyword("data"))) { cout << "'data' expected" << endl; return; } if (lexer.getNext()!=SPARQLLexer::LCurly) { cout << "'{' expected" << endl; return; } start=lexer.getReader(); stop=start; while (start==stop) { switch (lexer.getNext()) { case SPARQLLexer::Eof: cout << "'}' expected" << endl; return; case SPARQLLexer::RCurly: stop=lexer.getReader()-1; break; default: break; } } string turtle(start,stop); istringstream in(turtle); // Parse the input BulkOperation chunk(diffIndex); TurtleParser parser(in); while (true) { // Read the next triple std::string subject,predicate,object,objectSubType; Type::ID objectType; try { if (!parser.parse(subject,predicate,object,objectType,objectSubType)) break; } catch (const TurtleParser::Exception& e) { cout << e.message << endl; return; } chunk.insert(subject,predicate,object,objectType,objectSubType); } // And insert it chunk.commit(); cout << "ok" << endl << endl << "\\." << endl; } //--------------------------------------------------------------------------- } //--------------------------------------------------------------------------- int main(int argc,char* argv[]) { cout.sync_with_stdio(false); // Check the arguments if (argc!=2) { cerr << "usage: " << argv[0] << " <database>" << endl; return 1; } // Open the database Database db; if (!db.open(argv[1],true)) { cout << "unable to open database " << argv[1] << endl; return 1; } DifferentialIndex diffIndex(db); cout << "RDF-3X protocol 1" << endl; // And process queries while (true) { string query; while (true) { char c; if (!(cin.get(c))) return 0; if (c=='\n') break; if (c=='\\') { if (!(cin.get(c))) return 0; } query+=c; } switch (classifyQuery(query)) { case ExplainQuery: explainQuery(diffIndex,query); break; case InsertQuery: insertQuery(diffIndex,query); break; case RollbackQuery: diffIndex.clear(); cout << "ok" << endl << endl << "\\." << endl; break; case RegularQuery: default: runQuery(diffIndex,query); break; } cout.flush(); } } //---------------------------------------------------------------------------
32.890526
127
0.560008
[ "object", "vector", "transform" ]
984dc8b6602a0da800c22ab2ae817faa149abe95
8,217
cpp
C++
android-31/android/widget/ScrollView.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-30/android/widget/ScrollView.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/widget/ScrollView.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../content/Context.hpp" #include "../graphics/Canvas.hpp" #include "../graphics/Rect.hpp" #include "../view/KeyEvent.hpp" #include "../view/MotionEvent.hpp" #include "../view/View.hpp" #include "../view/ViewGroup_LayoutParams.hpp" #include "../../JString.hpp" #include "./ScrollView.hpp" namespace android::widget { // Fields // QJniObject forward ScrollView::ScrollView(QJniObject obj) : android::widget::FrameLayout(obj) {} // Constructors ScrollView::ScrollView(android::content::Context arg0) : android::widget::FrameLayout( "android.widget.ScrollView", "(Landroid/content/Context;)V", arg0.object() ) {} ScrollView::ScrollView(android::content::Context arg0, JObject arg1) : android::widget::FrameLayout( "android.widget.ScrollView", "(Landroid/content/Context;Landroid/util/AttributeSet;)V", arg0.object(), arg1.object() ) {} ScrollView::ScrollView(android::content::Context arg0, JObject arg1, jint arg2) : android::widget::FrameLayout( "android.widget.ScrollView", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V", arg0.object(), arg1.object(), arg2 ) {} ScrollView::ScrollView(android::content::Context arg0, JObject arg1, jint arg2, jint arg3) : android::widget::FrameLayout( "android.widget.ScrollView", "(Landroid/content/Context;Landroid/util/AttributeSet;II)V", arg0.object(), arg1.object(), arg2, arg3 ) {} // Methods void ScrollView::addView(android::view::View arg0) const { callMethod<void>( "addView", "(Landroid/view/View;)V", arg0.object() ); } void ScrollView::addView(android::view::View arg0, android::view::ViewGroup_LayoutParams arg1) const { callMethod<void>( "addView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", arg0.object(), arg1.object() ); } void ScrollView::addView(android::view::View arg0, jint arg1) const { callMethod<void>( "addView", "(Landroid/view/View;I)V", arg0.object(), arg1 ); } void ScrollView::addView(android::view::View arg0, jint arg1, android::view::ViewGroup_LayoutParams arg2) const { callMethod<void>( "addView", "(Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V", arg0.object(), arg1, arg2.object() ); } jboolean ScrollView::arrowScroll(jint arg0) const { return callMethod<jboolean>( "arrowScroll", "(I)Z", arg0 ); } void ScrollView::computeScroll() const { callMethod<void>( "computeScroll", "()V" ); } jboolean ScrollView::dispatchKeyEvent(android::view::KeyEvent arg0) const { return callMethod<jboolean>( "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z", arg0.object() ); } void ScrollView::draw(android::graphics::Canvas arg0) const { callMethod<void>( "draw", "(Landroid/graphics/Canvas;)V", arg0.object() ); } jboolean ScrollView::executeKeyEvent(android::view::KeyEvent arg0) const { return callMethod<jboolean>( "executeKeyEvent", "(Landroid/view/KeyEvent;)Z", arg0.object() ); } void ScrollView::fling(jint arg0) const { callMethod<void>( "fling", "(I)V", arg0 ); } jboolean ScrollView::fullScroll(jint arg0) const { return callMethod<jboolean>( "fullScroll", "(I)Z", arg0 ); } JString ScrollView::getAccessibilityClassName() const { return callObjectMethod( "getAccessibilityClassName", "()Ljava/lang/CharSequence;" ); } jint ScrollView::getBottomEdgeEffectColor() const { return callMethod<jint>( "getBottomEdgeEffectColor", "()I" ); } jint ScrollView::getMaxScrollAmount() const { return callMethod<jint>( "getMaxScrollAmount", "()I" ); } jint ScrollView::getTopEdgeEffectColor() const { return callMethod<jint>( "getTopEdgeEffectColor", "()I" ); } jboolean ScrollView::isFillViewport() const { return callMethod<jboolean>( "isFillViewport", "()Z" ); } jboolean ScrollView::isSmoothScrollingEnabled() const { return callMethod<jboolean>( "isSmoothScrollingEnabled", "()Z" ); } jboolean ScrollView::onGenericMotionEvent(android::view::MotionEvent arg0) const { return callMethod<jboolean>( "onGenericMotionEvent", "(Landroid/view/MotionEvent;)Z", arg0.object() ); } jboolean ScrollView::onInterceptTouchEvent(android::view::MotionEvent arg0) const { return callMethod<jboolean>( "onInterceptTouchEvent", "(Landroid/view/MotionEvent;)Z", arg0.object() ); } jboolean ScrollView::onNestedFling(android::view::View arg0, jfloat arg1, jfloat arg2, jboolean arg3) const { return callMethod<jboolean>( "onNestedFling", "(Landroid/view/View;FFZ)Z", arg0.object(), arg1, arg2, arg3 ); } void ScrollView::onNestedScroll(android::view::View arg0, jint arg1, jint arg2, jint arg3, jint arg4) const { callMethod<void>( "onNestedScroll", "(Landroid/view/View;IIII)V", arg0.object(), arg1, arg2, arg3, arg4 ); } void ScrollView::onNestedScrollAccepted(android::view::View arg0, android::view::View arg1, jint arg2) const { callMethod<void>( "onNestedScrollAccepted", "(Landroid/view/View;Landroid/view/View;I)V", arg0.object(), arg1.object(), arg2 ); } jboolean ScrollView::onStartNestedScroll(android::view::View arg0, android::view::View arg1, jint arg2) const { return callMethod<jboolean>( "onStartNestedScroll", "(Landroid/view/View;Landroid/view/View;I)Z", arg0.object(), arg1.object(), arg2 ); } void ScrollView::onStopNestedScroll(android::view::View arg0) const { callMethod<void>( "onStopNestedScroll", "(Landroid/view/View;)V", arg0.object() ); } jboolean ScrollView::onTouchEvent(android::view::MotionEvent arg0) const { return callMethod<jboolean>( "onTouchEvent", "(Landroid/view/MotionEvent;)Z", arg0.object() ); } jboolean ScrollView::pageScroll(jint arg0) const { return callMethod<jboolean>( "pageScroll", "(I)Z", arg0 ); } void ScrollView::requestChildFocus(android::view::View arg0, android::view::View arg1) const { callMethod<void>( "requestChildFocus", "(Landroid/view/View;Landroid/view/View;)V", arg0.object(), arg1.object() ); } jboolean ScrollView::requestChildRectangleOnScreen(android::view::View arg0, android::graphics::Rect arg1, jboolean arg2) const { return callMethod<jboolean>( "requestChildRectangleOnScreen", "(Landroid/view/View;Landroid/graphics/Rect;Z)Z", arg0.object(), arg1.object(), arg2 ); } void ScrollView::requestDisallowInterceptTouchEvent(jboolean arg0) const { callMethod<void>( "requestDisallowInterceptTouchEvent", "(Z)V", arg0 ); } void ScrollView::requestLayout() const { callMethod<void>( "requestLayout", "()V" ); } void ScrollView::scrollTo(jint arg0, jint arg1) const { callMethod<void>( "scrollTo", "(II)V", arg0, arg1 ); } void ScrollView::scrollToDescendant(android::view::View arg0) const { callMethod<void>( "scrollToDescendant", "(Landroid/view/View;)V", arg0.object() ); } void ScrollView::setBottomEdgeEffectColor(jint arg0) const { callMethod<void>( "setBottomEdgeEffectColor", "(I)V", arg0 ); } void ScrollView::setEdgeEffectColor(jint arg0) const { callMethod<void>( "setEdgeEffectColor", "(I)V", arg0 ); } void ScrollView::setFillViewport(jboolean arg0) const { callMethod<void>( "setFillViewport", "(Z)V", arg0 ); } void ScrollView::setSmoothScrollingEnabled(jboolean arg0) const { callMethod<void>( "setSmoothScrollingEnabled", "(Z)V", arg0 ); } void ScrollView::setTopEdgeEffectColor(jint arg0) const { callMethod<void>( "setTopEdgeEffectColor", "(I)V", arg0 ); } jboolean ScrollView::shouldDelayChildPressedState() const { return callMethod<jboolean>( "shouldDelayChildPressedState", "()Z" ); } void ScrollView::smoothScrollBy(jint arg0, jint arg1) const { callMethod<void>( "smoothScrollBy", "(II)V", arg0, arg1 ); } void ScrollView::smoothScrollTo(jint arg0, jint arg1) const { callMethod<void>( "smoothScrollTo", "(II)V", arg0, arg1 ); } } // namespace android::widget
21.342857
128
0.676524
[ "object" ]
9858ee95999d28173790b0df06f1065803488f57
18,413
cpp
C++
opengl/src/main.cpp
sp4ghet/pbr
842e91ac0aceb20b88d82e0b9a3436f8981eecbe
[ "MIT" ]
14
2020-09-12T20:49:12.000Z
2021-11-14T17:12:23.000Z
opengl/src/main.cpp
sp4ghet/pbr
842e91ac0aceb20b88d82e0b9a3436f8981eecbe
[ "MIT" ]
null
null
null
opengl/src/main.cpp
sp4ghet/pbr
842e91ac0aceb20b88d82e0b9a3436f8981eecbe
[ "MIT" ]
null
null
null
#include "camera.h" #include "glad/glad.h" #include "glfw3/glfw3.h" #include "shader.h" #include "stb/stb_image.h" #include <cstdio> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <math.h> #include <mesh.h> #include <model.h> #include <vector> void framebuffer_size_callback(GLFWwindow *window, int width, int height); void processInput(GLFWwindow *window); void mouse_button_callback(GLFWwindow *window, int button, int action, int mods); void scroll_callback(GLFWwindow *window, double xoffset, double yoffset); void mouse_callback(GLFWwindow *window, double xpos, double ypos); void renew_msaa_buffer(unsigned int &fbo, unsigned int &colorBuf, unsigned int &rbo); void renew_framebuffer(unsigned int &fbo, unsigned int &colorBuf, unsigned int &rbo); Camera camera(glm::vec3(0., 0., 10.)); float prevTime = 0., deltaTime = 0.; bool recompileFlag = false; std::pair<int, int> resolution = {800, 600}; glm::vec3 n = glm::vec3(0., 0., 1.); glm::vec3 t = glm::vec3(0., 1., 0.); std::vector<Vertex> quadVertices = { Vertex(glm::vec3(-1., 1., 0.), n, t, glm::vec2(0., 1.)), Vertex(glm::vec3(-1., -1., 0.), n, t, glm::vec2(0., 0.)), Vertex(glm::vec3(1., -1., 0.), n, t, glm::vec2(1., 0.)), Vertex(glm::vec3(1., 1., 0.), n, t, glm::vec2(1., 1.)), }; std::vector<unsigned int> quadIndices = {0, 1, 3, 1, 2, 3}; // clang-format off std::vector<Vertex> cubeVertices = { Vertex(glm::vec3(-1.0f, -1.0f, -1.0f), glm::vec3(0.,0.,-1.), glm::vec3(0.,1.,0.), glm::vec2(0., 0.)), Vertex(glm::vec3(-1.0f, 1.0f, -1.0f), glm::vec3(0.,0.,-1.), glm::vec3(0.,1.,0.), glm::vec2(0., 1.)), Vertex(glm::vec3( 1.0f, 1.0f, -1.0f), glm::vec3(0.,0.,-1.), glm::vec3(0.,1.,0.), glm::vec2(1., 1.)), Vertex(glm::vec3( 1.0f, -1.0f, -1.0f), glm::vec3(0.,0.,-1.), glm::vec3(0.,1.,0.), glm::vec2(1., 0.)), Vertex(glm::vec3(-1.0f, -1.0f, -1.0f), glm::vec3(-1., 0.,0.), glm::vec3(0.,1.,0.), glm::vec2(0., 0.)), Vertex(glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec3(-1., 0.,0.), glm::vec3(0.,1.,0.), glm::vec2(0., 1.)), Vertex(glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(-1., 0.,0.), glm::vec3(0.,1.,0.), glm::vec2(1., 1.)), Vertex(glm::vec3(-1.0f, 1.0f, -1.0f), glm::vec3(-1., 0.,0.), glm::vec3(0.,1.,0.), glm::vec2(1., 0.)), Vertex(glm::vec3(1.0f, -1.0f, 1.0f), glm::vec3(1., 0.,0.), glm::vec3(0.,1.,0.), glm::vec2(0., 1.)), Vertex(glm::vec3(1.0f, -1.0f, -1.0f), glm::vec3(1., 0.,0.), glm::vec3(0.,1.,0.), glm::vec2(0., 0.)), Vertex(glm::vec3(1.0f, 1.0f, -1.0f), glm::vec3(1., 0.,0.), glm::vec3(0.,1.,0.), glm::vec2(1., 0.)), Vertex(glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(1., 0.,0.), glm::vec3(0.,1.,0.), glm::vec2(1., 1.)), Vertex(glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(0., 0., 1.), glm::vec3(0.,1.,0.), glm::vec2(0., 1.)), Vertex(glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec3(0., 0., 1.), glm::vec3(0.,1.,0.), glm::vec2(0., 0.)), Vertex(glm::vec3( 1.0f, -1.0f, 1.0f), glm::vec3(0., 0., 1.), glm::vec3(0.,1.,0.), glm::vec2(1., 0.)), Vertex(glm::vec3( 1.0f, 1.0f, 1.0f), glm::vec3(0., 0., 1.), glm::vec3(0.,1.,0.), glm::vec2(1., 1.)), Vertex(glm::vec3(-1.0f, 1.0f, -1.0f), glm::vec3(0., 1., 0.), glm::vec3(0., 0., 1.), glm::vec2(0., 0.)), Vertex(glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(0., 1., 0.), glm::vec3(0., 0., 1.), glm::vec2(0., 1.)), Vertex(glm::vec3( 1.0f, 1.0f, 1.0f), glm::vec3(0., 1., 0.), glm::vec3(0., 0., 1.), glm::vec2(1., 1.)), Vertex(glm::vec3( 1.0f, 1.0f, -1.0f), glm::vec3(0., 1., 0.), glm::vec3(0., 0., 1.), glm::vec2(1., 0.)), Vertex(glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec3(0., -1., 0.), glm::vec3(0., 0., 1.), glm::vec2(0., 1.)), Vertex(glm::vec3(-1.0f, -1.0f, -1.0f), glm::vec3(0., -1., 0.), glm::vec3(0., 0., 1.), glm::vec2(0., 0.)), Vertex(glm::vec3( 1.0f, -1.0f, -1.0f), glm::vec3(0., -1., 0.), glm::vec3(0., 0., 1.), glm::vec2(1., 0.)), Vertex(glm::vec3( 1.0f, -1.0f, 1.0f), glm::vec3(0., -1., 0.), glm::vec3(0., 0., 1.), glm::vec2(1., 1.)), }; std::vector<unsigned int> cubeIndices = { 0,1,3, 1,2,3, 4,5,7, 5,6,7, 8,9,11, 9,10,11, 12,13,15, 13,14,15, 16,17,19, 17,18,19, 20,21,23, 21,22,23 }; // clang-format on unsigned int msFbo; unsigned int msColorBuf; unsigned int msRbo; unsigned int fbo; unsigned int colorBuf; unsigned int rbo; std::vector<Texture> fullScreenQuadTextures; Mesh quadMesh; int main(int, char **) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow *window = glfwCreateWindow(800, 600, "Learn OpenGL", NULL, NULL); if (window == NULL) { printf("Failed to create window\n"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { printf("Failed to initialize GLAD\n"); return -1; } glViewport(0, 0, 800, 600); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPosCallback(window, mouse_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetScrollCallback(window, scroll_callback); stbi_set_flip_vertically_on_load(true); // load images Shader shader("./shaders/simple.vert", "./shaders/simple.frag"); Shader outline("./shaders/simple.vert", "./shaders/fill.frag"); Shader screenShader("./shaders/fullscreen_quad.vert", "./shaders/postprocess.frag"); Shader skyboxShader("./shaders/skybox.vert", "./shaders/skybox.frag"); Shader shadowShader("./shaders/simpleShadow.vert", "./shaders/simpleShadow.frag"); printf("Shaders loaded...\n"); Model backpack("./resources/backpack/backpack.obj"); printf("Model loaded...\n"); std::vector<std::string> cubemap_faces = { "./resources/textures/skybox/right.jpg", "./resources/textures/skybox/left.jpg", "./resources/textures/skybox/top.jpg", "./resources/textures/skybox/bottom.jpg", "./resources/textures/skybox/front.jpg", "./resources/textures/skybox/back.jpg"}; unsigned int cubemapId = loadCubemap(cubemap_faces); printf("Cubemap loaded...\n"); std::vector<Texture> skyboxTextures = { Texture(cubemapId, GL_TEXTURE_CUBE_MAP, "skybox")}; Mesh skybox = Mesh(cubeVertices, cubeIndices, skyboxTextures); unsigned int boxTex = TextureFromFile("container.jpg", "./textures"); Texture crateTex(boxTex, GL_TEXTURE_2D, "texture_diffuse1"); Mesh cubeMesh = Mesh(cubeVertices, cubeIndices, std::vector<Texture>{crateTex}); Mesh planeMesh = Mesh(quadVertices, quadIndices, std::vector<Texture>{crateTex}); #ifdef DEBUG int nrAttributes; glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &nrAttributes); printf("Maximum vertex attributes supported: %d\n", nrAttributes); #endif renew_framebuffer(fbo, colorBuf, rbo); renew_msaa_buffer(msFbo, msColorBuf, msRbo); fullScreenQuadTextures = std::vector<Texture>{Texture(colorBuf, GL_TEXTURE_2D, "renderBuffer")}; quadMesh = Mesh(quadVertices, quadIndices, fullScreenQuadTextures); unsigned int depthMapFBO; glGenFramebuffers(1, &depthMapFBO); const int SHADOW_WIDTH = 2048, SHADOW_HEIGHT = 2048; unsigned int depthMap; glGenTextures(1, &depthMap); glBindTexture(GL_TEXTURE_2D, depthMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); float borderColor[] = {1., 1., 1., 1.}; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor); glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0); glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER, 0); glm::vec3 lightPos = glm::vec3(-4., 4., -4.); std::vector<glm::vec3> lightColors; lightColors.push_back(glm::vec3(3.f)); lightColors.push_back(glm::vec3(0.5f, 0.0f, 0.0f)); lightColors.push_back(glm::vec3(0.0f, 0.0f, 0.5f)); lightColors.push_back(glm::vec3(0.0f, 0.5f, 0.0f)); std::vector<glm::vec3> lightPositions; lightPositions.push_back(glm::vec3(-4., 4., -4.)); lightPositions.push_back(glm::vec3(4., 1., 4.)); lightPositions.push_back(glm::vec3(-4., 1., 4.)); lightPositions.push_back(glm::vec3(4., 1., -4.)); glm::mat4 proj, view; auto RenderScene = [&](bool shadowPass = false) { Shader useShader = shader; if (shadowPass) { useShader = shadowShader; } glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glm::mat4 lightView = glm::lookAt(lightPos, glm::vec3(0.f, 0.f, 0.f), glm::vec3(0., 1., 0.)); float shadowNear = .5, shadowFar = 20.f; glm::mat4 lightProj = glm::ortho(-10.f, 10.f, -10.f, 10.f, shadowNear, shadowFar); useShader.setMat4("lightVP", lightProj * lightView); useShader.setVec3("lightPos", lightPos.x, lightPos.y, lightPos.z); glActiveTexture(GL_TEXTURE14); glBindTexture(GL_TEXTURE_2D, depthMap); useShader.setInt("shadow_map", 14); glActiveTexture(GL_TEXTURE0); useShader.setVec3Array("lightPositions", lightPositions); useShader.setVec3Array("lightColors", lightColors); glm::mat4 model = glm::mat4(1.); model = glm::rotate(model, glm::radians(-90.f), glm::vec3(1., 0., 0.)); glm::mat4 mvp = proj * view * model; useShader.use(); useShader.setMat4("MVP", mvp); useShader.setMat4("model", model); useShader.setVec3("camPos", camera.Position.x, camera.Position.y, camera.Position.z); useShader.setBool("hasDiffuse", true); useShader.setBool("hasSpecular", true); useShader.setBool("hasNormal", true); useShader.setBool("hasRoughness", true); backpack.Draw(useShader); glm::mat4 lightCubeModel = glm::mat4(1.); lightCubeModel = glm::translate(lightCubeModel, lightPos); lightCubeModel = glm::scale(lightCubeModel, glm::vec3(0.1)); useShader.setMat4("model", lightCubeModel); mvp = proj * view * lightCubeModel; useShader.setMat4("MVP", mvp); useShader.setBool("hasDiffuse", true); useShader.setBool("hasSpecular", false); useShader.setBool("hasNormal", false); useShader.setBool("hasRoughness", false); cubeMesh.Draw(useShader); glm::mat4 cubeModel = glm::mat4(1.); cubeModel = glm::translate(cubeModel, glm::vec3(3., 0., 3.)); useShader.setMat4("model", cubeModel); mvp = proj * view * cubeModel; useShader.setMat4("MVP", mvp); useShader.setBool("hasDiffuse", true); useShader.setBool("hasSpecular", false); useShader.setBool("hasNormal", false); useShader.setBool("hasRoughness", false); cubeMesh.Draw(useShader); glm::mat4 planeModel = glm::mat4(10.); planeModel = glm::translate(planeModel, glm::vec3(0., -1., 0.)); planeModel = glm::rotate(planeModel, glm::radians(-90.f), glm::vec3(1., 0., 0.)); planeModel = glm::scale(planeModel, glm::vec3(10.)); useShader.setMat4("model", planeModel); mvp = proj * view * planeModel; useShader.setMat4("MVP", mvp); useShader.setBool("hasDiffuse", true); useShader.setBool("hasSpecular", false); useShader.setBool("hasNormal", false); useShader.setBool("hasRoughness", false); planeMesh.Draw(useShader); }; while (!glfwWindowShouldClose(window)) { deltaTime = (float)glfwGetTime() - prevTime; prevTime = (float)glfwGetTime(); if (recompileFlag) { shader.recompile(); screenShader.recompile(); skyboxShader.recompile(); shadowShader.recompile(); recompileFlag = false; } // input processInput(window); proj = glm::perspective(glm::radians(camera.Zoom), (float)resolution.first / (float)resolution.second, 0.001f, 100.f); view = camera.GetViewMatrix(); // rendering commands // render to shadow map glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT); glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); glClear(GL_DEPTH_BUFFER_BIT); glEnable(GL_CULL_FACE); shadowShader.use(); glCullFace(GL_FRONT); RenderScene(true); glCullFace(GL_BACK); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, resolution.first, resolution.second); // render to frame buffer glBindFramebuffer(GL_FRAMEBUFFER, msFbo); glClearColor(0.05f, 0.35f, 0.45f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); shader.use(); RenderScene(false); // render cubemap glDepthFunc(GL_LEQUAL); glDisable(GL_CULL_FACE); skyboxShader.use(); skyboxShader.setMat4("projection", proj); skyboxShader.setMat4("view", glm::mat4(glm::mat3(view))); skybox.Draw(skyboxShader); glDepthMask(GL_TRUE); glBindVertexArray(0); glActiveTexture(GL_TEXTURE0); // draw MSAA texture to intermediate buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, msFbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); glBlitFramebuffer(0, 0, resolution.first, resolution.second, 0, 0, resolution.first, resolution.second, GL_COLOR_BUFFER_BIT, GL_NEAREST); // restore default framebuffer glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(0.05f, 0.35f, 0.45f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_DEPTH_TEST); screenShader.use(); quadMesh.Draw(screenShader); // check and call events and swap the buffers glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } // ----------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow *window, int width, int height) { glViewport(0, 0, width, height); resolution = std::pair<int, int>(width, height); renew_framebuffer(fbo, colorBuf, rbo); renew_msaa_buffer(msFbo, msColorBuf, msRbo); fullScreenQuadTextures = std::vector<Texture>{Texture(colorBuf, GL_TEXTURE_2D, "renderBuffer")}; quadMesh = Mesh(quadVertices, quadIndices, fullScreenQuadTextures); } void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera.ProcessKeyBoard(FORWARD, deltaTime); } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera.ProcessKeyBoard(LEFT, deltaTime); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera.ProcessKeyBoard(BACKWARD, deltaTime); } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera.ProcessKeyBoard(RIGHT, deltaTime); } if (glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_PRESS && !recompileFlag) { recompileFlag = true; } } bool rightClick = false; void mouse_button_callback(GLFWwindow *window, int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) { rightClick = true; } if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_RELEASE) { rightClick = false; } } float lastX = -1., lastY = -1.; void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (!rightClick) { lastX = -1.; lastY = -1.; return; } float dx = xpos - lastX, dy = lastY - ypos; if (lastX < 0.f || lastY < 0.f) { dx = 0.; dy = 0.; } lastX = (float)xpos; lastY = (float)ypos; camera.ProcessMouseMovement(dx, dy); } void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { camera.ProcessMouseScroll((float)yoffset); } void renew_msaa_buffer(unsigned int &msFbo, unsigned int &msColorBuf, unsigned int &msRbo) { glGenFramebuffers(1, &msFbo); glBindFramebuffer(GL_FRAMEBUFFER, msFbo); glGenTextures(1, &msColorBuf); glBindTexture(GL_TEXTURE_2D, msColorBuf); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, resolution.first, resolution.second, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, msColorBuf, 0); glGenRenderbuffers(1, &msRbo); glBindRenderbuffer(GL_RENDERBUFFER, msRbo); glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH24_STENCIL8, resolution.first, resolution.second); glBindRenderbuffer(GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, msRbo); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { printf("ERROR::FRAMEBUFFER:: Frame buffer is not complete!\n"); } } void renew_framebuffer(unsigned int &fbo, unsigned int &colorBuf, unsigned int &rbo) { glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glGenTextures(1, &colorBuf); glBindTexture(GL_TEXTURE_2D, colorBuf); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, resolution.first, resolution.second, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuf, 0); glGenRenderbuffers(1, &rbo); glBindRenderbuffer(GL_RENDERBUFFER, rbo); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, resolution.first, resolution.second); glBindRenderbuffer(GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { printf("ERROR::FRAMEBUFFER:: Frame buffer is not complete!\n"); } }
36.103922
107
0.65595
[ "mesh", "render", "vector", "model" ]
986e994caf26d16bcd52d3d615b6de50d0ade141
3,070
cpp
C++
demo/hunter_demo/hunter_robot_demo.cpp
ihrabar/ugv_sdk
85e4757c165d57d01714c2cb44d045dd2f4a2422
[ "Apache-2.0" ]
19
2020-10-25T23:19:10.000Z
2022-03-31T07:44:30.000Z
demo/hunter_demo/hunter_robot_demo.cpp
ihrabar/ugv_sdk
85e4757c165d57d01714c2cb44d045dd2f4a2422
[ "Apache-2.0" ]
6
2021-01-13T02:20:01.000Z
2022-03-15T15:27:35.000Z
demo/hunter_demo/hunter_robot_demo.cpp
ihrabar/ugv_sdk
85e4757c165d57d01714c2cb44d045dd2f4a2422
[ "Apache-2.0" ]
17
2021-04-19T07:56:07.000Z
2022-02-28T02:11:25.000Z
/* * hunter_robot_demo.cpp * * Created on: Jul 08, 2021 11:12 * Description: * * Copyright (c) 2021 Weston Robot Pte. Ltd. */ #include <unistd.h> #include <memory> #include <iostream> #include "ugv_sdk/mobile_robot/hunter_robot.hpp" #include "ugv_sdk/utilities/protocol_detector.hpp" using namespace westonrobot; int main(int argc, char **argv) { std::string device_name; if (argc == 2) { device_name = {argv[1]}; std::cout << "Selected interface " << device_name << std::endl; } else { std::cout << "Usage: app_hunter_demo <interface>" << std::endl << "Example 1: ./app_hunter_demo can0" << std::endl; return -1; } std::unique_ptr<HunterRobot> hunter; ProtocolDectctor detector; detector.Connect(device_name); auto proto = detector.DetectProtocolVersion(5); if (proto == ProtocolVersion::AGX_V1) { hunter = std::unique_ptr<HunterRobot>(new HunterRobot(ProtocolVersion::AGX_V1)); } else if (proto == ProtocolVersion::AGX_V2) { hunter = std::unique_ptr<HunterRobot>(new HunterRobot(ProtocolVersion::AGX_V2)); } else { std::cout << "Detected protocol: UNKONWN" << std::endl; return -1; } if (hunter == nullptr) std::cout << "Failed to create robot object" << std::endl; hunter->Connect(device_name); if (hunter->GetParserProtocolVersion() == ProtocolVersion::AGX_V2) { hunter->EnableCommandedMode(); std::cout << "Protocol version 2" << std::endl; } else { std::cout << "Protocol version 1" << std::endl; } int count = 0; while (true) { // motion control std::cout << "Motor: 1.0, 0" << std::endl; // hunter->SetMotionCommand(1.0, 0.0); // get robot state auto state = hunter->GetRobotState(); std::cout << "-------------------------------" << std::endl; std::cout << "count: " << count << std::endl; std::cout << "control mode: " << static_cast<int>(state.system_state.control_mode) << " , vehicle state: " << static_cast<int>(state.system_state.vehicle_state) << " , error code: " << std::hex << state.system_state.error_code << ", battery voltage: " << state.system_state.battery_voltage << std::endl; std::cout << "velocity (linear, angular): " << state.motion_state.linear_velocity << ", " << state.motion_state.steering_angle << std::endl; auto actuator = hunter->GetActuatorState(); if (hunter->GetParserProtocolVersion() == ProtocolVersion::AGX_V1) { for (int i = 0; i < 3; ++i) { printf("motor %d: current %f, rpm %d, driver temp %f, motor temp %f\n", actuator.actuator_state[i].motor_id, actuator.actuator_state[i].current, actuator.actuator_state[i].rpm, actuator.actuator_state[i].driver_temp, actuator.actuator_state[i].motor_temp); } } else { } std::cout << "-------------------------------" << std::endl; usleep(20000); ++count; } return 0; }
30.39604
79
0.590879
[ "object" ]
9876d2c47c8d7f9cedb7c33e0b394697a0c8fe5a
2,639
cpp
C++
src/Primitive.cpp
joshbainbridge/morphogenetic-sim
36b80621f44a4f259def430737baf6cbb62891b8
[ "MIT" ]
1
2016-06-03T04:35:45.000Z
2016-06-03T04:35:45.000Z
src/Primitive.cpp
joshbainbridge/morphogenetic-sim
36b80621f44a4f259def430737baf6cbb62891b8
[ "MIT" ]
null
null
null
src/Primitive.cpp
joshbainbridge/morphogenetic-sim
36b80621f44a4f259def430737baf6cbb62891b8
[ "MIT" ]
null
null
null
#include <Primitive.h> Primitive::Primitive(boost::shared_ptr<ShapeInterface> _shape, boost::shared_ptr<Material> _material) { m_shape = _shape; m_material = _material; m_primitive_count = 0; m_transform << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1; m_aabb.updateAabb(Aabb(m_shape->AABBmin(), m_shape->AABBmax())); } //Update AABB according to its shape member and primitive hierarchy void Primitive::updateAabb() { m_aabb.updateAabb(Aabb(m_shape->AABBmin(), m_shape->AABBmax())); for (int i = 0; i < m_primitive_count; ++i) { m_primitives[i]->updateAabb(); m_aabb.updateAabb(m_primitives[i]->aabb()); } } //Find primitve intersection, discarding rays that don't intersect the AABB bool Primitive::intersect(const Ray3f _ray, Transmission *_output) const { //Intersect with bounding volume if(m_aabb.intersect(_ray)) { //If there are primitives, test them (if not, then just test shape) if (m_primitive_count != 0) { bool intersection_found = false; Transmission closest_intersection; //Loop through and test all primitives for (int i = 0; i < m_primitive_count; ++i) { Transmission primitive_intersection; if(m_primitives[i]->intersect(_ray, &primitive_intersection) && (primitive_intersection.distance < closest_intersection.distance)) { closest_intersection = primitive_intersection; intersection_found = true; } } //Now test against shape Transmission primitive_intersection; if (m_shape->intersect(_ray, &primitive_intersection) && (primitive_intersection.distance < closest_intersection.distance)) { closest_intersection = primitive_intersection; closest_intersection.material = m_material; intersection_found = true; } //If intersection found, set the output if (intersection_found) { *_output = closest_intersection; return true; } } else { //Just intersect shape if (m_shape->intersect(_ray, _output)) { _output->material = m_material; return true; } } } return false; } //Add primitive to form a bounding volume hierarchy void Primitive::addPrimitive(boost::shared_ptr<Primitive> _primitive) { m_primitives.push_back(_primitive); ++m_primitive_count; } //Return primitive using index boost::shared_ptr<Primitive> Primitive::getPrimitive(const int _index) const { return m_primitives[_index]; } //Remove all nested primitives void Primitive::clearPrimitives() { m_primitives.clear(); m_primitive_count = 0; }
26.128713
138
0.679045
[ "shape" ]
988ae3e56d7d7b9861a46e8be8632a7632c447a7
108
cpp
C++
src/KeyboardEvent.cpp
obscurelyme/SDLVulkanRenderer
0036a982c486a2816df963250bde24e5fa6ec4d7
[ "MIT" ]
null
null
null
src/KeyboardEvent.cpp
obscurelyme/SDLVulkanRenderer
0036a982c486a2816df963250bde24e5fa6ec4d7
[ "MIT" ]
null
null
null
src/KeyboardEvent.cpp
obscurelyme/SDLVulkanRenderer
0036a982c486a2816df963250bde24e5fa6ec4d7
[ "MIT" ]
null
null
null
#include "KeyboardEvent.hpp" std::vector<SDLKeyboardEventListener*> SDLKeyboardEventListener::_listeners{};
36
78
0.833333
[ "vector" ]
989ec00fa4b633a25246e6e2649b72f05e7973a6
6,046
cpp
C++
HW3/edemirci_Demirci_Emre_HW3.cpp
edemirci191/CS204-Homeworks
138ace62ddbf24c98e653530aa04cceb59e3559e
[ "MIT" ]
null
null
null
HW3/edemirci_Demirci_Emre_HW3.cpp
edemirci191/CS204-Homeworks
138ace62ddbf24c98e653530aa04cceb59e3559e
[ "MIT" ]
null
null
null
HW3/edemirci_Demirci_Emre_HW3.cpp
edemirci191/CS204-Homeworks
138ace62ddbf24c98e653530aa04cceb59e3559e
[ "MIT" ]
null
null
null
//*********************************************** // This program stores credit card information( number, month , year) in a given txt file using linkedlists // This code is written by Emre Demirci, 26531 // Start Date : Unknown // End Date : 3/11/2020 // Known Bugs : None, however if user enters a number like 1830912809129381012 (above int capacity) than it gives debug error, can be handled by using long long int // did not fix it because i found it unnecessary and it uses more memory. // Pre Scriptum: Some functions from linkedList.cpp and from lecture slides is used( i wrote proper message to specify which functions) // Pre Scriptum: Some functions from my previous homework (edemirci_Demirci_Emre_Hw2.cpp) are also used and updated //*********************************************** #include <iostream> #include <string> #include <fstream> #include <vector> #include <sstream> #include <memory> #include "doublelinked.h" using namespace std; //********************** Start: function prototypes ************************ void menu(); void error(); //********************** End: function prototypes ************************ //********************** Start: Define function bodies ********************* void menu() { cout << "1) Upload Card(s)" << endl; cout << "2) Display List Chronological " << endl; cout << "3) Display List Reverse Chronological" << endl; cout << "4) Card Search " << endl; cout << "5) Bulk Delete " << endl; cout << "6) Exit" << endl; } void error() { cout << "Invalid operation" << endl; } //************************* End: Define function bodies*********************** //************************* Start: Main ************************************** int main(){ bool dontenter = false; bool not_empty = true; string File_Name, inside_of_file,card_number,month,year_in_file; CardList object; // creating out main "structure(list)" int int_user_input = 8; // this value can be any integer but 6 do{ // while input is not 6 ( user decides not the exit enter this loop //***************************************** Start: Asking user for operation number ********************* // check if given number is correct if not then ask again bool valid_input = false; string user_input; do{ menu(); cin >> user_input; if(user_input.find_first_not_of("123456") == string::npos) // if user enters anything rather than 1,2,3,4,5,6 then it is invalid { if(stoi(user_input) > 6) // user can enter valid too but what if enter something like 12, this part checks that also { valid_input = false; error(); cout << endl; } else { valid_input = true; } } else { cout << "Invalid format! "; cout << endl; } }while(valid_input != true); int_user_input = stoi(user_input); //********************************** End: Asking user for operation number ************************************************* //********************************** Start: Asking for file name, if int_user_input is 1************************************ if(int_user_input != 6) { if(int_user_input == 1) { ifstream txtfile2; // to read file bool opening= true; cout << "Please enter file name: "; cin >> File_Name; cout << endl; txtfile2.open(File_Name); if(!(txtfile2.is_open())) { opening = false; cout << "Could not find a file named " << File_Name << endl ; } if(opening){ if(txtfile2.peek() == std::ifstream::traits_type::eof()) not_empty = false; // checks if file is empty basically peeks* while( not_empty == true && !txtfile2.eof() ) { //******End: asking for file name, if int_user_input is 1 ******************* //****** Start: file reading into sstream *************** dontenter = false; int month_int; int year_int; getline(txtfile2, inside_of_file); istringstream inside_of_file_line(inside_of_file); inside_of_file_line >> card_number >> month >> year_in_file; // seperated //******* End: file reading into ssteam ****************** month_int = stoi(month); year_int = stoi(year_in_file); // converting object.insertCardSorted(card_number,month_int,year_int); // start adding nodes } } } //*************************************** End: Asking for file name, if int_user_input is 1************************************** if(int_user_input == 2) // if input is 2 display list { object.displayListChronological(); } if(int_user_input == 3) // if input is 3 display list in a reverse order { object.displayListReverseChronological(); } if(int_user_input == 4) // if input is 4 search for card and print occurences { cout << "Please enter the credit card number: "; string creditcardnumber; cin >> creditcardnumber; cout << endl; object.cardSearch(creditcardnumber); } if(int_user_input == 5) // if input is 5 delete all the nodes until given month and year (included) { bool valid = true; cout << "Please enter month and year: "; string del_month, del_year; cin >> del_month >> del_year; if(del_month.find_first_not_of("1234567890") != string::npos || del_year.find_first_not_of("1234567890") != string::npos) { valid = false; } if(valid) { if(stoi(del_month) > 12 || stoi(del_month) < 0 ) valid = false; } if(valid) { object.bulkDelete(stoi(del_month),stoi(del_year)); } else { cout << "Invalid format!" << endl; } } not_empty = true; // so if user first enters creditCards3.txt as file name it keeps accepting other file names } }while(int_user_input != 6); // if input is 6 exit the loop object.deleteAll(); // Delete all pointers and return memory back to heap cout << "All the nodes have been deleted !" << endl; cout << "Terminating!!!" << endl; return 0; }
35.151163
165
0.564836
[ "object", "vector" ]
98a6ac5d0abef8d0606bdfb6d445edafbb2d5c6e
7,008
cpp
C++
problems/codeforces/1402/b-roads/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
problems/codeforces/1402/b-roads/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
problems/codeforces/1402/b-roads/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #ifdef LOCAL #include "code/formatting.hpp" #else #define debug(...) (void)0 #endif using namespace std; struct P { using T = int32_t; // points, vectors, coefs, manh -- integer/frac/double using L = int64_t; // cross, dot, dist2, norm2 -- integer/frac/double using H = __int128_t; // huge (circle predicates) -- int128/double using D = double; // dist, norm, angles -- double static constexpr bool FLOAT_POINT = is_floating_point_v<T>; T x, y; // int id = -1; P() : x(0), y(0) {} P(T x, T y) : x(x), y(y) {} auto paired() const { return make_pair(x, y); } friend bool operator==(P a, P b) { return a.x == b.x && a.y == b.y; } friend bool operator!=(P a, P b) { return !(a == b); } friend bool operator<(P a, P b) { return a.paired() < b.paired(); } friend bool operator>(P a, P b) { return a.paired() > b.paired(); } explicit operator bool() const noexcept { return x || y; } bool boxed(P min, P max) const { return min.x <= x && x <= max.x && min.y <= y && y <= max.y; } T& operator[](int i) { return *(&x + i); } T operator[](int i) const { return *(&x + i); } P operator-() const { return P(-x, -y); } P operator+() const { return P(x, y); } friend P operator+(P u, P v) { return P(u.x + v.x, u.y + v.y); } friend P operator-(P u, P v) { return P(u.x - v.x, u.y - v.y); } friend P operator*(T k, P u) { return P(u.x * k, u.y * k); } friend P operator*(P u, T k) { return P(u.x * k, u.y * k); } friend P operator/(P u, T k) { return P(u.x / k, u.y / k); } friend P& operator+=(P& u, P v) { return u = u + v; } friend P& operator-=(P& u, P v) { return u = u - v; } friend P& operator*=(P& u, T k) { return u = u * k; } friend P& operator/=(P& u, T k) { return u = u / k; } friend auto refl(P u) { return P(u.y, u.x); } friend auto conj(P u) { return P(u.x, -u.y); } // complex conjugate friend auto perp_ccw(P u) { return P(-u.y, u.x); } friend auto perp_cw(P u) { return P(u.y, -u.x); } friend auto manh(P u) { return abs(u.x) + abs(u.y); } friend auto manh(P a, P b) { return manh(a - b); } friend auto abs(P u) { return P(abs(u.x), abs(u.y)); } friend auto dot(P u, P v) { return L(u.x) * v.x + L(u.y) * v.y; } friend auto norm2(P u) { return dot(u, u); } friend auto norm(P u) { return std::sqrt(D(norm2(u))); } friend auto cross(P u, P v) { return L(u.x) * v.y - L(u.y) * v.x; } friend auto cross(P a, P b, P c) { return cross(b - a, c - a); } friend auto dist2(P a, P b) { return norm2(a - b); } friend auto dist(P a, P b) { return norm(a - b); } friend string to_string(P p) { // return '(' + to_string(p.x) + ',' + to_string(p.y) + ')'; return to_string(p.x) + ' ' + to_string(p.y); } friend ostream& operator<<(ostream& out, P p) { return out << to_string(p); } friend istream& operator>>(istream& in, P& p) { return in >> p.x >> p.y; } // The following only make sense if T is a floating point type friend auto unit(P u) { return u / norm(u); } friend auto rotate(P u, P::D rad) { return P(u.x * cos(rad) - u.y * sin(rad), u.x * sin(rad) + u.y * cos(rad)); } friend auto rotate(P u, P::D rad, P pivot) { return rotate(u - pivot, rad) + pivot; } }; int orientation(P a, P b, P c) { // +1=>a left of uv-> / -1=>a right of uv-> if constexpr (P::FLOAT_POINT) { // To return ±1 the crosses must all agree on sign and magnitude. auto va = cross(a, b, c), vb = cross(b, c, a), vc = cross(c, a, b); auto sa = (va > 0) - (va < 0), sb = (vb > 0) - (vb < 0), sc = (vc > 0) - (vc < 0); auto sum = abs(va + vb + vc), dif = max({va, vb, vc}) - min({va, vb, vc}); return sa == sb && sb == sc && dif <= 1e-5 * sum ? sa : 0; } else { auto sign = cross(a, b, c); return (sign > 0) - (sign < 0); } } struct shaft_scanner { using is_transparent = bool; static constexpr inline int INF = -1; const vector<P>& pts; const vector<int>& rank; const vector<array<int, 2>>& segments; shaft_scanner(const vector<P>& pts, const vector<int>& rank, const vector<array<int, 2>>& segments) : pts(pts), rank(rank), segments(segments) {} inline bool operator()(int i, int j) const { if (i == INF || j == INF || i == j) { return i != INF && j == INF; } auto [a, b] = segments[i]; auto [c, d] = segments[j]; if (a == c) { return cross(pts[a], pts[d], pts[b]) > 0; } else if (b == d) { return cross(pts[b], pts[a], pts[c]) > 0; } else if (rank[a] < rank[c]) { return cross(pts[a], pts[c], pts[b]) > 0; } else /* rank[a] > rank[c] */ { return cross(pts[c], pts[d], pts[a]) > 0; } } inline bool operator()(const P& p, int i) const { if (i == INF) { return true; } auto [a, b] = segments[i]; return cross(pts[a], pts[b], p) > 0; // if P lies on the segment, return false } inline bool operator()(int i, const P& p) const { if (i == INF) { return false; } auto [a, b] = segments[i]; return cross(pts[a], pts[b], p) < 0; // if P lies on the segment, return false } }; int main() { ios::sync_with_stdio(false), cin.tie(nullptr); int N; cin >> N; int S = N; N = 2 * N; vector<P> pts(N); for (int i = 0; i < N; i++) { cin >> pts[i]; } vector<int> index(N); iota(begin(index), end(index), 0); sort(begin(index), end(index), [&](int i, int j) { return pts[i] < pts[j]; }); vector<int> rank(N); for (int i = 0; i < N; i++) { rank[index[i]] = i; } vector<int> head(N, -1), tail(N, -1); vector<array<int, 2>> segments(S); for (int s = 0; s < S; s++) { segments[s] = {2 * s, 2 * s + 1}; } for (int s = 0; s < S; s++) { auto& [u, v] = segments[s]; if (rank[u] > rank[v]) { swap(u, v); } head[u] = s, tail[v] = s; } constexpr int INF = shaft_scanner::INF; map<int, int, shaft_scanner> shafts(shaft_scanner(pts, rank, segments)); shafts.emplace(INF, -1); vector<pair<int, int>> added; for (int i = 0; i < N; i++) { int u = index[i]; if (tail[u] != -1) { int s = tail[u]; shafts.erase(s); shafts.lower_bound(pts[u])->second = u; } else { auto shaft = shafts.lower_bound(pts[u]); if (shaft->second != -1) { added.push_back({shaft->second, u}); } shaft->second = u; } if (head[u] != -1) { int s = head[u]; shafts.emplace(s, u); } } for (auto [u, v] : added) { cout << pts[u] << ' ' << pts[v] << '\n'; } return 0; }
33.5311
90
0.495006
[ "vector" ]
0b08243d84c132b8424b27638e9c620fd1e0429d
5,649
hpp
C++
include/System/Resources/ResourceLocator.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/System/Resources/ResourceLocator.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/System/Resources/ResourceLocator.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Resources namespace System::Resources { // Forward declaring type: ResourceTypeCode struct ResourceTypeCode; } // Completed forward declares // Begin il2cpp-utils forward declares struct Il2CppObject; // Completed il2cpp-utils forward declares // Type namespace: System.Resources namespace System::Resources { // Forward declaring type: ResourceLocator struct ResourceLocator; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::System::Resources::ResourceLocator, "System.Resources", "ResourceLocator"); // Type namespace: System.Resources namespace System::Resources { // Size: 0xC #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: System.Resources.ResourceLocator // [TokenAttribute] Offset: FFFFFFFF struct ResourceLocator/*, public ::System::ValueType*/ { public: public: // System.Object _value // Size: 0x8 // Offset: 0x0 ::Il2CppObject* value; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); // System.Int32 _dataPos // Size: 0x4 // Offset: 0x8 int dataPos; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating value type constructor for type: ResourceLocator constexpr ResourceLocator(::Il2CppObject* value_ = {}, int dataPos_ = {}) noexcept : value{value_}, dataPos{dataPos_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Get instance field reference: System.Object _value ::Il2CppObject*& dyn__value(); // Get instance field reference: System.Int32 _dataPos int& dyn__dataPos(); // System.Int32 get_DataPosition() // Offset: 0x1D41AFC int get_DataPosition(); // System.Object get_Value() // Offset: 0x1D41B04 ::Il2CppObject* get_Value(); // System.Void set_Value(System.Object value) // Offset: 0x1D41B0C void set_Value(::Il2CppObject* value); // System.Void .ctor(System.Int32 dataPos, System.Object value) // Offset: 0x1D41AF0 ResourceLocator(int dataPos, ::Il2CppObject* value); // static System.Boolean CanCache(System.Resources.ResourceTypeCode value) // Offset: 0x1D41B14 static bool CanCache(::System::Resources::ResourceTypeCode value); }; // System.Resources.ResourceLocator #pragma pack(pop) static check_size<sizeof(ResourceLocator), 8 + sizeof(int)> __System_Resources_ResourceLocatorSizeCheck; static_assert(sizeof(ResourceLocator) == 0xC); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Resources::ResourceLocator::get_DataPosition // Il2CppName: get_DataPosition template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Resources::ResourceLocator::*)()>(&System::Resources::ResourceLocator::get_DataPosition)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Resources::ResourceLocator), "get_DataPosition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Resources::ResourceLocator::get_Value // Il2CppName: get_Value template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Resources::ResourceLocator::*)()>(&System::Resources::ResourceLocator::get_Value)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Resources::ResourceLocator), "get_Value", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Resources::ResourceLocator::set_Value // Il2CppName: set_Value template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Resources::ResourceLocator::*)(::Il2CppObject*)>(&System::Resources::ResourceLocator::set_Value)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Resources::ResourceLocator), "set_Value", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::Resources::ResourceLocator::ResourceLocator // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Resources::ResourceLocator::CanCache // Il2CppName: CanCache template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Resources::ResourceTypeCode)>(&System::Resources::ResourceLocator::CanCache)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System.Resources", "ResourceTypeCode")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Resources::ResourceLocator), "CanCache", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } };
47.470588
183
0.714994
[ "object", "vector" ]
0b0b23d1ed3291c17c1aba061f231ae8129a8dcb
2,395
hpp
C++
user/WBC_Controller/WBC_States/WBICTrot/WBICTrotTest.hpp
NmBoyd/Cheetah-Software
05e416fb26f968300826f0deb0953be9afb22bfe
[ "MIT" ]
1
2020-05-24T23:55:27.000Z
2020-05-24T23:55:27.000Z
user/WBC_Controller/WBC_States/WBICTrot/WBICTrotTest.hpp
WatsonZhouAnda/Cheetah-Software
05e416fb26f968300826f0deb0953be9afb22bfe
[ "MIT" ]
null
null
null
user/WBC_Controller/WBC_States/WBICTrot/WBICTrotTest.hpp
WatsonZhouAnda/Cheetah-Software
05e416fb26f968300826f0deb0953be9afb22bfe
[ "MIT" ]
1
2020-05-24T19:52:56.000Z
2020-05-24T19:52:56.000Z
#ifndef WBIC_TROT_TEST_Cheetah #define WBIC_TROT_TEST_Cheetah #include <Dynamics/Quadruped.h> #include <Utilities/filters.h> #include <WBC_States/Test.hpp> #include <lcm-cpp.hpp> #include <thread> #include "vision_data_t.hpp" #include "wbc_test_data_t.hpp" template <typename T> class StateProvider; template <typename T> class Path; namespace WBICTrotPhase { constexpr int lift_up = 0; constexpr int full_contact_1 = 1; constexpr int frhl_swing_start_trans = 2; constexpr int frhl_swing = 3; constexpr int frhl_swing_end_trans = 4; constexpr int full_contact_2 = 5; constexpr int flhr_swing_start_trans = 6; constexpr int flhr_swing = 7; constexpr int flhr_swing_end_trans = 8; constexpr int NUM_TROT_PHASE = 9; }; // namespace WBICTrotPhase template <typename T> class WBICTrotTest : public Test<T> { public: WBICTrotTest(FloatingBaseModel<T>*, const RobotType&, float _dt); virtual ~WBICTrotTest(); DVec<T> _jpos_des_pre; DVec<T> _des_jpos; DVec<T> _des_jvel; DVec<T> _des_jacc; Vec3<T> _body_pos; Vec3<T> _body_vel; Vec3<T> _body_acc; Vec3<T> _body_ori_rpy; // This does not have any frame meaning. just derivation of rpy Vec3<T> _body_ang_vel; Vec3<T> _front_foot_loc; Vec3<T> _hind_foot_loc; std::string _folder_name; void handleVisionLCM(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const vision_data_t* msg); void visionLCMThread(); protected: bool _b_remote_ctrl; Path<T>* _path; Vec3<T> _vision_loc; // (x, y, yaw) lcm::LCM _visionLCM; std::thread _visionLCMThread; bool _b_loc_update; std::vector<filter<T>*> _filtered_input_vel; Vec3<T> _input_vel; T _target_body_height; virtual void _UpdateTestOneStep(); virtual void _TestInitialization(); virtual int _NextPhase(const int& phase); virtual void _UpdateExtraData(Cheetah_Extra_Data<T>* ext_data); void _SettingParameter(); Controller<T>* body_up_ctrl_; Controller<T>* body_ctrl_; // Front Right and Hind Left leg swing Controller<T>* frhl_swing_start_trans_ctrl_; Controller<T>* frhl_swing_ctrl_; Controller<T>* frhl_swing_end_trans_ctrl_; // Front Left and Hind Right leg swing Controller<T>* flhr_swing_start_trans_ctrl_; Controller<T>* flhr_swing_ctrl_; Controller<T>* flhr_swing_end_trans_ctrl_; StateProvider<T>* _sp; lcm::LCM _wbcLCM; wbc_test_data_t _wbc_data_lcm; }; #endif
24.191919
79
0.74739
[ "vector" ]
0b0cf191d94dea36d143e4c678118936ca735bc4
4,241
cc
C++
Chapter06/sharkml/sharkml-dr.cc
bdonkey/Hands-On-Machine-Learning-with-CPP
d2b17abeb48db3d45369fdb1be806682ab9819ed
[ "MIT" ]
201
2020-05-13T12:50:50.000Z
2022-03-27T20:56:11.000Z
Chapter06/sharkml/sharkml-dr.cc
bdonkey/Hands-On-Machine-Learning-with-CPP
d2b17abeb48db3d45369fdb1be806682ab9819ed
[ "MIT" ]
1
2021-05-12T10:01:40.000Z
2021-05-14T19:35:05.000Z
Chapter06/sharkml/sharkml-dr.cc
bdonkey/Hands-On-Machine-Learning-with-CPP
d2b17abeb48db3d45369fdb1be806682ab9819ed
[ "MIT" ]
63
2020-06-05T15:03:39.000Z
2022-02-22T02:07:09.000Z
#include <plot.h> #define SHARK_CV_VERBOSE 1 #include <shark/Algorithms/Trainers/LDA.h> #include <shark/Algorithms/Trainers/PCA.h> #include <shark/Data/Csv.h> #include <shark/Data/Dataset.h> #include <shark/Models/Kernels/GaussianRbfKernel.h> #include <experimental/filesystem> #include <iostream> #include <unordered_map> namespace fs = std::experimental::filesystem; using namespace shark; const std::vector<std::string> colors{"black", "red", "blue", "green", "cyan"}; using DataType = double; using Coords = std::vector<DataType>; using PointCoords = std::pair<Coords, Coords>; using Clusters = std::unordered_map<size_t, PointCoords>; const std::string data_file_name{"swissroll.dat"}; const std::string labels_file_name{"swissroll_labels.dat"}; void PlotClusters(const Clusters& clusters, const std::string& name, const std::string& file_name) { plotcpp::Plot plt(true); // plt.SetTerminal("qt"); plt.SetTerminal("png"); plt.SetOutput(file_name); plt.SetTitle(name); plt.SetXLabel("x"); plt.SetYLabel("y"); // plt.SetAutoscale(); plt.GnuplotCommand("set size square"); plt.GnuplotCommand("set grid"); auto draw_state = plt.StartDraw2D<Coords::const_iterator>(); for (auto& cluster : clusters) { std::stringstream params; params << "lc rgb '" << colors[cluster.first] << "' pt 7"; plt.AddDrawing(draw_state, plotcpp::Points( cluster.second.first.begin(), cluster.second.first.end(), cluster.second.second.begin(), std::to_string(cluster.first) + " cls", params.str())); } plt.EndDraw2D(draw_state); plt.Flush(); } void PCAReduction(const UnlabeledData<RealVector>& data, const UnlabeledData<RealVector>& lables, size_t target_dim) { PCA pca(data); LinearModel<> encoder; pca.encoder(encoder, target_dim); auto new_data = encoder(data); Clusters clusters; for (size_t i = 0; i < new_data.numberOfElements(); ++i) { auto x = new_data.element(i)[0]; auto y = new_data.element(i)[1]; auto label = static_cast<int>(lables.element(i)[0]); clusters[label].first.push_back(x); clusters[label].second.push_back(y); } PlotClusters(clusters, "PCA", "pca-sharkml.png"); } void LDAReduction(const UnlabeledData<RealVector>& data, const UnlabeledData<RealVector>& labels, size_t target_dim) { LinearClassifier<> encoder; LDA lda; LabeledData<RealVector, unsigned int> dataset( labels.numberOfElements(), InputLabelPair<RealVector, unsigned int>( RealVector(data.element(0).size()), 0)); for (size_t i = 0; i < labels.numberOfElements(); ++i) { // labels should start from 0 dataset.element(i).label = static_cast<unsigned int>(labels.element(i)[0]) - 1; dataset.element(i).input = data.element(i); } lda.train(encoder, dataset); // project data auto new_labels = encoder(data); auto dc = encoder.decisionFunction(); auto new_data = dc(data); Clusters clusters; for (size_t i = 0; i < new_data.numberOfElements(); ++i) { auto l = new_labels.element(i); auto x = new_data.element(i)[l]; auto y = new_data.element(i)[l]; auto label = static_cast<int>(labels.element(i)[0]); clusters[label].first.push_back(x); clusters[label].second.push_back(y); } PlotClusters(clusters, "LDA", "lda-sharkml.png"); } int main(int argc, char** argv) { if (argc > 1) { auto data_dir = fs::path(argv[1]); auto data_file_path = data_dir / data_file_name; auto labels_file_path = data_dir / labels_file_name; if (fs::exists(data_file_path) && fs::exists(labels_file_path)) { UnlabeledData<RealVector> data; importCSV(data, data_file_path, ' '); UnlabeledData<RealVector> labels; importCSV(labels, labels_file_path); int target_dim = 2; PCAReduction(data, labels, target_dim); LDAReduction(data, labels, target_dim); } else { std::cerr << "Dataset file " << data_file_path << " missed\n"; } } else { std::cerr << "Please provider path to the datasets folder\n"; } return 0; }
30.292857
80
0.651026
[ "vector" ]
0b0d8f39d1655579e0bf7f5f3c83fddf4c9f62e2
10,199
cpp
C++
dnx-dev/src/dnx/dnx.cpp
cemoses/aspnet
b67c6a9c821627dcbe67ac814e625cfb726dc735
[ "Apache-2.0" ]
null
null
null
dnx-dev/src/dnx/dnx.cpp
cemoses/aspnet
b67c6a9c821627dcbe67ac814e625cfb726dc735
[ "Apache-2.0" ]
null
null
null
dnx-dev/src/dnx/dnx.cpp
cemoses/aspnet
b67c6a9c821627dcbe67ac814e625cfb726dc735
[ "Apache-2.0" ]
null
null
null
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #include "stdafx.h" #include <vector> #include "pal.h" #include "utils.h" #include "app_main.h" bool strings_equal_ignore_case(const dnx::char_t* s1, const dnx::char_t* s2) { #if defined(_WIN32) return _wcsicmp(s1, s2) == 0; #else return strcasecmp(s1, s2) == 0; #endif } bool string_ends_with_ignore_case(const dnx::char_t* s, const dnx::char_t* suffix) { auto str_len = x_strlen(s); auto suffix_len = x_strlen(suffix); if (suffix_len > str_len) { return false; } return strings_equal_ignore_case(s + str_len - suffix_len, suffix); } int split_path(const dnx::char_t* path) { for (auto i = static_cast<int>(x_strlen(path)) - 1; i >= 0; i--) { if (path[i] == _X('\\') || path[i] == _X('/')) { return i; } } return -1; } const dnx::char_t* allocate_and_copy(const dnx::char_t* value, size_t count) { auto buff_size = count + 1; auto buffer = new dnx::char_t[buff_size]; #if defined(_WIN32) wcsncpy_s(buffer, buff_size, value, count); #else strncpy(buffer, value, count); buffer[count] = '\0'; #endif return buffer; } const dnx::char_t* allocate_and_copy(const dnx::char_t* value) { return allocate_and_copy(value, x_strlen(value)); } int BootstrapperOptionValueNum(const dnx::char_t* pszCandidate) { if (strings_equal_ignore_case(pszCandidate, _X("--appbase")) || strings_equal_ignore_case(pszCandidate, _X("--lib")) || strings_equal_ignore_case(pszCandidate, _X("--packages")) || strings_equal_ignore_case(pszCandidate, _X("--configuration")) || strings_equal_ignore_case(pszCandidate, _X("--framework")) || strings_equal_ignore_case(pszCandidate, _X("--port")) || strings_equal_ignore_case(pszCandidate, _X("--project")) || strings_equal_ignore_case(pszCandidate, _X("-p"))) { return 1; } if (strings_equal_ignore_case(pszCandidate, _X("--watch")) || strings_equal_ignore_case(pszCandidate, _X("--debug")) || strings_equal_ignore_case(pszCandidate, _X("--help")) || strings_equal_ignore_case(pszCandidate, _X("-h")) || strings_equal_ignore_case(pszCandidate, _X("-?")) || strings_equal_ignore_case(pszCandidate, _X("--version"))) { return 0; } // It isn't a bootstrapper option return -1; } size_t FindOption(size_t argc, dnx::char_t**argv, const dnx::char_t* optionName) { for (size_t i = 0; i < argc; i++) { if (strings_equal_ignore_case(argv[i], optionName)) { return i; } auto option_num_args = BootstrapperOptionValueNum(argv[i]); if (option_num_args < 0) { return i; } i += option_num_args; } return argc; } dnx::char_t* GetOptionValue(size_t argc, dnx::char_t* argv[], const dnx::char_t* optionName) { auto index = FindOption(argc, argv, optionName); // no parameters or '--{optionName}' is the last value in the array or `--{optionName}` not found if (argc == 0 || index >= argc - 1 || argv[index][0] != _X('-')) { return nullptr; } return argv[index + 1]; } void AppendAppbaseFromFile(const dnx::char_t* path, std::vector<const dnx::char_t*>& expanded_args) { auto split_idx = split_path(path); expanded_args.push_back(allocate_and_copy(_X("--appbase"))); if (split_idx < 0) { expanded_args.push_back(allocate_and_copy(_X("."))); } else { expanded_args.push_back(allocate_and_copy(path, split_idx + 1)); } } void ExpandProject(const dnx::char_t* project_path, std::vector<const dnx::char_t*>& expanded_args) { auto split_idx = split_path(project_path); // note that we split the path first and check the file name to handle paths like c:\MyApp\my_project.json // (`split_idx + 1` works fine since `split_path` returns -1 if it does not find `\` or '/') if (strings_equal_ignore_case(project_path + split_idx + 1, _X("project.json"))) { // "dnx /path/project.json run" --> "dnx --appbase /path/ Microsoft.Dnx.ApplicationHost run" AppendAppbaseFromFile(project_path, expanded_args); expanded_args.push_back(allocate_and_copy(_X("Microsoft.Dnx.ApplicationHost"))); return; } expanded_args.push_back(allocate_and_copy(_X("--appbase"))); expanded_args.push_back(allocate_and_copy(project_path)); expanded_args.push_back(allocate_and_copy(_X("Microsoft.Dnx.ApplicationHost"))); } void ExpandNonHostArgument(const dnx::char_t* value, std::vector<const dnx::char_t*>& expanded_args) { if (string_ends_with_ignore_case(value, _X(".dll")) || string_ends_with_ignore_case(value, _X(".exe"))) { // "dnx /path/App.dll arg1" --> "dnx --appbase /path/ /path/App.dll arg1" // "dnx /path/App.exe arg1" --> "dnx --appbase /path/ /path/App.exe arg1" // "dnx App.exe arg1" --> "dnx --appbase . App.exe arg1" AppendAppbaseFromFile(value, expanded_args); expanded_args.push_back(allocate_and_copy(value)); return; } // "dnx run" --> "dnx --appbase . Microsoft.Dnx.ApplicationHost run" expanded_args.push_back(allocate_and_copy(_X("--appbase"))); expanded_args.push_back(allocate_and_copy(_X("."))); expanded_args.push_back(allocate_and_copy(_X("Microsoft.Dnx.ApplicationHost"))); expanded_args.push_back(allocate_and_copy(value)); } bool ExpandCommandLineArguments(size_t nArgc, dnx::char_t** ppszArgv, size_t& nExpandedArgc, dnx::char_t**& ppszExpandedArgv) { auto param_idx = FindOption(nArgc, ppszArgv, _X("--appbase")); // either no non-bootstrapper option found or --appbase was found - in either case expansion is not needed if (param_idx >= nArgc || ppszArgv[param_idx][0] == _X('-')) { return false; } bool arg_expanded = false; std::vector<const dnx::char_t*> expanded_args_temp; for (size_t source_idx = 0; source_idx < nArgc; source_idx++) { if (!arg_expanded) { if (strings_equal_ignore_case(_X("-p"), ppszArgv[source_idx]) || (strings_equal_ignore_case(_X("--project"), ppszArgv[source_idx]))) { // Note that ++source_idx is safe here since if we had a trailing -p/--project we would have exited // before entering the loop because we wouldn't have found any non host option ExpandProject(ppszArgv[++source_idx], expanded_args_temp); arg_expanded = true; } else if (source_idx == param_idx) { ExpandNonHostArgument(ppszArgv[source_idx], expanded_args_temp); arg_expanded = true; } else { expanded_args_temp.push_back(allocate_and_copy(ppszArgv[source_idx])); } } else { expanded_args_temp.push_back(allocate_and_copy(ppszArgv[source_idx])); } } nExpandedArgc = expanded_args_temp.size(); ppszExpandedArgv = new dnx::char_t*[nExpandedArgc]; for (size_t i = 0; i < nExpandedArgc; i++) { ppszExpandedArgv[i] = const_cast<dnx::char_t*>(expanded_args_temp[i]); } return true; } void FreeExpandedCommandLineArguments(size_t nArgc, dnx::char_t** ppszArgv) { for (size_t i = 0; i < nArgc; ++i) { delete[] ppszArgv[i]; } delete[] ppszArgv; } bool GetApplicationBase(const dnx::xstring_t& currentDirectory, size_t argc, dnx::char_t* argv[], /*out*/ dnx::char_t* fullAppBasePath) { dnx::char_t buffer[MAX_PATH]; const dnx::char_t* appBase = GetOptionValue(argc, argv, _X("--appbase")); // Note: We use application base from DNX_APPBASE environment variable only if --appbase // did not exist. if neither --appBase nor DNX_APPBASE existed we use current directory if (!appBase) { appBase = GetAppBasePathFromEnvironment(buffer) ? buffer : currentDirectory.c_str(); } // Prevent coreclr native bootstrapper from failing with relative appbase return GetFullPath(appBase, fullAppBasePath) != 0; } int CallApplicationProcessMain(size_t argc, dnx::char_t* argv[], dnx::trace_writer& trace_writer) { // Set the DNX_CONOSLE_HOST flag which will print exceptions to stderr instead of throwing SetConsoleHost(); auto currentDirectory = GetNativeBootstrapperDirectory(); // Set the DEFAULT_LIB environment variable to be the same directory as the exe SetEnvironmentVariable(_X("DNX_DEFAULT_LIB"), currentDirectory.c_str()); // Set the FRAMEWORK environment variable to the value provided on the command line // (it needs to be available BEFORE the application main is called) auto frameworkName = GetOptionValue(argc, argv, _X("--framework")); if (frameworkName) { SetEnvironmentVariable(_X("DNX_FRAMEWORK"), frameworkName); } CALL_APPLICATION_MAIN_DATA data = { 0 }; data.argc = static_cast<int>(argc); data.argv = const_cast<const dnx::char_t**>(argv); dnx::char_t appBaseBuffer[MAX_PATH]; if (!GetApplicationBase(currentDirectory, argc, argv, appBaseBuffer)) { return 1; } data.applicationBase = appBaseBuffer; try { const dnx::char_t* hostModuleName = #if defined(CORECLR_WIN) #if defined(ONECORE) || defined(ARM) _X("dnx.onecore.coreclr.dll"); #else _X("dnx.win32.coreclr.dll"); #endif #elif defined(CORECLR_DARWIN) _X("dnx.coreclr.dylib"); #elif defined(CORECLR_LINUX) _X("dnx.coreclr.so"); #else _X("dnx.clr.dll"); SetEnvironmentVariable(_X("DNX_IS_WINDOWS"), _X("1")); #endif // Note: need to keep as ASCII as GetProcAddress function takes ASCII params return CallApplicationMain(hostModuleName, "CallApplicationMain", &data, trace_writer); } catch (const std::exception& ex) { xout << dnx::utils::to_xstring_t(ex.what()) << std::endl; return 1; } }
32.794212
144
0.651044
[ "vector" ]
0b0e53686c8536bda7252cffac506b41a6c3851d
7,133
cpp
C++
src/utils/fieldinfo/main.cpp
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
src/utils/fieldinfo/main.cpp
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
src/utils/fieldinfo/main.cpp
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
#include <grid.h> #include <field.h> #include <elem.h> #include <diffreader.h> #include <diffsimu.h> #include <stdio.h> #include <vector> #include <geom.h> #include <math.h> #include <stdlib.h> #include <string.h> void printHelp() { printf("usage: fieldinfo [-g grid_name] [-gn grid_nr] [-P px py pz] [-L L1x L1y L1z L2x L2y L2z ndL] \n"); printf(" -l : list fields in file\n"); printf(" -gn grid_name : name of file with grid definition.\n"); printf(" -g grid_nr : index of grid inside the file to be read (first index = 1)\n"); printf(" -P px py pz : find element and field value in point px, py, pz\n"); printf(" -L L1x.... ndL : find elements and field values in ndL+1 points located on the line\n"); printf(" between points L1 and L2\n"); printf(" -s px py pz r np : calculate average value unside sphere with center px,py,pz, and radius r,\n"); printf(" and number of points on radius np (satisfactory results are for np=3)\n"); printf(" -f fldfname fc f1 f2 .. : read fields from specified indexes in file. fc - number of indexes\n"); printf(" -mmax iSub N : show N top most maximum field values in subdomain iSub. \n"); } bool calc_val( Field * f, Grid * g, Elem * e, double *v, double P[3]) { vector<double> vals(4); if ( g->_nodes.size() == f->size() ) { for (int j=0; j<4; j++) { vals[j] = f->val(e->_nodes[j] - 1); } *v = e->calcValPtv( P, vals); return true; } else { if (g->_elems.size() == f->size() ) { *v = f->val( e->nr - 1); return true; } else { printf("Error: Field size does not match node nor element vectors size.\n"); return false; } } return false; } void print_val(Grid *g, vector<Field*> fields,double P[3]) { Elem *e; e = g->getElemPtv( P ); //printf("vals = %g,%g,%g,%g\n",vals[0], vals[1], vals[2], vals[3]); double v; if (e == 0) printf("Unable to locate element for point P (%g,%g,%g)\n", P[0], P[1], P[2]); else { //printf("Point P (%g,%g,%g) is located in elem: %d\n", P[0], P[1], P[2],e->nr); printf("("); for (int fi = 0; fi < fields.size(); fi++){ if (calc_val(fields[fi],g,e, &v, P)) { if (fi>0) printf(", "); printf("%g", v ); } } printf(")\n"); } } double get_val(Grid *g, Field* f,double P[3], double *v) { Elem *e; e = g->getElemPtv( P ); if (e == 0) printf("Unable to locate element for point P (%g,%g,%g)\n", P[0], P[1], P[2]); else { return calc_val(f,g,e,v,P); } return false; } void csphere( Grid * g, vector<Field*> f, double p[3], double r, int np) { double sp; int ix,iy,iz; double pp[3]; double v; double v_mod; double v_mod_sum = 0; vector<int> ic( f.size() ); for (int i=0; i<ic.size(); i++) ic[i] = 0; vector<double> sum( f.size() ); for (int i=0; i<sum.size(); i++) sum[i] = 0; sp = 1 / (double) (2*np-2); for (ix=0;ix<(np*2 -1);ix++){ for (iy=0;iy<(np*2 -1);iy++){ for (iz=0;iz<(np*2 -1);iz++) { pp[0] = -1 + (double) ix * sp; pp[1] = -1 + (double) iy * sp; pp[2] = -1 + (double) iz * sp; //printf("pp = (%lf, %lf, %lf)\n",pp[0],pp[1],pp[2]); if (LENGTH(pp) <= 1) { MULT(pp,pp,r); ADD(pp,p,pp); //print_val(g,f,pp); v_mod = 0; for (int fi=0;fi<f.size();fi++) { if (get_val(g,f[fi],pp, &v) == true) { sum[fi] += v; v_mod += v*v; ic[fi]++; } } v_mod_sum += sqrt(v_mod); } } } } printf("Average value in sphere (collected from %d points): ", ic[0]); for (int i=0; i<sum.size(); i++) if (ic[i] != 0) { sum[i] /= ic[i]; if (i>0) printf(", "); printf("%lf",sum[i]); } if (ic[0] != 0) { printf(": |f|=%lf\n",v_mod_sum/ic[0]); } printf("\n"); } struct TValElem { double val; int ie; int is; }; int TVE_cmp( const void * v1, const void * v2 ) { TValElem *ve1, *ve2; ve1 = (TValElem*) v1; ve2 = (TValElem*) v2; if (ve1->val < ve2->val) return 1; else if (ve1->val > ve2->val) return -1; else return 0; } void showmax( Grid * g, vector<Field*> f, int iSub, int n ) { int i,j; TValElem * vv; double v; vv = new TValElem[ f[0]->size() ]; printf("Allocated... %d\n", f[0]->size() ); for (i=0; i< f[0]->size(); i++) { v = 0; for (j=0;j<f.size();j++) v += f[j]->val(i)*f[j]->val(i); vv[i].val = sqrt(v); vv[i].ie = i+1; } qsort( vv, f[0]->size(), sizeof( TValElem ), TVE_cmp ); j = 0; for (i=0; i<f[0]->size(); i++) { if (j == n) break; if ((iSub == 0) || ((g->_elems[ vv[i].ie ])->subdomain() == iSub)) { j++; printf("Val[%d] = %g, Elem = %d\n", j, vv[i].val, vv[i].ie); } } delete vv; } int main(int argc, char *argv[]) { int i; DpFieldFileInfo dffi; DpFieldReader dfr; vector<Field*> fields; char *fname; char *new_fname; bool bPoint = false; bool bLine = false; double P[3]; double L1[3], L2[3]; int ndL; int ignr = 1; char *gfname = 0; DpGridFileInfo dgfi; DpReader dr; Grid *g; bool bSphere = false; double P_sph[3], r_sph; int np_sph; bool bList = false; char * ffname; bool bMax = false; int iMaxSub = 0; int iMaxN = 0; printf("before\n"); DiffSimu smgr( argc, argv ); printf("after\n"); if (argc < 2) { printHelp(); exit(-1); } i = 1; while (i<argc) { if (strcmp("-l",argv[i]) == 0) { bList = true; ffname = argv[++i]; } if (strcmp("-P", argv[i]) == 0) { bPoint = true; P[0] = atof( argv[++i] ); P[1] = atof( argv[++i] ); P[2] = atof( argv[++i] ); } if (strcmp("-L",argv[i]) == 0) { bLine = true; L1[0] = atof( argv[++i] ); L1[1] = atof( argv[++i] ); L1[2] = atof( argv[++i] ); L2[0] = atof( argv[++i] ); L2[1] = atof( argv[++i] ); L2[2] = atof( argv[++i] ); ndL = atoi( argv[++i] ); } if (strcmp("-s", argv[i]) == 0) { bSphere = true; P_sph[0] = atof( argv[++i] ); P_sph[1] = atof( argv[++i] ); P_sph[2] = atof( argv[++i] ); r_sph = atof( argv[++i] ); np_sph = atoi( argv[++i] ); } if (strcmp("-mmax", argv[i]) == 0) { bMax = true; iMaxSub = atoi( argv[++i] ); iMaxN = atoi( argv[++i] ); } i++; } if (bList) { printf("before\n"); dffi.ReadFromFile( ffname ); printf("after\n"); dffi.debug(); } if (bPoint) { Elem * e; g = smgr.getGrid(); vector<Field *> fields; fields = smgr.getFields(); print_val(g,fields,P); } if (bLine) { Elem * e; g= smgr.getGrid(); g->prepareElemPtv(9); vector<Field *> fields; fields = smgr.getFields(); for (i=0; i <= ndL; i++) { P[0] = L1[0] + (L2[0] - L1[0]) * (i/(double)ndL); P[1] = L1[1] + (L2[1] - L1[1]) * (i/(double)ndL); P[2] = L1[2] + (L2[2] - L1[2]) * (i/(double)ndL); print_val(g,fields,P); } } if (bSphere) { smgr.getGrid()->prepareElemPtv(9); csphere(smgr.getGrid(), smgr.getFields(), P_sph, r_sph, np_sph ); } if (bMax) { showmax( smgr.getGrid(), smgr.getFields(), iMaxSub, iMaxN ); } return(0); }
21.813456
112
0.512407
[ "vector" ]
0b13a1847a3ac3f5d09230d43d7ece17d6d85be1
1,745
cpp
C++
test/table/tuple_test.cpp
gigimushroom/DatabaseBackendEngine
9cb22617a8de14ea6e6136614e6d91842aa06984
[ "MIT" ]
19
2018-10-14T08:16:20.000Z
2022-01-17T11:40:05.000Z
test/table/tuple_test.cpp
YiYeHuang/DatabaseBackendEngine
9cb22617a8de14ea6e6136614e6d91842aa06984
[ "MIT" ]
9
2018-09-03T01:09:57.000Z
2018-10-05T19:20:26.000Z
test/table/tuple_test.cpp
YiYeHuang/DatabaseBackendEngine
9cb22617a8de14ea6e6136614e6d91842aa06984
[ "MIT" ]
5
2018-09-24T05:14:12.000Z
2020-06-30T00:36:09.000Z
/** * tuple_test.cpp */ #include <algorithm> #include <cstdio> #include <iostream> #include <string> #include <vector> #include "buffer/buffer_pool_manager.h" #include "logging/common.h" #include "table/table_heap.h" #include "table/tuple.h" #include "vtable/virtual_table.h" #include "gtest/gtest.h" namespace cmudb { TEST(TupleTest, TableHeapTest) { // test1: parse create sql statement std::string createStmt = "a varchar, b smallint, c bigint, d bool, e varchar(16)"; Schema *schema = ParseCreateStatement(createStmt); Tuple tuple = ConstructTuple(schema); // create transaction Transaction *transaction = new Transaction(0); DiskManager *disk_manager = new DiskManager("test.db"); BufferPoolManager *buffer_pool_manager = new BufferPoolManager(50, disk_manager); LockManager *lock_manager = new LockManager(true); LogManager *log_manager = new LogManager(disk_manager); TableHeap *table = new TableHeap(buffer_pool_manager, lock_manager, log_manager, transaction); RID rid; std::vector<RID> rid_v; for (int i = 0; i < 5000; ++i) { table->InsertTuple(tuple, rid, transaction); // std::cout << rid << '\n'; rid_v.push_back(rid); } TableIterator itr = table->begin(transaction); while (itr != table->end()) { // std::cout << itr->ToString(schema) << std::endl; ++itr; } // int i = 0; std::random_shuffle(rid_v.begin(), rid_v.end()); for (auto rid : rid_v) { // std::cout << i++ << std::endl; assert(table->MarkDelete(rid, transaction) == 1); } remove("test.db"); // remove db file remove("test.log"); delete schema; delete table; delete buffer_pool_manager; delete disk_manager; } } // namespace cmudb
26.846154
69
0.667049
[ "vector" ]
0b19973de6299fef600571733fe1f9d7285fda35
12,683
cpp
C++
src/BabylonImGui/src/inspector/components/actiontabs/tabs/property_grid_tab_component.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
null
null
null
src/BabylonImGui/src/inspector/components/actiontabs/tabs/property_grid_tab_component.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
null
null
null
src/BabylonImGui/src/inspector/components/actiontabs/tabs/property_grid_tab_component.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
null
null
null
#include <babylon/inspector/components/actiontabs/tabs/property_grid_tab_component.h> #include <imgui.h> #include <babylon/bones/skeleton.h> #include <babylon/engines/scene.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/cameras/arc_rotate_camera_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/cameras/free_camera_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/lights/directional_light_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/lights/hemispheric_light_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/lights/point_light_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/lights/spot_light_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/materials/background_material_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/materials/material_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/materials/multi_material_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/materials/pbr_material_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/materials/pbr_metallic_roughness_material_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/materials/pbr_specular_glossiness_material_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/materials/standard_material_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/materials/texture_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/meshes/bone_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/meshes/mesh_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/meshes/skeleton_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/meshes/transform_node_property_grid_component.h> #include <babylon/inspector/components/actiontabs/tabs/propertygrids/scene_property_grid_component.h> #include <babylon/lights/directional_light.h> #include <babylon/lights/hemispheric_light.h> #include <babylon/lights/point_light.h> #include <babylon/lights/spot_light.h> #include <babylon/materials/background/background_material.h> #include <babylon/materials/material.h> #include <babylon/materials/multi_material.h> #include <babylon/materials/pbr/pbr_material.h> #include <babylon/materials/pbr/pbr_metallic_roughness_material.h> #include <babylon/materials/pbr/pbr_specular_glossiness_material.h> #include <babylon/materials/standard_material.h> #include <babylon/meshes/mesh.h> namespace BABYLON { PropertyGridTabComponent::PropertyGridTabComponent( const IPaneComponentProps& iProps) : PaneComponent{iProps}, _scenePropertyGridComponent{nullptr} { componentWillMount(); } PropertyGridTabComponent::~PropertyGridTabComponent() { componentWillUnmount(); } void PropertyGridTabComponent::componentWillMount() { IScenePropertyGridComponentProps sceneProps; sceneProps.scene = props.scene; _scenePropertyGridComponent = std::make_unique<ScenePropertyGridComponent>(sceneProps); } void PropertyGridTabComponent::componentWillUnmount() { } void PropertyGridTabComponent::render() { const auto& entity = props.selectedEntity; if (!entity && (!entity->uniqueId || entity->name.empty())) { // Info message ImGui::TextWrapped("%s", "Please select an entity in the scene explorer."); return; } auto entityId = entity->uniqueId.value_or(0ull); auto& entityName = entity->name; if (entity->type == EntityType::Scene) { if (_scenePropertyGridComponent) { _scenePropertyGridComponent->render(); } return; } if (entity->type == EntityType::Mesh) { auto& mesh = _entityCache.mesh; if (!mesh || mesh->uniqueId != entityId) { mesh = std::dynamic_pointer_cast<Mesh>( props.scene->getMeshByUniqueID(entityId)); _reservedDataStore.mesh[mesh->uniqueId] = MeshReservedDataStore{}; } if (mesh) { if (mesh->getTotalVertices() > 0) { MeshPropertyGridComponent::render( mesh, _reservedDataStore.mesh[mesh->uniqueId]); } else { TransformNodePropertyGridComponent::render(mesh); } } return; } if (entity->type == EntityType::FreeCamera || entity->type == EntityType::UniversalCamera) { auto& freeCamera = _entityCache.freeCamera; if (!freeCamera || freeCamera->uniqueId != entityId) { freeCamera = std::dynamic_pointer_cast<FreeCamera>( props.scene->getCameraByUniqueID(entityId)); } if (freeCamera) { FreeCameraPropertyGridComponent::render(freeCamera); } return; } if (entity->type == EntityType::ArcRotateCamera) { auto& arcRotateCamera = _entityCache.arcRotateCamera; if (!arcRotateCamera || arcRotateCamera->uniqueId != entityId) { arcRotateCamera = std::dynamic_pointer_cast<ArcRotateCamera>( props.scene->getCameraByUniqueID(entityId)); } if (arcRotateCamera) { ArcRotateCameraPropertyGridComponent::render(arcRotateCamera); } return; } if (entity->type == EntityType::HemisphericLight) { auto& hemisphericLight = _entityCache.hemisphericLight; if (!hemisphericLight || hemisphericLight->uniqueId != entityId) { hemisphericLight = std::dynamic_pointer_cast<HemisphericLight>( props.scene->getLightByUniqueID(entityId)); } if (hemisphericLight) { HemisphericLightPropertyGridComponent::render(hemisphericLight); } return; } if (entity->type == EntityType::PointLight) { auto& pointLight = _entityCache.pointLight; if (!pointLight || pointLight->uniqueId != entityId) { pointLight = std::dynamic_pointer_cast<PointLight>( props.scene->getLightByUniqueID(entityId)); } if (pointLight) { PointLightPropertyGridComponent::render(pointLight); } return; } if (entity->type == EntityType::DirectionalLight) { auto& directionalLight = _entityCache.directionalLight; if (!directionalLight || directionalLight->uniqueId != entityId) { directionalLight = std::dynamic_pointer_cast<DirectionalLight>( props.scene->getLightByUniqueID(entityId)); } if (directionalLight) { DirectionalLightPropertyGridComponent::render(directionalLight); } return; } if (entity->type == EntityType::SpotLight) { auto& spotLight = _entityCache.spotLight; if (!spotLight || spotLight->uniqueId != entityId) { spotLight = std::dynamic_pointer_cast<SpotLight>( props.scene->getLightByUniqueID(entityId)); } if (spotLight) { SpotLightPropertyGridComponent::render(spotLight); } return; } if (entity->type == EntityType::TransformNode) { auto& transformNode = _entityCache.transformNode; if (!transformNode || transformNode->uniqueId != entityId) { transformNode = std::dynamic_pointer_cast<TransformNode>( props.scene->getTransformNodeByUniqueID(entityId)); } if (transformNode) { TransformNodePropertyGridComponent::render(transformNode); } return; } if (entity->type == EntityType::MultiMaterial) { auto& multiMaterial = _entityCache.multiMaterial; if (!multiMaterial || multiMaterial->uniqueId != entityId) { multiMaterial = std::dynamic_pointer_cast<MultiMaterial>( props.scene->getMaterialByUniqueID(entityId)); } if (multiMaterial) { MultiMaterialPropertyGridComponent::render(multiMaterial); } return; } if (entity->type == EntityType::StandardMaterial) { auto& standardMaterial = _entityCache.standardMaterial; if (!standardMaterial || standardMaterial->uniqueId != entityId) { standardMaterial = std::dynamic_pointer_cast<StandardMaterial>( props.scene->getMaterialByUniqueID(entityId)); } if (standardMaterial) { StandardMaterialPropertyGridComponent::render(standardMaterial); } return; } if (entity->type == EntityType::PBRMaterial) { auto& pbrMaterial = _entityCache.pbrMaterial; if (!pbrMaterial || pbrMaterial->uniqueId != entityId) { pbrMaterial = std::dynamic_pointer_cast<PBRMaterial>( props.scene->getMaterialByUniqueID(entityId)); } if (pbrMaterial) { PBRMaterialPropertyGridComponent::render(pbrMaterial); } return; } if (entity->type == EntityType::PBRMetallicRoughnessMaterial) { auto& pbrMetallicRoughnessMaterial = _entityCache.pbrMetallicRoughnessMaterial; if (!pbrMetallicRoughnessMaterial || pbrMetallicRoughnessMaterial->uniqueId != entityId) { pbrMetallicRoughnessMaterial = std::dynamic_pointer_cast<PBRMetallicRoughnessMaterial>( props.scene->getMaterialByUniqueID(entityId)); } if (pbrMetallicRoughnessMaterial) { PBRMetallicRoughnessMaterialPropertyGridComponent::render( pbrMetallicRoughnessMaterial); } return; } if (entity->type == EntityType::PBRSpecularGlossinessMaterial) { auto& pbrSpecularGlossinessMaterial = _entityCache.pbrSpecularGlossinessMaterial; if (!pbrSpecularGlossinessMaterial || pbrSpecularGlossinessMaterial->uniqueId != entityId) { pbrSpecularGlossinessMaterial = std::dynamic_pointer_cast<PBRSpecularGlossinessMaterial>( props.scene->getMaterialByUniqueID(entityId)); } if (pbrSpecularGlossinessMaterial) { PBRSpecularGlossinessMaterialPropertyGridComponent::render( pbrSpecularGlossinessMaterial); } return; } if (entity->type == EntityType::BackgroundMaterial) { auto& backgroundMaterial = _entityCache.backgroundMaterial; if (!backgroundMaterial || backgroundMaterial->uniqueId != entityId) { backgroundMaterial = std::dynamic_pointer_cast<BackgroundMaterial>( props.scene->getMaterialByUniqueID(entityId)); } if (backgroundMaterial) { BackgroundMaterialPropertyGridComponent::render(backgroundMaterial); } return; } if (entity->type == EntityType::Material) { auto& material = _entityCache.material; if (!material || material->uniqueId != entityId) { material = std::dynamic_pointer_cast<Material>( props.scene->getMaterialByUniqueID(entityId)); } if (material) { MaterialPropertyGridComponent::render(material); } return; } if (entity->type == EntityType::Texture) { auto& texture = _entityCache.texture; if (!texture || texture->name != entityName) { auto it = std::find_if(props.scene->textures.begin(), props.scene->textures.end(), [&entityName](const BaseTexturePtr& texture) { return texture->name == entityName; }); texture = (it == props.scene->textures.end()) ? nullptr : std::static_pointer_cast<Texture>(*it); _reservedDataStore.texture[texture->name] = TextureReservedDataStore{}; } if (texture) { TexturePropertyGridComponent::render( texture, _reservedDataStore.texture[texture->name]); } return; } if (entity->type == EntityType::Skeleton) { auto& skeleton = _entityCache.skeleton; if (!skeleton || skeleton->uniqueId != entityId) { skeleton = std::dynamic_pointer_cast<Skeleton>( props.scene->getSkeletonByUniqueID(entityId)); _reservedDataStore.skeleton[skeleton->uniqueId] = SkeletonReservedDataStore{}; _reservedDataStore.animation[skeleton->uniqueId] = AnimationReservedDataStore{}; _reservedDataStore.animation[skeleton->uniqueId].scene = props.scene; } if (skeleton) { SkeletonPropertyGridComponent::render( skeleton, _reservedDataStore.skeleton[skeleton->uniqueId], _reservedDataStore.animation[skeleton->uniqueId]); } return; } if (entity->type == EntityType::Bone) { auto& bone = _entityCache.bone; if (!bone || bone->uniqueId != entityId) { bone = std::dynamic_pointer_cast<Bone>( props.scene->getBoneByUniqueID(entityId)); } if (bone) { BonePropertyGridComponent::render(bone); } return; } } } // end of namespace BABYLON
37.973054
138
0.727588
[ "mesh", "render" ]
0b1da6c017265a88be6ad5583b00f6ff66e33502
3,692
cpp
C++
src/qt_gui/objreader.cpp
jung1981/linux-track
92db912deb9dafe40aa30b00223ed065c9e334aa
[ "MIT" ]
136
2015-07-17T07:48:39.000Z
2022-03-11T21:42:58.000Z
src/qt_gui/objreader.cpp
rfvizarra/linuxtrack
b8e788587362634ad4485399c5531945a0ed666b
[ "MIT" ]
91
2015-07-24T00:40:33.000Z
2022-03-31T13:15:49.000Z
src/qt_gui/objreader.cpp
rfvizarra/linuxtrack
b8e788587362634ad4485399c5531945a0ed666b
[ "MIT" ]
27
2015-08-10T14:10:03.000Z
2022-03-08T14:55:05.000Z
#include <iostream> #include <QFile> #include <QRegExp> #include <QTextStream> #include "objreader.h" #include "pathconfig.h" #include "ltr_gui_prefs.h" int cnt = 0; int vcnt = 0; int tcnt = 0; object_t object; std::vector<object_t> object_table; static void add_vertex(float x, float y, float z, float nx, float ny, float nz, float s, float t) { ++cnt; object.vtx_table.push_back((vtx_t){x, y, z, nx, ny, nz, s, t}); } static void add_index(int index) { ++vcnt; object.vtx_indices.push_back(index); } static void add_tris(int offset, int count, bool glass) { ++tcnt; object.tris_table.push_back((tri_t){offset, count, glass}); } bool glass = false; static QRegExp vt_line(QString::fromUtf8("^\\s*VT\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s*$")); static QRegExp idx10_line(QString::fromUtf8("^\\s*IDX10\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s*$")); static QRegExp idx_line(QString::fromUtf8("^\\s*IDX\\s+(\\S+)\\s*$")); static QRegExp tris_line(QString::fromUtf8("^\\s*TRIS\\s+(\\S+)\\s+(\\S+)\\s*$")); static QRegExp texture_line(QString::fromUtf8("^\\s*TEXTURE\\s+(.*)\\s*$")); static QRegExp glass_line(QString::fromUtf8("^\\s*GLASS\\s*$")); static void process_line(const QString &line) { if(vt_line.indexIn(line) != -1){ float x, y, z, nx, ny, nz, s, t; x = vt_line.cap(1).toFloat(); y = vt_line.cap(2).toFloat(); z = vt_line.cap(3).toFloat(); nx = vt_line.cap(4).toFloat(); ny = vt_line.cap(5).toFloat(); nz = vt_line.cap(6).toFloat(); s = vt_line.cap(7).toFloat(); t = vt_line.cap(8).toFloat(); add_vertex(x, y, z, nx, ny, nz, s, t); }else if(idx10_line.indexIn(line) != -1){ add_index(idx10_line.cap(1).toInt()); add_index(idx10_line.cap(2).toInt()); add_index(idx10_line.cap(3).toInt()); add_index(idx10_line.cap(4).toInt()); add_index(idx10_line.cap(5).toInt()); add_index(idx10_line.cap(6).toInt()); add_index(idx10_line.cap(7).toInt()); add_index(idx10_line.cap(8).toInt()); add_index(idx10_line.cap(9).toInt()); add_index(idx10_line.cap(10).toInt()); }else if(idx_line.indexIn(line) != -1){ add_index(idx_line.cap(1).toInt()); }else if(tris_line.indexIn(line) != -1){ add_tris(tris_line.cap(1).toInt(), tris_line.cap(2).toInt(), glass); glass = false; }else if(texture_line.indexIn(line) != -1){ if(!texture_line.cap(1).isEmpty()){ object.texture = PrefProxy::getDataPath(texture_line.cap(1)); //std::cout<<"Texture: "<<qPrintable(object.texture)<<std::endl; } }else if(glass_line.indexIn(line) != -1){ glass = true; } } static void obj_init(object_t &obj) { obj.vtx_table.clear(); obj.vtx_indices.clear(); obj.tris_table.clear(); obj.texture = QString::fromUtf8(""); } void read_obj() { char *obj_list[] = {(char *)"sphere.obj", (char *)"sparow_opaq.obj", (char *)"sparow_glass.obj", NULL}; for(int i = 0; obj_list[i] != NULL; ++i){ QFile f(PrefProxy::getDataPath(QString::fromUtf8(obj_list[i]))); obj_init(object); cnt = 0; vcnt = 0; tcnt = 0; if(!f.open(QIODevice::ReadOnly | QIODevice::Text)) continue; QTextStream in(&f); while(!in.atEnd()){ QString line = in.readLine(); process_line(line); } f.close(); object_table.push_back(object); //std::cout<<(char *)obj_list[i]<<std::endl; //std::cout<< cnt <<" vertices processed!"<< std::endl; //std::cout<< vcnt <<" indexes processed!"<< std::endl; //std::cout<< tcnt <<" tris processed!"<< std::endl; } }
30.262295
164
0.597508
[ "object", "vector" ]
0b2543a2b8e8281c5059ecfde80612aba8ee0f16
13,753
cpp
C++
Engine/GameObject.cpp
CapitanLiteral/Wingman
f4e0ef00d3e5190c2d41591a8280402ca482f585
[ "MIT" ]
null
null
null
Engine/GameObject.cpp
CapitanLiteral/Wingman
f4e0ef00d3e5190c2d41591a8280402ca482f585
[ "MIT" ]
3
2016-10-31T14:33:02.000Z
2016-10-31T23:46:30.000Z
Engine/GameObject.cpp
CapitanLiteral/Wingman
f4e0ef00d3e5190c2d41591a8280402ca482f585
[ "MIT" ]
null
null
null
#include "Application.h" #include "Globals.h" #include "GameObjectManager.h" #include "SDL\include\SDL.h" #include "GameObject.h" #include "ComponentMaterial.h" #include "ComponentMesh.h" #include "ComponentCamera.h" #include "Component.h" #include "MathGeoLib\include\MathGeoLib.h" #include "OpenGL.h" #include <string> GameObject::GameObject(GameObject* parent, const float3 translation, const float3 scale, const Quat rotation, const char* name) { this->name = name; //this->position = translation; //this->scale = scale; //this->rotation = rotation; this->parent = parent; localTransform = float4x4::FromTRS(translation, rotation, scale); if (parent != NULL) { parent->addChild(this); } aabb_color.Set(0, 0, 1, 1); } GameObject::~GameObject() { for (std::vector<Component*>::iterator iterator = components.begin(); iterator != components.end(); iterator++) { if ((*iterator) != nullptr) { RELEASE(*iterator); } } for (std::vector<GameObject*>::iterator iterator = children.begin(); iterator != children.end(); iterator++) { if ((*iterator) != nullptr) { RELEASE(*iterator); } } } Component* GameObject::createComponent(ComponentType type) { Component* ret; if (type == MESH) { ComponentMesh* mesh = new ComponentMesh(this); mesh->type = type; components.push_back(mesh); return mesh; } else if (type == MATERIAL) { ComponentMaterial* material = new ComponentMaterial(this); material->type = type; components.push_back(material); return material; } else if (type == CAMERA) { ComponentCamera* camera = new ComponentCamera(this); camera->type = type; components.push_back(camera); return camera; } return ret; } void GameObject::update() { for (std::vector<GameObject*>::iterator it = children.begin(); it != children.end(); it++) { (*it)->update(); } for (std::vector<Component*>::iterator it = components.begin(); it != components.end(); it++) { //(*it)->Update(); if ((*it)->type == MESH) { ComponentMesh* component = (ComponentMesh*)(*it); component->Update(); } if ((*it)->type == CAMERA) { ComponentCamera* component = (ComponentCamera*)(*it); component->Update(); } } updateBoundingBoxes(); if (drawAABB) { draw_AABB(); } //for (std::vector<GameObject*>::iterator iterator = children.begin(); iterator != children.end(); iterator++) //{ // if ((*iterator)->mustBeDeleted) // { // // //RELEASE((*iterator)); // } //} } Component * GameObject::findComponent(ComponentType) { Component* ret = nullptr; if (components.size() > 0) { for (std::vector<Component*>::iterator it = components.begin(); it != components.end(); it++) { //switch... if ((*it)->type == CAMERA) { ret = (*it); } } } return ret; } void GameObject::addChild(GameObject* child) { if (child != NULL) { children.push_back(child); } else { SDL_Log("Failed to add a child to %s", name); } } const float4x4 GameObject::getLocalTransform() { return localTransform; } const float4x4 GameObject::getGlobalTransform() { return globalTransform; } void GameObject::refreshTransform(float4x4 mat) { if (parent != NULL) { globalTransform = parent->globalTransform * localTransform; } for (std::vector<GameObject*>::iterator iterator = children.begin(); iterator != children.end(); iterator++) { (*iterator)->refreshTransform(globalTransform); } } void GameObject::setPosition(float3 position) { float3 pos; float3 sca; Quat rot; localTransform.Decompose(pos, rot, sca); localTransform = float4x4::FromTRS(position, rot, sca); refreshTransform(globalTransform); //This need refactor TODO findComponents for (std::vector<Component*>::iterator iterator = components.begin(); iterator != components.end(); iterator++) { if ((*iterator)->type == MESH) { ComponentMesh* mesh = (ComponentMesh*)(*iterator); mesh->updateBoundingBoxes(); } } } void GameObject::setRotation(Quat rotation) { float3 pos; float3 sca; Quat rot; localTransform.Decompose(pos, rot, sca); localTransform = float4x4::FromTRS(pos, rotation, sca); refreshTransform(globalTransform); //This need refactor TODO findComponents for (std::vector<Component*>::iterator iterator = components.begin(); iterator != components.end(); iterator++) { if ((*iterator)->type == MESH) { ComponentMesh* mesh = (ComponentMesh*)(*iterator); mesh->updateBoundingBoxes(); } } } void GameObject::setRotation(float* rot) { float3 r; r.Set(rot); while (r.x < 0) r.x += 360; while (r.y < 0) r.y += 360; while (r.z < 0) r.z += 360; while (r.x >= 360) r.x -= 360; while (r.y >= 360) r.y -= 360; while (r.z >= 360) r.z -= 360; r.x *= DEGTORAD; r.y *= DEGTORAD; r.z *= DEGTORAD; setRotation(Quat::FromEulerXYZ(r.x, r.y, r.z)); } void GameObject::setRotation(float x, float y, float z) { while (x < 0) x += 360; while (y < 0) y += 360; while (z < 0) z += 360; while (x >= 360) x -= 360; while (y >= 360) y -= 360; while (z >= 360) z -= 360; x *= DEGTORAD; y *= DEGTORAD; z *= DEGTORAD; setRotation(Quat::FromEulerXYZ(x, y, z)); } float3 GameObject::getRotation() const { float3 pos; float3 sca; Quat rot; localTransform.Decompose(pos, rot, sca); float3 ret = rot.ToEulerXYZ(); ret.x *= RADTODEG; ret.y *= RADTODEG; ret.z *= RADTODEG; while (ret.x < 0) ret.x += 360; while (ret.y < 0) ret.y += 360; while (ret.z < 0) ret.z += 360; while (ret.x >= 360) ret.x -= 360; while (ret.y >= 360) ret.y -= 360; while (ret.z >= 360) ret.z -= 360; return ret; } float* GameObject::getEulerRot() const { float3 pos; float3 sca; Quat rot; localTransform.Decompose(pos, rot, sca); float3 rotationEuler = rot.ToEulerXYZ(); rotationEuler.x *= RADTODEG; rotationEuler.y *= RADTODEG; rotationEuler.z *= RADTODEG; while (rotationEuler.x < 0) rotationEuler.x += 360; while (rotationEuler.y < 0) rotationEuler.y += 360; while (rotationEuler.z < 0) rotationEuler.z += 360; while (rotationEuler.x >= 360) rotationEuler.x -= 360; while (rotationEuler.y >= 360) rotationEuler.y -= 360; while (rotationEuler.z >= 360) rotationEuler.z -= 360; return (float*)&rotationEuler; } void GameObject::setScale(float3 scale) { float3 pos; float3 sca; Quat rot; localTransform.Decompose(pos, rot, sca); localTransform = float4x4::FromTRS(pos, rot, scale); refreshTransform(globalTransform); //This need refactor TODO findComponents for (std::vector<Component*>::iterator iterator = components.begin(); iterator != components.end(); iterator++) { if ((*iterator)->type == MESH) { ComponentMesh* mesh = (ComponentMesh*)(*iterator); mesh->updateBoundingBoxes(); } } } void GameObject::setGlobalTransform(float3 pos, Quat rot, float3 scale) { globalTransform = float4x4::FromTRS(pos, rot, scale); } void GameObject::Serialize(Json::Value & root) { Json::Value go; float3 pos; float3 scale; Quat rot; localTransform.Decompose(pos, rot, scale); //Position for (int i = 0; i < 3; i++) { go["pos"].append(*(pos.ptr()+i)); } //Rotation float3 euler_rot = rot.ToEulerXYZ(); euler_rot *= RADTODEG; for (int i = 0; i < 3; i++) { go["rot"].append(*(euler_rot.ptr() + i)); } //Scale for (int i = 0; i < 3; i++) { go["scale"].append(*(scale.ptr() + i)); } //name go["name"] = name; //UUID if (name == "ROOT") { UUID = 0; } else { LCG random; UUID = random.Int(); } go["UUID"] = UUID; //Parent UUID if (parent != nullptr) go["parent_UUID"] = parent->UUID; else go["parent_UUID"] = 0; std::string uuid_str = std::to_string(UUID); //Json::Value jcomponents; for (std::vector<Component*>::iterator iterator = components.begin(); iterator != components.end(); iterator++) { if ((*iterator) != nullptr && (*iterator)->type == CAMERA) { Json::Value jcomponents; (*iterator)->Serialize(jcomponents); go["components"].append(jcomponents); } } for (std::vector<Component*>::iterator iterator = components.begin(); iterator != components.end(); iterator++) { if ((*iterator) != nullptr && (*iterator)->type == MATERIAL) { Json::Value jcomponents; (*iterator)->Serialize(jcomponents); go["components"].append(jcomponents); } } for (std::vector<Component*>::iterator iterator = components.begin(); iterator != components.end(); iterator++) { if ((*iterator) != nullptr && (*iterator)->type == MESH) { Json::Value jcomponents; (*iterator)->Serialize(jcomponents); go["components"].append(jcomponents); } } //go["components"] = jcomponents; //root[uuid_str] = go; if (name != "ROOT") root["gameObjects"].append(go); //Recursive for (std::vector<GameObject*>::iterator iterator = children.begin(); iterator != children.end(); iterator++) { (*iterator)->Serialize(root); } } void GameObject::Deserialize(Json::Value & root) { App->goManager->setFocusGO(nullptr); GameObject* go_root = App->goManager->root; for (std::vector<GameObject*>::iterator iterator = go_root->children.begin(); iterator != go_root->children.end(); iterator++) { //(*iterator)->mustBeDeleted = true; App->goManager->toDelete.push_back((*iterator)); //RELEASE((*iterator)); } go_root->children.clear(); Json::Value gos = root.get("gameObjects", 0); for (int i = 0; i != gos.size(); i++) { float3 pos; float3 scale; float3 eulerRot; Quat rot; Json::Value jgo = gos[i]; uint32_t jUUID = jgo.get("UUID", -1).asInt64(); uint32_t jparent_UUID = jgo.get("parent_UUID", -1).asInt64(); //Position Json::Value jpos = jgo.get("pos", 0); for (int i = 0; i != jpos.size(); i++) *(pos.ptr() + i) = jpos[i].asFloat(); //Scale Json::Value jscale = jgo.get("scale", 0); for (int i = 0; i != jscale.size(); i++) *(scale.ptr() + i) = jscale[i].asFloat(); //Rotation Json::Value jeulerRot = jgo.get("rot", 0); for (int i = 0; i != jeulerRot.size(); i++) *(eulerRot.ptr() + i) = jeulerRot[i].asFloat(); rot = rot.FromEulerXYZ(eulerRot.x, eulerRot.y, eulerRot.z); std::string name = jgo["name"].asString(); GameObject* newGo = new GameObject(go_root, pos, scale, rot, name.c_str()); newGo->UUID = jUUID; newGo->parent_UUID = jparent_UUID; Json::Value jcomponents = jgo.get("components", 0); for (int i = 0; i != jcomponents.size(); i++) { Json::Value jcomponent = jcomponents[i]; Component* component;// = new Component(newGo); std::string jtype = jcomponent.get("component_type", -1).asString(); if (jtype == "camera") { component = newGo->createComponent(CAMERA); component->Deserialize(jcomponent); } else if (jtype == "mesh") { component = newGo->createComponent(MESH); component->Deserialize(jcomponent); for (std::vector<Component*>::iterator iterator = newGo->components.begin(); iterator != newGo->components.end(); iterator++) { if ((*iterator)->type == MATERIAL) { ComponentMaterial* material = (ComponentMaterial*)(*iterator); ComponentMesh* mesh = (ComponentMesh*)component; if (material->UUID == mesh->associatedUUID) { mesh->associatedMaterial = material; } } } } else if (jtype == "material") { component = newGo->createComponent(MATERIAL); component->Deserialize(jcomponent); } } } } GameObject * GameObject::findByUUID(uint32_t UUID) { GameObject* ret = nullptr; if (this->UUID == UUID) ret = this; else for (std::vector<GameObject*>::iterator iterator = children.begin(); iterator != children.end(); iterator++) { if (ret == nullptr) ret = (*iterator)->findByUUID(UUID); } return ret; } AABB GameObject::getAABB() const { return aabb; } void GameObject::setAABB(AABB aabb) { this->aabb = aabb; } void GameObject::draw_AABB() { glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDisable(GL_CULL_FACE); glLineWidth(1.f); glColor4f(aabb_color.r, aabb_color.g, aabb_color.b, aabb_color.a); float3 vertices[8]; aabb.GetCornerPoints(vertices); //glColor4f(color.r, color.g, color.b, color.a); glBegin(GL_QUADS); glVertex3fv((GLfloat*)&vertices[1]); glVertex3fv((GLfloat*)&vertices[5]); glVertex3fv((GLfloat*)&vertices[7]); glVertex3fv((GLfloat*)&vertices[3]); glVertex3fv((GLfloat*)&vertices[4]); glVertex3fv((GLfloat*)&vertices[0]); glVertex3fv((GLfloat*)&vertices[2]); glVertex3fv((GLfloat*)&vertices[6]); glVertex3fv((GLfloat*)&vertices[5]); glVertex3fv((GLfloat*)&vertices[4]); glVertex3fv((GLfloat*)&vertices[6]); glVertex3fv((GLfloat*)&vertices[7]); glVertex3fv((GLfloat*)&vertices[0]); glVertex3fv((GLfloat*)&vertices[1]); glVertex3fv((GLfloat*)&vertices[3]); glVertex3fv((GLfloat*)&vertices[2]); glVertex3fv((GLfloat*)&vertices[3]); glVertex3fv((GLfloat*)&vertices[7]); glVertex3fv((GLfloat*)&vertices[6]); glVertex3fv((GLfloat*)&vertices[2]); glVertex3fv((GLfloat*)&vertices[0]); glVertex3fv((GLfloat*)&vertices[4]); glVertex3fv((GLfloat*)&vertices[5]); glVertex3fv((GLfloat*)&vertices[1]); glEnd(); glEnable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); //glLineWidth(1.f); } void GameObject::updateBoundingBoxes() { aabb.SetNegativeInfinity(); std::vector<AABB> aabbVector; for (std::vector<Component*>::iterator iterator = components.begin(); iterator != components.end(); iterator++) { if ((*iterator)->type == MESH) { ComponentMesh* mesh = (ComponentMesh*) (*iterator); aabbVector.push_back(mesh->getAABB()); } } for (std::vector<AABB>::iterator iterator = aabbVector.begin(); iterator != aabbVector.end(); iterator++) { aabb.Enclose((*iterator)); } //aabb.Transform(parent->globalTransform); }
21.422118
127
0.649313
[ "mesh", "vector", "transform" ]
0b291493dbe80535b38b855ae8bf8e7f5df92183
14,555
cpp
C++
src/configure/Process.cpp
hotgloupi/configure
888cf725c93df5a1cf01794cc0a581586a82855c
[ "BSD-3-Clause" ]
1
2015-11-13T10:37:35.000Z
2015-11-13T10:37:35.000Z
src/configure/Process.cpp
hotgloupi/configure
888cf725c93df5a1cf01794cc0a581586a82855c
[ "BSD-3-Clause" ]
19
2015-02-10T17:18:58.000Z
2015-07-11T11:31:08.000Z
src/configure/Process.cpp
hotgloupi/configure
888cf725c93df5a1cf01794cc0a581586a82855c
[ "BSD-3-Clause" ]
null
null
null
#include "Process.hpp" #include "log.hpp" #include "Filesystem.hpp" #include "quote.hpp" #include "error.hpp" #include <boost/config.hpp> #include <boost/algorithm/string/join.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file_descriptor.hpp> #include <cassert> #include <stdexcept> #include <inttypes.h> #include <string.h> #if defined(BOOST_POSIX_API) # include <sys/wait.h> # include <unistd.h> # if defined(__APPLE__) && defined(__DYNAMIC__) # include <crt_externs.h> // For _NSGetEnviron() # endif #elif defined(BOOST_WINDOWS_API) # include <Windows.h> # include <io.h> #else # error "Unsupported platform" #endif namespace io = boost::iostreams; namespace configure { namespace { char** get_environ() { #if defined(__APPLE__) && defined(__DYNAMIC__) return *_NSGetEnviron(); #else return environ; #endif } #ifdef BOOST_WINDOWS_API typedef HANDLE file_descriptor_t; #else typedef int file_descriptor_t; #endif struct Pipe { private: io::file_descriptor_source _source; io::file_descriptor_sink _sink; public: Pipe() { file_descriptor_t fds[2]; #ifdef BOOST_WINDOWS_API if (!::CreatePipe(&fds[0], &fds[1], NULL, 0)) CONFIGURE_THROW_SYSTEM_ERROR("CreatePipe()"); #else if (::pipe(fds) == -1) CONFIGURE_THROW_SYSTEM_ERROR("pipe()"); #endif _source = io::file_descriptor_source( fds[0], io::file_descriptor_flags::close_handle); _sink = io::file_descriptor_sink( fds[1], io::file_descriptor_flags::close_handle); } public: io::file_descriptor_sink& sink() { return _sink; } io::file_descriptor_source& source() { return _source; } public: void close() { _sink.close(); _source.close(); } }; #ifdef BOOST_WINDOWS_API struct Child { public: typedef HANDLE process_handle_type; private: PROCESS_INFORMATION _proc_info; public: explicit Child(PROCESS_INFORMATION const& proc_info) : _proc_info(proc_info) {} Child(Child&& other) : _proc_info(other._proc_info) { other._proc_info.hProcess = INVALID_HANDLE_VALUE; other._proc_info.hThread = INVALID_HANDLE_VALUE; } ~Child() { ::CloseHandle(_proc_info.hProcess); ::CloseHandle(_proc_info.hThread); } process_handle_type process_handle() const { return _proc_info.hProcess; } bool wait(int ms, int& exit_code) { int ret = ::WaitForSingleObject( this->process_handle(), (ms < 0 ? INFINITE : ms) ); switch (ret) { case WAIT_FAILED: CONFIGURE_THROW_SYSTEM_ERROR("WaitForSingleObject()"); case WAIT_ABANDONED: log::warning( "Wait on child", *this, "has been abandoned"); break; case WAIT_TIMEOUT: log::debug("The child", *this, "is still alive"); break; case WAIT_OBJECT_0: { DWORD exit_code_out; if (!::GetExitCodeProcess(this->process_handle(), &exit_code_out)) CONFIGURE_THROW_SYSTEM_ERROR("GetExitCodeProcess()"); log::debug("The child", *this, "exited with status code", exit_code_out); exit_code = exit_code_out; return true; } } return false; } }; #else struct Child { public: typedef pid_t process_handle_type; private: process_handle_type _pid; public: explicit Child(process_handle_type pid) : _pid(pid) {} process_handle_type process_handle() const { return _pid; } bool wait(int ms, int& exit_code) { pid_t ret; int status; int options = 0; if (ms == 0) options = WNOHANG; else if (options > 0) assert(false && "not implemented"); do { log::debug("Checking exit status of child", *this); ret = ::waitpid(this->process_handle(), &status, options); } while (ret == -1 && errno == EINTR); if (ret == -1) CONFIGURE_THROW_SYSTEM_ERROR("waitpid()"); if (ret != 0) { log::debug("The child", *this, "exited with status code", WEXITSTATUS(status)); exit_code = WEXITSTATUS(status); return true; } else log::debug("The child", *this, "is still alive"); return false; } }; #endif std::ostream& operator <<(std::ostream& out, Child const& child) { return out << "<Process " << child.process_handle() << ">"; } } // !anonymous struct Process::Impl { Command const command; Options const options; boost::optional<ExitCode> exit_code; io::file_descriptor_sink stdin_sink; io::file_descriptor_source stdout_source; io::file_descriptor_source stderr_source; Child child; Impl(Command cmd, Options options) : command(_prepare_command(std::move(cmd))) , options(std::move(options)) , exit_code(boost::none) , child(_create_child()) { log::debug("Spawn process for command:", boost::join(this->command, " ")); } #ifdef BOOST_POSIX_API pid_t _create_child() { char** env = {NULL}; if (this->options.inherit_env) { env = get_environ(); } std::unique_ptr<Pipe> stdin_pipe; std::unique_ptr<Pipe> stdout_pipe; std::unique_ptr<Pipe> stderr_pipe; std::tuple<bool, Stream, std::unique_ptr<Pipe>&, int> channels[] = { std::make_tuple(false, this->options.stdin_, std::ref(stdin_pipe), STDIN_FILENO), std::make_tuple(true, this->options.stdout_, std::ref(stdout_pipe), STDOUT_FILENO), std::make_tuple(true, this->options.stderr_, std::ref(stderr_pipe), STDERR_FILENO), }; for (auto& channel: channels) if (std::get<1>(channel) == Stream::PIPE) { log::debug("Creating pipe for", std::get<3>(channel)); std::get<2>(channel).reset(new Pipe); } log::debug("Spawning process:", boost::join(this->command, " ")); pid_t child = ::fork(); if (child < 0) { CONFIGURE_THROW_SYSTEM_ERROR("fork()"); } else if (child == 0) // Child { if (this->options.working_directory) { auto const& dir = this->options.working_directory.get(); if (::chdir(dir.c_str()) < 0) { log::error("Cannot set working directory to '" + dir.string() + "':", ::strerror(errno)); ::exit(EXIT_FAILURE); } } for (auto& channel: channels) { Stream kind = std::get<1>(channel); bool is_sink = std::get<0>(channel); int old_fd = std::get<3>(channel); if (kind == Stream::PIPE) { int new_fd = (is_sink ? std::get<2>(channel)->sink().handle() : std::get<2>(channel)->source().handle()); retry_dup2: int ret = ::dup2(new_fd, old_fd); if (ret == -1) { if (errno == EINTR) goto retry_dup2; ::exit(EXIT_FAILURE); } } else if (kind == Stream::DEVNULL) { log::debug("Closing", old_fd); ::close(old_fd); } } stdin_pipe.reset(); stdout_pipe.reset(); stderr_pipe.reset(); std::vector<char const*> args; for (auto& arg: this->command) args.push_back(arg.c_str()); args.push_back(nullptr); ::execve(args[0], (char**) &args[0], env); ::exit(EXIT_FAILURE); } else // Parent { if (this->options.stdin_ == Stream::PIPE) this->stdin_sink = stdin_pipe->sink(); if (this->options.stdout_ == Stream::PIPE) this->stdout_source = stdout_pipe->source(); if (this->options.stderr_ == Stream::PIPE) this->stderr_source = stderr_pipe->source(); } return child; } #elif defined(BOOST_WINDOWS_API) Child _create_child() { LPSECURITY_ATTRIBUTES proc_attrs = 0; LPSECURITY_ATTRIBUTES thread_attrs = 0; BOOL inherit_handles = false; LPVOID env = nullptr; LPCTSTR work_dir = nullptr; if (this->options.working_directory) work_dir = this->options.working_directory.get().string().c_str(); #if (_WIN32_WINNT >= 0x0600) DWORD creation_flags = EXTENDED_STARTUPINFO_PRESENT; STARTUPINFOEX startup_info_ex; ZeroMemory(&startup_info_ex, sizeof(STARTUPINFOEX)); STARTUPINFO& startup_info = startup_info_ex.StartupInfo; startup_info.cb = sizeof(STARTUPINFOEX); #else DWORD creation_flags = 0; STARTUPINFO startup_info; ZeroMemory(&startup_info, sizeof(STARTUPINFO)); startup_info.cb = sizeof(STARTUPINFO); #endif std::unique_ptr<Pipe> stdin_pipe; if (this->options.stdin_ == Stream::PIPE) { stdin_pipe.reset(new Pipe); ::SetHandleInformation(stdin_pipe->source().handle(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); startup_info.hStdInput = stdin_pipe->source().handle(); startup_info.dwFlags |= STARTF_USESTDHANDLES; inherit_handles = true; this->stdin_sink = stdin_pipe->sink(); } else if (this->options.stdin_ == Stream::DEVNULL) { startup_info.hStdInput = INVALID_HANDLE_VALUE; startup_info.dwFlags |= STARTF_USESTDHANDLES; } std::unique_ptr<Pipe> stdout_pipe; if (this->options.stdout_ == Stream::PIPE) { stdout_pipe.reset(new Pipe); ::SetHandleInformation(stdout_pipe->sink().handle(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); startup_info.hStdOutput = stdout_pipe->sink().handle(); startup_info.dwFlags |= STARTF_USESTDHANDLES; inherit_handles = true; this->stdout_source = stdout_pipe->source(); } else if (this->options.stdout_ == Stream::DEVNULL) { startup_info.hStdOutput = INVALID_HANDLE_VALUE; startup_info.dwFlags |= STARTF_USESTDHANDLES; } std::unique_ptr<Pipe> stderr_pipe; if (this->options.stderr_ == Stream::PIPE) { stderr_pipe.reset(new Pipe); ::SetHandleInformation(stderr_pipe->sink().handle(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); startup_info.hStdError = stderr_pipe->sink().handle(); startup_info.dwFlags |= STARTF_USESTDHANDLES; inherit_handles = true; this->stderr_source = stderr_pipe->source(); } else if (this->options.stderr_ == Stream::DEVNULL) { startup_info.hStdError = INVALID_HANDLE_VALUE; startup_info.dwFlags |= STARTF_USESTDHANDLES; } PROCESS_INFORMATION proc_info; std::unique_ptr<char, void (*)(void*)> cmd_line( ::_strdup( quote<CommandParser::windows_shell>(this->command).c_str()), &::free); if (cmd_line == nullptr) throw std::bad_alloc(); auto ret = ::CreateProcess(this->command.at(0).c_str(), cmd_line.get(), proc_attrs, thread_attrs, inherit_handles, creation_flags, env, work_dir, &startup_info, &proc_info); if (!ret) CONFIGURE_THROW_SYSTEM_ERROR("CreateProcess()"); return Child(proc_info); } #endif // !BOOST_WINDOWS_API Command _prepare_command(Command cmd) { if (auto exe = Filesystem::which(cmd[0])) cmd[0] = exe.get().string(); else CONFIGURE_THROW( error::FileNotFound( "Cannot find the program '" + cmd[0] + "'" ) << error::command(cmd) ); return std::move(cmd); } }; Process::Process(Command cmd, Options options) : _this(new Impl(std::move(cmd), std::move(options))) {} Process::~Process() { this->wait(); } Process::Options const& Process::options() const { return _this->options; } boost::optional<Process::ExitCode> Process::exit_code() { if (!_this->exit_code) { int exit_code; if (_this->child.wait(0, exit_code)) _this->exit_code = exit_code; } return _this->exit_code; } Process::ExitCode Process::wait() { if (!this->exit_code()) { log::debug("Waiting for child", _this->child, "to terminate"); int exit_code; bool ended = _this->child.wait(-1, exit_code); if (!ended) throw std::logic_error("Should be terminated"); _this->exit_code = exit_code; } return _this->exit_code.get(); } Process::ExitCode Process::call(Command cmd, Options options) { Process p(std::move(cmd), std::move(options)); return p.wait(); } void Process::check_call(Command cmd, Options options) { auto ret = Process::call(std::move(cmd), std::move(options)); if (ret != 0) CONFIGURE_THROW(error::RuntimeError( "Program failed with exit code " + std::to_string(ret))); } std::string Process::check_output(Command cmd) { Options options; options.stdout_ = Stream::PIPE; options.stderr_ = Stream::DEVNULL; return Process::check_output(std::move(cmd), std::move(options), false); } std::string Process::check_output(Command cmd, Options options) { return Process::check_output(std::move(cmd), std::move(options), false); } std::string Process::check_output(Command cmd, Options options, bool ignore_errors) { Process p(std::move(cmd), std::move(options)); char buf[4096]; std::string res; #ifdef BOOST_WINDOWS_API DWORD size; #else ssize_t size; #endif std::vector<io::file_descriptor_source*> srcs; if (p._this->options.stdout_ == Stream::PIPE) srcs.push_back(&p._this->stdout_source); if (p._this->options.stderr_ == Stream::PIPE) srcs.push_back(&p._this->stderr_source); size_t closed = 0; while (closed < srcs.size()) { for (auto& src: srcs) { if (src == nullptr) continue; #ifdef BOOST_WINDOWS_API bool success = ::ReadFile(src->handle(), buf, sizeof(buf), &size, NULL); if (!success) { switch (::GetLastError()) { case ERROR_MORE_DATA: break; case ERROR_BROKEN_PIPE: log::debug("output pipe of", p._this->child, "ended"); break; default: CONFIGURE_THROW_SYSTEM_ERROR("ReadFile()"); } } #else size = ::read(src->handle(), buf, sizeof(buf)); if (size < 0) { if (errno == EINTR) { log::debug("Read interrupted by a signal, let's retry"); continue; } CONFIGURE_THROW_SYSTEM_ERROR("read()"); } log::debug("Read from", p._this->child, "returned", size); #endif if (size > 0) { log::debug( "read", size, "bytes from child", p._this->child, "stdout"); res.append(buf, size); } if (size == 0) { src = nullptr; closed += 1; } } } if (p.wait() != 0 && !ignore_errors) throw std::runtime_error("Program failed"); return res; } }
26.084229
84
0.620474
[ "vector" ]
0b2a3dc78de5fc3f6f19e07cb9cf18d38279cc8a
7,273
cpp
C++
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_DEBUG_PARTICLES_2D.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_DEBUG_PARTICLES_2D.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_DEBUG_PARTICLES_2D.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
//##################################################################### // Copyright 2010. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #include <PhysBAM_Tools/Arrays/INDIRECT_ARRAY.h> #include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_DEBUG_PARTICLES_2D.h> #include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_SHAPES.h> using namespace PhysBAM; //##################################################################### // Constructor //##################################################################### template<class T> OPENGL_DEBUG_PARTICLES_2D<T>:: OPENGL_DEBUG_PARTICLES_2D(GEOMETRY_PARTICLES<TV>& particle_input,const OPENGL_COLOR& color_input) :particles(particle_input),default_color(color_input),velocity_color(OPENGL_COLOR(1,.078f,.576f)),draw_velocities(false),draw_arrows(true),scale_velocities((T).025) {} //##################################################################### // Destructor //##################################################################### template<class T> OPENGL_DEBUG_PARTICLES_2D<T>:: ~OPENGL_DEBUG_PARTICLES_2D() { } //##################################################################### // Function Use_Bounding_Box //##################################################################### template<class T> bool OPENGL_DEBUG_PARTICLES_2D<T>:: Use_Bounding_Box() const { return particles.X.Size()>0; } //##################################################################### // Function Bounding_Box //##################################################################### template<class T> RANGE<VECTOR<float,3> > OPENGL_DEBUG_PARTICLES_2D<T>:: Bounding_Box() const { return World_Space_Box(RANGE<TV>::Bounding_Box(particles.X)); } //##################################################################### // Function Display //##################################################################### template<class T> void OPENGL_DEBUG_PARTICLES_2D<T>:: Display(const int in_color) const { ARRAY<typename OPENGL_POLICY<T>::T_GL> vertices; glMatrixMode(GL_MODELVIEW); glPushMatrix(); Send_Transform_To_GL_Pipeline(); glPushAttrib(GL_ENABLE_BIT | GL_POINT_BIT); glPointSize(5); glDisable(GL_LIGHTING); GLint mode=0; #ifndef USE_OPENGLES glGetIntegerv(GL_RENDER_MODE,&mode); #endif ARRAY_VIEW<VECTOR<T,3> >* colors=particles.array_collection->template Get_Array<VECTOR<T,3> >(ATTRIBUTE_ID_COLOR); ARRAY_VIEW<T>* sizes=particles.array_collection->template Get_Array<T>(ATTRIBUTE_ID_DISPLAY_SIZE); ARRAY_VIEW<TV>* V=particles.array_collection->template Get_Array<TV>(ATTRIBUTE_ID_V); #ifndef USE_OPENGLES if(draw_velocities && V && mode!=GL_SELECT){ #else if(draw_velocities && V){ #endif glPushAttrib(GL_LINE_BIT | GL_ENABLE_BIT | GL_CURRENT_BIT); glDisable(GL_LIGHTING); velocity_color.Send_To_GL_Pipeline(); vertices.Resize(0); for(int i=1;i<=particles.X.m;i++){ TV X=particles.X(i); TV Y=X+(*V)(i)*scale_velocities; if(draw_arrows) OPENGL_SHAPES::Draw_Arrow(X,Y,vertices); else OpenGL_Line(X,Y,vertices);} OpenGL_Draw_Arrays(GL_LINES,2,vertices); glPopAttrib();} #ifndef USE_OPENGLES if(mode==GL_SELECT) glPushName(0); #endif for(int i=1;i<=particles.X.m;i++){ #ifndef USE_OPENGLES if(mode==GL_SELECT) glLoadName(i); #endif if(colors) OPENGL_COLOR((*colors)(i)).Send_To_GL_Pipeline(); else default_color.Send_To_GL_Pipeline(); if(sizes) OPENGL_SHAPES::Draw_Circle(particles.X(i),(*sizes)(i),20,true); else{ vertices.Resize(0); OpenGL_Vertex(particles.X(i),vertices); OpenGL_Draw_Arrays(GL_POINTS,2,vertices);}} #ifndef USE_OPENGLES if(mode==GL_SELECT) glPopName(); #endif glPopAttrib(); glPopMatrix(); } //##################################################################### // Function Select_Point //##################################################################### template<class T> void OPENGL_DEBUG_PARTICLES_2D<T>:: Select_Point(int index) { //Set_Point_Color(index,OPENGL_COLOR::Yellow()); } //##################################################################### // Function Select_Points //##################################################################### template<class T> void OPENGL_DEBUG_PARTICLES_2D<T>:: Select_Points(const ARRAY<int> &indices) { //Set_Point_Colors(indices,OPENGL_COLOR::Yellow()); } //##################################################################### // Function Clear_Selection //##################################################################### template<class T> void OPENGL_DEBUG_PARTICLES_2D<T>:: Clear_Selection() { //Store_Point_Colors(false); } //##################################################################### // Function Get_Selection //##################################################################### template<class T> OPENGL_SELECTION *OPENGL_DEBUG_PARTICLES_2D<T>:: Get_Selection(GLuint *buffer,int buffer_size) { std::stringstream ss; ss<<"Get_Selection "<<buffer_size<<std::endl; LOG::filecout(ss.str()); if(buffer_size==1){ OPENGL_SELECTION_DEBUG_PARTICLES_2D<T> *selection=new OPENGL_SELECTION_DEBUG_PARTICLES_2D<T>(this); selection->index=buffer[0]; return selection;} else return 0; } //##################################################################### // Function Highlight_Selection //##################################################################### template<class T> void OPENGL_DEBUG_PARTICLES_2D<T>:: Highlight_Selection(OPENGL_SELECTION *selection) { if(selection->type!=OPENGL_SELECTION::DEBUG_PARTICLES_2D) return; OPENGL_SELECTION_DEBUG_PARTICLES_2D<T> *real_selection=(OPENGL_SELECTION_DEBUG_PARTICLES_2D<T>*)selection; Select_Point(real_selection->index); } //##################################################################### // Function Clear_Highlight //##################################################################### template<class T> void OPENGL_DEBUG_PARTICLES_2D<T>:: Clear_Highlight() { Clear_Selection(); } //##################################################################### // Function Bounding_Box //##################################################################### template<class T> RANGE<VECTOR<float,3> > OPENGL_SELECTION_DEBUG_PARTICLES_2D<T>:: Bounding_Box() const { PHYSBAM_ASSERT(object); return object->Bounding_Box(); } //##################################################################### // Function Print_Selection_Info //##################################################################### template<class T> void OPENGL_DEBUG_PARTICLES_2D<T>:: Print_Selection_Info(std::ostream &output_stream,OPENGL_SELECTION *selection) const { if(selection->type!=OPENGL_SELECTION::DEBUG_PARTICLES_2D) return; output_stream<<"Particle "<<dynamic_cast<OPENGL_SELECTION_DEBUG_PARTICLES_2D<T>&>(*selection).index<<std::endl; } template class OPENGL_DEBUG_PARTICLES_2D<float>; #ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT template class OPENGL_DEBUG_PARTICLES_2D<double>; #endif
39.743169
168
0.539667
[ "object", "vector" ]
0b2d6ee4c82ce2e077a5cea0507a63365e6ea654
3,869
cpp
C++
test/unit/src/PolyLineTest.cpp
rsh/Cinder-Emscripten
4a08250c56656865c7c3a52fb9380980908b1439
[ "BSD-2-Clause" ]
3,494
2015-01-02T08:42:09.000Z
2022-03-31T14:16:23.000Z
test/unit/src/PolyLineTest.cpp
rsh/Cinder-Emscripten
4a08250c56656865c7c3a52fb9380980908b1439
[ "BSD-2-Clause" ]
1,284
2015-01-02T07:31:47.000Z
2022-03-30T02:06:43.000Z
test/unit/src/PolyLineTest.cpp
rsh/Cinder-Emscripten
4a08250c56656865c7c3a52fb9380980908b1439
[ "BSD-2-Clause" ]
780
2015-01-02T22:14:29.000Z
2022-03-30T00:16:56.000Z
#include "cinder/app/App.h" #include "cinder/PolyLine.h" #include "catch.hpp" using namespace ci; using namespace ci::app; using namespace std; TEST_CASE("PolyLine2f") { SECTION("reverse") { vector<vec2> input( { vec2( 1, 2 ), vec2( 3, 4 ) } ); PolyLine2f p1( input ); p1.reverse(); CHECK( p1.getPoints()[0] == input[1] ); CHECK( p1.getPoints()[1] == input[0] ); PolyLine2f p2 = p1.reversed(); CHECK( p2.getPoints()[0] == input[0] ); CHECK( p2.getPoints()[1] == input[1] ); } SECTION("Orientation") { SECTION("Just two points") { vector<vec2> input({ vec2( 294.641, 105.359 ), vec2( 387.617, 12.3833 ), }); PolyLine2f p1 = PolyLine2f( input ); bool colinear; REQUIRE_FALSE( p1.isClockwise() ); REQUIRE_FALSE( p1.isClockwise( &colinear ) ); REQUIRE( colinear ); REQUIRE_FALSE( p1.isCounterclockwise() ); REQUIRE_FALSE( p1.isCounterclockwise( &colinear ) ); REQUIRE( colinear ); } SECTION("Three in a row") { vector<vec2> input({ vec2( 0, 0 ), vec2( 100, 0 ), vec2( -29, 0 ) }); PolyLine2f p1 = PolyLine2f( input ); bool colinear; REQUIRE_FALSE( p1.isClockwise() ); REQUIRE_FALSE( p1.isClockwise( &colinear ) ); REQUIRE( colinear ); REQUIRE_FALSE( p1.isCounterclockwise() ); REQUIRE_FALSE( p1.isCounterclockwise( &colinear ) ); REQUIRE( colinear ); } SECTION("Open polygon") { vector<vec2> input({ vec2( 294.641, 105.359 ), vec2( 387.617, 12.3833 ), vec2( 412.967, 2.96674 ), vec2( 417.987, -7.98667 ), vec2( 386.023, -94.0354 ) }); bool colinear; PolyLine2f p1 = PolyLine2f( input ); REQUIRE( p1.isClockwise() ); REQUIRE( p1.isClockwise( &colinear ) ); REQUIRE_FALSE( colinear ); reverse( input.begin(), input.end() ); PolyLine2f p2 = PolyLine2f( input ); REQUIRE_FALSE( p2.isClockwise() ); REQUIRE_FALSE( p2.isClockwise( &colinear ) ); REQUIRE_FALSE( colinear ); } SECTION("Closed polygon") { vector<vec2> input({ vec2( 294.641, 105.359 ), vec2( 387.617, 12.3833 ), vec2( 412.967, 2.96674 ), vec2( 417.987, -7.98667 ), vec2( 386.023, -94.0354 ), vec2( 294.641, 105.359 ) }); bool colinear; PolyLine2f p1 = PolyLine2f( input ); REQUIRE( p1.isClockwise() ); REQUIRE( p1.isClockwise( &colinear ) ); REQUIRE_FALSE( colinear ); reverse( input.begin(), input.end() ); PolyLine2f p2 = PolyLine2f( input ); REQUIRE_FALSE( p2.isClockwise() ); REQUIRE_FALSE( p2.isClockwise( &colinear ) ); REQUIRE_FALSE( colinear ); } } SECTION("contains") { SECTION("simple polygon") { // Square PolyLine2f poly( { vec2( 0, 0 ), vec2( 0, 1 ), vec2( 1, 1 ), vec2( 1, 0 ), vec2( 0, 0 ) } ); SECTION("points inside") { CHECK( poly.contains( vec2( 0.25, 0.5 ) ) ); CHECK( poly.contains( vec2( 0.5, 0.25 ) ) ); } SECTION("point outside") { CHECK_FALSE( poly.contains( vec2( -0.5, 0.25 ) ) ); } SECTION("point on vertex") { CHECK_FALSE( poly.contains( vec2( 0, 0 ) ) ); } SECTION("point on edge") { CHECK_FALSE( poly.contains( vec2( 0, 0.5 ) ) ); } } SECTION("self intersecting polygon") { // Infinity sign: |><| PolyLine2f poly( { vec2( 0, 0 ), vec2( 0, 1 ), vec2( 1, 0 ), vec2( 1, 1 ), vec2( 0, 0 ) } ); SECTION("point inside") { CHECK( poly.contains( vec2( 0.25, 0.5 ) ) ); } SECTION("point outside") { CHECK_FALSE( poly.contains( vec2( 0.5, 0.25 ) ) ); } SECTION("point on vertex") { CHECK_FALSE( poly.contains( vec2( 0, 1 ) ) ); } SECTION("point on edge") { CHECK_FALSE( poly.contains( vec2( 0.25, 0.25 ) ) ); } } } SECTION("calcCentroid") { PolyLine2f poly( { vec2( 0, 0 ), vec2( 0, 1 ), vec2( 1, 1 ), vec2( 1, 0 ) } ); CHECK( poly.calcCentroid() == vec2( 0.5, 0.5 ) ); } }
21.142077
95
0.581804
[ "vector" ]
0b321910a07be7748b259ca274fca432eb8bd73b
5,207
cpp
C++
Tools/Tools/DumpRenderTree/TestNetscapePlugIn.subproj/TestObject.cpp
VincentWei/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
Tools/Tools/DumpRenderTree/TestNetscapePlugIn.subproj/TestObject.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
null
null
null
Tools/Tools/DumpRenderTree/TestNetscapePlugIn.subproj/TestObject.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
/* * Copyright (C) 2007 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * 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 "TestObject.h" #include "PluginObject.h" #include <string.h> #include <stdlib.h> static bool testEnumerate(NPObject *npobj, NPIdentifier **value, uint32_t *count); static bool testHasMethod(NPObject*, NPIdentifier name); static bool testInvoke(NPObject*, NPIdentifier name, const NPVariant* args, uint32_t argCount, NPVariant* result); static bool testHasProperty(NPObject*, NPIdentifier name); static bool testGetProperty(NPObject*, NPIdentifier name, NPVariant*); static NPObject *testAllocate(NPP npp, NPClass *theClass); static void testDeallocate(NPObject *obj); static bool testConstruct(NPObject* obj, const NPVariant* args, uint32_t argCount, NPVariant* result); static NPClass testClass = { NP_CLASS_STRUCT_VERSION, testAllocate, testDeallocate, 0, testHasMethod, testInvoke, 0, testHasProperty, testGetProperty, 0, 0, testEnumerate, testConstruct }; NPClass *getTestClass(void) { return &testClass; } static bool identifiersInitialized = false; #define ID_OBJECT_POINTER 2 #define NUM_ENUMERATABLE_TEST_IDENTIFIERS 2 #define NUM_TEST_IDENTIFIERS 3 static NPIdentifier testIdentifiers[NUM_TEST_IDENTIFIERS]; static const NPUTF8 *testIdentifierNames[NUM_TEST_IDENTIFIERS] = { "foo", "bar", "objectPointer", }; #define ID_THROW_EXCEPTION_METHOD 0 #define NUM_METHOD_IDENTIFIERS 1 static NPIdentifier testMethodIdentifiers[NUM_METHOD_IDENTIFIERS]; static const NPUTF8 *testMethodIdentifierNames[NUM_METHOD_IDENTIFIERS] = { "throwException", }; static void initializeIdentifiers(void) { browser->getstringidentifiers(testIdentifierNames, NUM_TEST_IDENTIFIERS, testIdentifiers); browser->getstringidentifiers(testMethodIdentifierNames, NUM_METHOD_IDENTIFIERS, testMethodIdentifiers); } static NPObject *testAllocate(NPP /*npp*/, NPClass* /*theClass*/) { NPObject *newInstance = static_cast<NPObject*>(malloc(sizeof(NPObject))); if (!identifiersInitialized) { identifiersInitialized = true; initializeIdentifiers(); } return newInstance; } static void testDeallocate(NPObject *obj) { free(obj); } static bool testHasMethod(NPObject*, NPIdentifier name) { for (unsigned i = 0; i < NUM_METHOD_IDENTIFIERS; i++) { if (testMethodIdentifiers[i] == name) return true; } return false; } static bool testInvoke(NPObject* header, NPIdentifier name, const NPVariant* /*args*/, uint32_t /*argCount*/, NPVariant* /*result*/) { if (name == testMethodIdentifiers[ID_THROW_EXCEPTION_METHOD]) { browser->setexception(header, "test object throwException SUCCESS"); return true; } return false; } static bool testHasProperty(NPObject*, NPIdentifier name) { for (unsigned i = 0; i < NUM_TEST_IDENTIFIERS; i++) { if (testIdentifiers[i] == name) return true; } return false; } static bool testGetProperty(NPObject* npobj, NPIdentifier name, NPVariant* result) { if (name == testIdentifiers[ID_OBJECT_POINTER]) { int32_t objectPointer = static_cast<int32_t>(reinterpret_cast<long long>(npobj)); INT32_TO_NPVARIANT(objectPointer, *result); return true; } return false; } static bool testEnumerate(NPObject* /*npobj*/, NPIdentifier **value, uint32_t *count) { *count = NUM_ENUMERATABLE_TEST_IDENTIFIERS; *value = (NPIdentifier*)browser->memalloc(NUM_ENUMERATABLE_TEST_IDENTIFIERS * sizeof(NPIdentifier)); memcpy(*value, testIdentifiers, sizeof(NPIdentifier) * NUM_ENUMERATABLE_TEST_IDENTIFIERS); return true; } static bool testConstruct(NPObject* npobj, const NPVariant* /*args*/, uint32_t /*argCount*/, NPVariant* result) { browser->retainobject(npobj); // Just return the same object. OBJECT_TO_NPVARIANT(npobj, *result); return true; }
30.994048
132
0.733436
[ "object" ]
0b3297e10bf3a7af24bf6ca2fdb7f30a74ab7af3
1,145
cpp
C++
src/float32array.cpp
colinbdclark/node-dsp
840bf5ecad5b4ce7be8a421160163597317d451f
[ "MIT" ]
1
2019-03-05T16:52:41.000Z
2019-03-05T16:52:41.000Z
src/float32array.cpp
colinbdclark/node-dsp
840bf5ecad5b4ce7be8a421160163597317d451f
[ "MIT" ]
null
null
null
src/float32array.cpp
colinbdclark/node-dsp
840bf5ecad5b4ce7be8a421160163597317d451f
[ "MIT" ]
null
null
null
#include <node.h> #include "float32array.h" using namespace v8; Float32Array::Float32Array (Local<Object> obj) : data(NULL), length(0) { init(obj); } Float32Array::Float32Array (Local<Value> val) : data(NULL), length(0) { if (!val->IsObject()) return; init(val->ToObject()); } Local<Object> Float32Array::New (int length) { HandleScope scope; Local<Function> float32_array_constructor; Local<Object> global = Context::GetCurrent()->Global(); Local<Value> val = global->Get(String::New("Float32Array")); assert(!val.IsEmpty() && "type not found: Float32Array"); assert(val->IsFunction() && "not a constructor: Float32Array"); float32_array_constructor = Local<Function>::New(val.As<Function>()); Local<Value> size = Integer::NewFromUnsigned(length); Local<Object> array = float32_array_constructor->NewInstance(1, &size); return array; } void Float32Array::init (Local<Object> obj) { if ( obj->GetIndexedPropertiesExternalArrayDataType() != kExternalFloatArray ) return; length = obj->GetIndexedPropertiesExternalArrayDataLength(); data = static_cast<float*>( obj->GetIndexedPropertiesExternalArrayData() ); }
23.854167
73
0.727511
[ "object" ]
0b36a99fc0fe1bf25f86f57bd84067cb69c5b422
11,150
cpp
C++
src/PhilipsHueDSB/BridgeRT/AllJoynAbout.cpp
TheSuperShoe/IoT-Experiments
20fdc0075735ae2a9351f481a0067cfc6bd47947
[ "MIT" ]
1,433
2015-04-30T09:26:53.000Z
2022-03-26T12:44:12.000Z
AllJoyn/Platform/BridgeRT/AllJoynAbout.cpp
LeCampusAzure/ms-iot-samples
c0da021a312a631c8a26771a0d203e0de80fc597
[ "MIT" ]
530
2015-05-02T09:12:48.000Z
2018-01-03T17:52:01.000Z
AllJoyn/Platform/BridgeRT/AllJoynAbout.cpp
LeCampusAzure/ms-iot-samples
c0da021a312a631c8a26771a0d203e0de80fc597
[ "MIT" ]
1,878
2015-04-30T04:18:57.000Z
2022-03-15T16:51:17.000Z
// // Copyright (c) 2015, Microsoft Corporation // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #include "pch.h" #include <vector> #include <strsafe.h> #include "DsbServiceNames.h" #include "AllJoynAbout.h" #include "Shlwapi.h" #include "alljoyn_c/AjAPI.h" #include "BridgeUtils.h" using namespace BridgeRT; using namespace Windows::Storage; using namespace Platform; #define APPDATA_CONTAINER_DSB_SETTINGS L"DSBSettings" #define DSB_SETTING_DEVICE_ID L"ID" static const size_t DEVICE_GUID_STRING_LEN = 39; // 38 chars + terminator null static const char DEFAULT_LANGUAGE_FOR_ABOUT[] = "en"; static const WCHAR UNKNOWN_ADAPTER[] = L"Unknown device"; static const WCHAR UNKNOWN_MANUFACTURER[] = L"Unknown"; static const WCHAR UNKNOWN_VERSION[] = L"0.0.0.0"; static const WCHAR DSB_DEFAULT_APP_NAME[] = L"Device System Bridge"; static const WCHAR DSB_DEFAULT_MODEL[] = L"DSB"; static const WCHAR DSB_DEFAULT_DESCRIPTION[] = L"Device System Bridge"; // {EF116A26-9888-47C2-AE85-B77142F24EFA} static const GUID DSB_DEFAULT_APP_GUID = { 0xef116a26, 0x9888, 0x47c2,{ 0xae, 0x85, 0xb7, 0x71, 0x42, 0xf2, 0x4e, 0xfa } }; AllJoynAbout::AllJoynAbout() : m_aboutData(NULL), m_aboutObject(NULL), m_isAnnounced(false) { } AllJoynAbout::~AllJoynAbout() { ShutDown(); } QStatus AllJoynAbout::Initialize(_In_ alljoyn_busattachment bus) { QStatus status = ER_OK; // sanity check if (NULL == bus) { status = ER_BAD_ARG_1; goto leave; } // create the about object that is used to communicate about data // note that the about interface won't be part of the announce m_aboutObject = alljoyn_aboutobj_create(bus, UNANNOUNCED); if (NULL == m_aboutObject) { status = ER_OUT_OF_MEMORY; goto leave; } // create about data with default language m_aboutData = alljoyn_aboutdata_create(DEFAULT_LANGUAGE_FOR_ABOUT); if (NULL == m_aboutData) { status = ER_OUT_OF_MEMORY; goto leave; } // fill about data with default value status = SetDefaultAboutData(); leave: if (ER_OK != status) { ShutDown(); } return status; } void AllJoynAbout::ShutDown() { if (NULL != m_aboutObject) { if (m_isAnnounced) { alljoyn_aboutobj_unannounce(m_aboutObject); } alljoyn_aboutobj_destroy(m_aboutObject); m_aboutObject = NULL; m_isAnnounced = false; } if (NULL != m_aboutData) { alljoyn_aboutdata_destroy(m_aboutData); m_aboutData = NULL; } } QStatus AllJoynAbout::Announce(alljoyn_sessionport sp) { QStatus status = ER_OK; // sanity check if (NULL == m_aboutObject) { status = ER_INIT_FAILED; goto leave; } if (!alljoyn_aboutdata_isvalid(m_aboutData, DEFAULT_LANGUAGE_FOR_ABOUT)) { status = ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD; goto leave; } status = alljoyn_aboutobj_announce(m_aboutObject, sp, m_aboutData); if (ER_OK != status) { goto leave; } m_isAnnounced = true; leave: return status; } QStatus AllJoynAbout::AddObject(_In_ alljoyn_busobject busObject, _In_ const alljoyn_interfacedescription interfaceDescription) { return alljoyn_busobject_setannounceflag(busObject, interfaceDescription, ANNOUNCED); } QStatus AllJoynAbout::RemoveObject(_In_ alljoyn_busobject busObject, _In_ const alljoyn_interfacedescription interfaceDescription) { return alljoyn_busobject_setannounceflag(busObject, interfaceDescription, UNANNOUNCED); } QStatus AllJoynAbout::SetManufacturer(_In_z_ const wchar_t* value) { std::string stringValue = ConvertTo<std::string>(value); return alljoyn_aboutdata_setmanufacturer(m_aboutData, stringValue.c_str(), nullptr); } QStatus AllJoynAbout::SetDeviceName(_In_z_ const wchar_t *value) { std::string stringValue = ConvertTo<std::string>(value); return alljoyn_aboutdata_setdevicename(m_aboutData, stringValue.c_str(), nullptr); } QStatus AllJoynAbout::SetSWVersion(_In_z_ const wchar_t *value) { std::string stringValue = ConvertTo<std::string>(value); return alljoyn_aboutdata_setsoftwareversion(m_aboutData, stringValue.c_str()); } QStatus AllJoynAbout::SetHWVersion(_In_z_ const wchar_t *value) { std::string stringValue = ConvertTo<std::string>(value); return alljoyn_aboutdata_sethardwareversion(m_aboutData, stringValue.c_str()); } QStatus AllJoynAbout::SetDeviceId(_In_z_ const wchar_t * value) { std::string stringValue = ConvertTo<std::string>(value); return alljoyn_aboutdata_setdeviceid(m_aboutData, stringValue.c_str()); } QStatus AllJoynAbout::SetModel(_In_z_ const wchar_t * value) { std::string stringValue = ConvertTo<std::string>(value); return alljoyn_aboutdata_setmodelnumber(m_aboutData, stringValue.c_str()); } QStatus AllJoynAbout::SetDescription(_In_z_ const wchar_t * value) { std::string stringValue = ConvertTo<std::string>(value); return alljoyn_aboutdata_setdescription(m_aboutData, stringValue.c_str(), nullptr); } QStatus AllJoynAbout::SetApplicationName(_In_z_ const wchar_t *value) { std::string stringValue = ConvertTo<std::string>(value); return alljoyn_aboutdata_setappname(m_aboutData, stringValue.c_str(), nullptr); } QStatus AllJoynAbout::SetApplicationGuid(_In_ const GUID &value) { uint8_t buffer[sizeof(value)]; int offset = 0; // convert GUID into array of unsigned int 8 using the right endian order *((unsigned long *)&buffer[offset]) = _byteswap_ulong(value.Data1); offset += sizeof(value.Data1); *((unsigned short *)&buffer[offset]) = _byteswap_ushort(value.Data2); offset += sizeof(value.Data2); *((unsigned short *)&buffer[offset]) = _byteswap_ushort(value.Data3); offset += sizeof(value.Data3); for (int index = 0; index < sizeof(value.Data4); index++) { buffer[offset + index] = value.Data4[index]; } return alljoyn_aboutdata_setappid(m_aboutData, buffer, sizeof(buffer)); } QStatus AllJoynAbout::SetDefaultAboutData() { QStatus status = ER_OK; std::string deviceId; std::string deviceName; // only set the required fields: // - DefaultLanguage (already set upon m_aboutData creation) // - DeviceId // - DeviceName // - AppId // - AppName // - Manufacturer // - ModelNumber // - Description // - SoftwareVersion // default device ID to bridge device Id CHK_AJSTATUS( GetDeviceID(deviceId) ); CHK_AJSTATUS( alljoyn_aboutdata_setdeviceid(m_aboutData, deviceId.c_str())); // default about data to bridge about data CHK_AJSTATUS(SetDeviceName(UNKNOWN_ADAPTER)); CHK_AJSTATUS(SetSWVersion(UNKNOWN_VERSION)); CHK_AJSTATUS(SetDescription(DSB_DEFAULT_DESCRIPTION)); CHK_AJSTATUS(SetApplicationGuid(DSB_DEFAULT_APP_GUID)); CHK_AJSTATUS(SetApplicationName(DSB_DEFAULT_APP_NAME)); CHK_AJSTATUS(SetManufacturer(UNKNOWN_MANUFACTURER)); CHK_AJSTATUS(SetModel(DSB_DEFAULT_MODEL)); if (!alljoyn_aboutdata_isvalid(m_aboutData, DEFAULT_LANGUAGE_FOR_ABOUT)) { status = ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD; } leave: return status; } QStatus AllJoynAbout::ReadDeviceID(_Out_ std::wstring &deviceId) { QStatus status = ER_OK; auto localSettings = ApplicationData::Current->LocalSettings; auto container = localSettings->CreateContainer(APPDATA_CONTAINER_DSB_SETTINGS, ApplicationDataCreateDisposition::Always); // empty output string deviceId.clear(); if (localSettings->Containers->HasKey(APPDATA_CONTAINER_DSB_SETTINGS)) { auto values = localSettings->Containers->Lookup(APPDATA_CONTAINER_DSB_SETTINGS)->Values; //check if the id exists bool idPresent = values->HasKey(DSB_SETTING_DEVICE_ID); if (idPresent) { //get the value String^ value = dynamic_cast<String^>(values->Lookup(DSB_SETTING_DEVICE_ID)); if (!value || value->IsEmpty()) { status = ER_FAIL; } else { deviceId = value->Data(); } } else { status = ER_FAIL; } } else { status = ER_FAIL; } return status; } QStatus AllJoynAbout::CreateAndSaveDeviceID(_Out_ std::wstring &deviceId) { QStatus status = ER_OK; HRESULT hr = S_OK; GUID guid = { 0 }; int length = 0; WCHAR *tempGuid = nullptr; WCHAR tempString[DEVICE_GUID_STRING_LEN]; // empty output string deviceId.clear(); //Create GUID hr = ::CoCreateGuid(&guid); if (FAILED(hr)) { status = ER_FAIL; goto leave; } //Convert GUID into String length = ::StringFromGUID2(guid, tempString, DEVICE_GUID_STRING_LEN); if (0 == length) { status = ER_FAIL; goto leave; } // remove '{' and '}' from GUID string tempGuid = tempString; if (tempString[length - 2] == L'}') { tempString[length - 2] = L'\0'; } if (tempString[0] == L'{') { tempGuid = &tempString[1]; } deviceId = tempGuid; { //create the setting auto localSettings = ApplicationData::Current->LocalSettings; auto container = localSettings->CreateContainer(APPDATA_CONTAINER_DSB_SETTINGS, ApplicationDataCreateDisposition::Always); if (localSettings->Containers->HasKey(APPDATA_CONTAINER_DSB_SETTINGS)) { auto values = localSettings->Containers->Lookup(APPDATA_CONTAINER_DSB_SETTINGS)->Values; values->Insert(DSB_SETTING_DEVICE_ID, ref new String(deviceId.c_str())); } else { status = ER_FAIL; goto leave; } } leave: if (ER_OK != status) { // reset device Id in case of error deviceId.clear(); } return status; } QStatus AllJoynAbout::GetDeviceID(_Out_ std::string &deviceId) { QStatus status = ER_OK; std::wstring tempId; // reset out param deviceId.clear(); // read device Id (create it if necessary) status = ReadDeviceID(tempId); if (status != ER_OK) { status = CreateAndSaveDeviceID(tempId); if (status != ER_OK) { goto leave; } } //convert types deviceId = ConvertTo<std::string>(tempId); leave: return status; }
27.59901
130
0.68296
[ "object", "vector" ]
0b392bfe1fd211c9f9ffd5e2c10e09ce1fff6384
7,598
hh
C++
aspects/fluid/source/test/UtGunnsFluidSimpleH2Redox.hh
nasa/gunns
248323939a476abe5178538cd7a3512b5f42675c
[ "NASA-1.3" ]
18
2020-01-23T12:14:09.000Z
2022-02-27T22:11:35.000Z
aspects/fluid/source/test/UtGunnsFluidSimpleH2Redox.hh
nasa/gunns
248323939a476abe5178538cd7a3512b5f42675c
[ "NASA-1.3" ]
39
2020-11-20T12:19:35.000Z
2022-02-22T18:45:55.000Z
aspects/fluid/source/test/UtGunnsFluidSimpleH2Redox.hh
nasa/gunns
248323939a476abe5178538cd7a3512b5f42675c
[ "NASA-1.3" ]
7
2020-02-10T19:25:43.000Z
2022-03-16T01:10:00.000Z
#ifndef UtGunnsFluidSimpleH2Redox_EXISTS #define UtGunnsFluidSimpleH2Redox_EXISTS //////////////////////////////////////////////////////////////////////////////////////////////////// /// @defgroup UT_TSM_GUNNS_FLUID_SOURCE_SIMPLE_H2_REDOX Simple H2 Redox Unit Tests /// @ingroup UT_TSM_GUNNS_FLUID_SOURCE /// /// @copyright Copyright 2019 United States Government as represented by the Administrator of the /// National Aeronautics and Space Administration. All Rights Reserved. /// /// @details Unit Tests for the GUNNS Fluid Simple H2 Redox link model. /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestFixture.h> #include "aspects/fluid/source/GunnsFluidSimpleH2Redox.hh" //////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Inherit from GunnsFluidSimpleH2Redox and befriend UtGunnsFluidSimpleH2Redox. /// /// @details Class derived from the unit under test. It just has a constructor with the same /// arguments as the parent and a default destructor, but it befriends the unit test case /// driver class to allow it access to protected data members. //////////////////////////////////////////////////////////////////////////////////////////////////// class FriendlyGunnsFluidSimpleH2Redox : public GunnsFluidSimpleH2Redox { public: FriendlyGunnsFluidSimpleH2Redox(); virtual ~FriendlyGunnsFluidSimpleH2Redox(); friend class UtGunnsFluidSimpleH2Redox; }; inline FriendlyGunnsFluidSimpleH2Redox::FriendlyGunnsFluidSimpleH2Redox() : GunnsFluidSimpleH2Redox() {}; inline FriendlyGunnsFluidSimpleH2Redox::~FriendlyGunnsFluidSimpleH2Redox() {} //////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Simple H2 Redox unit tests. //// /// @details This class provides the unit tests for the GUNNS Fluid Simple H2 Redox link model /// within the CPPUnit framework. //////////////////////////////////////////////////////////////////////////////////////////////////// class UtGunnsFluidSimpleH2Redox: public CppUnit::TestFixture { public: /// @brief Default constructs this Simple H2 Redox unit test. UtGunnsFluidSimpleH2Redox(); /// @brief Default constructs this Simple H2 Redox unit test. virtual ~UtGunnsFluidSimpleH2Redox(); /// @brief Executes before each test. void setUp(); /// @brief Executes after each test. void tearDown(); /// @brief Tests config and input data. void testConfigAndInput(); /// @brief Tests default construction. void testDefaultConstruction(); /// @brief Tests initialize method. void testNominalInitialization(); /// @brief Tests accessor methods. void testAccessors(); /// @brief Tests modifier methods. void testModifiers(); /// @brief Tests restart method. void testRestart(); /// @brief Tests step method. void testStep(); /// @brief Tests computeFlows method. void testComputeFlows(); /// @brief Tests transportFlows method. void testTransportFlows(); /// @brief Tests specific port mapping rules. void testPortMapping(); /// @brief Tests initialize method exceptions. void testInitializationExceptions(); private: CPPUNIT_TEST_SUITE(UtGunnsFluidSimpleH2Redox); CPPUNIT_TEST(testConfigAndInput); CPPUNIT_TEST(testDefaultConstruction); CPPUNIT_TEST(testNominalInitialization); CPPUNIT_TEST(testAccessors); CPPUNIT_TEST(testModifiers); CPPUNIT_TEST(testRestart); CPPUNIT_TEST(testStep); CPPUNIT_TEST(testComputeFlows); CPPUNIT_TEST(testTransportFlows); CPPUNIT_TEST(testPortMapping); CPPUNIT_TEST(testInitializationExceptions); CPPUNIT_TEST_SUITE_END(); /// @brief Enumeration for the number of nodes and fluid constituents. enum {N_NODES = 5, N_FLUIDS = 5}; DefinedFluidProperties* tFluidProperties; /**< (--) Defined fluid properties. */ FluidProperties::FluidType tTypes[N_FLUIDS]; /**< (--) Array of Fluid Types. */ PolyFluidConfigData* tFluidConfig; /**< (--) Fluid config data. */ PolyFluidInputData* tFluidInput0; /**< (--) Fluid 0 input data. */ PolyFluidInputData* tFluidInput1; /**< (--) Fluid 1 input data. */ PolyFluidInputData* tFluidInput2; /**< (--) Fluid 2 input data. */ std::vector<GunnsBasicLink*> tLinks; /**< (--) Link vector. */ std::string tName; /**< (--) Nominal name. */ GunnsFluidNode tNodes[N_NODES]; /**< (--) Fluid nodes. */ GunnsNodeList tNodeList; /**< (--) Node List. */ int tPort0; /**< (--) Nominal H2/H2O port index. */ int tPort1; /**< (--) Nominal O2 port index. */ int tNumCells; /**< (--) Nominal config data. */ double tCellVoltageLoaded; /**< (V) Nominal config data. */ double tCellH2ReactRate; /**< (kg/s/amp) Nominal config data. */ double tMaxEfficiency; /**< (--) Nominal config data. */ GunnsFluidSimpleH2RedoxConfigData* tConfigData; /**< (-) Pointer to nominal configuration data. */ bool tMalfBlockageFlag; /**< (--) Nominal input data. */ double tMalfBlockageValue; /**< (--) Nominal input data. */ double tCurrent; /**< (amp) Nominal input data. */ bool tTrippedOff; /**< (--) Nominal input data. */ GunnsFluidSimpleH2RedoxInputData* tInputData; /**< (--) Pointer to nominal input data. */ FriendlyGunnsFluidSimpleH2Redox* tArticle; /**< (--) Pointer to the friendly adsorber under test. */ double tTimeStep; /**< (s) Nominal time step. */ static int TEST_ID; /**< (--) Test identification number. */ //////////////////////////////////////////////////////////////////////////////////////////// /// @details Copy constructor unavailable since declared private and not implemented. //////////////////////////////////////////////////////////////////////////////////////////// UtGunnsFluidSimpleH2Redox(const UtGunnsFluidSimpleH2Redox&); //////////////////////////////////////////////////////////////////////////////////////////// /// @details Assignment operator unavailable since declared private and not implemented. //////////////////////////////////////////////////////////////////////////////////////////// UtGunnsFluidSimpleH2Redox& operator =(const UtGunnsFluidSimpleH2Redox&); }; ///@} #endif
58.446154
126
0.504475
[ "vector", "model" ]
0b3e64211e9da5f5099b73bffe01ede79522762b
29,601
cpp
C++
Editor/Project_Json.cpp
humdingerb/Medo
61616300a5379e4985cb44dd41af512345e3289c
[ "MIT" ]
95
2020-12-23T02:35:35.000Z
2022-02-20T19:30:13.000Z
Editor/Project_Json.cpp
humdingerb/Medo
61616300a5379e4985cb44dd41af512345e3289c
[ "MIT" ]
21
2020-12-23T05:01:36.000Z
2022-01-11T08:38:26.000Z
Editor/Project_Json.cpp
humdingerb/Medo
61616300a5379e4985cb44dd41af512345e3289c
[ "MIT" ]
8
2020-12-23T04:47:34.000Z
2021-08-29T17:18:56.000Z
/* PROJECT: Medo * AUTHORS: Zenja Solaja, Melbourne Australia * COPYRIGHT: Zen Yes Pty Ltd, 2019-2021 * DESCRIPTION: Project data */ #include <cstdio> #include <cstdlib> #include <vector> #include <support/String.h> #include <support/SupportDefs.h> #include <interface/Alert.h> #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "Project.h" #include "FileUtility.h" #include "MediaSource.h" #include "MedoWindow.h" #include "TimelineView.h" #include "EffectsManager.h" #include "EffectNode.h" #include "RenderActor.h" struct SOURCE { unsigned int id; MediaSource::MEDIA_TYPE type; std::string filename; std::string label; }; static const char *kMediaType[] = {"invalid", "video", "audio", "video_audio", "image"}; static_assert(sizeof(kMediaType)/sizeof(char *) == MediaSource::NUMBER_MEDIA_TYPES, "sizeof(kMediaType) != MediaSource::NUMBER_MEDIA_TYPES"); struct CLIP { unsigned int id; unsigned int source; int64 start; int64 end; int64 timeline; BString tag; bool video_enabled; bool audio_enabled; }; struct EFFECT { unsigned int id; MediaEffect *media_effect; }; struct NOTE { unsigned int id; int64 timeline; BString text; }; struct TRACK { unsigned int id; bool global; bool video_enabled; bool audio_enabled; float audio_levels[2]; std::vector<unsigned int> clips; std::vector<unsigned int> effects; std::vector<unsigned int> notes; }; /* FUNCTION: LoadProject ARGUMENTS: data clear_media RETURN: true if successful DESCRIPTION: Parse "*.medo" json file */ const bool Project :: LoadProject(const char *data, const bool clear_media) { RESOLUTION inResolution; std::vector<SOURCE> inSources; std::vector<CLIP> inClips; std::vector<EFFECT> inEffects; std::vector<NOTE> inNotes; std::vector<TRACK> inTracks; TimelineView::SESSION inSession; #define ERROR_EXIT(a) {printf("Project::LoadProject() Error(%s)\n", a); return false;} rapidjson::Document document; rapidjson::ParseResult res = document.Parse<rapidjson::kParseTrailingCommasFlag>(data); if (!res) { printf("JSON parse error: %s (Byte offset: %lu)\n", rapidjson::GetParseError_En(res.Code()), res.Offset()); for (int c=-20; c < 20; c++) printf("%c", data[res.Offset() + c]); printf("\n"); ERROR_EXIT("Invalid JSON"); } //if (!document.IsObject()) // ERROR_EXIT("Invalid JSON"); // "medo" (header) { if (!document.HasMember("medo")) ERROR_EXIT("Missing object \"medo\""); const rapidjson::Value &header = document["medo"]; if (!header.HasMember("version") || !header["version"].IsInt()) ERROR_EXIT("Missing attribute medo::version"); int version = header["version"].GetInt(); if (version != 1) ERROR_EXIT("medo::version != 1"); } // "resolution" { if (!document.HasMember("resolution")) ERROR_EXIT("Missing object \"resolution\""); const rapidjson::Value &resolution = document["resolution"]; if (!resolution.HasMember("width") || !resolution["width"].IsUint()) ERROR_EXIT("Missing attribute resolution::width"); inResolution.width = resolution["width"].GetUint(); if (!resolution.HasMember("height") || !resolution["height"].IsUint()) ERROR_EXIT("Missing attribute resolution::height"); inResolution.height = resolution["height"].GetUint(); if (!resolution.HasMember("frame_rate") || !resolution["frame_rate"].IsFloat()) ERROR_EXIT("Missing attribute resolution::frame_rate"); inResolution.frame_rate = resolution["frame_rate"].GetFloat(); } // "sources" { if (!document.HasMember("sources")) ERROR_EXIT("Missing object \"sources\""); const rapidjson::Value &sources = document["sources"]; if (!sources.IsArray()) ERROR_EXIT("\"sources\" is not an array"); for (auto &v : sources.GetArray()) { SOURCE aSource; // "id" if (!v.HasMember("id") || !v["id"].IsUint()) ERROR_EXIT("Missing attribute source::id"); aSource.id = v["id"].GetUint(); bool valid_id = true; for (auto i : inSources) { if (aSource.id == i.id) valid_id = false; } if (!valid_id) ERROR_EXIT("Duplicate sources::id"); // "type" if (!v.HasMember("type") || !v["type"].IsString()) ERROR_EXIT("Missing attribute sources::type"); const char *type = v["type"].GetString(); bool valid_source_type = false; for (size_t i=0; i < sizeof(kMediaType)/sizeof(char *); i++) { if (strcmp(type, kMediaType[i]) == 0) { aSource.type = (MediaSource::MEDIA_TYPE) i; valid_source_type = true; break; } } if (!valid_source_type) ERROR_EXIT("Invalid sources::type"); // "file" if (!v.HasMember("file") || !v["file"].IsString()) ERROR_EXIT("Missing attribute sources::file"); aSource.filename.assign(v["file"].GetString()); // "label" if (v.HasMember("label") && v["label"].IsString()) aSource.label.assign(v["label"].GetString()); FILE *file = fopen(aSource.filename.c_str(), "rb"); if (!file) { BAlert *alert = new BAlert("Invisible title", aSource.filename.c_str(), "File not found"); alert->Go(); ERROR_EXIT("Attribute sources::file"); } fclose(file); inSources.push_back(aSource); } } // "clips" { if (!document.HasMember("clips")) ERROR_EXIT("Missing object \"clips\""); const rapidjson::Value &clips = document["clips"]; if (!clips.IsArray()) ERROR_EXIT("\"clips\" is not an array"); for (auto &v : clips.GetArray()) { CLIP aClip; // "id" if (!v.HasMember("id") || !v["id"].IsUint()) ERROR_EXIT("Missing attribute clips::id"); aClip.id = v["id"].GetUint(); bool valid_id = true; for (auto i : inClips) { if (aClip.id == i.id) valid_id = false; } if (!valid_id) ERROR_EXIT("Duplicate clips::id"); // "source" if (!v.HasMember("source") || !v["source"].IsUint()) ERROR_EXIT("Missing attribute clips::source"); aClip.source = v["source"].GetUint(); bool valid_source = false; for (auto &source : inSources) { if (aClip.source == source.id) { valid_source = true; break; } } if (!valid_source) ERROR_EXIT("Clip refers to invalid source"); // "start" if (!v.HasMember("start") || !v["start"].IsInt64()) ERROR_EXIT("Missing attribute clips::start"); aClip.start = v["start"].GetInt64(); // "end" if (!v.HasMember("end") || !v["end"].IsInt64()) ERROR_EXIT("Missing attribute clips::end"); aClip.end = v["end"].GetInt64(); // "timeline" if (!v.HasMember("timeline") || !v["timeline"].IsInt64()) ERROR_EXIT("Missing attribute clips::timeline"); aClip.timeline = v["timeline"].GetInt64(); // "video_enabled" if (!v.HasMember("video_enabled") || (!v["video_enabled"].IsBool())) ERROR_EXIT("Missing attribute clips::video_enabled"); aClip.video_enabled = v["video_enabled"].GetBool(); // "audio_enabled" if (!v.HasMember("audio_enabled") || (!v["audio_enabled"].IsBool())) ERROR_EXIT("Missing attribute clips::audio_enabled"); aClip.audio_enabled = v["audio_enabled"].GetBool(); // "tag" if (v.HasMember("tag")) { if (!v["tag"].IsString()) ERROR_EXIT("Clip has invalid tag"); aClip.tag.SetTo(v["tag"].GetString()); } inClips.push_back(aClip); } } // "effects" { if (!document.HasMember("effects")) ERROR_EXIT("Missing object \"effects\""); const rapidjson::Value &effects = document["effects"]; if (!effects.IsArray()) ERROR_EXIT("\"effects\" is not an array"); for (auto &v : effects.GetArray()) { EFFECT anEffect; // "id" if (!v.HasMember("id") || !v["id"].IsUint()) ERROR_EXIT("Missing attribute effects::id"); anEffect.id = v["id"].GetInt(); bool valid_id = true; for (auto i : inEffects) { if (anEffect.id == i.id) valid_id = false; } if (!valid_id) ERROR_EXIT("Duplicate effects::id"); // "vendor" if (!v.HasMember("vendor") || !v["vendor"].IsString()) ERROR_EXIT("Missing attribute effects::vendor"); std::string effect_vendor(v["vendor"].GetString()); // "name" if (!v.HasMember("name") || !v["name"].IsString()) ERROR_EXIT("Missing attribute effects::name"); std::string effect_name(v["name"].GetString()); anEffect.media_effect = gEffectsManager->CreateMediaEffect(effect_vendor.c_str(), effect_name.c_str()); if (anEffect.media_effect) { // "start" if (!v.HasMember("start") || !v["start"].IsInt64()) ERROR_EXIT("Missing attribute effects::start"); anEffect.media_effect->mTimelineFrameStart = v["start"].GetInt64(); // "end" if (!v.HasMember("end") || !v["end"].IsInt64()) ERROR_EXIT("Missing attribute effects::end"); anEffect.media_effect->mTimelineFrameEnd = v["end"].GetInt64(); // "priority" if (!v.HasMember("priority") || !v["priority"].IsInt()) ERROR_EXIT("Missing attribute effects::priority"); anEffect.media_effect->mPriority = v["priority"].GetInt(); // "enabled" if (!v.HasMember("enabled") || !v["enabled"].IsBool()) ERROR_EXIT("Missing attribute effects::enabled"); anEffect.media_effect->mEnabled = v["enabled"].GetBool(); // "parameters" if (v.HasMember("parameters")) { anEffect.media_effect->mEffectNode->LoadParameters(v["parameters"], anEffect.media_effect); // TODO //anEffect.media_effect has_parameters = false; } else ;//anEffect.has_parameters = false; inEffects.push_back(anEffect); } } } // "notes" { if (!document.HasMember("notes")) ERROR_EXIT("Missing object \"notes\""); const rapidjson::Value &notes = document["notes"]; if (!notes.IsArray()) ERROR_EXIT("\"notes\" is not an array"); for (auto &v : notes.GetArray()) { NOTE aNote; // "id" if (!v.HasMember("id") || !v["id"].IsUint()) ERROR_EXIT("Missing attribute notes::id"); aNote.id = v["id"].GetInt(); bool valid_id = true; for (auto i : inNotes) { if (aNote.id == i.id) valid_id = false; } if (!valid_id) ERROR_EXIT("Duplicate notes::id"); // "timeline" if (!v.HasMember("timeline") || !v["timeline"].IsInt64()) ERROR_EXIT("Missing attribute notes::timeline"); aNote.timeline = v["timeline"].GetInt64(); // "text" if (!v.HasMember("text") || !v["text"].IsString()) ERROR_EXIT("Missing attribute notes::text"); aNote.text.SetTo(v["text"].GetString()); inNotes.push_back(aNote); } } // "tracks" { if (!document.HasMember("tracks")) ERROR_EXIT("Missing object \"tracks\""); const rapidjson::Value &tracks = document["tracks"]; if (!tracks.IsArray()) ERROR_EXIT("\"tracks\" is not an array"); for (auto &v : tracks.GetArray()) { TRACK aTrack; // "id" if (!v.HasMember("id") || !v["id"].IsUint()) ERROR_EXIT("Missing attribute tracks::id"); aTrack.id = v["id"].GetInt(); bool valid_id = true; for (auto i : inTracks) { if (aTrack.id == i.id) valid_id = false; } if (!valid_id) ERROR_EXIT("Duplicate tracks::id"); // "global" if (v.HasMember("global")) { if (!v["global"].IsBool()) ERROR_EXIT("Corrupt attribute tracks::global"); aTrack.global = v["global"].GetBool(); } else aTrack.global = false; // "video_enabled" if (v.HasMember("video_enabled") && v["video_enabled"].IsBool()) aTrack.video_enabled = v["video_enabled"].GetBool(); else ERROR_EXIT("Corrupt attribute tracks::video_enabled"); // "audio_enabled" if (v.HasMember("audio_enabled") && v["audio_enabled"].IsBool()) aTrack.audio_enabled = v["audio_enabled"].GetBool(); else ERROR_EXIT("Corrupt attribute tracks::video_enabled"); // levels if (!v.HasMember("levels") || !v["levels"].IsArray()) ERROR_EXIT("track::\"levels\" is not an array"); const rapidjson::Value &levels = v["levels"]; if (levels.GetArray().Size() != 2) ERROR_EXIT("track::\"levels\" size must be 2"); for (rapidjson::SizeType lvl=0; lvl < levels.GetArray().Size(); lvl++) { if (!levels.GetArray()[lvl].IsFloat()) ERROR_EXIT("Invalid track::\"levels\" member (must be float)"); aTrack.audio_levels[lvl] = levels.GetArray()[lvl].GetFloat(); if (aTrack.audio_levels[lvl] < 0.0f) aTrack.audio_levels[lvl] = 0.0f; if (aTrack.audio_levels[lvl] > 2.0f) aTrack.audio_levels[lvl] = 2.0f; } //clips if (!v.HasMember("clips") || !v["clips"].IsArray()) ERROR_EXIT("track::\"clips\" is not an array"); const rapidjson::Value &clips = v["clips"]; rapidjson::SizeType num_clips = clips.GetArray().Size(); for (rapidjson::SizeType c=0; c < num_clips; c++) { if (!clips.GetArray()[c].IsUint()) ERROR_EXIT("Invalid tracks::clips::reference"); unsigned int clip_id = clips.GetArray()[c].GetUint(); bool valid_clip_id = false; for (auto &i : inClips) { if (clip_id == i.id) { valid_clip_id = true; break; } } if (!valid_clip_id) { printf("clip_id == %d\n", clip_id); ERROR_EXIT("Invalid tracks::clips::clip_id"); } aTrack.clips.push_back(clip_id); } // effects if (!v.HasMember("effects") || !v["effects"].IsArray()) ERROR_EXIT("track::\"effects\" is not an array"); const rapidjson::Value &effects = v["effects"]; rapidjson::SizeType num_effects = effects.GetArray().Size(); for (rapidjson::SizeType e=0; e < num_effects; e++) { if (!effects.GetArray()[e].IsUint()) ERROR_EXIT("Invalid tracks::effects::reference"); unsigned int effect_id = effects.GetArray()[e].GetUint(); bool valid_effect_id = false; for (auto &i : inEffects) { if (effect_id == i.id) { valid_effect_id = true; break; } } if (!valid_effect_id) ERROR_EXIT("Invalid tracks::effects::effect_id"); aTrack.effects.push_back(effect_id); } // notes if (!v.HasMember("notes") || !v["notes"].IsArray()) ERROR_EXIT("track::\"notes\" is not an array"); const rapidjson::Value &notes = v["notes"]; rapidjson::SizeType num_notes = notes.GetArray().Size(); for (rapidjson::SizeType n=0; n < num_notes; n++) { if (!notes.GetArray()[n].IsUint()) ERROR_EXIT("Invalid tracks::notes::reference"); unsigned int note_id = notes.GetArray()[n].GetUint(); bool valid_note_id = false; for (auto &i : inNotes) { if (note_id == i.id) { valid_note_id = true; break; } } if (!valid_note_id) ERROR_EXIT("Invalid tracks::notes::note_id"); aTrack.notes.push_back(note_id); } inTracks.push_back(aTrack); } } // "session" if (document.HasMember("session")) { const rapidjson::Value &session = document["session"]; if (!session.HasMember("horizontal_scroll") || !session["horizontal_scroll"].IsFloat()) ERROR_EXIT("Missing attribute session::horizontal_scroll"); inSession.horizontal_scroll = session["horizontal_scroll"].GetFloat(); if (!session.HasMember("vertical_scroll") || !session["vertical_scroll"].IsFloat()) ERROR_EXIT("Missing attribute session::vertical_scroll"); inSession.vertical_scroll = session["vertical_scroll"].GetFloat(); if (!session.HasMember("zoom_index") || !session["zoom_index"].IsUint()) ERROR_EXIT("Missing attribute session::zoom_index"); inSession.zoom_index = session["zoom_index"].GetUint(); if (!session.HasMember("current_frame") || !session["current_frame"].IsInt64()) ERROR_EXIT("Missing attribute session::current_frame"); inSession.current_frame = session["current_frame"].GetInt64(); if (!session.HasMember("marker_a") || !session["marker_a"].IsInt64()) ERROR_EXIT("Missing attribute session::marker_a"); inSession.marker_a = session["marker_a"].GetInt64(); if (!session.HasMember("marker_b") || !session["marker_b"].IsInt64()) ERROR_EXIT("Missing attribute session::marker_b"); inSession.marker_b = session["marker_b"].GetInt64(); } // TODO check if source exists // TODO check if clip end valid // Reset project if (clear_media) { MedoWindow::GetInstance()->RemoveAllMediaSources(); } while (gProject->mTimelineTracks.size() > 0) gProject->RemoveTimelineTrack(gProject->mTimelineTracks[0]); bool same_resolution = (gProject->mResolution.width == inResolution.width) && (gProject->mResolution.height == inResolution.height); gProject->mResolution.width = inResolution.width; gProject->mResolution.height = inResolution.height; gProject->mResolution.frame_rate = inResolution.frame_rate; if (!same_resolution) { // Recreate RenderView (different thread) sem_id sem = create_sem(0, "invalidate_project"); if (sem < B_OK) { printf("Project::LoadProject() Cannot create sem\n"); exit(1); } gRenderActor->Async(&RenderActor::AsyncInvalidateProjectSettings, gRenderActor, sem); acquire_sem(sem); delete_sem(sem); } // Sources for (auto &s : inSources) { MediaSource *source = MedoWindow::GetInstance()->AddMediaSource(s.filename.c_str()); if (!s.label.empty()) source->SetLabel(s.label.c_str()); } // Create tracks for (auto &i : inTracks) { TimelineTrack *track = new TimelineTrack; track->mVideoEnabled = i.video_enabled; track->mAudioEnabled = i.audio_enabled; track->mAudioLevels[0] = i.audio_levels[0]; track->mAudioLevels[1] = i.audio_levels[1]; gProject->AddTimelineTrack(track); } // Tracks for (auto &t :inTracks) { for (auto &c : t.clips) { const CLIP &clip = inClips[c]; // TODO index MediaClip media_clip; media_clip.mMediaSource = mMediaSources[clip.source]; // TODO index media_clip.mMediaSourceType = inSources[clip.source].type; media_clip.mSourceFrameStart = clip.start; media_clip.mSourceFrameEnd = clip.end; media_clip.mTimelineFrameStart = clip.timeline; media_clip.mTag = clip.tag; media_clip.mVideoEnabled = clip.video_enabled; media_clip.mAudioEnabled = clip.audio_enabled; mTimelineTracks[t.id]->AddClip(media_clip); // TODO index } mTimelineTracks[t.id]->SortClips(); int32 highest_priority = 0; for (auto &e : t.effects) { const EFFECT &effect = inEffects[e]; // TODO index if (effect.media_effect->mPriority > highest_priority) highest_priority = effect.media_effect->mPriority; mTimelineTracks[t.id]->mEffects.push_back(effect.media_effect); // TODO index } mTimelineTracks[t.id]->mNumberEffectLayers = (t.effects.empty() ? 0 : highest_priority + 1); mTimelineTracks[t.id]->SortEffects(); for (auto &n : t.notes) { const NOTE &note = inNotes[n]; // TODO index MediaNote media_note; media_note.mTimelineFrame = note.timeline; media_note.mText = note.text; mTimelineTracks[t.id]->mNotes.push_back(media_note); } } // Session MedoWindow::GetInstance()->fTimelineView->SetSession(inSession); return true; } /* FUNCTION: SaveProject ARGUMENTS: filename RETURN: true if successful DESCRIPTION: Save json file */ const bool Project :: SaveProject(FILE *file) { // Prepare output std::vector<SOURCE> outSources; std::vector<CLIP> outClips; std::vector<EFFECT> outEffects; std::vector<NOTE> outNotes; std::vector<TRACK> outTracks; // vSources uint32_t source_id = 0; for (auto &s : mMediaSources) { SOURCE aSource; aSource.id = source_id++; aSource.type = s->GetMediaType(); aSource.filename = s->GetFilename().String(); aSource.label = s->GetLabel().String(); outSources.push_back(aSource); } // vClips uint32_t clip_id = 0; for (auto &t : mTimelineTracks) { for (auto &c : t->mClips) { CLIP aClip; source_id = 0; for (auto &s : mMediaSources) { if (c.mMediaSource == s) break; source_id++; } aClip.id = clip_id++; aClip.source = source_id; aClip.start = c.mSourceFrameStart; aClip.end = c.mSourceFrameEnd; aClip.timeline = c.mTimelineFrameStart; aClip.tag = c.mTag; aClip.video_enabled = c.mVideoEnabled; aClip.audio_enabled = c.mAudioEnabled; outClips.push_back(aClip); } } // vEffects uint32_t effect_id = 0; for (auto &t : mTimelineTracks) { for (auto e : t->mEffects) { EFFECT anEffect; anEffect.id = effect_id++; anEffect.media_effect = e; outEffects.push_back(anEffect); } } // vNotes uint32_t note_id = 0; for (auto &t : mTimelineTracks) { for (auto n : t->mNotes) { NOTE aNote; aNote.id = note_id++; aNote.timeline = n.mTimelineFrame; aNote.text = n.mText.ReplaceAll("\n", "\\n"); outNotes.push_back(aNote); } } // vTracks uint32_t track_id = 0; clip_id = 0; effect_id = 0; note_id = 0; for (auto &t : mTimelineTracks) { TRACK aTrack; aTrack.id = track_id++; aTrack.video_enabled = t->mVideoEnabled; aTrack.audio_enabled = t->mAudioEnabled; aTrack.audio_levels[0] = t->mAudioLevels[0]; aTrack.audio_levels[1] = t->mAudioLevels[1]; aTrack.global = false; for (auto &c : t->mClips) { aTrack.clips.push_back(clip_id++); } for (auto e : t->mEffects) { aTrack.effects.push_back(effect_id++); } for (auto n : t->mNotes) { aTrack.notes.push_back(note_id++); } outTracks.push_back(aTrack); } TimelineView::SESSION session = MedoWindow::GetInstance()->fTimelineView->GetSession(); //******************** Save project ********************* char buffer[0x200]; // 512 bytes sprintf(buffer, "{\n"); fwrite(buffer, strlen(buffer), 1, file); // "medo" sprintf(buffer, "\t\"medo\": {\n"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\"version\": %d\n", 1); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t},\n"); fwrite(buffer, strlen(buffer), 1, file); // "resolution" sprintf(buffer, "\t\"resolution\": {\n"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\"width\": %u,\n", mResolution.width); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\"height\": %u,\n", mResolution.height); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\"frame_rate\": %f\n", mResolution.frame_rate); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t},\n"); fwrite(buffer, strlen(buffer), 1, file); // "sources" sprintf(buffer, "\t\"sources\": [\n"); fwrite(buffer, strlen(buffer), 1, file); size_t sources_count = 0; for (auto &s : outSources) { sprintf(buffer, "\t\t{\n"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"id\": %u,\n", s.id); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"type\": \"%s\",\n", kMediaType[s.type]); fwrite(buffer, strlen(buffer), 1, file); if (!s.label.empty()) { sprintf(buffer, "\t\t\t\"label\": \"%s\",\n", s.label.c_str()); fwrite(buffer, strlen(buffer), 1, file); } sprintf(buffer, "\t\t\t\"file\": \"%s\"\n", s.filename.c_str()); fwrite(buffer, strlen(buffer), 1, file); if (++sources_count < outSources.size()) sprintf(buffer, "\t\t},\n"); else sprintf(buffer, "\t\t}\n"); fwrite(buffer, strlen(buffer), 1, file); } sprintf(buffer, "\t],\n"); fwrite(buffer, strlen(buffer), 1, file); // "clips" sprintf(buffer, "\t\"clips\": [\n"); fwrite(buffer, strlen(buffer), 1, file); size_t clips_count = 0; for (auto &c : outClips) { sprintf(buffer, "\t\t{\n"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"id\": %u,\n", c.id); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"source\": %u,\n", c.source); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"start\": %ld,\n", c.start); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"end\": %ld,\n", c.end); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"timeline\": %ld,\n", c.timeline); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"video_enabled\": %s,\n", c.video_enabled ? "true" : "false"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"audio_enabled\": %s,\n", c.audio_enabled ? "true" : "false"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"tag\": \"%s\"\n", c.tag.String()); fwrite(buffer, strlen(buffer), 1, file); if (++clips_count < outClips.size()) sprintf(buffer, "\t\t},\n"); else sprintf(buffer, "\t\t}\n"); fwrite(buffer, strlen(buffer), 1, file); } sprintf(buffer, "\t],\n"); fwrite(buffer, strlen(buffer), 1, file); // "effects" sprintf(buffer, "\t\"effects\": [\n"); fwrite(buffer, strlen(buffer), 1, file); size_t effects_count = 0; for (auto &i : outEffects) { sprintf(buffer, "\t\t{\n"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"id\": %u,\n", i.id); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"vendor\": \"%s\",\n", i.media_effect->mEffectNode->GetVendorName()); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"name\": \"%s\",\n", i.media_effect->mEffectNode->GetEffectName()); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"start\": %ld,\n", i.media_effect->mTimelineFrameStart); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"end\": %ld,\n", i.media_effect->mTimelineFrameEnd); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"priority\": %u,\n", i.media_effect->mPriority); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"enabled\": %s%s\n", (i.media_effect->mEnabled ? "true" : "false"), i.media_effect->mEffectData ? "," : ""); fwrite(buffer, strlen(buffer), 1, file); if (i.media_effect->mEffectData) { sprintf(buffer, "\t\t\t\"parameters\":{\n"); fwrite(buffer, strlen(buffer), 1, file); i.media_effect->mEffectNode->SaveParameters(file, i.media_effect); sprintf(buffer, "\t\t\t}\n"); fwrite(buffer, strlen(buffer), 1, file); } if (++effects_count < outEffects.size()) sprintf(buffer, "\t\t},\n"); else sprintf(buffer, "\t\t}\n"); fwrite(buffer, strlen(buffer), 1, file); } sprintf(buffer, "\t],\n"); fwrite(buffer, strlen(buffer), 1, file); // "notes" sprintf(buffer, "\t\"notes\": [\n"); fwrite(buffer, strlen(buffer), 1, file); size_t note_count = 0; for (auto &n : outNotes) { sprintf(buffer, "\t\t{\n"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"id\": %u,\n", n.id); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"timeline\": %ld,\n", n.timeline); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"text\": \"%s\"\n", n.text.String()); fwrite(buffer, strlen(buffer), 1, file); if (++note_count < outNotes.size()) sprintf(buffer, "\t\t},\n"); else sprintf(buffer, "\t\t}\n"); fwrite(buffer, strlen(buffer), 1, file); } sprintf(buffer, "\t],\n"); fwrite(buffer, strlen(buffer), 1, file); // "tracks" sprintf(buffer, "\t\"tracks\": [\n"); fwrite(buffer, strlen(buffer), 1, file); size_t tracks_count = 0; for (auto &i : outTracks) { sprintf(buffer, "\t\t{\n"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"id\": %u,\n", i.id); fwrite(buffer, strlen(buffer), 1, file); if (i.global) { sprintf(buffer, "\t\t\t\"global\": true,\n"); fwrite(buffer, strlen(buffer), 1, file); } sprintf(buffer, "\t\t\t\"video_enabled\": %s,\n", i.video_enabled ? "true" : "false"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"audio_enabled\": %s,\n", i.audio_enabled ? "true" : "false"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"levels\": [%f, %f],\n", i.audio_levels[0], i.audio_levels[1]); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"clips\": ["); fwrite(buffer, strlen(buffer), 1, file); for (size_t c=0; c < i.clips.size();c++) { sprintf(buffer, "%u%s", i.clips[c], c+1<i.clips.size() ? ", " : ""); fwrite(buffer, strlen(buffer), 1, file); } sprintf(buffer, "],\n"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"effects\": ["); fwrite(buffer, strlen(buffer), 1, file); for (size_t e=0; e < i.effects.size();e++) { sprintf(buffer, "%u%s", i.effects[e], e+1<i.effects.size() ? ", " : ""); fwrite(buffer, strlen(buffer), 1, file); } sprintf(buffer, "],\n"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\t\"notes\": ["); fwrite(buffer, strlen(buffer), 1, file); for (size_t n=0; n < i.notes.size(); n++) { sprintf(buffer, "%u%s", i.notes[n], n+1<i.notes.size() ? ", " : ""); fwrite(buffer, strlen(buffer), 1, file); } sprintf(buffer, "]\n"); fwrite(buffer, strlen(buffer), 1, file); if (++tracks_count < outTracks.size()) sprintf(buffer, "\t\t},\n"); else sprintf(buffer, "\t\t}\n"); fwrite(buffer, strlen(buffer), 1, file); } sprintf(buffer, "\t],\n"); fwrite(buffer, strlen(buffer), 1, file); // "session" sprintf(buffer, "\t\"session\": {\n"); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\"horizontal_scroll\": %f,\n", session.horizontal_scroll); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\"vertical_scroll\": %f,\n", session.vertical_scroll); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\"zoom_index\": %d,\n", session.zoom_index); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\"current_frame\": %ld,\n", session.current_frame); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\"marker_a\": %ld,\n", session.marker_a); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t\t\"marker_b\": %ld\n", session.marker_b); fwrite(buffer, strlen(buffer), 1, file); sprintf(buffer, "\t}\n}\n"); fwrite(buffer, strlen(buffer), 1, file); return true; }
30.39117
141
0.63758
[ "object", "vector" ]
0b3ec0bf7fcd2b1d1b962f71f433addbe6142f38
1,613
hpp
C++
OREData/ored/portfolio/builders/yoycapfloor.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
OREData/ored/portfolio/builders/yoycapfloor.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
OREData/ored/portfolio/builders/yoycapfloor.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2018 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file portfolio/builders/yoycapfloor.hpp \brief Engine builder for year-on-year inflation caps/floors \ingroup builders */ #pragma once #include <ored/portfolio/builders/cachingenginebuilder.hpp> #include <ored/portfolio/enginefactory.hpp> namespace ore { namespace data { //! Engine Builder for Year on Year Caps, Floors and Collars on an IborIndex /*! Pricing engines are cached by currency \ingroup builders */ class YoYCapFloorEngineBuilder : public CachingPricingEngineBuilder<string, const string&> { public: YoYCapFloorEngineBuilder() : CachingEngineBuilder("YYCapModel", "YYCapEngine", {"YYCapFloor"}) {} protected: virtual string keyImpl(const string& indexName) override { return indexName; } virtual boost::shared_ptr<PricingEngine> engineImpl(const string& indexName) override; }; } // namespace data } // namespace ore
33.604167
101
0.774954
[ "model" ]
0b4225d1c80d63613d5c5b30abe3ad3a810c0c44
13,931
cpp
C++
test/chainer_trt.cpp
tkerola/chainer-trt
4e1adc0370e11ad7736a5fafdfd5aeca168c700e
[ "MIT" ]
null
null
null
test/chainer_trt.cpp
tkerola/chainer-trt
4e1adc0370e11ad7736a5fafdfd5aeca168c700e
[ "MIT" ]
null
null
null
test/chainer_trt.cpp
tkerola/chainer-trt
4e1adc0370e11ad7736a5fafdfd5aeca168c700e
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018 Preferred Networks, Inc. All rights reserved. */ #include <gtest/gtest.h> #include "chainer_trt/chainer_trt.hpp" #include "test_helper.hpp" class ChainerTRT_HPP_Test : public ::testing::Test {}; TEST_F(ChainerTRT_HPP_Test, MakeDims) { auto t = chainer_trt::internal::make_dims(10, 20, 30, 40); ASSERT_EQ(t.nbDims, 4); ASSERT_EQ(t.d[0], 10); ASSERT_EQ(t.type[0], nvinfer1::DimensionType::kCHANNEL); ASSERT_EQ(t.d[1], 20); ASSERT_EQ(t.type[1], nvinfer1::DimensionType::kSPATIAL); ASSERT_EQ(t.d[2], 30); ASSERT_EQ(t.type[2], nvinfer1::DimensionType::kSPATIAL); ASSERT_EQ(t.d[3], 40); ASSERT_EQ(t.type[3], nvinfer1::DimensionType::kSPATIAL); } TEST_F(ChainerTRT_HPP_Test, MakeDimsWith8ItemsShouldBeOK) { auto t = chainer_trt::internal::make_dims(1, 2, 3, 4, 5, 6, 7, 8); ASSERT_EQ(t.nbDims, 8); } TEST_F(ChainerTRT_HPP_Test, MakeDimsWithMoreThan8ItemsCannotBeCompiled) { // This code causes compile error // make_dims(1, 2, 3, 4, 5, 6, 7, 8, 9); } TEST_F(ChainerTRT_HPP_Test, MakeDimsWithNonIntValuesCannotBeCompiled) { // This code causes compile error // make_dims(1, 2, 3, "hello world"); } TEST_F(ChainerTRT_HPP_Test, CheckInputOutputExistenceByName) { // x = Variable(np.random.randn(1, 3, 16, 16).astype(np.float32)) // with chainer.using_config('train', False), RetainHook(): // y = x + 1 // retriever = ModelRetriever(out) // retriever.register_inputs(x, name='named_input') // retriever(y, name='named_out').save() const std::string fixture = "test/fixtures/chainer_trt/named_net"; auto m = chainer_trt::model::build_fp32(fixture, 2, 1); ASSERT_EQ((int)m->get_input_names().size(), 1); ASSERT_EQ(m->get_input_names()[0], "named_input"); ASSERT_EQ((int)m->get_output_names().size(), 1); ASSERT_EQ(m->get_output_names()[0], "named_out"); ASSERT_TRUE(m->has_input("named_input")); ASSERT_TRUE(m->has_output("named_out")); ASSERT_FALSE(m->has_input("named_out")); ASSERT_FALSE(m->has_input("fooooobarrrrrrrr")); ASSERT_FALSE(m->has_output("named_input")); ASSERT_FALSE(m->has_output("foooooobarrrrrrr")); assert_vector_eq(m->get_input_dimensions("named_input"), std::vector<int>{3, 16, 16}); assert_vector_eq(m->get_output_dimensions("named_out"), std::vector<int>{3, 16, 16}); ASSERT_THROW(m->get_input_dimensions("named_out"), std::invalid_argument); ASSERT_THROW(m->get_output_dimensions("named_input"), std::invalid_argument); } TEST_F(ChainerTRT_HPP_Test, GetInputOutput) { // x = Variable(np.random.randn(1, 3, 16, 16).astype(np.float32)) // with chainer.using_config('train', False), RetainHook(): // y = x + 1 // retriever = ModelRetriever(out) // retriever.register_inputs(x, name='named_input') // retriever(y, name='named_out').save() const int model_batch_size = 4, infer_batch_size = 2; const std::string fixture = "test/fixtures/chainer_trt/named_net"; auto m = chainer_trt::model::build_fp32(fixture, 2, model_batch_size); chainer_trt::infer rt(m); chainer_trt::buffer buf(m, infer_batch_size); // Send data through named input (an array initialized by 10) const int size_per_batch = 3 * 16 * 16; const int size_all_batch = infer_batch_size * size_per_batch; std::vector<float> in_cpu(size_all_batch, 10.0f); cudaMemcpy(buf.get_input("named_input"), in_cpu.data(), sizeof(float) * size_all_batch, cudaMemcpyHostToDevice); // Run inference rt(buf); std::vector<float> out_cpu(infer_batch_size * 3 * 16 * 16, 0.0f); buf.output_device_to_host(std::vector<void *>{(void *)out_cpu.data()}); // Check values (10+1==11) for(float y : out_cpu) ASSERT_EQ(y, 11.0f); // Check interface ASSERT_EQ(buf.get_input_size("named_input"), (int)sizeof(float) * size_all_batch); ASSERT_EQ(buf.get_input_size("named_input", false), (int)sizeof(float) * size_per_batch); ASSERT_EQ(buf.get_input_size(0), (int)sizeof(float) * size_all_batch); ASSERT_EQ(buf.get_output_size("named_out"), (int)sizeof(float) * size_all_batch); ASSERT_EQ(buf.get_output_size("named_out", false), (int)sizeof(float) * size_per_batch); ASSERT_EQ(buf.get_output_size(0), (int)sizeof(float) * size_all_batch); ASSERT_NO_THROW(buf.get_input("named_input")); ASSERT_NO_THROW(buf.get_input(0)); ASSERT_NO_THROW(buf.get_output("named_out")); ASSERT_NO_THROW(buf.get_output(0)); ASSERT_ANY_THROW(buf.get_input_size(1)); ASSERT_ANY_THROW(buf.get_input_size(-1)); // not to confuse input with outputs ASSERT_ANY_THROW(buf.get_input_size("named_out")); ASSERT_ANY_THROW(buf.get_input_size("foooooooo")); ASSERT_ANY_THROW(buf.get_input(1)); ASSERT_ANY_THROW(buf.get_input(-1)); ASSERT_ANY_THROW(buf.get_input("named_out")); ASSERT_ANY_THROW(buf.get_input("foooooooo")); ASSERT_ANY_THROW(buf.get_output_size(1)); ASSERT_ANY_THROW(buf.get_output_size(-1)); // not to confuse output with inputs ASSERT_ANY_THROW(buf.get_output_size("named_input")); ASSERT_ANY_THROW(buf.get_output_size("foooooooooo")); ASSERT_ANY_THROW(buf.get_output(1)); ASSERT_ANY_THROW(buf.get_output(-1)); ASSERT_ANY_THROW(buf.get_output("named_input")); ASSERT_ANY_THROW(buf.get_output("foooooooooo")); // Check values obtained through name cudaMemcpy(out_cpu.data(), buf.get_output("named_out"), sizeof(float) * size_all_batch, cudaMemcpyDeviceToHost); for(float y : out_cpu) ASSERT_EQ(y, 11.0f); } TEST_F(ChainerTRT_HPP_Test, MakeBindingByDict) { // s = (1, 3, 8, 8) // x1 = chainer.Variable(np.random.random(s).astype(np.float32)) // x2 = chainer.Variable(np.random.random(s).astype(np.float32)) // c = 2 * chainer.Variable(np.ones(s).astype(np.float32)) // with chainer.using_config('train', False): // with RetainHook(): // y = x1 + x2 // y = y * c // retriever = ModelRetriever(out) // retriever.register_inputs(x1, name="x1") // retriever.register_inputs(x2, name="x2") // retriever(y, name="out") // retriever.save() const std::string dir = "test/fixtures/chainer_trt/raw_binding"; auto m = chainer_trt::model::build_fp32(dir, 1, 1); chainer_trt::infer rt(m); const int size = 3 * 8 * 8; float *in1_gpu, *in2_gpu, *out_gpu; cudaMalloc((void **)&in1_gpu, sizeof(float) * size); cudaMalloc((void **)&in2_gpu, sizeof(float) * size); cudaMalloc((void **)&out_gpu, sizeof(float) * size); const auto in1_cpu = load_values<float>(dir + "/in1.csv"); const auto in2_cpu = load_values<float>(dir + "/in2.csv"); std::vector<float> out_cpu(size, 0); const auto expected_out_cpu = load_values<float>(dir + "/out.csv"); cudaMemcpy(in1_gpu, in1_cpu.data(), sizeof(float) * size, cudaMemcpyHostToDevice); cudaMemcpy(in2_gpu, in2_cpu.data(), sizeof(float) * size, cudaMemcpyHostToDevice); // check valid binding (by name) ASSERT_NO_THROW({ rt.create_bindings({{"x1", (void *)in1_gpu}, {"x2", (void *)in2_gpu}, {"out", (void *)out_gpu}}); }); // check valid binding (by name, including non-used one) ASSERT_NO_THROW({ rt.create_bindings({{"x1", (void *)in1_gpu}, {"x2", (void *)in2_gpu}, {"out", (void *)out_gpu}, {"ghost", nullptr}}); }); // check valid binding (pointer vector) ASSERT_NO_THROW({ rt.create_bindings({(void *)in1_gpu, (void *)in2_gpu}, {(void *)out_gpu}); }); // check invalid bindings (insufficient case) ASSERT_ANY_THROW({ rt.create_bindings({{"x1", (void *)in1_gpu}, {"x2", (void *)in2_gpu}}); }); ASSERT_ANY_THROW({ rt.create_bindings({{"x1", (void *)in1_gpu}, {"out", (void *)out_gpu}}); }); ASSERT_ANY_THROW( { rt.create_bindings({(void *)in1_gpu}, {(void *)out_gpu}); }); ASSERT_ANY_THROW( { rt.create_bindings({(void *)in1_gpu}, {(void *)in1_gpu}); }); // check invalid bindings (too much case) ASSERT_ANY_THROW(rt.create_bindings({(void *)in1_gpu, nullptr, nullptr}, {(void *)out_gpu})); // check getting binding index ASSERT_EQ(rt.get_binding_index("x1"), 0); ASSERT_EQ(rt.get_binding_index("x2"), 1); ASSERT_EQ(rt.get_binding_index("out"), 2); ASSERT_ANY_THROW(rt.get_binding_index("ghost")); ASSERT_ANY_THROW(rt.get_binding_index("ConstantInput-0")); // check outputs auto bindings = rt.create_bindings({{"x1", (void *)in1_gpu}, {"x2", (void *)in2_gpu}, {"out", (void *)out_gpu}}); ASSERT_EQ((int)bindings.size(), 3); // x1, x2, out rt(1, bindings); cudaMemcpy(out_cpu.data(), out_gpu, sizeof(float) * size, cudaMemcpyDeviceToHost); assert_vector_eq(out_cpu, expected_out_cpu); } TEST_F(ChainerTRT_HPP_Test, InferFromGPUWithName) { const std::string dir = "test/fixtures/chainer_trt/raw_binding"; auto m = chainer_trt::model::build_fp32(dir, 1, 1); chainer_trt::infer rt(m); const int size = 3 * 8 * 8; float *in1_gpu, *in2_gpu, *out_gpu; cudaMalloc((void **)&in1_gpu, sizeof(float) * size); cudaMalloc((void **)&in2_gpu, sizeof(float) * size); cudaMalloc((void **)&out_gpu, sizeof(float) * size); const auto in1_cpu = load_values<float>(dir + "/in1.csv"); const auto in2_cpu = load_values<float>(dir + "/in2.csv"); std::vector<float> out_cpu(size, 0); const auto expected_out_cpu = load_values<float>(dir + "/out.csv"); cudaMemcpy(in1_gpu, in1_cpu.data(), sizeof(float) * size, cudaMemcpyHostToDevice); cudaMemcpy(in2_gpu, in2_cpu.data(), sizeof(float) * size, cudaMemcpyHostToDevice); // Insufficient inputs ASSERT_THROW( { rt(1, {{"x1", in1_gpu}}, {{"out", out_gpu}}); }, std::invalid_argument); // Unknown input ASSERT_THROW( { rt(1, {{"x1", in1_gpu}, {"xhogehoge", in2_gpu}}, {{"out", out_gpu}}); }, std::invalid_argument); // Insufficient outputs ASSERT_THROW( { rt(1, {{"x1", in1_gpu}, {"x2", in2_gpu}}, {}); }, std::invalid_argument); // Unknown output ASSERT_THROW( { rt(1, {{"x1", in1_gpu}, {"x2", in2_gpu}}, {{"outhogehoge", out_gpu}}); }, std::invalid_argument); // Allow too much inputs (just ignore) ASSERT_NO_THROW({ rt(1, {{"x1", in1_gpu}, {"x2", in2_gpu}, {"x3", in2_gpu}}, {{"out", out_gpu}}); }); // Allow too much outputs (just ignore) ASSERT_NO_THROW({ rt(1, {{"x1", in1_gpu}, {"x2", in2_gpu}}, {{"out", out_gpu}, {"out3", out_gpu}}); }); // OK case rt(1, {{"x1", in1_gpu}, {"x2", in2_gpu}}, {{"out", out_gpu}}); cudaMemcpy(out_cpu.data(), out_gpu, sizeof(float) * size, cudaMemcpyDeviceToHost); assert_vector_eq(out_cpu, expected_out_cpu); } TEST_F(ChainerTRT_HPP_Test, InferFromCPUWithName) { const std::string dir = "test/fixtures/chainer_trt/raw_binding"; auto m = chainer_trt::model::build_fp32(dir, 1, 1); chainer_trt::infer rt(m); const int size = 3 * 8 * 8; const auto in1 = load_values<float>(dir + "/in1.csv"); const auto in2 = load_values<float>(dir + "/in2.csv"); std::vector<float> out(size, 0); const auto expected_out = load_values<float>(dir + "/out.csv"); // Insufficient inputs ASSERT_THROW( { rt.infer_from_cpu(1, {{"x1", in1.data()}}, {{"out", out.data()}}); }, std::invalid_argument); // Unknown input ASSERT_THROW( { rt.infer_from_cpu(1, {{"x1", in1.data()}, {"xhogehoge", in2.data()}}, {{"out", out.data()}}); }, std::invalid_argument); // Insufficient outputs ASSERT_THROW( { rt.infer_from_cpu(1, {{"x1", in1.data()}, {"x2", in2.data()}}, {}); }, std::invalid_argument); // Unknown output ASSERT_THROW( { rt.infer_from_cpu(1, {{"x1", in1.data()}, {"x2", in2.data()}}, {{"outhogehoge", out.data()}}); }, std::invalid_argument); // Allow too much inputs (just ignore) ASSERT_NO_THROW({ rt.infer_from_cpu( 1, {{"x1", in1.data()}, {"x2", in2.data()}, {"x3", in2.data()}}, {{"out", out.data()}}); }); // Allow too much outputs (just ignore) ASSERT_NO_THROW({ rt.infer_from_cpu(1, {{"x1", in1.data()}, {"x2", in2.data()}}, {{"out", out.data()}, {"out3", out.data()}}); }); // OK case rt.infer_from_cpu(1, {{"x1", in1.data()}, {"x2", in2.data()}}, {{"out", out.data()}}); assert_vector_eq(out, expected_out); } TEST_F(ChainerTRT_HPP_Test, InferFromCPUWithNameUsingBuffer) { const std::string dir = "test/fixtures/chainer_trt/raw_binding"; auto m = chainer_trt::model::build_fp32(dir, 1, 1); chainer_trt::infer rt(m); const int size = 3 * 8 * 8; const auto in1 = load_values<float>(dir + "/in1.csv"); const auto in2 = load_values<float>(dir + "/in2.csv"); std::vector<float> out(size, 0); const auto expected_out = load_values<float>(dir + "/out.csv"); auto buffer = rt.create_buffer(1); buffer->input_host_to_device({{"x1", in1.data()}, {"x2", in2.data()}}); rt(*buffer); buffer->output_device_to_host({{"out", out.data()}}); assert_vector_eq(out, expected_out); }
36.564304
80
0.61295
[ "vector", "model" ]
0b4755c58e1f0d4a24b9e710e773864bec6a568b
877
hpp
C++
12/passage_pathing.hpp
ComicSansMS/AdventOfCode2021
60902d14c356c3375266703e85aca991241afc84
[ "Unlicense" ]
null
null
null
12/passage_pathing.hpp
ComicSansMS/AdventOfCode2021
60902d14c356c3375266703e85aca991241afc84
[ "Unlicense" ]
null
null
null
12/passage_pathing.hpp
ComicSansMS/AdventOfCode2021
60902d14c356c3375266703e85aca991241afc84
[ "Unlicense" ]
null
null
null
#ifndef ADVENT_OF_CODE_12_PASSAGE_PATHING_INCLUDE_GUARD #define ADVENT_OF_CODE_12_PASSAGE_PATHING_INCLUDE_GUARD #include <fmt/format.h> #include <array> #include <cstdint> #include <string> #include <string_view> #include <vector> struct Cave { std::string name; bool isBig; std::vector<std::size_t> neighbours; friend bool operator==(Cave const&, Cave const&) = default; }; struct Edge { std::size_t start_index; std::size_t destination_index; friend bool operator==(Edge const&, Edge const&) = default; }; struct Graph { std::vector<Cave> caves; std::vector<Edge> edges; std::size_t startCaveIndex; std::size_t endCaveIndex; }; Graph parseInput(std::string_view input); struct Path { std::vector<std::size_t> nodes; }; std::vector<Path> allPaths(Graph const& g); std::vector<Path> allPaths2(Graph const& g); #endif
19.488889
63
0.710376
[ "vector" ]
0b478cce7b26d23648f05dab3cea4b4d3874bb66
2,377
cc
C++
gazebo/physics/BoxShape.cc
SamFerwerda/Gazebo10-commits
b33ac5982fb75cac894fa145f7268146d44e0724
[ "ECL-2.0", "Apache-2.0" ]
2
2020-06-19T14:52:45.000Z
2020-11-05T10:25:10.000Z
gazebo/physics/BoxShape.cc
SamFerwerda/Gazebo10-commits
b33ac5982fb75cac894fa145f7268146d44e0724
[ "ECL-2.0", "Apache-2.0" ]
1
2020-06-04T10:26:04.000Z
2020-06-04T10:26:04.000Z
gazebo/physics/BoxShape.cc
SamFerwerda/Gazebo10-commits
b33ac5982fb75cac894fa145f7268146d44e0724
[ "ECL-2.0", "Apache-2.0" ]
2
2019-11-10T07:19:09.000Z
2019-11-21T19:11:11.000Z
/* * Copyright (C) 2012 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef _WIN32 // Ensure that Winsock2.h is included before Windows.h, which can get // pulled in by anybody (e.g., Boost). #include <Winsock2.h> #endif #include "gazebo/physics/BoxShape.hh" using namespace gazebo; using namespace physics; ////////////////////////////////////////////////// BoxShape::BoxShape(CollisionPtr _parent) : Shape(_parent) { this->AddType(Base::BOX_SHAPE); } ////////////////////////////////////////////////// BoxShape::~BoxShape() { } ////////////////////////////////////////////////// void BoxShape::Init() { this->SetSize(this->sdf->Get<ignition::math::Vector3d>("size")); } ////////////////////////////////////////////////// void BoxShape::SetSize(const ignition::math::Vector3d &_size) { this->sdf->GetElement("size")->Set(_size); } ////////////////////////////////////////////////// ignition::math::Vector3d BoxShape::Size() const { return this->sdf->Get<ignition::math::Vector3d>("size"); } ////////////////////////////////////////////////// void BoxShape::SetScale(const ignition::math::Vector3d &_scale) { if (_scale.X() < 0 || _scale.Y() < 0 || _scale.Z() < 0) return; if (_scale == this->scale) return; this->SetSize((_scale/this->scale)*this->Size()); this->scale = _scale; } ////////////////////////////////////////////////// void BoxShape::FillMsg(msgs::Geometry &_msg) { _msg.set_type(msgs::Geometry::BOX); msgs::Set(_msg.mutable_box()->mutable_size(), this->Size()); } ////////////////////////////////////////////////// void BoxShape::ProcessMsg(const msgs::Geometry &_msg) { this->SetSize(msgs::ConvertIgn(_msg.box().size())); } ////////////////////////////////////////////////// double BoxShape::ComputeVolume() const { return IGN_BOX_VOLUME_V(this->Size()); }
26.707865
75
0.564577
[ "geometry", "shape" ]
0b47d6064d7904ff710762adedef65b1752fe519
8,079
cc
C++
cros-disks/sandboxed_process.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
cros-disks/sandboxed_process.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
cros-disks/sandboxed_process.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cros-disks/sandboxed_process.h" #include <utility> #include <stdlib.h> #include <sys/mount.h> #include <sys/wait.h> #include <unistd.h> #include <base/bind.h> #include <base/check.h> #include <base/files/file_util.h> #include <base/files/scoped_file.h> #include <base/logging.h> #include <base/notreached.h> #include <base/posix/safe_strerror.h> #include <chromeos/libminijail.h> #include "cros-disks/mount_options.h" #include "cros-disks/quote.h" namespace cros_disks { namespace { int Exec(char* const args[], char* const env[]) { const char* const path = args[0]; execve(path, args, env); const int ret = (errno == ENOENT ? MINIJAIL_ERR_NO_COMMAND : MINIJAIL_ERR_NO_ACCESS); PLOG(ERROR) << "Cannot exec " << quote(path); return ret; } } // namespace SandboxedProcess::SandboxedProcess() : jail_(minijail_new()) { CHECK(jail_) << "Failed to create a process jail"; } SandboxedProcess::~SandboxedProcess() { minijail_destroy(jail_); } void SandboxedProcess::LoadSeccompFilterPolicy(const std::string& policy_file) { minijail_parse_seccomp_filters(jail_, policy_file.c_str()); minijail_use_seccomp_filter(jail_); } void SandboxedProcess::NewCgroupNamespace() { minijail_namespace_cgroups(jail_); } void SandboxedProcess::NewIpcNamespace() { minijail_namespace_ipc(jail_); } void SandboxedProcess::NewMountNamespace() { minijail_namespace_vfs(jail_); } void SandboxedProcess::EnterExistingMountNamespace(const std::string& ns_path) { minijail_namespace_enter_vfs(jail_, ns_path.c_str()); } void SandboxedProcess::NewPidNamespace() { minijail_namespace_pids(jail_); minijail_run_as_init(jail_); minijail_reset_signal_mask(jail_); minijail_reset_signal_handlers(jail_); minijail_skip_remount_private(jail_); // crbug.com/1008262 use_pid_namespace_ = true; } bool SandboxedProcess::SetUpMinimalMounts() { if (minijail_bind(jail_, "/", "/", 0)) return false; if (minijail_bind(jail_, "/proc", "/proc", 0)) return false; minijail_remount_proc_readonly(jail_); minijail_mount_tmp_size(jail_, 128 * 1024 * 1024); // Create a minimal /dev with a very restricted set of device nodes. minijail_mount_dev(jail_); if (minijail_bind(jail_, "/dev/log", "/dev/log", 0)) return false; return true; } bool SandboxedProcess::BindMount(const std::string& from, const std::string& to, bool writeable, bool recursive) { int flags = MS_BIND; if (!writeable) { flags |= MS_RDONLY; } if (recursive) { flags |= MS_REC; } return minijail_mount(jail_, from.c_str(), to.c_str(), "", flags) == 0; } bool SandboxedProcess::Mount(const std::string& src, const std::string& to, const std::string& type, const char* data) { return minijail_mount_with_data(jail_, src.c_str(), to.c_str(), type.c_str(), 0, data) == 0; } bool SandboxedProcess::EnterPivotRoot() { return minijail_enter_pivot_root(jail_, "/mnt/empty") == 0; } void SandboxedProcess::NewNetworkNamespace() { // As of 2021-08-04, this can log a warning to /var/log/messages: // "ioctl(SIOCSIFFLAGS) failed: Operation not permitted" // // This libminijail message is harmless: https://crbug.com/1226229 minijail_namespace_net(jail_); } void SandboxedProcess::SetNoNewPrivileges() { minijail_no_new_privs(jail_); } void SandboxedProcess::SetCapabilities(uint64_t capabilities) { minijail_use_caps(jail_, capabilities); } void SandboxedProcess::SetGroupId(gid_t group_id) { minijail_change_gid(jail_, group_id); } void SandboxedProcess::SetUserId(uid_t user_id) { minijail_change_uid(jail_, user_id); } void SandboxedProcess::SetSupplementaryGroupIds(base::span<const gid_t> gids) { minijail_set_supplementary_gids(jail_, gids.size(), gids.data()); } bool SandboxedProcess::AddToCgroup(const std::string& cgroup) { return minijail_add_to_cgroup(jail_, cgroup.c_str()) == 0; } void SandboxedProcess::PreserveFile(int fd) { if (const int ret = minijail_preserve_fd(jail_, fd, fd)) { LOG(FATAL) << "Cannot preserve file descriptor " << fd << ": " << base::safe_strerror(-ret); } } pid_t SandboxedProcess::StartImpl(base::ScopedFD in_fd, base::ScopedFD out_fd) { char* const* const args = GetArguments(); DCHECK(args && args[0]); char* const* const env = GetEnvironment(); DCHECK(env); pid_t child_pid = kInvalidProcessId; minijail_close_open_fds(jail_); // Set up stdin, stdout and stderr to be connected to the matching pipes in // the jailed process. CHECK_EQ(minijail_preserve_fd(jail_, in_fd.get(), STDIN_FILENO), 0); CHECK_EQ(minijail_preserve_fd(jail_, out_fd.get(), STDOUT_FILENO), 0); CHECK_EQ(minijail_preserve_fd(jail_, out_fd.get(), STDERR_FILENO), 0); if (!use_pid_namespace_) { if (const int ret = minijail_run_env_pid_pipes( jail_, args[0], args, env, &child_pid, nullptr, nullptr, nullptr); ret < 0) { errno = -ret; PLOG(ERROR) << "Cannot start minijail process"; return kInvalidProcessId; } } else { // The sandboxed process will run in a PID namespace. PreserveFile(launcher_pipe_.child_fd.get()); SubprocessPipe termination_pipe(SubprocessPipe::kParentToChild); PreserveFile(termination_pipe.child_fd.get()); // Create child 'init' process in the PID namespace. child_pid = minijail_fork(jail_); if (child_pid < 0) { errno = -child_pid; PLOG(ERROR) << "Cannot run minijail_fork"; return kInvalidProcessId; } if (child_pid == 0) { // In child 'init' process. SandboxedInit(base::BindOnce(Exec, args, env), std::move(launcher_pipe_.child_fd), std::move(termination_pipe.child_fd)) .Run(); NOTREACHED(); } else { // In parent process. PCHECK(base::SetNonBlocking(launcher_pipe_.parent_fd.get())); launcher_pipe_.child_fd.reset(); DCHECK(!termination_fd_.is_valid()); termination_fd_ = std::move(termination_pipe.parent_fd); DCHECK(termination_fd_.is_valid()); } } return child_pid; } int SandboxedProcess::WaitImpl() { if (use_pid_namespace_) { launcher_watch_.reset(); return SandboxedInit::WaitForLauncher(&launcher_pipe_.parent_fd); } while (true) { const int status = minijail_wait(jail_); if (status >= 0) return status; if (const int err = -status; err != EINTR) { LOG(ERROR) << "Cannot wait for process " << pid() << ": " << base::safe_strerror(err); return MINIJAIL_ERR_INIT; } } } int SandboxedProcess::WaitNonBlockingImpl() { if (use_pid_namespace_) { const int exit_code = SandboxedInit::PollLauncher(&launcher_pipe_.parent_fd); if (exit_code >= 0) launcher_watch_.reset(); return exit_code; } // TODO(chromium:971667) Use Minijail's non-blocking wait once it exists. int wstatus; const pid_t child_pid = pid(); const int ret = waitpid(child_pid, &wstatus, WNOHANG); if (ret < 0) { PLOG(ERROR) << "Cannot wait for process " << child_pid; return MINIJAIL_ERR_INIT; } if (ret == 0) { // Process is still running. return -1; } return SandboxedInit::WaitStatusToExitCode(wstatus); } int FakeSandboxedProcess::OnProcessLaunch( const std::vector<std::string>& argv) { return 0; } pid_t FakeSandboxedProcess::StartImpl(base::ScopedFD, base::ScopedFD) { DCHECK(!ret_code_); ret_code_ = OnProcessLaunch(arguments()); return 42; } int FakeSandboxedProcess::WaitImpl() { DCHECK(ret_code_); return ret_code_.value(); } int FakeSandboxedProcess::WaitNonBlockingImpl() { if (ret_code_) return ret_code_.value(); return -1; } } // namespace cros_disks
28.149826
80
0.680777
[ "vector" ]
0b4e545bf7123e92d142a113930a592d2eb15ad2
19,018
cpp
C++
rcnn/rcnn.cpp
khoiucd/tensorrtx
79d1db19b93600cfc5355e541f604ff1e09124e4
[ "MIT" ]
null
null
null
rcnn/rcnn.cpp
khoiucd/tensorrtx
79d1db19b93600cfc5355e541f604ff1e09124e4
[ "MIT" ]
null
null
null
rcnn/rcnn.cpp
khoiucd/tensorrtx
79d1db19b93600cfc5355e541f604ff1e09124e4
[ "MIT" ]
null
null
null
#include <iostream> #include <opencv2/opencv.hpp> #include "backbone.hpp" #include "RpnDecodePlugin.h" #include "RpnNmsPlugin.h" #include "RoiAlignPlugin.h" #include "PredictorDecodePlugin.h" #include "BatchedNmsPlugin.h" #include "calibrator.hpp" #define DEVICE 0 #define BATCH_SIZE 1 #define BACKBONE_RESNETTYPE R50 // data static const std::vector<float> PIXEL_MEAN = { 103.53, 116.28, 123.675 }; static const std::vector<float> PIXEL_STD = {1.0, 1.0, 1.0}; static constexpr float MIN_SIZE = 800.0; static constexpr float MAX_SIZE = 1333.0; static constexpr int NUM_CLASSES = 80; static constexpr int INPUT_H = 480; static constexpr int INPUT_W = 640; static int IMAGE_HEIGHT = 800; static int IMAGE_WIDTH = 1333; // rpn static const std::vector<float> ANCHOR_SIZES = { 32, 64, 128, 256, 512 }; static const std::vector<float> ASPECT_RATIOS = { 0.5, 1.0, 2.0 }; static constexpr int PRE_NMS_TOP_K_TEST = 6000; static constexpr float RPN_NMS_THRESH = 0.7; static constexpr int POST_NMS_TOPK = 1000; // roialign static constexpr int STRIDES = 16; static constexpr int SAMPLING_RATIO = 0; static constexpr int POOLER_RESOLUTION = 14; // roihead static constexpr float NMS_THRESH_TEST = 0.5; static constexpr int DETECTIONS_PER_IMAGE = 100; static constexpr float SCORE_THRESH = 0.6; static const std::vector<float> BBOX_REG_WEIGHTS = { 10.0, 10.0, 5.0, 5.0 }; static const char* INPUT_NODE_NAME = "images"; static const std::vector<std::string> OUTPUT_NAMES = { "scores", "boxes", "labels" }; std::vector<float> GenerateAnchors(const std::vector<float>& anchor_sizes, const std::vector<float>& aspect_ratios) { std::vector<float> res; for (auto as : anchor_sizes) { float area = as * as; for (auto ar : aspect_ratios) { float w = sqrt(area / ar); float h = ar * w; res.push_back(-w / 2.0); res.push_back(-h / 2.0); res.push_back(w / 2.0); res.push_back(h / 2.0); } } return res; } // transpose && resize && normalization && padding ITensor* DataPreprocess(INetworkDefinition *network, ITensor& input) { // get h and w auto input_hw = input.getDimensions(); int c = input_hw.d[2]; int height = input_hw.d[0]; int width = input_hw.d[1]; // resize float ratio = MIN_SIZE / static_cast<float>(std::min(height, width)); float newh = 0, neww = 0; if (height < width) { newh = MIN_SIZE; neww = ratio * width; } else { newh = ratio * height; neww = MIN_SIZE; } if (std::max(newh, neww) > MAX_SIZE) { ratio = MAX_SIZE / static_cast<float>(std::max(newh, neww)); newh = newh * ratio; neww = neww * ratio; } height = static_cast<int>(newh + 0.5); width = static_cast<int>(neww + 0.5); auto resize_layer = network->addResize(input); assert(resize_layer); resize_layer->setResizeMode(ResizeMode::kLINEAR); resize_layer->setOutputDimensions(Dims3{ height, width, c }); IMAGE_HEIGHT = height; IMAGE_WIDTH = width; // HWC->CHW auto channel_permute = network->addShuffle(*resize_layer->getOutput(0)); assert(channel_permute); channel_permute->setFirstTranspose(Permutation{ 2, 0, 1 }); // sub pixel mean auto pixel_mean = network->addConstant(Dims3{ 3, 1, 1 }, Weights{ DataType::kFLOAT, PIXEL_MEAN.data(), 3 }); assert(pixel_mean); auto sub = network->addElementWise(*channel_permute->getOutput(0), *pixel_mean->getOutput(0), ElementWiseOperation::kSUB); assert(sub); auto pixel_std = network->addConstant(Dims3{ 3, 1, 1 }, Weights{DataType::kFLOAT, PIXEL_STD.data(), 3}); assert(pixel_std); auto div = network->addElementWise(*sub->getOutput(0), *pixel_std->getOutput(0), ElementWiseOperation::kDIV); assert(div); return div->getOutput(0); } void calculateRatio() { float ratio = MIN_SIZE / static_cast<float>(std::min(INPUT_H, INPUT_W)); float newh = 0, neww = 0; if (INPUT_H < INPUT_W) { newh = MIN_SIZE; neww = ratio * INPUT_W; } else { newh = ratio * INPUT_H; neww = MIN_SIZE; } if (std::max(newh, neww) > MAX_SIZE) { ratio = MAX_SIZE / static_cast<float>(std::max(newh, neww)); newh = newh * ratio; neww = neww * ratio; } IMAGE_HEIGHT = static_cast<int>(newh + 0.5); IMAGE_WIDTH = static_cast<int>(neww + 0.5); } ITensor* RPN(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, ITensor& features, int out_channels = 256) { int num_anchors = ANCHOR_SIZES.size() * ASPECT_RATIOS.size(); int box_dim = 4; // rpn head conv auto rpn_head_conv = network->addConvolutionNd(features, out_channels, DimsHW{ 3, 3 }, weightMap["proposal_generator.rpn_head.conv.weight"], weightMap["proposal_generator.rpn_head.conv.bias"]); assert(rpn_head_conv); rpn_head_conv->setStrideNd(DimsHW{ 1, 1 }); rpn_head_conv->setPaddingNd(DimsHW{ 1, 1 }); auto rpn_head_relu = network->addActivation(*rpn_head_conv->getOutput(0), ActivationType::kRELU); assert(rpn_head_relu); // objectness logits auto rpn_head_logits = network->addConvolutionNd(*rpn_head_relu->getOutput(0), num_anchors, DimsHW{ 1, 1 }, weightMap["proposal_generator.rpn_head.objectness_logits.weight"], weightMap["proposal_generator.rpn_head.objectness_logits.bias"]); assert(rpn_head_logits); rpn_head_logits->setStrideNd(DimsHW{ 1, 1 }); // anchor deltas auto rpn_head_deltas = network->addConvolutionNd(*rpn_head_relu->getOutput(0), num_anchors * box_dim, DimsHW{ 1, 1 }, weightMap["proposal_generator.rpn_head.anchor_deltas.weight"], weightMap["proposal_generator.rpn_head.anchor_deltas.bias"]); assert(rpn_head_deltas); auto rpn_head_deltas_dim = rpn_head_deltas->getOutput(0)->getDimensions(); rpn_head_deltas->setStrideNd(DimsHW{ 1, 1 }); auto anchors = GenerateAnchors(ANCHOR_SIZES, ASPECT_RATIOS); auto rpnDecodePlugin = RpnDecodePlugin(PRE_NMS_TOP_K_TEST, anchors, STRIDES, IMAGE_HEIGHT, IMAGE_WIDTH); std::vector<ITensor*> faster_decode_inputs = { rpn_head_logits->getOutput(0), rpn_head_deltas->getOutput(0) }; auto rpnDecodeLayer = network->addPluginV2(faster_decode_inputs.data(), faster_decode_inputs.size(), rpnDecodePlugin); std::vector<ITensor*> nms_input = { rpnDecodeLayer->getOutput(0), rpnDecodeLayer->getOutput(1) }; // nms auto nmsPlugin = RpnNmsPlugin(RPN_NMS_THRESH, POST_NMS_TOPK); auto nmsLayer = network->addPluginV2(nms_input.data(), nms_input.size(), nmsPlugin); return nmsLayer->getOutput(0); } std::vector<ITensor*> ROIHeads(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, ITensor& proposals, ITensor& features) { std::vector<ITensor*> roi_inputs = { &proposals, &features }; auto roiAlignPlugin = RoiAlignPlugin(POOLER_RESOLUTION, 1 / static_cast<float>(STRIDES), SAMPLING_RATIO, POST_NMS_TOPK, features.getDimensions().d[0]); auto roiAlignLayer = network->addPluginV2(roi_inputs.data(), roi_inputs.size(), roiAlignPlugin); // res5 auto box_features = MakeStage(network, weightMap, "roi_heads.res5", *roiAlignLayer->getOutput(0), num_blocks_per_stage.at(BACKBONE_RESNETTYPE)[3], 1024, 512, 2048, 2); auto box_features_mean = network->addReduce(*box_features, ReduceOperation::kAVG, 12, true); // score auto scores = network->addFullyConnected(*box_features_mean->getOutput(0), NUM_CLASSES + 1, weightMap["roi_heads.box_predictor.cls_score.weight"], weightMap["roi_heads.box_predictor.cls_score.bias"]); auto probs = network->addSoftMax(*scores->getOutput(0)); auto probs_dim = probs->getOutput(0)->getDimensions(); auto score_slice = network->addSlice(*probs->getOutput(0), Dims4{ 0, 0, 0, 0 }, Dims4{ probs_dim.d[0], probs_dim.d[1] - 1, 1, 1 }, Dims4{ 1, 1, 1, 1 }); auto proposal_deltas = network->addFullyConnected(*box_features_mean->getOutput(0), NUM_CLASSES * 4, weightMap["roi_heads.box_predictor.bbox_pred.weight"], weightMap["roi_heads.box_predictor.bbox_pred.bias"]); // decode std::vector<ITensor*> predictorDecodeInput = { score_slice->getOutput(0), proposal_deltas->getOutput(0), &proposals }; auto predictorDecodePlugin = PredictorDecodePlugin(probs_dim.d[0], IMAGE_HEIGHT, IMAGE_WIDTH, BBOX_REG_WEIGHTS); auto predictorDecodeLayer = network->addPluginV2(predictorDecodeInput.data(), predictorDecodeInput.size(), predictorDecodePlugin); // nms std::vector<ITensor*> nmsInput = { predictorDecodeLayer->getOutput(0), predictorDecodeLayer->getOutput(1), predictorDecodeLayer->getOutput(2) }; auto batchedNmsPlugin = BatchedNmsPlugin(NMS_THRESH_TEST, DETECTIONS_PER_IMAGE); auto batchedNmsLayer = network->addPluginV2(nmsInput.data(), nmsInput.size(), batchedNmsPlugin); std::vector<ITensor*> result = { batchedNmsLayer->getOutput(0), batchedNmsLayer->getOutput(1), batchedNmsLayer->getOutput(2) }; return result; } ICudaEngine* createEngine_rcnn(unsigned int maxBatchSize, const std::string& wtsfile, IBuilder* builder, IBuilderConfig* config, DataType dt, const std::string& modelType, const std::string& quantizationType, const std::string& calibImgListFile, const std::string& calibFile) { /* description: after fuse bn */ INetworkDefinition* network = builder->createNetworkV2(0U); // Create input tensor of shape {INPUT_H, INPUT_W, 3} with name INPUT_BLOB_NAME ITensor* data = network->addInput(INPUT_NODE_NAME, dt, Dims3{ INPUT_H, INPUT_W, 3 }); assert(data); // preprocess data = DataPreprocess(network, *data); std::map<std::string, Weights> weightMap; loadWeights(wtsfile, weightMap); // backbone ITensor* features = BuildResNet(network, weightMap, *data, BACKBONE_RESNETTYPE, 64, 64, 256); auto proposals = RPN(network, weightMap, *features, 1024); auto results = ROIHeads(network, weightMap, *proposals, *features); // build output for (int i = 0; i < results.size(); i++) { network->markOutput(*results[i]); results[i]->setName(OUTPUT_NAMES[i].c_str()); } // build engine builder->setMaxBatchSize(maxBatchSize); config->setMaxWorkspaceSize(1ULL << 30); if (quantizationType == "fp32") { } else if (quantizationType == "fp16") { config->setFlag(BuilderFlag::kFP16); } else if (quantizationType == "int8") { std::cout << "Your platform support int8: " << (builder->platformHasFastInt8() ? "true" : "false") << std::endl; assert(builder->platformHasFastInt8()); config->setFlag(BuilderFlag::kINT8); Int8EntropyCalibrator2* calibrator = new Int8EntropyCalibrator2(1, INPUT_W, INPUT_H, "./coco_calib/", "int8calib.table", INPUT_NODE_NAME); config->setInt8Calibrator(calibrator); } else { throw("does not support model type"); } std::cout << "Building engine, please wait for a while..." << std::endl; ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config); std::cout << "Build engine successfully!" << std::endl; // destroy network network->destroy(); // Release host memory for (auto& mem : weightMap) { delete[] mem.second.values; } return engine; } void BuildRcnnModel(unsigned int maxBatchSize, IHostMemory** modelStream, const std::string& wtsfile, const std::string& modelType = "faster", const std::string& quantizationType = "fp32", const std::string& calibImgListFile = "./imglist.txt", const std::string& calibFile = "./calib.table") { // Create builder IBuilder* builder = createInferBuilder(gLogger); IBuilderConfig* config = builder->createBuilderConfig(); ICudaEngine* engine = createEngine_rcnn(maxBatchSize, wtsfile, builder, config, DataType::kFLOAT, modelType, quantizationType, calibImgListFile, calibFile); assert(engine != nullptr); // Serialize the engine (*modelStream) = engine->serialize(); // Close everything down engine->destroy(); builder->destroy(); } bool parse_args(int argc, char** argv, std::string& wtsFile, std::string& engineFile, std::string& imgDir) { if (argc < 4) return false; if (std::string(argv[1]) == "-s") { wtsFile = std::string(argv[2]); engineFile = std::string(argv[3]); } else if (std::string(argv[1]) == "-d") { engineFile = std::string(argv[2]); imgDir = std::string(argv[3]); } else { return false; } return true; } int main(int argc, char** argv) { cudaSetDevice(DEVICE); std::string wtsFile = ""; std::string engineFile = ""; std::string imgDir; if (!parse_args(argc, argv, wtsFile, engineFile, imgDir)) { std::cerr << "arguments not right!" << std::endl; std::cerr << "./rcnn -s [.wts] [.engine] // serialize model to plan file" << std::endl; std::cerr << "./rcnn -d [.engine] ../samples // deserialize plan file and run inference" << std::endl; return -1; } if (!wtsFile.empty()) { IHostMemory* modelStream{ nullptr }; BuildRcnnModel(BATCH_SIZE, &modelStream, wtsFile, "faster", "fp32"); assert(modelStream != nullptr); std::ofstream p(engineFile, std::ios::binary); if (!p) { std::cerr << "could not open plan output file" << std::endl; return -1; } p.write(reinterpret_cast<const char*>(modelStream->data()), modelStream->size()); modelStream->destroy(); return 0; } // calculate ratio calculateRatio(); // deserialize the .engine and run inference std::ifstream file(engineFile, std::ios::binary); if (!file.good()) { std::cerr << "read " << engineFile << " error!" << std::endl; return -1; } std::string trtModelStream; size_t modelSize{ 0 }; file.seekg(0, file.end); modelSize = file.tellg(); file.seekg(0, file.beg); trtModelStream.resize(modelSize); assert(!trtModelStream.empty()); file.read(const_cast<char*>(trtModelStream.c_str()), modelSize); file.close(); // build engine std::cout << "build engine" << std::endl; IRuntime* runtime = createInferRuntime(gLogger); assert(runtime != nullptr); ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream.c_str(), modelSize); assert(engine != nullptr); IExecutionContext* context = engine->createExecutionContext(); assert(context != nullptr); runtime->destroy(); cudaStream_t stream; CUDA_CHECK(cudaStreamCreate(&stream)); // prepare input file std::vector<std::string> fileList; if (read_files_in_dir(imgDir.c_str(), fileList) < 0) { std::cerr << "read_files_in_dir failed." << std::endl; return -1; } // prepare input data std::vector<float> data(BATCH_SIZE * INPUT_H * INPUT_W * 3, 0); void *data_d, *scores_d, *boxes_d, *classes_d; CUDA_CHECK(cudaMalloc(&data_d, BATCH_SIZE * INPUT_H * INPUT_W * 3 * sizeof(float))); CUDA_CHECK(cudaMalloc(&scores_d, BATCH_SIZE * DETECTIONS_PER_IMAGE * sizeof(float))); CUDA_CHECK(cudaMalloc(&boxes_d, BATCH_SIZE * DETECTIONS_PER_IMAGE * 4 * sizeof(float))); CUDA_CHECK(cudaMalloc(&classes_d, BATCH_SIZE * DETECTIONS_PER_IMAGE * sizeof(float))); std::unique_ptr<float[]> scores_h(new float[BATCH_SIZE * DETECTIONS_PER_IMAGE]); std::unique_ptr<float[]> boxes_h(new float[BATCH_SIZE * DETECTIONS_PER_IMAGE * 4]); std::unique_ptr<float[]> classes_h(new float[BATCH_SIZE * DETECTIONS_PER_IMAGE]); int fcount = 0; int fileLen = fileList.size(); for (int f = 0; f < fileLen; f++) { fcount++; if (fcount < BATCH_SIZE && f + 1 != fileLen) continue; for (int b = 0; b < fcount; b++) { cv::Mat img = cv::imread(imgDir + "/" + fileList[f - fcount + 1 + b]); img = preprocessImg(img, INPUT_W, INPUT_H); if (img.empty()) continue; for (int i = 0; i < INPUT_H * INPUT_W * 3; i++) data[b*INPUT_H * INPUT_W * 3 + i] = static_cast<float>(*(img.data + i)); } // Run inference auto start = std::chrono::system_clock::now(); CUDA_CHECK(cudaMemcpyAsync(data_d, data.data(), BATCH_SIZE * INPUT_H * INPUT_W * 3 * sizeof(float), cudaMemcpyHostToDevice, stream)); std::vector<void*> buffers = { data_d, scores_d, boxes_d, classes_d }; context->enqueue(BATCH_SIZE, buffers.data(), stream, nullptr); CUDA_CHECK(cudaMemcpyAsync(scores_h.get(), scores_d, BATCH_SIZE * DETECTIONS_PER_IMAGE * sizeof(float), cudaMemcpyDeviceToHost, stream)); CUDA_CHECK(cudaMemcpyAsync(boxes_h.get(), boxes_d, BATCH_SIZE * DETECTIONS_PER_IMAGE * 4 * sizeof(float), cudaMemcpyDeviceToHost, stream)); CUDA_CHECK(cudaMemcpyAsync(classes_h.get(), classes_d, BATCH_SIZE * DETECTIONS_PER_IMAGE * sizeof(float), cudaMemcpyDeviceToHost, stream)); cudaStreamSynchronize(stream); auto end = std::chrono::system_clock::now(); std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl; float h_ratio = static_cast<float>(INPUT_H) / IMAGE_HEIGHT; float w_ratio = static_cast<float>(INPUT_W) / IMAGE_WIDTH; for (int b = 0; b < fcount; b++) { cv::Mat img = cv::imread(imgDir + "/" + fileList[f - fcount + 1 + b]); img = preprocessImg(img, INPUT_W, INPUT_H); for (int i = 0; i < DETECTIONS_PER_IMAGE; i++) { if (scores_h[b * DETECTIONS_PER_IMAGE + i] > SCORE_THRESH) { float x1 = boxes_h[b * DETECTIONS_PER_IMAGE * 4 + i * 4 + 0] * w_ratio; float y1 = boxes_h[b * DETECTIONS_PER_IMAGE * 4 + i * 4 + 1] * h_ratio; float x2 = boxes_h[b * DETECTIONS_PER_IMAGE * 4 + i * 4 + 2] * w_ratio; float y2 = boxes_h[b * DETECTIONS_PER_IMAGE * 4 + i * 4 + 3] * h_ratio; int label = classes_h[b * DETECTIONS_PER_IMAGE + i]; float score = scores_h[b * DETECTIONS_PER_IMAGE + i]; printf("boxes:[%.6f, %.6f, %.6f, %.6f] scores: %.4f label: %d \n", x1, y1, x2, y2, score, label); cv::Rect r(x1, y1, x2 - x1, y2 - y1); cv::rectangle(img, r, cv::Scalar(0x27, 0xC1, 0x36), 2); cv::putText(img, std::to_string(label), cv::Point(r.x, r.y - 1), cv::FONT_HERSHEY_PLAIN, 1.2, cv::Scalar(0xFF, 0xFF, 0xFF), 2); } } cv::imwrite("_" + fileList[f - fcount + 1 + b], img); } fcount = 0; } cudaStreamDestroy(stream); CUDA_CHECK(cudaFree(data_d)); CUDA_CHECK(cudaFree(scores_d)); CUDA_CHECK(cudaFree(boxes_d)); CUDA_CHECK(cudaFree(classes_d)); context->destroy(); engine->destroy(); return 0; }
40.723769
120
0.654222
[ "shape", "vector", "model" ]
0b575f5fef6c955ccff4e73ea87dd68eb1bd8ad7
13,936
cpp
C++
services/ces/src/common_event_subscriber_manager.cpp
openharmony-sig-ci/notification_ces_standard
658c1a312da2d100f4c223d85bf0759b55163b42
[ "Apache-2.0" ]
null
null
null
services/ces/src/common_event_subscriber_manager.cpp
openharmony-sig-ci/notification_ces_standard
658c1a312da2d100f4c223d85bf0759b55163b42
[ "Apache-2.0" ]
null
null
null
services/ces/src/common_event_subscriber_manager.cpp
openharmony-sig-ci/notification_ces_standard
658c1a312da2d100f4c223d85bf0759b55163b42
[ "Apache-2.0" ]
1
2021-09-13T12:06:55.000Z
2021-09-13T12:06:55.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <time.h> #include "common_event_subscriber_manager.h" #include "event_log_wrapper.h" namespace OHOS { namespace EventFwk { #define FREEZE_TIMEOUT_SECOND 120 const int LENGTH = 80; CommonEventSubscriberManager::CommonEventSubscriberManager() : death_(sptr<IRemoteObject::DeathRecipient>(new SubscriberDeathRecipient())), FREEZE_EVENT_TIMEOUT(FREEZE_TIMEOUT_SECOND) { EVENT_LOGI("CommonEventSubscriberManager instance created"); } CommonEventSubscriberManager::~CommonEventSubscriberManager() { EVENT_LOGI("CommonEventSubscriberManager instance destoryed"); } int CommonEventSubscriberManager::InsertSubscriber(const SubscribeInfoPtr &eventSubscriberInfo, const sptr<IRemoteObject> &commonEventListener, const struct tm &recordTime, const pid_t &pid, const uid_t &uid, const std::string &bundleName) { EVENT_LOGI("enter"); if (eventSubscriberInfo == nullptr) { EVENT_LOGE("eventSubscriberInfo is null"); return ERR_INVALID_VALUE; } if (commonEventListener == nullptr) { EVENT_LOGE("commonEventListener is null"); return ERR_INVALID_VALUE; } std::vector<std::string> events = eventSubscriberInfo->GetMatchingSkills().GetEvents(); if (events.size() <= 0) { EVENT_LOGE("No subscribed events"); return ERR_INVALID_VALUE; } auto record = std::make_shared<EventSubscriberRecord>(); if (record == nullptr) { EVENT_LOGE("Failed to create EventSubscriberRecord"); return ERR_INVALID_VALUE; } record->eventSubscriberInfo = eventSubscriberInfo; record->commonEventListener = commonEventListener; record->recordTime = recordTime; record->pid = pid; record->uid = uid; record->bundleName = bundleName; if (death_ != nullptr) { commonEventListener->AddDeathRecipient(death_); } return InsertSubscriberRecordLocked(events, record); } int CommonEventSubscriberManager::RemoveSubscriber(const sptr<IRemoteObject> &commonEventListener) { EVENT_LOGI("enter"); if (commonEventListener == nullptr) { EVENT_LOGE("commonEventListener is null"); return ERR_INVALID_VALUE; } if (death_ != nullptr) { commonEventListener->RemoveDeathRecipient(death_); } return RemoveSubscriberRecordLocked(commonEventListener); } std::vector<std::shared_ptr<EventSubscriberRecord>> CommonEventSubscriberManager::GetSubscriberRecords(const Want &want) { EVENT_LOGI("enter"); auto records = std::vector<SubscriberRecordPtr>(); GetSubscriberRecordsByWantLocked(want, records); return records; } void CommonEventSubscriberManager::DumpDetailed( const std::string &title, const SubscriberRecordPtr &record, const std::string format, std::string &dumpInfo) { char systime[LENGTH]; strftime(systime, sizeof(char) * LENGTH, "%Y%m%d %I:%M %p", &record->recordTime); std::string recordTime = format + "Time: " + std::string(systime) + "\n"; std::string pid = format + "PID: " + std::to_string(record->pid) + "\n"; std::string uid = format + "UID: " + std::to_string(record->uid) + "\n"; std::string bundleName = format + "BundleName: " + record->bundleName + "\n"; std::string priority = format + "Priority: " + std::to_string(record->eventSubscriberInfo->GetPriority()) + "\n"; std::string permission = format + "Permission: " + record->eventSubscriberInfo->GetPermission() + "\n"; std::string deviceId = format + "DevicedID: " + record->eventSubscriberInfo->GetDeviceId() + "\n"; std::string events = format + "\tEvent: "; std::string separator; for (int eventNum = 0; eventNum < record->eventSubscriberInfo->GetMatchingSkills().CountEvent(); ++eventNum) { if (eventNum == 0) { separator = ""; } else { separator = ", "; } events = events + separator + record->eventSubscriberInfo->GetMatchingSkills().GetEvent(eventNum); } events = events + "\n"; std::string entities = format + "\tEntity: "; for (int entityNum = 0; entityNum < record->eventSubscriberInfo->GetMatchingSkills().CountEntities(); ++entityNum) { if (entityNum == 0) { separator = ""; } else { separator = ", "; } entities = entities + separator + record->eventSubscriberInfo->GetMatchingSkills().GetEntity(entityNum); } entities = entities + "\n"; std::string scheme = format + "\tScheme: "; for (int schemeNum = 0; schemeNum < record->eventSubscriberInfo->GetMatchingSkills().CountSchemes(); ++schemeNum) { if (schemeNum == 0) { separator = ""; } else { separator = ", "; } scheme = scheme + separator + record->eventSubscriberInfo->GetMatchingSkills().GetScheme(schemeNum); } scheme = scheme + "\n"; std::string matchingSkills = format + "MatchingSkills:\n" + events + entities + scheme; std::string isFreeze = record->isFreeze ? "true" : "false"; isFreeze = format + "IsFreeze: " + isFreeze + "\n"; std::string freezeTime; if (record->freezeTime == 0) { freezeTime = format + "FreezeTime: -\n"; } else { freezeTime = format + "FreezeTime: " + std::to_string(record->freezeTime) + "\n"; } dumpInfo = title + recordTime + pid + uid + bundleName + priority + permission + deviceId + matchingSkills + isFreeze + freezeTime; } void CommonEventSubscriberManager::DumpState(const std::string &event, std::vector<std::string> &state) { EVENT_LOGI("enter"); std::vector<SubscriberRecordPtr> records; std::lock_guard<std::mutex> lock(mutex_); GetSubscriberRecordsByEvent(event, records); if (records.size() == 0) { state.emplace_back("Subscribers:\tNo information"); return; } int num = 0; for (auto record : records) { num++; std::string title = std::to_string(num); if (num == 1) { title = "Subscribers:\tTotal " + std::to_string(records.size()) + " subscribers\nNO " + title + "\n"; } else { title = "NO " + title + "\n"; } std::string dumpInfo; DumpDetailed(title, record, "\t", dumpInfo); state.emplace_back(dumpInfo); } } int CommonEventSubscriberManager::InsertSubscriberRecordLocked( const std::vector<std::string> &events, const SubscriberRecordPtr &record) { if (events.size() == 0) { EVENT_LOGE("No subscribed events"); return ERR_INVALID_VALUE; } if (record == nullptr) { EVENT_LOGE("record is null"); return ERR_INVALID_VALUE; } std::lock_guard<std::mutex> lock(mutex_); for (auto event : events) { auto infoItem = eventSubscribers_.find(event); if (infoItem != eventSubscribers_.end()) { infoItem->second.insert(record); } else { std::multiset<SubscriberRecordPtr> EventSubscribersPtr; EventSubscribersPtr.insert(record); eventSubscribers_[event] = EventSubscribersPtr; } } subscribers_.emplace_back(record); return ERR_OK; } int CommonEventSubscriberManager::RemoveSubscriberRecordLocked(const sptr<IRemoteObject> &commonEventListener) { if (commonEventListener == nullptr) { EVENT_LOGE("commonEventListener is null"); return ERR_INVALID_VALUE; } std::lock_guard<std::mutex> lock(mutex_); std::vector<std::string> events; for (auto it = subscribers_.begin(); it != subscribers_.end(); ++it) { if (commonEventListener == (*it)->commonEventListener) { RemoveFrozenEventsBySubscriber((*it)); (*it)->commonEventListener = nullptr; events = (*it)->eventSubscriberInfo->GetMatchingSkills().GetEvents(); subscribers_.erase(it); break; } } for (auto event : events) { for (auto it = eventSubscribers_[event].begin(); it != eventSubscribers_[event].end(); ++it) { if ((commonEventListener == (*it)->commonEventListener) || ((*it)->commonEventListener == nullptr)) { (*it)->commonEventListener = nullptr; eventSubscribers_[event].erase(it); break; } } if (eventSubscribers_[event].size() == 0) { eventSubscribers_.erase(event); } } return ERR_OK; } void CommonEventSubscriberManager::GetSubscriberRecordsByWantLocked( const Want &want, std::vector<SubscriberRecordPtr> &records) { std::lock_guard<std::mutex> lock(mutex_); if (eventSubscribers_.size() <= 0) { return; } auto recordsItem = eventSubscribers_.find(want.GetAction()); if (recordsItem == eventSubscribers_.end()) { return; } std::multiset<SubscriberRecordPtr> subscriberRecords = recordsItem->second; for (auto it = subscriberRecords.begin(); it != subscriberRecords.end(); it++) { if ((*it)->eventSubscriberInfo->GetMatchingSkills().Match(want)) { records.emplace_back(*it); } } } void CommonEventSubscriberManager::GetSubscriberRecordsByEvent( const std::string &event, std::vector<SubscriberRecordPtr> &records) { if (event.empty()) { records = subscribers_; } else { auto infoItem = eventSubscribers_.find(event); if (infoItem != eventSubscribers_.end()) { for (auto recordPtr : infoItem->second) { records.emplace_back(recordPtr); } } } } void CommonEventSubscriberManager::UpdateFreezeInfo( const uid_t &uid, const bool &freezeState, const int64_t &freezeTime) { EVENT_LOGI("enter"); std::lock_guard<std::mutex> lock(mutex_); std::vector<std::string> events; for (auto recordPtr : subscribers_) { if (recordPtr->uid == uid) { if (freezeState) { recordPtr->freezeTime = freezeTime; } else { recordPtr->freezeTime = 0; } recordPtr->isFreeze = freezeState; EVENT_LOGI("recordPtr->uid: %{public}d", recordPtr->uid); EVENT_LOGI("recordPtr->isFreeze: %{public}d", recordPtr->isFreeze); } } } void CommonEventSubscriberManager::InsertFrozenEvents( const SubscriberRecordPtr &subscriberRecord, const CommonEventRecord &eventRecord) { EVENT_LOGI("enter"); if (subscriberRecord == nullptr) { EVENT_LOGE("subscriberRecord is null"); return; } auto record = std::make_shared<CommonEventRecord>(eventRecord); std::lock_guard<std::mutex> lock(mutex_); auto frozenRecordsItem = frozenEvents_.find(subscriberRecord->uid); if (frozenRecordsItem != frozenEvents_.end()) { auto eventRecordsItem = frozenRecordsItem->second.find(subscriberRecord); if (eventRecordsItem != frozenRecordsItem->second.end()) { eventRecordsItem->second.emplace_back(record); time_t backRecordTime = mktime(&eventRecordsItem->second.back()->recordTime); time_t frontRecordTime = mktime(&eventRecordsItem->second.front()->recordTime); EVENT_LOGD("backRecordTime: %{public}ld", backRecordTime); EVENT_LOGD("frontRecordTime: %{public}ld", frontRecordTime); time_t timeDiff = backRecordTime - frontRecordTime; EVENT_LOGD("timeDiff: %{public}ld", timeDiff); if (timeDiff > FREEZE_EVENT_TIMEOUT) { eventRecordsItem->second.erase(eventRecordsItem->second.begin()); } } else { std::vector<EventRecordPtr> EventRecords; EventRecords.emplace_back(record); frozenRecordsItem->second[subscriberRecord] = EventRecords; } } else { std::map<SubscriberRecordPtr, std::vector<EventRecordPtr>> frozenRecords; std::vector<EventRecordPtr> EventRecords; EventRecords.emplace_back(record); frozenRecords[subscriberRecord] = EventRecords; frozenEvents_[subscriberRecord->uid] = frozenRecords; } } std::map<SubscriberRecordPtr, std::vector<EventRecordPtr>> CommonEventSubscriberManager::GetFrozenEvents( const uid_t &uid) { EVENT_LOGI("enter"); std::map<SubscriberRecordPtr, std::vector<EventRecordPtr>> frozenEvents; std::lock_guard<std::mutex> lock(mutex_); auto infoItem = frozenEvents_.find(uid); if (infoItem != frozenEvents_.end()) { frozenEvents = infoItem->second; } RemoveFrozenEvents(uid); return frozenEvents; } void CommonEventSubscriberManager::RemoveFrozenEvents(const uid_t &uid) { EVENT_LOGI("enter"); auto infoItem = frozenEvents_.find(uid); if (infoItem != frozenEvents_.end()) { frozenEvents_.erase(uid); } } void CommonEventSubscriberManager::RemoveFrozenEventsBySubscriber(const SubscriberRecordPtr &subscriberRecord) { EVENT_LOGI("enter"); auto frozenRecordsItem = frozenEvents_.find(subscriberRecord->uid); if (frozenRecordsItem != frozenEvents_.end()) { auto eventRecordsItems = frozenRecordsItem->second.find(subscriberRecord); if (eventRecordsItems != frozenRecordsItem->second.end()) { frozenRecordsItem->second.erase(subscriberRecord); } } } } // namespace EventFwk } // namespace OHOS
34.325123
120
0.653487
[ "vector" ]
0b5ec4857ac13d8199c2bcf9bf796e0a092c023c
6,591
hh
C++
packages/SPn/solvers/StratimikosSolver.t.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
19
2015-06-04T09:02:41.000Z
2021-04-27T19:32:55.000Z
packages/SPn/solvers/StratimikosSolver.t.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
null
null
null
packages/SPn/solvers/StratimikosSolver.t.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
5
2016-10-05T20:48:28.000Z
2021-06-21T12:00:54.000Z
//----------------------------------*-C++-*----------------------------------// /*! * \file SPn/solvers/StratimikosSolver.t.hh * \author Chris Baker * \date Thu May 17 14:18:09 2012 * \brief StratimikosSolver template member definitions * \note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #ifndef SPn_solvers_StratimikosSolver_t_hh #define SPn_solvers_StratimikosSolver_t_hh #include <iostream> #include "Thyra_EpetraThyraWrappers.hpp" #include "Thyra_TpetraThyraWrappers.hpp" #include "Teuchos_XMLParameterListHelpers.hpp" #include "Stratimikos_DefaultLinearSolverBuilder.hpp" #include "comm/global.hh" #include "harness/DBC.hh" #include "harness/Warnings.hh" #include "StratimikosSolver.hh" #include "LinAlgTypedefs.hh" #include "ThyraTraits.hh" namespace profugus { //---------------------------------------------------------------------------// // Constructor //---------------------------------------------------------------------------// /*! * \brief Constructor */ template <class T> StratimikosSolver<T>::StratimikosSolver(Teuchos::RCP<ParameterList> db) : LinearSolver<T>(db) , d_updated_operator( false ) { using Teuchos::sublist; // read database // get stratimikos database and convert to a ParameterList Teuchos::RCP<ParameterList> builderplist = Teuchos::sublist(db, "Stratimikos"); CHECK(!builderplist.is_null()); if (db->isParameter("linear_solver_xml_file")) { Teuchos::updateParametersFromXmlFile( db->get<std::string>("linear_solver_xml_file"), builderplist.ptr()); } if ( !Teuchos::isParameterType<std::string>( *builderplist, "Preconditioner Type") ) { builderplist->set("Preconditioner Type", "None"); } if ( !Teuchos::isParameterType<std::string>( *builderplist, "Linear Solver Type") ) { builderplist->set("Linear Solver Type","AztecOO"); } Stratimikos::DefaultLinearSolverBuilder builder; builder.setParameterList(builderplist); b_label = "Stratimikos " + builder.getLinearSolveStrategyName(); d_factory = Thyra::createLinearSolveStrategy(builder); d_solver = d_factory->createOp(); } //---------------------------------------------------------------------------// // PUBLIC FUNCTIONS //---------------------------------------------------------------------------// // //---------------------------------------------------------------------------// /*! * \brief Solve linear system. * * \param x pointer to solution vector * \param b pointer to RHS vector */ template <class T> void StratimikosSolver<T>::solve(Teuchos::RCP<MV> x, Teuchos::RCP<const MV> b) { using Teuchos::RCP; using Teuchos::rcp; using Teuchos::ptrInArg; INSIST(d_thyraA != Teuchos::null, "set_operator has not been called"); REQUIRE(x != Teuchos::null); REQUIRE(b != Teuchos::null); REQUIRE(MVT::GetNumberVecs(*x) == MVT::GetNumberVecs(*b)); REQUIRE(b_tolerance >= 0.0); REQUIRE(b_max_iters > 0); // Create Thyra preconditioner if we have an operator for it RCP<const Prec> prec; if( d_prec!=Teuchos::null ) { prec = unspecifiedPrec(d_prec); } // Initialize LOWS if( prec != Teuchos::null ) { Thyra::initializePreconditionedOp<ST>( *d_factory, d_thyraA, prec, d_solver.ptr()); } // If the operator has changed but we are reusing the preconditioner then // reinitialize the linearOpWithSolve object. else if ( d_updated_operator ) { // Reuse as much information from previous solve as possible Thyra::initializeAndReuseOp<ST>( *d_factory, d_thyraA, d_solver.ptr()); d_updated_operator = false; } // make Thyra view into the solution vector RCP<Thyra::MultiVectorBase<ST> > thyra_x = ThyraTraits<T>::buildThyraMV(x,d_thyraA->domain()); // make Thyra view of the right-hand side RCP<const Thyra::MultiVectorBase<ST> > thyra_b = ThyraTraits<T>::buildThyraConstMV(b,d_thyraA->range()); // solve Thyra::SolveCriteria<ST> criteria; // measure convergence against |A*x-b| / |b| criteria.solveMeasureType = Thyra::SolveMeasureType( Thyra::SOLVE_MEASURE_NORM_RESIDUAL, Thyra::SOLVE_MEASURE_NORM_RHS); // set the tolerance criteria.requestedTol = b_tolerance; // set maximum iterations criteria.extraParameters = Teuchos::parameterList(); criteria.extraParameters->template set<int>("Maximum Iterations", b_max_iters); // solve Thyra::SolveStatus<ST> solveStatus = Thyra::solve<ST>( *d_solver, Thyra::NOTRANS, *thyra_b, thyra_x.ptr(), ptrInArg(criteria)); // get the number of iterations for the solve b_num_iters = solveStatus.extraParameters->template get<int>("Iteration Count"); if( b_verbosity >= LinearSolver<T>::LOW ) { ST final_res = solveStatus.achievedTol; profugus::pout << b_label << " performed " << b_num_iters << " iterations. Final residual norm is " << profugus::scientific << profugus::setprecision(3) << final_res << profugus::endl; } } //---------------------------------------------------------------------------// /*! * \brief Set operator and convert to Thyra operator * * \param A operator */ //---------------------------------------------------------------------------// template <class T> void StratimikosSolver<T>::set_operator(Teuchos::RCP<OP> A) { // Create thyra operator d_thyraA = ThyraTraits<T>::buildThyraOP(A); // Indicate that the operator has been updated. d_updated_operator = true; ENSURE(d_thyraA != Teuchos::null ); } //---------------------------------------------------------------------------// /*! * \brief Set preconditioner. * * \param P operator to be applied as preconditioner. */ //---------------------------------------------------------------------------// template <class T> void StratimikosSolver<T>::set_preconditioner(Teuchos::RCP<OP> P) { // Create thyra operator d_prec = ThyraTraits<T>::buildThyraOP(P); ENSURE( d_prec != Teuchos::null ); } } // end namespace profugus #endif //solvers_StratimikosSolver_t_hh //---------------------------------------------------------------------------// // end of StratimikosSolver.t.hh //---------------------------------------------------------------------------//
31.84058
84
0.564406
[ "object", "vector" ]
0b5f8e291957b93d5ce1e7c00c34514e806b4c21
15,197
cc
C++
multidim_image_augmentation/ops/apply_deformation_ops.cc
zhongzisha/multidim-image-augmentation
4927015902fd20d395b5a1fe1b4caab2278e52ea
[ "Apache-2.0" ]
122
2018-11-30T13:07:35.000Z
2022-01-27T13:25:32.000Z
multidim_image_augmentation/ops/apply_deformation_ops.cc
zhongzisha/multidim-image-augmentation
4927015902fd20d395b5a1fe1b4caab2278e52ea
[ "Apache-2.0" ]
20
2018-12-26T04:30:32.000Z
2021-02-04T13:52:32.000Z
multidim_image_augmentation/ops/apply_deformation_ops.cc
LaudateCorpus1/multidim-image-augmentation
7a180ec02fba2aac98f89cfff6fa6b647484d7cc
[ "Apache-2.0" ]
25
2018-11-30T13:08:32.000Z
2022-02-04T17:55:20.000Z
// Copyright 2018 Google LLC // // 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 // // https://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 "multidim_image_augmentation/ops/apply_deformation_ops.h" #include <array> #include <string> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" namespace deepmind { namespace multidim_image_augmentation { namespace { using tensorflow::Status; using tensorflow::shape_inference::DimensionHandle; using tensorflow::shape_inference::InferenceContext; using tensorflow::shape_inference::ShapeHandle; enum SpatialDims { k2SpatialDims = 2, k3SpatialDims = 3, }; template <SpatialDims> Status ApplyDeformationShapeFunction(InferenceContext* context); REGISTER_OP("ApplyDeformation2D") .Input("input: input_type") // The order of these Input() calls .Input("deformation: float") // must match their order in .Input("padding_constant: input_type") // `OperationInputIndices`. .Output("output: output_type") .Attr("interpolation: {'linear', 'nearest'} = 'linear'") .Attr( "extrapolation: {'mirror', 'zero_padding', 'const_padding'} = 'mirror'") .Attr( "conversion: {'no_conversion', 'indexed_to_one_hot'} = 'no_conversion'") .Attr("output_spatial_shape: list(int) = []") .Attr("output_num_channels: int = -1") .Attr("input_type: {float, uint8, int32} = DT_FLOAT") .Attr("output_type: {float, uint8, int32} = DT_FLOAT") .SetShapeFn(ApplyDeformationShapeFunction<k2SpatialDims>) .Doc(R"doc( Applies a deformation field (vector field) to a given 2D image. Applies a deformation field (vector field) to a given 2D image with different interpolation, extrapolation and conversion options. The deformation field describes the backward transformation, i.e. for each position in the _output_ image it specifies the corresponding position in the _input_ image: ``` O(x) = I(D(x)) where (in the case of 2D single-channel images): x in R^2 I: R^2 --> R (input image) O: R^2 --> R (output image) D: R^2 --> R^2 (deformation field) ``` The implementation iterates over all positions in the output image. For each output position it fetches the corresponding input position from the deformation field, interpolates (or extrapolates) the value at this position in the input image and stores the resulting value in the output image. The vectors in the deformation field must be provided as raw pixel coordinates, i.e. (x0, x1) relative to the upper-left-front corner of the array. Usage example for a 2D image with 3 channels: ```python from multidim_image_augmentation import augmentation_ops with tf.Session(): input = np.random.random([10, 7, 3]).astype(np.float32) deformation = np.ndarray([10, 7, 2], dtype=np.float32) for x0 in range(deformation.shape[0]): for x1 in range(deformation.shape[1]): deformation[x0, x1, 0] = x0 deformation[x0, x1, 1] = x1 result = augmentation_ops.apply_deformation2d( input, deformation, []) self.assertEqual(result.get_shape(), input.shape) output = result.eval() self.assertAllEqual(output, input) ``` input: The multi-channel input image is a 3-D Tensor of shape `[s0, s1, num_channels]` where `s` stands for `spatial shape`. If `indexed_to_one_hot` conversion is requested the number of channels must be 1. deformation: The deformation vector field is a 3-D Tensor of shape `[s0, s1, num_components]` where `s` stands for `spatial shape`. `num_components` must be 2. The spatial shape must be equal or larger than the required output image shape. If it is larger, the central part of the deformation field is used. This is especially useful when a segmentation network takes a larger source image than the target segmentation map (e.g. a u-net that uses valid convolutions only), but both need to be deformed with the same deformation field. padding_constant: A 1-D Tensor with shape `[num_channels]`. The padding value. Type must match the input image and size must match the number of output channels. For `zero_padding` or `mirror` extrapolations this tensor can be empty. output: The multi-channel output image is a 3-D Tensor of shape `[s0, s1, num_channels]` where `s` stands for `spatial shape`. The spatial shape is usually equal to that of the deformation field. A smaller shape can be specified by the `output_spatial_shape` attribute. In case of `no_conversion` the number of channels will be identical to the input image. For `indexed_to_one_hot` a sufficient number of channels to store the one-hot encoded vectors must be specified by the `output_num_channels` attribute. interpolation: The interpolation style determines how output values are computed. Select from `nearest` neighbor interpolation or `linear` interpolation. (Note 2D deform does not support `mixed_nearest_linear`.) extrapolation: The extrapolation style determines how the output is filled where the deformation field calls out elements beyond the bounds of the input image. Select from `mirror` for extrapolation by mirroring, `zero_padding` to pad with zeros, or `const_padding` to pad with a constant value: see the `padding_constant` attribute. conversion: On-the-fly value conversion. `no_conversion` passes input to output channels (e.g. 5 channel input yeilds a 5 channel output). `indexed_to_one_hot` converts the indexed input segmentation map (1 channel with values like 3 for class 3) to a one-hot-encoded output segmentation map (e.g. 8 channels with values like (0, 0, 0, 1, 0, 0, 0, 0) for class 3). The one-hot values will be collected from the neighbouring pixels. I.e. the result would be identical when first applying the one-hot mapping to the input image and then applying a deformation with linear interpolation to the resulting multi-channel image. output_spatial_shape: spatial shape of output image [x0, x1]. If smaller than the full deformation field, the applied deformation field will be centrally cropped from the full deformation field. Default: use shape of the full deformation field. output_num_channels: Specifies the number of output channels. If no output conversion is in use the output channels will match the number of input channels -- passing a negative (or ommitting) will do this for you. For `indexed_to_one_hot` conversion this must be equal or greater than the largest integral value + 1 in the input value space. See also the `conversion` attribute. Default: `output` number channels matches that of `intput`. )doc"); REGISTER_OP("ApplyDeformation3D") .Input("input: input_type") // The order of these Input() calls .Input("deformation: float") // must match their order in .Input("padding_constant: input_type") // `OperationInputIndices`. .Output("output: output_type") .Attr( "interpolation: {'linear', 'nearest', 'mixed_nearest_linear'} = " "'linear'") .Attr( "extrapolation: {'mirror', 'zero_padding', 'const_padding'} = 'mirror'") .Attr( "conversion: {'no_conversion', 'indexed_to_one_hot'} = 'no_conversion'") .Attr("output_spatial_shape: list(int) = []") .Attr("output_num_channels: int = -1") .Attr("input_type: {float, uint8, int32} = DT_FLOAT") .Attr("output_type: {float, uint8, int32} = DT_FLOAT") .SetShapeFn(ApplyDeformationShapeFunction<k3SpatialDims>) .Doc(R"doc( Applies a deformation field (vector field) to a given 3D image. Applies a deformation field (vector field) to a given 3D image with different interpolation, extrapolation and conversion options. The deformation field describes the backward transformation, i.e. for each position in the _output_ image it specifies the corresponding position in the _input_ image: ``` O(x) = I(D(x)) where (in the case of 3D single-channel images): x in R^3 I: R^3 --> R (input image) O: R^3 --> R (output image) D: R^3 --> R^3 (deformation field) ``` The implementation iterates over all positions in the output image. For each output position it fetches the corresponding input position from the deformation field, interpolates (or extrapolates) the value at this position in the input image and stores the resulting value in the output image. The vectors in the deformation field must be provided as raw pixel coordinates, i.e. (x0, x1, x2) relative to the upper-left-front corner of the array. Usage example for a 3D image with 2 channels: ```python from multidim_image_augmentation import augmentation_ops with tf.Session(): input = np.random.random([10, 7, 5, 2]).astype(np.float32) deformation = np.ndarray([10, 7, 5, 3], dtype=np.float32) for x0 in range(deformation.shape[0]): for x1 in range(deformation.shape[1]): for x2 in range(deformation.shape[2]): deformation[x0, x1, 0] = x0 deformation[x0, x1, 1] = x1 deformation[x0, x1, 2] = x2 result = augmentation_ops.apply_deformation3D( input, deformation, []) self.assertEqual(result.get_shape(), input.shape) output = result.eval() self.assertAllEqual(output, input) ``` input: The multi-channel input image is a 4-D Tensor of shape `[s0, s1, s2, num_channels]` where `s` stands for `spatial shape`. If `indexed_to_one_hot` conversion is requested the number of channels must be 1. deformation: The deformation vector field is a 4-D Tensor of shape `[s0, s1, s2, num_components]` where `s` stands for `spatial shape`. `num_components` must be 3. The spatial shape must be equal or larger than the output image. If it is larger, the central part of the deformation field is used. This is especially useful when a segmentation network takes a larger source image than the target segmentation map (e.g. a u-net that uses valid convolutions only), but both need to be deformed with the same deformation field. padding_constant: A 1-D Tensor with shape `[num_channels]`. The padding value. Type must match the iput image and size must match the number of output channels. For `zero_padding` or `mirror` extrapolations this tensor can be empty. output: The multi-channel output image is a 4-D tensor of shape `[s0, s1, s2, num_channels]` where `s` stands for `spatial shape`. The spatial shape is usually equal to that of the deformation field. A smaller shape can be specified by the `output_spatial_shape` attribute. In case of `no_conversion` the number of channels will be identical to the input image. For `indexed_to_one_hot` a sufficient number of channels to store the one-hot encoded vectors must be specified by the `output_num_channels` attribute. interpolation: The interpolation style determines how output value are computed. Select from `nearest` neighbor interpolation, `linear` interpolation, or `mixed_nearest_linear` which uses nearest neighbour interpolation in x0-direction, and linear interpolation in (x1, x2)-direction. This is useful if there is a jitter between the slices, and you apply an non-integer scaling in the x0-direction. extrapolation: The extrapolation style determines how the output is filled where the deformation field calls out elements beyond the bounds of the input image. Select from `mirror` for extrapolation by mirroring, `zero_padding` to pad with zeros, or `const_padding` to pad with a constant value: see the `padding_constant` attribute. conversion: On-the-fly conversation. `no_conversion` provides passes input to output channels (e.g. 5 channel input yields a 5 channel output). `indexed_to_one_hot` converts the indexed input segmentation map (1 channel with values like 3 for class 3) to a one-hot-encoded output segmentation map (e.g. 8 channels with values like (0, 0, 0, 1, 0, 0, 0, 0) for class 3). The one-hot values will be collected from the neighbouring pixels. I.e. the result would be identical when first applying the one-hot mapping to the input image and then applying a deformation with linear interpolation to the resulting multi-channel image. output_spatial_shape: spatial shape of output image [x0, x1, x2]. If smaller than the full deformation field, the applied deformation field will be centrally cropped from the full deformation field. Default: use shape of the full deformation field. output_num_channels: Specifies the number of output channels. If no output conversion is in use the output channels will match the number of input channels -- passing a negative (or ommitting) will do this for you. For `indexed_to_one_hot` conversion this must be equal or greater than the largest integral value + 1 in the input value space. See also the `conversion` attribute. Default: `output` number channels matches that of `intput`. )doc"); template <SpatialDims spatial_dims> Status ApplyDeformationShapeFunction(InferenceContext* context) { DeformationAttributes attrs; TF_RETURN_IF_ERROR(GetAttributes<Status>(context, &attrs)); // One additional dimension for the channels. static const int kTensorRank = spatial_dims + 1; ShapeHandle input_shape, deform_shape; TF_RETURN_IF_ERROR(context->WithRank(context->input(kInputIndex), kTensorRank, &input_shape)); TF_RETURN_IF_ERROR(context->WithRank(context->input(kDeformIndex), kTensorRank, &deform_shape)); ShapeHandle output_shape(deform_shape); for (int i = 0; i < attrs.requested_output_spatial_shape.size(); ++i) { if (attrs.requested_output_spatial_shape[i] >= 0) { auto dim = context->MakeDim(attrs.requested_output_spatial_shape[i]); TF_RETURN_IF_ERROR( context->ReplaceDim(output_shape, i, dim, &output_shape)); } } DimensionHandle num_channels = (attrs.output_num_channels >= 0) ? context->MakeDim(attrs.output_num_channels) : context->Dim(input_shape, spatial_dims); // Assert that `padding_size` matches the number of channels if const padding // is being used. if (attrs.extrapolation_style == "const_padding") { ShapeHandle padding_shape; TF_RETURN_IF_ERROR(context->WithRank(context->input(kPaddingConstIndex), 1, &padding_shape)); DimensionHandle padding_size = context->Dim(padding_shape, 0); TF_RETURN_IF_ERROR( context->Merge(padding_size, num_channels, &num_channels)); } TF_RETURN_IF_ERROR(context->ReplaceDim(output_shape, spatial_dims, num_channels, &output_shape)); context->set_output(0, output_shape); return Status::OK(); } } // namespace } // namespace multidim_image_augmentation } // namespace deepmind
47.342679
80
0.737514
[ "shape", "vector", "3d" ]
0b66fd78500cfb4350be8168ce78a33c96ab0166
568
cpp
C++
A_Anton_and_Polyhedrons.cpp
ar1936/CPP
4c76c2bf5308d8d3b6e295482e3ce4284fbeaf13
[ "MIT" ]
1
2021-04-20T13:49:56.000Z
2021-04-20T13:49:56.000Z
A_Anton_and_Polyhedrons.cpp
ar1936/cpp
4c76c2bf5308d8d3b6e295482e3ce4284fbeaf13
[ "MIT" ]
null
null
null
A_Anton_and_Polyhedrons.cpp
ar1936/cpp
4c76c2bf5308d8d3b6e295482e3ce4284fbeaf13
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int n, sum=0; cin>>n; vector <string>v; string s; for(int i=0;i<n;i++) { cin>>s; v.push_back(s); } for(int i=0;i<v.size();i++) { if(v[i]=="Icosahedron") sum+=20; else if(v[i]=="Dodecahedron") sum+=12; else if (v[i]=="Tetrahedron") sum+=4; else if (v[i]=="Octahedron") sum+=8; else if (v[i]=="Cube") sum+=6; } cout<<sum; return 0; }
18.933333
38
0.410211
[ "vector" ]
0b68e47633790e934a53c8df7278e0947d40373e
26,120
cpp
C++
fallen/Editor/Source/MapTab.cpp
jordandavidson/MuckyFoot-UrbanChaos
00f7bda3f061bff9ecbb611d430f8f71bd557d14
[ "MIT" ]
188
2017-05-20T03:26:33.000Z
2022-03-10T16:58:39.000Z
fallen/Editor/Source/MapTab.cpp
jordandavidson/MuckyFoot-UrbanChaos
00f7bda3f061bff9ecbb611d430f8f71bd557d14
[ "MIT" ]
7
2017-05-28T14:28:13.000Z
2022-01-09T01:47:38.000Z
fallen/Editor/Source/MapTab.cpp
inco1/MuckyFoot-UrbanChaos
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
[ "MIT" ]
43
2017-05-20T07:31:32.000Z
2022-03-09T18:39:35.000Z
#include "Editor.hpp" #include "MapTab.hpp" #include "engine.h" //#include "collide.hpp" static counter; //#define ShowWorkWindow(x) {DrawLineC(0+(counter-1)&255,0,WorkWindowWidth-1,WorkWindowHeight-1,0);DrawLineC(0+(counter++)&255,0,WorkWindowWidth-1,WorkWindowHeight-1,255);DrawLineC(0,WorkWindowHeight-1,WorkWindowWidth-1,0,255); ShowWorkWindow(x);} //--------------------------------------------------------------- //debug stuff /* void cross_work_window(void) { DrawLineC(0,0,WorkWindowWidth-1,WorkWindowHeight-1,255); DrawLineC(0,WorkWindowHeight-1,WorkWindowWidth-1,0,255); } */ //--------------------------------------------------------------- #define SELECT_WHOLE_THING 99 #define MAP_MODE_WAIT 0 #define MAP_MODE_DEFINE_MAP 1 #define MAP_MODE_SELECT_AND_PLACE 2 #define MAP_MODE_PLACE_CURRENT_MAP 3 #define CTRL_MAP_X_AXIS_FREE 1 #define CTRL_MAP_Y_AXIS_FREE 2 #define CTRL_MAP_Z_AXIS_FREE 3 #define CTRL_MAP_DEF_MODE 4 #define CTRL_MAP_DEFINE_MAP 5 #define CTRL_MAP_EDIT_TEXT 6 #define CTRL_MAP_SELECT_AND_PLACE 7 #define CTRL_MAP_ZOOM_1 8 #define CTRL_MAP_ZOOM_2 9 #define CTRL_MAP_ZOOM_3 10 ControlDef map_tab_def[] = { { CHECK_BOX, 0, "X Free", 120, 300-10, 0, 10 }, { CHECK_BOX, 0, "Y Free", 120, 313-10, 0, 10 }, { CHECK_BOX, 0, "Z Free", 120, 326-10, 0, 10 }, { CHECK_BOX, 0, "Def Mode", 10, 10, 0, 10 }, { BUTTON, 0, "Define A MapBlock" , 100, 10, 0, 0}, { EDIT_TEXT, 0, "", 150, 28, 70, 0 }, { BUTTON, 0, "Select & Place MapBlock" , 10, 50, 0, 0}, { BUTTON, 0, "Zoom Close", 200, 300-10, 0, 10 }, { BUTTON, 0, "Zoom Medium", 200, 313-10, 0, 10 }, { BUTTON, 0, "Zoom Far", 200, 326-10, 0, 10 }, { 0 } }; MapTab *the_maptab; struct MapInfo map_info[MAX_MAP_INFO]; UWORD next_map_info=1; void redraw_map_tab(void); //--------------------------------------------------------------- // MOVE THIS TO ANOTHER FILE void draw_world_map(void) { SLONG c0; struct MapInfo *p_map; SLONG prim; for(c0=1;c0<next_map_info;c0++) { p_map=&map_info[c0]; if(p_map->Background) if(p_map->X) { set_camera_angledy(p_map->AngleY); prim=map_things[p_map->Background].IndexOther; draw_a_prim_at(prim,p_map->X,p_map->Y,p_map->Z,1); clear_camera_angledy(); } } } MapTab::MapTab(EditorModule *parent) { Parent=parent; InitControlSet(map_tab_def); AxisMode=3; SetControlState(CTRL_MAP_X_AXIS_FREE,CTRL_SELECTED); SetControlState(CTRL_MAP_Y_AXIS_FREE,CTRL_SELECTED); SetControlState(CTRL_MAP_Z_AXIS_FREE,CTRL_SELECTED); SetControlState(CTRL_MAP_DEF_MODE,CTRL_SELECTED); ((CEditText*)GetControlPtr(CTRL_MAP_EDIT_TEXT))->SetFlags(CONTROL_INACTIVE); Axis=X_AXIS|Y_AXIS|Z_AXIS; Mode=0; DefMode=1; // map_info[0].Plane.Depth=320; the_maptab=this; } MapTab::~MapTab() { } void MapTab::Clear(void) { } void delete_map_info(SWORD index) { SLONG c0; for(c0=index;c0<next_map_info-1;c0++) { map_info[c0]=map_info[c0+1]; } next_map_info--; } void MapTab::Recalc(void) { } void MapTab::DrawTabContent(void) { EdRect content_rect; content_rect = ContentRect; content_rect.ShrinkRect(1,1); content_rect.FillRect(CONTENT_COL); SetWorkWindowBounds(ContentLeft()+1,ContentTop()+1,ContentWidth()-1,ContentHeight()-1); DrawControlSet(); ShowWorkWindow(0); } void redraw_map_tab(void) { switch(the_maptab->Mode) { default: the_maptab->DrawTabContent(); the_maptab->Parent->DrawContent(); SetWorkWindowBounds(the_maptab->Parent->GetLeft(), the_maptab->Parent->GetTop(), the_maptab->Parent->GetWidth(), the_maptab->Parent->GetHeight()); break; } } //--------------------------------------------------------------- extern void hilight_map_info(UBYTE view_flag); void MapTab::DrawModuleContent(SLONG x,SLONG y,SLONG w,SLONG h) { SLONG wwx,wwy,www,wwh; EdRect drawrect; RedrawModuleContent=0; wwx=WorkWindowRect.Left; wwy=WorkWindowRect.Top; www=WorkWindowRect.Width; wwh=WorkWindowRect.Height; if(DefMode) { SetWorkWindowBounds(x,y,w-1,h-3); drawrect.SetRect(0,0,w-1,h-3); drawrect.FillRect(CONTENT_COL_BR); drawrect.HiliteRect(HILITE_COL,HILITE_COL); set_camera_front(); draw_editor_map(0); render_view(0); hilight_map_info(0); } else { SetWorkWindowBounds(x,y,w-1,h/2-3); drawrect.SetRect(0,0,w-1,h/2-3); drawrect.FillRect(CONTENT_COL_BR); drawrect.HiliteRect(HILITE_COL,HILITE_COL); set_camera_plan(); // draw_editor_map(0); draw_world_map(); render_view(0); hilight_map_info(1); SetWorkWindowBounds(x,y+h/2+4,w-1,h/2-4); drawrect.SetRect(0,0,w-1,h/2-4); drawrect.FillRect(CONTENT_COL_BR); drawrect.HiliteRect(HILITE_COL,HILITE_COL); set_camera_front(); // draw_editor_map(0); draw_world_map(); render_view(0); // hilight_map_things(MAP_THING_TYPE_MAP); hilight_map_info(1); } SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT } //--------------------------------------------------------------- void MapTab::HandleTab(MFPoint *current_point) { SLONG update = 0; ModeTab::HandleTab(current_point); KeyboardInterface(); } inline SLONG is_point_in_box(SLONG x,SLONG y,SLONG left,SLONG top,SLONG w,SLONG h) { if(x>left&&x<left+w&&y>top&&y<top+h) return(1); else return(0); } //--------------------------------------------------------------- SLONG MapTab::KeyboardInterface(void) { if(Keys[KB_TAB]) { Keys[KB_TAB]=0; AxisMode++; if(AxisMode>3) AxisMode=0; switch(AxisMode) { case 0: SetControlState(CTRL_MAP_X_AXIS_FREE,CTRL_SELECTED); SetControlState(CTRL_MAP_Y_AXIS_FREE,CTRL_DESELECTED); SetControlState(CTRL_MAP_Z_AXIS_FREE,CTRL_DESELECTED); Axis=X_AXIS; break; case 1: SetControlState(CTRL_MAP_X_AXIS_FREE,CTRL_DESELECTED); SetControlState(CTRL_MAP_Y_AXIS_FREE,CTRL_SELECTED); SetControlState(CTRL_MAP_Z_AXIS_FREE,CTRL_DESELECTED); Axis=Y_AXIS; break; case 2: SetControlState(CTRL_MAP_X_AXIS_FREE,CTRL_DESELECTED); SetControlState(CTRL_MAP_Y_AXIS_FREE,CTRL_DESELECTED); SetControlState(CTRL_MAP_Z_AXIS_FREE,CTRL_SELECTED); Axis=Z_AXIS; break; case 3: SetControlState(CTRL_MAP_X_AXIS_FREE,CTRL_SELECTED); SetControlState(CTRL_MAP_Y_AXIS_FREE,CTRL_SELECTED); SetControlState(CTRL_MAP_Z_AXIS_FREE,CTRL_SELECTED); Axis=X_AXIS|Y_AXIS|Z_AXIS; break; } SetWorkWindowBounds(ContentLeft()+1,ContentTop()+1,ContentWidth()-1,ContentHeight()-1); DrawControlSet(); ShowWorkWindow(0); } return(0); } //#define QDIST3(x,y,z) (x>y ? (x>z ? x+(y>>2)+(z>>2) : z+(x>>2)+(y>>2)) : (y>z ? (y+(x>>2)+(z>>2) : z+(x>>2)+(y>>2) )) inline SLONG normalise_xyz(SLONG *x,SLONG *y,SLONG *z) { SLONG dist; dist=(*x)*(*x)+(*y)*(*y)+(*z)*(*z); dist=sqrl(dist); if(dist==0) dist=1; *x=(*x<<8)/dist; *y=(*y<<8)/dist; *z=(*z<<8)/dist; return(dist); } UWORD CreateMapPlane(SLONG x,SLONG y,SLONG z) { z=z; map_info[next_map_info].Left=x; map_info[next_map_info].Right=x+300; map_info[next_map_info].Top=y; map_info[next_map_info].Bottom=y+300; // map_info[next_map_info].Depth=z; next_map_info++; return(next_map_info-1); } /* void draw_3d_line(SLONG x1,SLONG y1,SLONG z1,SLONG x2,SLONG y2,SLONG z2,SLONG col) { struct SVector point[2]; struct SVector res[2]; SLONG sx,sy,sz,c0; ULONG f1,f2; point[0].X=x1; point[0].Y=y1; point[0].Z=z1; f1=rotate_point_gte(&point[0],&res[0]); point[1].X=x2; point[1].Y=y2; point[1].Z=z2; f2=rotate_point_gte(&point[1],&res[1]); f1=f1&f2; if(!(f1 & EF_CLIPFLAGS)) DrawLineC(res[0].X,res[0].Y,res[1].X,res[1].Y,col); } */ void draw_3d_text(SLONG x1,SLONG y1,SLONG z1,CBYTE *str,SLONG col) { struct SVector point; struct SVector res; ULONG f1; point.X=x1; point.Y=y1; point.Z=z1; f1=rotate_point_gte(&point,&res); if(!(f1 & EF_CLIPFLAGS)) QuickTextC(res.X,res.Y,str,col); } void draw_a_map_info(UBYTE view_flag,UWORD index) { struct MapInfo *p_map; SLONG col=WHITE_COL; EdRect rect; CBYTE str[100]; p_map=&map_info[index]; if(view_flag) { if(p_map->Background) if(p_map->X) { set_camera_angledy(p_map->AngleY); calc_prims_screen_box(map_things[p_map->Background].IndexOther,p_map->X,p_map->Y,p_map->Z,&rect); clear_camera_angledy(); rect.OutlineRect(WHITE_COL); sprintf(str," %s back %d index %d \n",p_map->Name,p_map->Background,index); QuickTextC(rect.GetLeft()+3,rect.GetTop()+3,str,col); } } else { draw_3d_line(p_map->Left,p_map->Top,0,p_map->Right,p_map->Top,0,col); draw_3d_line(p_map->Right,p_map->Top,0,p_map->Right,p_map->Bottom,0,col); draw_3d_line(p_map->Left,p_map->Bottom,0,p_map->Right,p_map->Bottom,0,col); draw_3d_line(p_map->Left,p_map->Bottom,0,p_map->Left,p_map->Top,0,col); // sprintf(str," %s back %d x %d y %d z %d \n",p_map->Name,p_map->Background,p_map->X,p_map->Y,p_map->Z); draw_3d_text(p_map->Left+3,p_map->Top+3,0,p_map->Name,col); } } void hilight_map_info(UBYTE view_flag) { SLONG c0; if(next_map_info>1) for(c0=1;c0<next_map_info;c0++) { draw_a_map_info(view_flag,c0); } } static void create_box_from_vect(EdRect *rect,SLONG x1,SLONG y1,SLONG z1,SLONG x2,SLONG y2,SLONG z2) { struct SVector point[2]; struct SVector res[2]; ULONG f1,f2; point[0].X=x1; point[0].Y=y1; point[0].Z=z1; f1=rotate_point_gte(&point[0],&res[0]); point[1].X=x2; point[1].Y=y2; point[1].Z=z2; f2=rotate_point_gte(&point[1],&res[1]); // f1=f1&f2; rect->SetRect(res[0].X,res[0].Y,res[1].X-res[0].X,res[1].Y-res[0].Y); rect->NormalRect(); rect->SetRect(rect->GetLeft()-3,rect->GetTop()-3,rect->GetWidth()+6,rect->GetHeight()+6); rect->OutlineRect(WHITE_COL); } static void create_box_from_point(EdRect *rect,SLONG x1,SLONG y1,SLONG z1) { struct SVector point[1]; struct SVector res[1]; ULONG f1,f2; point[0].X=x1; point[0].Y=y1; point[0].Z=z1; f1=rotate_point_gte(&point[0],&res[0]); rect->SetRect(res[0].X,res[0].Y,10,10); rect->NormalRect(); rect->SetRect(rect->GetLeft()-10,rect->GetTop()-10,rect->GetWidth()+10,rect->GetHeight()+10); rect->OutlineRect(WHITE_COL); } SLONG select_this_map_info(SLONG index,MFPoint *mouse) { struct MapInfo *p_map; EdRect rect; p_map=&map_info[index]; //corners create_box_from_point(&rect,p_map->Left,p_map->Top,0); if(rect.PointInRect(mouse)) return(5); create_box_from_point(&rect,p_map->Right,p_map->Top,0); if(rect.PointInRect(mouse)) return(6); create_box_from_point(&rect,p_map->Right,p_map->Bottom,0); if(rect.PointInRect(mouse)) return(7); create_box_from_point(&rect,p_map->Left,p_map->Bottom,0); if(rect.PointInRect(mouse)) return(8); //edges create_box_from_vect(&rect,p_map->Left,p_map->Top,0,p_map->Right,p_map->Top,0); if(rect.PointInRect(mouse)) return(1); create_box_from_vect(&rect,p_map->Right,p_map->Top,0,p_map->Right,p_map->Bottom,0); if(rect.PointInRect(mouse)) return(2); create_box_from_vect(&rect,p_map->Left,p_map->Bottom,0,p_map->Right,p_map->Bottom,0); if(rect.PointInRect(mouse)) return(3); create_box_from_vect(&rect,p_map->Left,p_map->Top,0,p_map->Left,p_map->Bottom,0); if(rect.PointInRect(mouse)) return(4); //whole thing create_box_from_vect(&rect,p_map->Left,p_map->Top,0,p_map->Right,p_map->Bottom,0); if(rect.PointInRect(mouse)) return(SELECT_WHOLE_THING); return(0); } extern void calc_prims_world_box(UWORD prim,SLONG x,SLONG y,SLONG z, EdRect *rect); void calc_things_world_box(SLONG map_thing,EdRect *rect) { struct MapThing *p_mthing; p_mthing=TO_MTHING(map_thing); switch(p_mthing->Type) { case MAP_THING_TYPE_PRIM: //3ds Prim Mesh calc_prims_world_box(p_mthing->IndexOther,p_mthing->X,p_mthing->Y,p_mthing->Z,rect); break; case MAP_THING_TYPE_LIGHT: break; case MAP_THING_TYPE_SPRITE: case MAP_THING_TYPE_AGENT: break; } } void SetBackgroundForMap(SWORD map) { SWORD index; struct MapThing *p_thing; EdRect rect; EdRect map_rect; struct MapInfo *p_map; p_map=&map_info[map]; map_rect.SetRect(p_map->Left,p_map->Top,p_map->Bottom-p_map->Top,p_map->Right-p_map->Left); index=background_prim; while(index) { p_thing=TO_MTHING(index); calc_things_world_box(index,&rect); if(map_rect.IntersectRect(&rect)) { p_map->Background=index; return; } index=p_thing->IndexNext; } } SLONG select_map_info(MFPoint *mouse,SLONG *ret) { SLONG c0; for(c0=1;c0<next_map_info;c0++) { *ret=select_this_map_info(c0,mouse); if(*ret) return(c0); } return(0); } SLONG select_map_infoxyz(MFPoint *mouse) { SLONG c0; struct MapThing *p_mthing; struct MapInfo *p_map; EdRect rect; for(c0=1;c0<next_map_info;c0++) { p_map=&map_info[c0]; if(p_map->Background) { p_mthing=TO_MTHING(p_map->Background); set_camera_angledy(p_map->AngleY); calc_prims_screen_box(p_mthing->IndexOther,p_map->X,p_map->Y,p_map->Z,&rect); clear_camera_angledy(); rect.OutlineRect(WHITE_COL); if(rect.PointInRect(mouse)) { return(c0); } } } return(0); } void normal_info(struct MapInfo *p_map) { if(p_map->Right<p_map->Left) SWAP(p_map->Left,p_map->Right); if(p_map->Bottom<p_map->Top) SWAP(p_map->Top,p_map->Bottom); } SLONG MapTab::DragAMapDef(UBYTE flags,MFPoint *clicked_point,UWORD copy) { SLONG side; SLONG drag=0; SLONG x,y,w,h; SLONG wwx,wwy,www,wwh; SLONG window=0; SLONG col = 0; SLONG screen_change=0; SLONG last_world_mouse; flags=flags; copy=copy; wwx=WorkWindowRect.Left; wwy=WorkWindowRect.Top; www=WorkWindowRect.Width; wwh=WorkWindowRect.Height; x=Parent->ContentLeft(); y=Parent->ContentTop(); w=Parent->ContentWidth(); h=Parent->ContentHeight(); col++; SetWorkWindowBounds(x,y,w-1,h-3); set_camera_front(); drag=select_map_info(clicked_point,&side); if(drag) { struct MapInfo *p_map; p_map=&map_info[drag]; CurrentMap=drag; while(SHELL_ACTIVE && LeftButton) { last_world_mouse=SetWorldMouse(0); if(last_world_mouse) { switch(side) { case 1: //top map_info[CurrentMap].Top=engine.MousePosY; break; case 3: //bot map_info[CurrentMap].Bottom=engine.MousePosY; break; case 2: //right map_info[CurrentMap].Right=engine.MousePosX; break; case 4: //left map_info[CurrentMap].Left=engine.MousePosX; break; case 5: //topleft map_info[CurrentMap].Top=engine.MousePosY; map_info[CurrentMap].Left=engine.MousePosX; break; case 6: //topright map_info[CurrentMap].Right=engine.MousePosX; map_info[CurrentMap].Top=engine.MousePosY; break; case 7: //botright map_info[CurrentMap].Right=engine.MousePosX; map_info[CurrentMap].Bottom=engine.MousePosY; break; case 8: //botleft map_info[CurrentMap].Left=engine.MousePosX; map_info[CurrentMap].Bottom=engine.MousePosY; break; } } DrawModuleContent(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth(),Parent->ContentHeight()); SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth(),Parent->ContentHeight()); ShowWorkWindow(0); screen_change=1; /* SetWorkWindowBounds(this->ContentLeft()+1,this->ContentTop()+1,this->ContentWidth(),this->ContentHeight()); DrawBox(0,0,this->ContentWidth(),this->ContentHeight(),CONTENT_COL); set_camera(); draw_editor_map(0); render_view(0); ShowWorkWindow(0); */ editor_user_interface(0); KeyboardInterface(); } normal_info(&map_info[CurrentMap]); SetBackgroundForMap(CurrentMap); if(!last_world_mouse) { //delete col delete_map_info(drag); CurrentMap=0; } RequestUpdate(); } SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT return(screen_change); } SLONG MapTab::DragAMapDefXYZ(UBYTE flags,MFPoint *clicked_point,UWORD copy) { SLONG drag=0; SLONG x,y,w,h; SLONG wwx,wwy,www,wwh; SLONG window=0; SLONG col = 0; SLONG screen_change=0; SLONG last_world_mouse; SLONG old_angley,old_mousex; MFPoint local_point; flags=flags; copy=copy; wwx=WorkWindowRect.Left; wwy=WorkWindowRect.Top; www=WorkWindowRect.Width; wwh=WorkWindowRect.Height; x=Parent->ContentLeft(); y=Parent->ContentTop(); w=Parent->ContentWidth(); h=Parent->ContentHeight(); col++; SetWorkWindowBounds(x,y,w-1,(h/2)-3); set_camera_plan(); drag=select_map_infoxyz(clicked_point); if(!drag) { SetWorkWindowBounds(x,y+h/2+4,w-1,h/2-4); set_camera_front(); local_point =*clicked_point; local_point.Y-=h/2; drag=select_map_infoxyz(&local_point); } if(drag) { SLONG dx,dy,dz; struct MapInfo *p_map; p_map=&map_info[drag]; CurrentMap=drag; last_world_mouse=SetWorldMouse(0); dx=map_info[drag].X-engine.MousePosX; dy=map_info[drag].Y-engine.MousePosY; dz=map_info[drag].Z-engine.MousePosZ; engine.MousePosX=map_info[drag].X; engine.MousePosY=map_info[drag].Y; engine.MousePosZ=map_info[drag].Z; old_angley=map_info[drag].AngleY; old_mousex=MouseX; while(SHELL_ACTIVE && (LeftButton||RightButton)) { SLONG nx,ny,nz; last_world_mouse=SetWorldMouse(0); nx=map_info[drag].X; ny=map_info[drag].Y; nz=map_info[drag].Z; if(last_world_mouse) { if(Axis&X_AXIS) nx=engine.MousePosX+dx; if(Axis&Y_AXIS) ny=engine.MousePosY+dy; if(Axis&Z_AXIS) nz=engine.MousePosZ+dz; if(LeftButton) { map_info[CurrentMap].X=nx; map_info[CurrentMap].Y=ny; map_info[CurrentMap].Z=nz; } if(RightButton) { map_info[CurrentMap].AngleY=old_angley+((-MouseX+old_mousex)<<2); if(map_info[CurrentMap].AngleY<0) map_info[CurrentMap].AngleY=(2048+map_info[CurrentMap].AngleY)&2047; } } DrawModuleContent(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth(),Parent->ContentHeight()); SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth(),Parent->ContentHeight()); ShowWorkWindow(0); screen_change=1; editor_user_interface(0); KeyboardInterface(); } if(!last_world_mouse) { CurrentMap=0; } RequestUpdate(); } SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT return(screen_change); } SLONG MapTab::DragEngine(UBYTE flags,MFPoint *clicked_point) { SLONG wwx,wwy,www,wwh; SLONG screen_change=0; SLONG last_world_mouse; flags=flags; clicked_point=clicked_point; wwx=WorkWindowRect.Left; wwy=WorkWindowRect.Top; www=WorkWindowRect.Width; wwh=WorkWindowRect.Height; { SLONG start_x=0,start_y=0,start_z=0,flag=0; SLONG old_x,old_y,old_z; SLONG nx,ny,nz; old_x=nx=engine.X; old_y=ny=engine.Y; old_z=nz=engine.Z; while(SHELL_ACTIVE && MiddleButton) { last_world_mouse=SetWorldMouse(0); if(last_world_mouse) { if(!flag) { flag=1; start_x=engine.MousePosX<<8; start_y=engine.MousePosY<<8; start_z=engine.MousePosZ<<8; } nx=engine.MousePosX<<8; ny=engine.MousePosY<<8; nz=engine.MousePosZ<<8; engine.X = (old_x+(-nx+start_x)); engine.Y = (old_y+(-ny+start_y)); engine.Z = (old_z+(-nz+start_z)); // engine.Z=nz<<8; DrawModuleContent(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth(),Parent->ContentHeight()); SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth(),Parent->ContentHeight()); ShowWorkWindow(0); screen_change=1; engine.X=old_x; engine.Y=old_y; engine.Z=old_z; } } if(flag) { engine.X= (old_x+(-nx+start_x)); engine.Y= (old_y+(-ny+start_y)); engine.Z= (old_z+(-nz+start_z)); } } return(screen_change); } void MapTab::SetMapPos(SLONG x,SLONG y,SLONG z) { map_info[CurrentMap].X=x; map_info[CurrentMap].Y=y; map_info[CurrentMap].Z=z; map_info[CurrentMap].AngleY=0; } SLONG MapTab::HandleModuleContentClick(MFPoint *clicked_point,UBYTE flags,SLONG x,SLONG y,SLONG w,SLONG h) { x=x; y=y; w=w; h=h; switch(flags) { case NO_CLICK: break; case LEFT_CLICK: switch (Mode) { case MAP_MODE_DEFINE_MAP: if(SetWorldMouse(1)) { CurrentMap=CreateMapPlane(engine.MousePosX,engine.MousePosY,engine.MousePosZ); strcpy(map_info[CurrentMap].Name,((CEditText*)GetControlPtr(CTRL_MAP_EDIT_TEXT))->GetEditString()); Mode=0; } return(1); case MAP_MODE_WAIT: if(DefMode) DragAMapDef(flags,clicked_point,0); else DragAMapDefXYZ(flags,clicked_point,0); break; case MAP_MODE_SELECT_AND_PLACE: { SLONG side; CurrentMap=select_map_info(clicked_point,&side); DefMode=0; SetControlState(CTRL_MAP_DEF_MODE,CTRL_DESELECTED); Mode=MAP_MODE_PLACE_CURRENT_MAP; RequestUpdate(); } return(1); case MAP_MODE_PLACE_CURRENT_MAP: if(SetWorldMouse(1)) { SetMapPos(engine.MousePosX,engine.MousePosY,engine.MousePosZ); RequestUpdate(); Mode=0; } break; } break; case RIGHT_CLICK: switch (Mode) { case MAP_MODE_WAIT: if(!DefMode) DragAMapDefXYZ(flags,clicked_point,0); break; } // Right click in content. break; case MIDDLE_CLICK: DragEngine(flags,clicked_point); break; } return(0); } UWORD MapTab::HandleTabClick(UBYTE flags,MFPoint *clicked_point) { UWORD control_id; Control *current_control; MFPoint local_point; // This is a fudge to update the front screen buffer. ShowWorkScreen(0); switch(flags) { case NO_CLICK: break; case LEFT_CLICK: SetWorkWindowBounds(ContentLeft()+1,ContentTop()+1,ContentWidth()-1,ContentHeight()-1); local_point = *clicked_point; GlobalToLocal(&local_point); { current_control = GetControlList(); while(current_control) { if(!(current_control->GetFlags()&CONTROL_INACTIVE) && current_control->PointInControl(&local_point)) { // Handle control. control_id = current_control->TrackControl(&local_point); HandleControl(control_id); // Tidy up display. if(LockWorkScreen()) { DrawTab(); UnlockWorkScreen(); } ShowWorkWindow(0); return control_id; } current_control = current_control->GetNextControl(); } } break; case RIGHT_CLICK: SetWorkWindowBounds(ContentLeft()+1,ContentTop()+1,ContentWidth()-1,ContentHeight()-1); local_point = *clicked_point; GlobalToLocal(&local_point); break; } return 0; } //--------------------------------------------------------------- SLONG MapTab::SetWorldMouse(ULONG flag) { MFPoint mouse_point; MFPoint local_point; SLONG wwx,wwy,www,wwh; wwx=WorkWindowRect.Left; wwy=WorkWindowRect.Top; www=WorkWindowRect.Width; wwh=WorkWindowRect.Height; mouse_point.X = MouseX; mouse_point.Y = MouseY; local_point = mouse_point; Parent->GlobalToLocal(&local_point); if(DefMode) { if(is_point_in_box(local_point.X,local_point.Y,0,0,Parent->ContentWidth()-1,Parent->ContentHeight())) { SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth()-1,Parent->ContentHeight()-4); set_camera_front(); calc_world_pos_front(local_point.X,local_point.Y); if(flag) engine.MousePosZ=engine.Z>>8; SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT return(1); } else return(0); } else { if(is_point_in_box(local_point.X,local_point.Y,0,0,Parent->ContentWidth()-1,Parent->ContentHeight()/2)) { SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth()-1,Parent->ContentHeight()/2-3); set_camera_plan(); calc_world_pos_plan(local_point.X,local_point.Y); if(flag) engine.MousePosY=engine.Y>>8; SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT return(1); } else if(is_point_in_box(local_point.X,local_point.Y,0,Parent->ContentHeight()/2,Parent->ContentWidth()-1,Parent->ContentHeight()/2)) { SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+Parent->ContentHeight()/2+3,Parent->ContentWidth()-1,Parent->ContentHeight()/2-4); set_camera_front(); calc_world_pos_front(local_point.X,local_point.Y-Parent->ContentHeight()/2); if(flag) engine.MousePosZ=engine.Z>>8; SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT return(1); } else return(0); } } void MapTab::HandleControl(UWORD control_id) { switch(control_id&0xff) { case CTRL_MAP_X_AXIS_FREE: ToggleControlSelectedState(CTRL_MAP_X_AXIS_FREE); if(Axis&X_AXIS) Axis&=~X_AXIS; else Axis|=X_AXIS; break; case CTRL_MAP_Y_AXIS_FREE: ToggleControlSelectedState(CTRL_MAP_Y_AXIS_FREE); if(Axis&Y_AXIS) Axis&=~Y_AXIS; else Axis|=Y_AXIS; break; case CTRL_MAP_Z_AXIS_FREE: ToggleControlSelectedState(CTRL_MAP_Z_AXIS_FREE); if(Axis&Z_AXIS) Axis&=~Z_AXIS; else Axis|=Z_AXIS; break; case CTRL_MAP_DEFINE_MAP: DefMode=1; SetControlState(CTRL_MAP_DEF_MODE,CTRL_SELECTED); Mode=MAP_MODE_DEFINE_MAP; ((CEditText*)GetControlPtr(CTRL_MAP_EDIT_TEXT))->SetFlags( ((CEditText*)GetControlPtr(CTRL_MAP_EDIT_TEXT))->GetFlags()&~CONTROL_INACTIVE); ((CEditText*)GetControlPtr(CTRL_MAP_EDIT_TEXT))->SetEditString("No Name"); RequestUpdate(); break; case CTRL_MAP_DEF_MODE: ToggleControlSelectedState(CTRL_MAP_DEF_MODE); DefMode^=1; RequestUpdate(); break; /* case CTRL_ANIM_NAME_EDIT: if(CurrentMap) strcpy(map_info[CurrentMap].Name,((CEditText*)GetControlPtr(CTRL_MAP_EDIT_TEXT))->GetEditString()); RequestUpdate(); break; */ case CTRL_MAP_SELECT_AND_PLACE: Mode=MAP_MODE_SELECT_AND_PLACE; DefMode=1; SetControlState(CTRL_MAP_DEF_MODE,CTRL_SELECTED); RequestUpdate(); break; case CTRL_MAP_ZOOM_1: engine.Scale=896; RequestUpdate(); break; case CTRL_MAP_ZOOM_2: engine.Scale=200; RequestUpdate(); break; case CTRL_MAP_ZOOM_3: engine.Scale=60; RequestUpdate(); break; /* case CTRL_MAP_DELETE: delete_all_lights(); RequestUpdate(); Mode=0; break; */ } } //---------------------------------------------------------------
22.363014
248
0.68124
[ "mesh" ]
0b6b221289cd2ed726fb1cf9dde40c60a7fa825a
14,055
cpp
C++
mp/src/game/server/hl2rp/hl2_roleplayer.cpp
HL2RP/HL2RP
7f8570785a106e66036d014bcb4e6bd669421b97
[ "Unlicense" ]
2
2018-07-15T21:40:41.000Z
2022-01-29T15:18:29.000Z
mp/src/game/server/hl2rp/hl2_roleplayer.cpp
HL2RP/HL2RP
7f8570785a106e66036d014bcb4e6bd669421b97
[ "Unlicense" ]
null
null
null
mp/src/game/server/hl2rp/hl2_roleplayer.cpp
HL2RP/HL2RP
7f8570785a106e66036d014bcb4e6bd669421b97
[ "Unlicense" ]
null
null
null
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com #include <cbase.h> #include "hl2_roleplayer.h" #include "hl2rp_gameinterface.h" #include "trigger_city_zone.h" #include <dal.h> #include <player_dao.h> #include <hl2mp_gameinterface.h> #include <viewport_panel_names.h> #define HL2_ROLEPLAYER_MOTDGUIDE_MAX_SEND_DELAY 2.0f #define HL2_ROLEPLAYER_HUD_THINK_PERIOD 1.0f #define HL2_ROLEPLAYER_HUD_EXTRA_HOLD_TIME 0.1f // Simple way to fix flickering due to self-networking inaccuracy #define HL2_ROLEPLAYER_AUTOMATIC_CRIME_GAIN 3 // Periodic crime gain when within an automatic crime zone and applicable #ifdef HL2RP_FULL IMPLEMENT_HL2RP_NETWORKCLASS(HL2Roleplayer) SendPropInt(SENDINFO(m_iMaxHealth)), SendPropBool(SENDINFO(mIsInStickyWalkMode)), SendPropInt(SENDINFO(mSeconds)), SendPropInt(SENDINFO(mCrime)) END_NETWORK_TABLE() #endif // HL2RP_FULL LINK_ENTITY_TO_CLASS(info_player_citizen, CServerOnlyEntity) LINK_ENTITY_TO_CLASS(info_player_police, CServerOnlyEntity) const char* gPlayerDatabasePropNames[EPlayerDatabasePropType::_Count] = { "name", "seconds", "crime", "accessFlags", "health", "armor", "miscFlags", HL2RP_LEARNED_HUD_HINTS_FIELD_NAME }; CRestorablePlayerEquipment::CRestorablePlayerEquipment(CHL2Roleplayer* pPlayer) : mHealth(pPlayer->m_iHealth), mArmor(pPlayer->ArmorValue()) { pPlayer->mDatabaseIOFlags.SetBit(EPlayerDatabaseIOFlag::IsEquipmentSaveDisabled); } void CRestorablePlayerEquipment::Restore(CHL2Roleplayer* pPlayer) { pPlayer->SetHealth(mHealth > 0 ? mHealth : pPlayer->GetHealth()); pPlayer->SetArmorValue(mArmor); FOR_EACH_MAP_FAST(mAmmoCountByIndex, i) { pPlayer->GiveAmmo(mAmmoCountByIndex[i], mAmmoCountByIndex.Key(i), false); } FOR_EACH_DICT_FAST(mClipsByWeaponClassname, i) { CBaseCombatWeapon* pWeapon = pPlayer->Weapon_OwnsThisType(mClipsByWeaponClassname.GetElementName(i)); if (pWeapon == NULL) { CBaseEntity* pEntity = CBaseEntity::CreateNoSpawn(mClipsByWeaponClassname.GetElementName(i), pPlayer->GetLocalOrigin(), vec3_angle); if (pEntity != NULL) { // If created entity is not a valid weapon, remove it if (!pEntity->IsBaseCombatWeapon()) { UTIL_RemoveImmediate(pEntity); continue; } // Proceed to give the weapon. Set loaded clips ignoring maximum allowed, for convenience. pWeapon = pEntity->MyCombatWeaponPointer(); DispatchSpawn(pWeapon); if (pWeapon->UsesClipsForAmmo1()) { pWeapon->m_iClip1 = Max(0, mClipsByWeaponClassname[i].first); } else { pWeapon->SetPrimaryAmmoCount(0); } if (pWeapon->UsesClipsForAmmo2()) { pWeapon->m_iClip2 = Max(0, mClipsByWeaponClassname[i].second); } else { pWeapon->SetSecondaryAmmoCount(0); } // Equip directly instead of via Touch(), since it prevents picking weapon when player is out of world pPlayer->Weapon_Equip(pWeapon); } } else { // Add up loaded clips ignoring maximum allowed, for convenience if (pWeapon->UsesClipsForAmmo1()) { pWeapon->m_iClip1 += Max(0, mClipsByWeaponClassname[i].first); } if (pWeapon->UsesClipsForAmmo2()) { pWeapon->m_iClip2 += Max(0, mClipsByWeaponClassname[i].second); } } } pPlayer->mDatabaseIOFlags.ClearBit(EPlayerDatabaseIOFlag::IsEquipmentSaveDisabled); } CHL2Roleplayer::CHL2Roleplayer() { } void CHL2Roleplayer::InitialSpawn() { BaseClass::InitialSpawn(); if (GetNetworkIDString()[0] != '\0') { LoadFromDatabase(); } } void CHL2Roleplayer::OnDisconnect() { mDatabaseIOFlags.ClearBit(EPlayerDatabaseIOFlag::IsLoaded); ClearActiveWeapon(); // Reset the counters that could double when retrying to self listenserver (player instance may be reused) SetArmorValue(0); mSeconds = mCrime = 0; } void CHL2Roleplayer::Spawn() { BaseClass::Spawn(); HUDThink(); if (GetTeamNumber() != TEAM_COMBINE && mRestorableCitizenEquipment.IsValid()) { mRestorableCitizenEquipment->Restore(this); mRestorableCitizenEquipment.Delete(); } } CBaseEntity* CHL2Roleplayer::EntSelectSpawnPoint() { const char* pClassname = (GetTeamNumber() == TEAM_COMBINE) ? "info_player_police" : "info_player_citizen"; CUtlVector<CBaseEntity*> spawnPoints; for (CBaseEntity* pSpawnPoint = NULL; (pSpawnPoint = gEntList.FindEntityByClassname(pSpawnPoint, pClassname)) != NULL;) { spawnPoints.AddToTail(pSpawnPoint); } if (!spawnPoints.IsEmpty()) { InitSLAMProtectTime(); return spawnPoints.Random(); } return BaseClass::EntSelectSpawnPoint(); } void CHL2Roleplayer::NetworkVarChanged_m_iHealth() { if (!mDatabaseIOFlags.IsBitSet(EPlayerDatabaseIOFlag::IsEquipmentSaveDisabled)) { OnDatabasePropChanged(GetHealth(), EPlayerDatabasePropType::Health); } } void CHL2Roleplayer::NetworkVarChanged_m_ArmorValue() { if (!mDatabaseIOFlags.IsBitSet(EPlayerDatabaseIOFlag::IsEquipmentSaveDisabled)) { OnDatabasePropChanged(ArmorValue(), EPlayerDatabasePropType::Armor); } } void CHL2Roleplayer::NetworkArrayChanged_m_hMyWeapons(int index, const CBaseCombatWeaponHandle& oldWeapon) { (oldWeapon == NULL) ? OnWeaponChanged(m_hMyWeapons[index], true) : OnWeaponChanged(oldWeapon, false); } void CHL2Roleplayer::OnWeaponChanged(CBaseCombatWeapon* pWeapon, bool isOwned) { if (!mDatabaseIOFlags.IsBitSet(EPlayerDatabaseIOFlag::IsLoaded)) { mDatabaseIOFlags.SetBit(EPlayerDatabaseIOFlag::UpdateWeaponsOnLoaded); } else if (!mDatabaseIOFlags.IsBitSet(EPlayerDatabaseIOFlag::IsEquipmentSaveDisabled)) { DAL().AddDAO(new CPlayersWeaponsSaveDAO(this, pWeapon, isOwned)); } } void CHL2Roleplayer::NetworkArrayChanged_m_iAmmo(int index, const int&) { if (!mDatabaseIOFlags.IsBitSet(EPlayerDatabaseIOFlag::IsLoaded)) { mDatabaseIOFlags.SetBit(EPlayerDatabaseIOFlag::UpdateAmmunitionOnLoaded); } else if (!mDatabaseIOFlags.IsBitSet(EPlayerDatabaseIOFlag::IsEquipmentSaveDisabled)) { DAL().AddDAO(new CPlayersAmmunitionSaveDAO(this, index, m_iAmmo[index])); } } void CHL2Roleplayer::PostThink() { BaseClass::PostThink(); if (mDatabaseIOFlags.IsBitSet(EPlayerDatabaseIOFlag::IsLoaded)) { if (!mMiscFlags.IsBitSet(EDatabaseMiscFlag::IsMOTDGuideSent) && gpGlobals->curtime >= mMOTDGuideSendReadyTime) { const char* pLanguage = engine->GetClientConVarValue(entindex(), "cl_language"); const char* pLangMOTDGuideFileName = UTIL_VarArgs("%s_%s", HL2RP_MOTD_GUIDE_BASE_NAME, pLanguage); if (g_pStringTableInfoPanel->FindStringIndex(pLangMOTDGuideFileName) == INVALID_STRING_INDEX) { pLangMOTDGuideFileName = UTIL_VarArgs("%s_%s", HL2RP_MOTD_GUIDE_BASE_NAME, "english"); } KeyValuesAD data("data"); data->SetString("title", HL2RP_TITLE); data->SetString("type", "1"); data->SetString("msg", pLangMOTDGuideFileName); ShowViewPortPanel(PANEL_INFO, true, data); mMiscFlags.SetBit(EDatabaseMiscFlag::IsMOTDGuideSent); } } if (IsAlive()) { localizebuf_t message; if (ComputeAimingEntityAndHUD(message)) { #ifdef HL2RP_LEGACY SendHUDMessage(EHUDType::AimingEntity, message, HL2RP_CENTER_HUD_SPECIAL_POS, HL2RP_AIMING_HUD_DEFAULT_Y_POS, mhAimingEntity->IsPlayer() ? HL2RP_AIMING_HUD_DEFAULT_PLAYER_COLOR : HL2RP_AIMING_HUD_DEFAULT_GENERAL_COLOR); #endif // HL2RP_LEGACY } // Send City Zone HUD, except for polices inside an automatic crime zone (unneeded) if (mhCityZone != NULL && (GetTeamNumber() != TEAM_COMBINE || mhCityZone->mType != CCityZone::EType::AutoCrime) && AcquireHUDTime(EHUDType::Alert)) { CLocalizeFmtStr message; gHL2RPLocalizer.Localize(this, message, false, "#HL2RP_CityZone_Notice", STRING(mhCityZone->GetEntityName())); message.AppendFormat(" (%s)", gHL2RPLocalizer.Localize(this, CCityZone::sTypeTokens[mhCityZone->mType])); SendHUDMessage(EHUDType::Alert, message, HL2RP_CENTER_HUD_SPECIAL_POS, HL2RP_ALERT_HUD_DEFAULT_Y_POS, HL2RP_ALERT_HUD_DEFAULT_COLOR); } } else { mhCityZone = NULL; } } #ifdef HL2RP_LEGACY void CHL2Roleplayer::LocalPrint(int type, const char* pText) { Print(type, pText); } void CHL2Roleplayer::LocalDisplayHUDHint(EPlayerHUDHintType type, const char* pToken) { SendHUDHint(type, pToken); } void CHL2Roleplayer::SendMainHUD() { localizebuf_t message; ComputeMainHUD(message); SendHUDMessage(EHUDType::Main, message, HL2RP_MAIN_HUD_DEFAULT_X_POS, HL2RP_MAIN_HUD_DEFAULT_Y_POS, mCrime > 0 ? HL2RP_MAIN_HUD_DEFAULT_CRIMINAL_TEXT_COLOR : HL2RP_MAIN_HUD_DEFAULT_NORMAL_TEXT_COLOR); } #endif // HL2RP_LEGACY void CHL2Roleplayer::Print(int type, const char* pText) { ClientPrint(this, type, pText); } void CHL2Roleplayer::HUDThink() { SendMainHUD(); SetContextThink(&ThisClass::HUDThink, gpGlobals->curtime + HL2_ROLEPLAYER_HUD_THINK_PERIOD, "HUDThink"); if (IsAlive()) { ++mSeconds; if (GetTeamNumber() != TEAM_COMBINE && mhCityZone != NULL && mhCityZone->mType == CCityZone::EType::AutoCrime) { mCrime += HL2_ROLEPLAYER_AUTOMATIC_CRIME_GAIN; } else { --mCrime; } } } void CHL2Roleplayer::SendHUDHint(EPlayerHUDHintType type, const char* pToken) { if (!mLearnedHUDHints.IsBitSet(type)) { #ifdef HL2RP_FULL CSingleUserRecipientFilter filter(this); filter.MakeReliable(); UserMessageBegin(filter, HL2RP_KEY_HINT_USER_MESSAGE); WRITE_LONG(type); WRITE_STRING(pToken); MessageEnd(); #else Print(HUD_PRINTCENTER, gHL2RPLocalizer.Localize(this, pToken)); #endif // HL2RP_FULL mLearnedHUDHints.SetBit(type); } } bool CHL2Roleplayer::AcquireHUDTime(EHUDType type, bool force) { if (force || mHUDExpireTimers[type].Expired()) { mHUDExpireTimers[type].Set(HL2_ROLEPLAYER_HUD_THINK_PERIOD); return true; } return false; } void CHL2Roleplayer::SendHUDMessage(EHUDType type, const char* pMessage, float xPos, float yPos, const Color& color) { hudtextparms_t params{}; params.channel = type; params.x = (xPos < 0.0f) ? HL2RP_CENTER_HUD_SPECIAL_POS : xPos / 640.0f; params.y = (yPos < 0.0f) ? HL2RP_CENTER_HUD_SPECIAL_POS : yPos / 480.0f; params.r1 = color.r(); params.g1 = color.g(); params.b1 = color.b(); params.a1 = color.a(); params.holdTime = HL2_ROLEPLAYER_HUD_THINK_PERIOD + HL2_ROLEPLAYER_HUD_EXTRA_HOLD_TIME; UTIL_HudMessage(this, params, pMessage); } bool CHL2Roleplayer::PassesDamageFilter(const CTakeDamageInfo& info) { return (mDatabaseIOFlags.IsBitSet(EPlayerDatabaseIOFlag::IsLoaded) && BaseClass::PassesDamageFilter(info)); } void CHL2Roleplayer::Weapon_Drop(CBaseCombatWeapon* pWeapon, const Vector* pDirection, const Vector* pVelocity) { BaseClass::Weapon_Drop(pWeapon, pDirection, pVelocity); if (pWeapon != NULL) { void DropVariableAmmo(CBasePlayer*, CBaseCombatWeapon*); DropVariableAmmo(this, pWeapon); } } void CHL2Roleplayer::Weapon_Equip(CBaseCombatWeapon* pWeapon) { // Equip, but revert any extra clips or ammo given by BaseClass (conservation principle) int clip1 = pWeapon->Clip1(), clip2 = pWeapon->Clip2(); int primaryAmmoCount = GetAmmoCount(pWeapon->GetPrimaryAmmoType()); int secondaryAmmoCount = GetAmmoCount(pWeapon->GetSecondaryAmmoType()); BaseClass::Weapon_Equip(pWeapon); pWeapon->m_iClip1 = clip1; pWeapon->m_iClip2 = clip2; if (pWeapon->UsesPrimaryAmmo()) { SetAmmoCount(primaryAmmoCount, pWeapon->GetPrimaryAmmoType()); TransferPrimaryAmmoFromWeapon(pWeapon); } if (pWeapon->UsesSecondaryAmmo()) { SetAmmoCount(secondaryAmmoCount, pWeapon->GetSecondaryAmmoType()); TransferSecondaryAmmoFromWeapon(pWeapon); } } bool CHL2Roleplayer::Weapon_EquipAmmoOnly(CBaseCombatWeapon* pOtherWeapon) { CBaseCombatWeapon* pMyWeapon = Weapon_OwnsThisType(pOtherWeapon->GetClassname()); if (pMyWeapon != NULL) { // Transfer both reload ammo and clips to the reserve ammo int givenAmmoCount = 0; if (pMyWeapon->UsesPrimaryAmmo()) { givenAmmoCount += TransferPrimaryAmmoFromWeapon(pOtherWeapon); } if (pMyWeapon->UsesSecondaryAmmo()) { givenAmmoCount += TransferSecondaryAmmoFromWeapon(pOtherWeapon); } if (pOtherWeapon->Clip1() > 0) { int takenClip = GiveAmmo(pOtherWeapon->Clip1(), pOtherWeapon->GetPrimaryAmmoType(), false); pOtherWeapon->m_iClip1 -= takenClip; givenAmmoCount += takenClip; } if (pOtherWeapon->Clip2() > 0) { int takenClip = GiveAmmo(pOtherWeapon->Clip2(), pOtherWeapon->GetSecondaryAmmoType(), false); pOtherWeapon->m_iClip2 -= takenClip; givenAmmoCount += takenClip; } return (givenAmmoCount > 0); } return false; } void CHL2Roleplayer::Event_Killed(const CTakeDamageInfo& info) { BaseClass::Event_Killed(info); RemoveAllAmmo(); // Default code doesn't call this when player doesn't have weapons SetArmorValue(0); } void CHL2Roleplayer::OnDatabasePropChanged(const SFieldDTO& field, EPlayerDatabasePropType type) { if (type == EPlayerDatabasePropType::Crime) { SendMainHUD(); } if (mDatabaseIOFlags.IsBitSet(EPlayerDatabaseIOFlag::IsLoaded)) { return DAL().AddDAO(new CPlayersMainDataSaveDAO(this, field, type)); } // Set to update main data once player loads mDatabaseIOFlags.SetBit(EPlayerDatabaseIOFlag::UpdateMainDataOnLoaded); } void CHL2Roleplayer::LoadFromDatabase() { if (!IsFakeClient()) { DAL().AddDAO(new CPlayerLoadDAO(this)); } } int CHL2Roleplayer::TransferPrimaryAmmoFromWeapon(CBaseCombatWeapon* pWeapon) { int givenCount = GiveAmmo(pWeapon->GetPrimaryAmmoCount(), pWeapon->GetPrimaryAmmoType(), false); pWeapon->SetPrimaryAmmoCount(pWeapon->GetPrimaryAmmoCount() - givenCount); return givenCount; } int CHL2Roleplayer::TransferSecondaryAmmoFromWeapon(CBaseCombatWeapon* pWeapon) { int givenCount = GiveAmmo(pWeapon->GetSecondaryAmmoCount(), pWeapon->GetSecondaryAmmoType(), false); pWeapon->SetSecondaryAmmoCount(pWeapon->GetSecondaryAmmoCount() - givenCount); return givenCount; } CON_COMMAND_F(closed_htmlpage, "Handles player closing main MOTD window", FCVAR_HIDDEN) { CHL2Roleplayer* pPlayer = ToHL2Roleplayer(UTIL_GetCommandClient()); if (pPlayer != NULL) { pPlayer->mMOTDGuideSendReadyTime = gpGlobals->curtime + HL2_ROLEPLAYER_MOTDGUIDE_MAX_SEND_DELAY; } }
28.11
119
0.759872
[ "vector" ]
0b762d45866d7025e7777e40d6f58608f2abe039
24,863
cc
C++
ns-3-dev/src/internet/model/ipv6-static-routing.cc
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
11
2015-11-24T11:07:28.000Z
2021-12-23T04:10:29.000Z
ns-3-dev/src/internet/model/ipv6-static-routing.cc
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
null
null
null
ns-3-dev/src/internet/model/ipv6-static-routing.cc
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
6
2016-03-01T06:32:21.000Z
2022-03-24T19:31:41.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #include "ns3/log.h" #include "ns3/packet.h" #include "ns3/ipv6-route.h" #include "ns3/net-device.h" #include "ipv6-static-routing.h" #include "ipv6-routing-table-entry.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("Ipv6StaticRouting"); NS_OBJECT_ENSURE_REGISTERED (Ipv6StaticRouting); TypeId Ipv6StaticRouting::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6StaticRouting") .SetParent<Ipv6RoutingProtocol> () .AddConstructor<Ipv6StaticRouting> () ; return tid; } Ipv6StaticRouting::Ipv6StaticRouting () : m_ipv6 (0) { NS_LOG_FUNCTION_NOARGS (); } Ipv6StaticRouting::~Ipv6StaticRouting () { NS_LOG_FUNCTION_NOARGS (); } void Ipv6StaticRouting::SetIpv6 (Ptr<Ipv6> ipv6) { NS_LOG_FUNCTION (this << ipv6); NS_ASSERT (m_ipv6 == 0 && ipv6 != 0); uint32_t i = 0; m_ipv6 = ipv6; for (i = 0; i < m_ipv6->GetNInterfaces (); i++) { if (m_ipv6->IsUp (i)) { NotifyInterfaceUp (i); } else { NotifyInterfaceDown (i); } } } void Ipv6StaticRouting::AddHostRouteTo (Ipv6Address dst, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse, uint32_t metric) { NS_LOG_FUNCTION (this << dst << nextHop << interface << prefixToUse << metric); AddNetworkRouteTo (dst, Ipv6Prefix::GetOnes (), nextHop, interface, prefixToUse, metric); } void Ipv6StaticRouting::AddHostRouteTo (Ipv6Address dst, uint32_t interface, uint32_t metric) { NS_LOG_FUNCTION (this << dst << interface << metric); AddNetworkRouteTo (dst, Ipv6Prefix::GetOnes (), interface, metric); } void Ipv6StaticRouting::AddNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, Ipv6Address nextHop, uint32_t interface, uint32_t metric) { NS_LOG_FUNCTION (this << network << networkPrefix << nextHop << interface << metric); Ipv6RoutingTableEntry* route = new Ipv6RoutingTableEntry (); *route = Ipv6RoutingTableEntry::CreateNetworkRouteTo (network, networkPrefix, nextHop, interface); m_networkRoutes.push_back (std::make_pair (route, metric)); } void Ipv6StaticRouting::AddNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse, uint32_t metric) { NS_LOG_FUNCTION (this << network << networkPrefix << nextHop << interface << prefixToUse << metric); Ipv6RoutingTableEntry* route = new Ipv6RoutingTableEntry (); *route = Ipv6RoutingTableEntry::CreateNetworkRouteTo (network, networkPrefix, nextHop, interface, prefixToUse); m_networkRoutes.push_back (std::make_pair (route, metric)); } void Ipv6StaticRouting::AddNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, uint32_t interface, uint32_t metric) { NS_LOG_FUNCTION (this << network << networkPrefix << interface); Ipv6RoutingTableEntry* route = new Ipv6RoutingTableEntry (); *route = Ipv6RoutingTableEntry::CreateNetworkRouteTo (network, networkPrefix, interface); m_networkRoutes.push_back (std::make_pair (route, metric)); } void Ipv6StaticRouting::SetDefaultRoute (Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse, uint32_t metric) { NS_LOG_FUNCTION (this << nextHop << interface << prefixToUse); AddNetworkRouteTo (Ipv6Address ("::"), Ipv6Prefix::GetZero (), nextHop, interface, prefixToUse, metric); } void Ipv6StaticRouting::AddMulticastRoute (Ipv6Address origin, Ipv6Address group, uint32_t inputInterface, std::vector<uint32_t> outputInterfaces) { NS_LOG_FUNCTION (this << origin << group << inputInterface); Ipv6MulticastRoutingTableEntry* route = new Ipv6MulticastRoutingTableEntry (); *route = Ipv6MulticastRoutingTableEntry::CreateMulticastRoute (origin, group, inputInterface, outputInterfaces); m_multicastRoutes.push_back (route); } void Ipv6StaticRouting::SetDefaultMulticastRoute (uint32_t outputInterface) { NS_LOG_FUNCTION (this << outputInterface); Ipv6RoutingTableEntry *route = new Ipv6RoutingTableEntry (); Ipv6Address network = Ipv6Address ("ff00::"); /* RFC 3513 */ Ipv6Prefix networkMask = Ipv6Prefix (8); *route = Ipv6RoutingTableEntry::CreateNetworkRouteTo (network, networkMask, outputInterface); m_networkRoutes.push_back (std::make_pair (route, 0)); } uint32_t Ipv6StaticRouting::GetNMulticastRoutes () const { NS_LOG_FUNCTION_NOARGS (); return m_multicastRoutes.size (); } Ipv6MulticastRoutingTableEntry Ipv6StaticRouting::GetMulticastRoute (uint32_t index) const { NS_LOG_FUNCTION (this << index); NS_ASSERT_MSG (index < m_multicastRoutes.size (), "Ipv6StaticRouting::GetMulticastRoute () : Index out of range"); if (index < m_multicastRoutes.size ()) { uint32_t tmp = 0; for (MulticastRoutesCI i = m_multicastRoutes.begin (); i != m_multicastRoutes.end (); i++) { if (tmp == index) { return *i; } tmp++; } } return 0; } bool Ipv6StaticRouting::RemoveMulticastRoute (Ipv6Address origin, Ipv6Address group, uint32_t inputInterface) { NS_LOG_FUNCTION (this << origin << group << inputInterface); for (MulticastRoutesI i = m_multicastRoutes.begin (); i != m_multicastRoutes.end (); i++) { Ipv6MulticastRoutingTableEntry *route = *i; if (origin == route->GetOrigin () && group == route->GetGroup () && inputInterface == route->GetInputInterface ()) { delete *i; m_multicastRoutes.erase (i); return true; } } return false; } void Ipv6StaticRouting::RemoveMulticastRoute (uint32_t index) { NS_LOG_FUNCTION (this << index); uint32_t tmp = 0; for (MulticastRoutesI i = m_multicastRoutes.begin (); i != m_multicastRoutes.end (); i++) { if (tmp == index) { delete *i; m_multicastRoutes.erase (i); return; } tmp++; } } bool Ipv6StaticRouting::HasNetworkDest (Ipv6Address network, uint32_t interfaceIndex) { NS_LOG_FUNCTION (this << network << interfaceIndex); /* in the network table */ for (NetworkRoutesI j = m_networkRoutes.begin (); j != m_networkRoutes.end (); j++) { Ipv6RoutingTableEntry* rtentry = j->first; Ipv6Prefix prefix = rtentry->GetDestNetworkPrefix (); Ipv6Address entry = rtentry->GetDestNetwork (); if (prefix.IsMatch (network, entry) && rtentry->GetInterface () == interfaceIndex) { return true; } } /* beuh!!! not route at all */ return false; } Ptr<Ipv6Route> Ipv6StaticRouting::LookupStatic (Ipv6Address dst, Ptr<NetDevice> interface) { NS_LOG_FUNCTION (this << dst << interface); Ptr<Ipv6Route> rtentry = 0; uint16_t longestMask = 0; uint32_t shortestMetric = 0xffffffff; /* when sending on link-local multicast, there have to be interface specified */ if (dst == Ipv6Address::GetAllNodesMulticast () || dst.IsSolicitedMulticast () || dst == Ipv6Address::GetAllRoutersMulticast () || dst == Ipv6Address::GetAllHostsMulticast ()) { NS_ASSERT_MSG (interface, "Try to send on link-local multicast address, and no interface index is given!"); rtentry = Create<Ipv6Route> (); rtentry->SetSource (SourceAddressSelection (m_ipv6->GetInterfaceForDevice (interface), dst)); rtentry->SetDestination (dst); rtentry->SetGateway (Ipv6Address::GetZero ()); rtentry->SetOutputDevice (interface); return rtentry; } for (NetworkRoutesI it = m_networkRoutes.begin (); it != m_networkRoutes.end (); it++) { Ipv6RoutingTableEntry* j = it->first; uint32_t metric = it->second; Ipv6Prefix mask = j->GetDestNetworkPrefix (); uint16_t maskLen = mask.GetPrefixLength (); Ipv6Address entry = j->GetDestNetwork (); NS_LOG_LOGIC ("Searching for route to " << dst << ", mask length " << maskLen << ", metric " << metric); if (mask.IsMatch (dst, entry)) { NS_LOG_LOGIC ("Found global network route " << j << ", mask length " << maskLen << ", metric " << metric); /* if interface is given, check the route will output on this interface */ if (!interface || interface == m_ipv6->GetNetDevice (j->GetInterface ())) { if (maskLen < longestMask) { NS_LOG_LOGIC ("Previous match longer, skipping"); continue; } if (maskLen > longestMask) { shortestMetric = 0xffffffff; } longestMask = maskLen; if (metric > shortestMetric) { NS_LOG_LOGIC ("Equal mask length, but previous metric shorter, skipping"); continue; } shortestMetric = metric; Ipv6RoutingTableEntry* route = j; uint32_t interfaceIdx = route->GetInterface (); rtentry = Create<Ipv6Route> (); if (route->GetGateway ().IsAny ()) { rtentry->SetSource (SourceAddressSelection (interfaceIdx, route->GetDest ())); } else if (route->GetDest ().IsAny ()) /* default route */ { rtentry->SetSource (SourceAddressSelection (interfaceIdx, route->GetPrefixToUse ().IsAny () ? route->GetGateway () : route->GetPrefixToUse ())); } else { rtentry->SetSource (SourceAddressSelection (interfaceIdx, route->GetGateway ())); } rtentry->SetDestination (route->GetDest ()); rtentry->SetGateway (route->GetGateway ()); rtentry->SetOutputDevice (m_ipv6->GetNetDevice (interfaceIdx)); } } } if(rtentry) { NS_LOG_LOGIC ("Matching route via " << rtentry->GetDestination () << " (throught " << rtentry->GetGateway () << ") at the end"); } return rtentry; } void Ipv6StaticRouting::DoDispose () { NS_LOG_FUNCTION_NOARGS (); for (NetworkRoutesI j = m_networkRoutes.begin (); j != m_networkRoutes.end (); j = m_networkRoutes.erase (j)) { delete j->first; } m_networkRoutes.clear (); for (MulticastRoutesI i = m_multicastRoutes.begin (); i != m_multicastRoutes.end (); i = m_multicastRoutes.erase (i)) { delete (*i); } m_multicastRoutes.clear (); m_ipv6 = 0; Ipv6RoutingProtocol::DoDispose (); } Ptr<Ipv6MulticastRoute> Ipv6StaticRouting::LookupStatic (Ipv6Address origin, Ipv6Address group, uint32_t interface) { NS_LOG_FUNCTION (this << origin << group << interface); Ptr<Ipv6MulticastRoute> mrtentry = 0; for (MulticastRoutesI i = m_multicastRoutes.begin (); i != m_multicastRoutes.end (); i++) { Ipv6MulticastRoutingTableEntry* route = *i; /* We've been passed an origin address, a multicast group address and an interface index. We have to decide if the current route in the list is a match. The first case is the restrictive case where the origin, group and index matches. This picks up exact routes during forwarded and exact routes from the local node (in which case the ifIndex is a wildcard). */ if (origin == route->GetOrigin () && group == route->GetGroup ()) { /* skipping SSM case */ NS_LOG_LOGIC ("Find source specific multicast route" << *i); } if (group == route->GetGroup ()) { if (interface == Ipv6::IF_ANY || interface == route->GetInputInterface ()) { NS_LOG_LOGIC ("Found multicast route" << *i); mrtentry = Create<Ipv6MulticastRoute> (); mrtentry->SetGroup (route->GetGroup ()); mrtentry->SetOrigin (route->GetOrigin ()); mrtentry->SetParent (route->GetInputInterface ()); for (uint32_t j = 0; j < route->GetNOutputInterfaces (); j++) { if (route->GetOutputInterface (j)) { NS_LOG_LOGIC ("Setting output interface index " << route->GetOutputInterface (j)); mrtentry->SetOutputTtl (route->GetOutputInterface (j), Ipv6MulticastRoute::MAX_TTL - 1); } } return mrtentry; } } } return mrtentry; } uint32_t Ipv6StaticRouting::GetNRoutes () { return m_networkRoutes.size (); } Ipv6RoutingTableEntry Ipv6StaticRouting::GetDefaultRoute () { NS_LOG_FUNCTION_NOARGS (); Ipv6Address dst ("::"); uint32_t shortestMetric = 0xffffffff; Ipv6RoutingTableEntry* result = 0; for (NetworkRoutesI it = m_networkRoutes.begin (); it != m_networkRoutes.end (); it++) { Ipv6RoutingTableEntry* j = it->first; uint32_t metric = it->second; Ipv6Prefix mask = j->GetDestNetworkPrefix (); uint16_t maskLen = mask.GetPrefixLength (); Ipv6Address entry = j->GetDestNetwork (); if (maskLen) { continue; } if (metric > shortestMetric) { continue; } shortestMetric = metric; result = j; } if (result) { return result; } else { return Ipv6RoutingTableEntry (); } } Ipv6RoutingTableEntry Ipv6StaticRouting::GetRoute (uint32_t index) { NS_LOG_FUNCTION (this << index); uint32_t tmp = 0; for (NetworkRoutesI it = m_networkRoutes.begin (); it != m_networkRoutes.end (); it++) { if (tmp == index) { return it->first; } tmp++; } NS_ASSERT (false); // quiet compiler. return 0; } uint32_t Ipv6StaticRouting::GetMetric (uint32_t index) { NS_LOG_FUNCTION_NOARGS (); uint32_t tmp = 0; for (NetworkRoutesI it = m_networkRoutes.begin (); it != m_networkRoutes.end (); it++) { if (tmp == index) { return it->second; } tmp++; } NS_ASSERT (false); // quiet compiler. return 0; } void Ipv6StaticRouting::RemoveRoute (uint32_t index) { NS_LOG_FUNCTION (this << index); uint32_t tmp = 0; for (NetworkRoutesI it = m_networkRoutes.begin (); it != m_networkRoutes.end (); it++) { if (tmp == index) { delete it->first; m_networkRoutes.erase (it); return; } tmp++; } NS_ASSERT (false); } void Ipv6StaticRouting::RemoveRoute (Ipv6Address network, Ipv6Prefix prefix, uint32_t ifIndex, Ipv6Address prefixToUse) { NS_LOG_FUNCTION (this << network << prefix << ifIndex); for (NetworkRoutesI it = m_networkRoutes.begin (); it != m_networkRoutes.end (); it++) { Ipv6RoutingTableEntry* rtentry = it->first; if (network == rtentry->GetDest () && rtentry->GetInterface () == ifIndex && rtentry->GetPrefixToUse () == prefixToUse) { delete it->first; m_networkRoutes.erase (it); return; } } } Ptr<Ipv6Route> Ipv6StaticRouting::RouteOutput (Ptr<Packet> p, const Ipv6Header &header, Ptr<NetDevice> oif, Socket::SocketErrno &sockerr) { NS_LOG_FUNCTION (this << header << oif); Ipv6Address destination = header.GetDestinationAddress (); Ptr<Ipv6Route> rtentry = 0; if (destination.IsMulticast ()) { // Note: Multicast routes for outbound packets are stored in the // normal unicast table. An implication of this is that it is not // possible to source multicast datagrams on multiple interfaces. // This is a well-known property of sockets implementation on // many Unix variants. // So, we just log it and fall through to LookupStatic () NS_LOG_LOGIC ("RouteOutput ()::Multicast destination"); } rtentry = LookupStatic (destination, oif); if (rtentry) { sockerr = Socket::ERROR_NOTERROR; } else { sockerr = Socket::ERROR_NOROUTETOHOST; } return rtentry; } bool Ipv6StaticRouting::RouteInput (Ptr<const Packet> p, const Ipv6Header &header, Ptr<const NetDevice> idev, UnicastForwardCallback ucb, MulticastForwardCallback mcb, LocalDeliverCallback lcb, ErrorCallback ecb) { NS_LOG_FUNCTION (this << p << header << header.GetSourceAddress () << header.GetDestinationAddress () << idev); NS_ASSERT (m_ipv6 != 0); // Check if input device supports IP NS_ASSERT (m_ipv6->GetInterfaceForDevice (idev) >= 0); uint32_t iif = m_ipv6->GetInterfaceForDevice (idev); Ipv6Address dst = header.GetDestinationAddress (); if (dst.IsMulticast ()) { NS_LOG_LOGIC ("Multicast destination"); Ptr<Ipv6MulticastRoute> mrtentry = LookupStatic (header.GetSourceAddress (), header.GetDestinationAddress (), m_ipv6->GetInterfaceForDevice (idev)); if (mrtentry) { NS_LOG_LOGIC ("Multicast route found"); mcb (mrtentry, p, header); // multicast forwarding callback return true; } else { NS_LOG_LOGIC ("Multicast route not found"); return false; // Let other routing protocols try to handle this } } // TODO: Configurable option to enable RFC 1222 Strong End System Model // Right now, we will be permissive and allow a source to send us // a packet to one of our other interface addresses; that is, the // destination unicast address does not match one of the iif addresses, // but we check our other interfaces. This could be an option // (to remove the outer loop immediately below and just check iif). for (uint32_t j = 0; j < m_ipv6->GetNInterfaces (); j++) { for (uint32_t i = 0; i < m_ipv6->GetNAddresses (j); i++) { Ipv6InterfaceAddress iaddr = m_ipv6->GetAddress (j, i); Ipv6Address addr = iaddr.GetAddress (); if (addr.IsEqual (header.GetDestinationAddress ())) { if (j == iif) { NS_LOG_LOGIC ("For me (destination " << addr << " match)"); } else { NS_LOG_LOGIC ("For me (destination " << addr << " match) on another interface " << header.GetDestinationAddress ()); } lcb (p, header, iif); return true; } NS_LOG_LOGIC ("Address "<< addr << " not a match"); } } // Check if input device supports IP forwarding if (m_ipv6->IsForwarding (iif) == false) { NS_LOG_LOGIC ("Forwarding disabled for this interface"); ecb (p, header, Socket::ERROR_NOROUTETOHOST); return false; } // Next, try to find a route NS_LOG_LOGIC ("Unicast destination"); Ptr<Ipv6Route> rtentry = LookupStatic (header.GetDestinationAddress ()); if (rtentry != 0) { NS_LOG_LOGIC ("Found unicast destination- calling unicast callback"); ucb (rtentry, p, header); // unicast forwarding callback return true; } else { NS_LOG_LOGIC ("Did not find unicast destination- returning false"); return false; // Let other routing protocols try to handle this } } void Ipv6StaticRouting::NotifyInterfaceUp (uint32_t i) { for (uint32_t j = 0; j < m_ipv6->GetNAddresses (i); j++) { if (m_ipv6->GetAddress (i, j).GetAddress () != Ipv6Address () && m_ipv6->GetAddress (i, j).GetPrefix () != Ipv6Prefix ()) { if (m_ipv6->GetAddress (i, j).GetPrefix () == Ipv6Prefix (128)) { /* host route */ AddHostRouteTo (m_ipv6->GetAddress (i, j).GetAddress (), i); } else { AddNetworkRouteTo (m_ipv6->GetAddress (i, j).GetAddress ().CombinePrefix (m_ipv6->GetAddress (i, j).GetPrefix ()), m_ipv6->GetAddress (i, j).GetPrefix (), i); } } } } void Ipv6StaticRouting::NotifyInterfaceDown (uint32_t i) { NS_LOG_FUNCTION (this << i); uint32_t j = 0; uint32_t max = GetNRoutes (); /* remove all static routes that are going through this interface */ while (j < max) { Ipv6RoutingTableEntry route = GetRoute (j); if (route.GetInterface () == i) { RemoveRoute (j); } else { j++; } } } void Ipv6StaticRouting::NotifyAddAddress (uint32_t interface, Ipv6InterfaceAddress address) { if (!m_ipv6->IsUp (interface)) { return; } Ipv6Address networkAddress = address.GetAddress ().CombinePrefix (address.GetPrefix ()); Ipv6Prefix networkMask = address.GetPrefix (); if (address.GetAddress () != Ipv6Address () && address.GetPrefix () != Ipv6Prefix ()) { AddNetworkRouteTo (networkAddress, networkMask, interface); } } void Ipv6StaticRouting::NotifyRemoveAddress (uint32_t interface, Ipv6InterfaceAddress address) { if (!m_ipv6->IsUp (interface)) { return; } Ipv6Address networkAddress = address.GetAddress ().CombinePrefix (address.GetPrefix ()); Ipv6Prefix networkMask = address.GetPrefix (); // Remove all static routes that are going through this interface // which reference this network for (uint32_t j = 0; j < GetNRoutes (); j++) { Ipv6RoutingTableEntry route = GetRoute (j); if (route.GetInterface () == interface && route.IsNetwork () && route.GetDestNetwork () == networkAddress && route.GetDestNetworkPrefix () == networkMask) { RemoveRoute (j); } } } void Ipv6StaticRouting::NotifyAddRoute (Ipv6Address dst, Ipv6Prefix mask, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse) { NS_LOG_INFO (this << dst << mask << nextHop << interface << prefixToUse); if (dst != Ipv6Address::GetZero ()) { AddNetworkRouteTo (dst, mask, nextHop, interface); } else /* default route */ { /* this case is mainly used by configuring default route following RA processing, * in case of multipe prefix in RA, the first will configured default route */ /* for the moment, all default route has the same metric * so according to the longest prefix algorithm, * the default route choosen will be the last added */ SetDefaultRoute (nextHop, interface, prefixToUse); } } void Ipv6StaticRouting::NotifyRemoveRoute (Ipv6Address dst, Ipv6Prefix mask, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse) { NS_LOG_FUNCTION (this << dst << mask << nextHop << interface); if (dst != Ipv6Address::GetZero ()) { for (NetworkRoutesI j = m_networkRoutes.begin (); j != m_networkRoutes.end (); j++) { Ipv6RoutingTableEntry* rtentry = j->first; Ipv6Prefix prefix = rtentry->GetDestNetworkPrefix (); Ipv6Address entry = rtentry->GetDestNetwork (); if (dst == entry && prefix == mask && rtentry->GetInterface () == interface) { delete j->first; m_networkRoutes.erase (j); } } } else { /* default route case */ RemoveRoute (dst, mask, interface, prefixToUse); } } Ipv6Address Ipv6StaticRouting::SourceAddressSelection (uint32_t interface, Ipv6Address dest) { NS_LOG_FUNCTION (this << interface << dest); Ipv6Address ret; /* first address of an IPv6 interface is link-local ones */ ret = m_ipv6->GetAddress (interface, 0).GetAddress (); if (dest == Ipv6Address::GetAllNodesMulticast () || dest == Ipv6Address::GetAllRoutersMulticast () || dest == Ipv6Address::GetAllHostsMulticast ()) { return ret; } /* useally IPv6 interfaces have one link-local address and one global address */ for (uint32_t i = 1; i < m_ipv6->GetNAddresses (interface); i++) { Ipv6InterfaceAddress test = m_ipv6->GetAddress (interface, i); if (test.GetAddress ().CombinePrefix (test.GetPrefix ()) == dest.CombinePrefix (test.GetPrefix ())) { return test.GetAddress (); } } return ret; } } /* namespace ns3 */
32.757576
172
0.631782
[ "vector", "model" ]
0b79db3bb85156b780f70dd63ad6be794b3bb738
4,701
cpp
C++
gui/src/QMainCanvas.cpp
xbai0624/MPD_GEM_View_SSP
823740845773c6b938159c40b8c04fb83a3a259f
[ "MIT" ]
null
null
null
gui/src/QMainCanvas.cpp
xbai0624/MPD_GEM_View_SSP
823740845773c6b938159c40b8c04fb83a3a259f
[ "MIT" ]
null
null
null
gui/src/QMainCanvas.cpp
xbai0624/MPD_GEM_View_SSP
823740845773c6b938159c40b8c04fb83a3a259f
[ "MIT" ]
null
null
null
#include "QMainCanvas.h" #include <TH1F.h> #include <TSystem.h> #include <TStyle.h> #include <iostream> #include <QMouseEvent> //////////////////////////////////////////////////////////////////////////////// // ctor QMainCanvas::QMainCanvas(QWidget* parent) : QWidget(parent) { fCanvas = new QRootCanvas(this); layout = new QVBoxLayout(this); layout->addWidget(fCanvas); fRootCanvas = fCanvas->GetCanvas(); connect(fCanvas, SIGNAL(ItemSelected()), this, SIGNAL(ItemSelected())); connect(fCanvas, SIGNAL(ItemDeSelected()), this, SIGNAL(ItemDeSelected())); fRootTimer = new QTimer(this); QObject::connect(fRootTimer, SIGNAL(timeout()), this, SLOT(handle_root_events())); fRootTimer->start(20); } //////////////////////////////////////////////////////////////////////////////// // drawing interface void QMainCanvas::DrawCanvas(const std::vector<TH1I*> &hists, int w, int h) { gStyle->SetOptStat(0); fRootCanvas->Clear(); fRootCanvas->Divide(w, h); int ii = 0; for(auto &i: hists) { fRootCanvas->cd(ii+1); i -> Draw(); ii++; } fRootCanvas->Modified(); fRootCanvas->Update(); } //////////////////////////////////////////////////////////////////////////////// // drawing interface, overloaded void QMainCanvas::DrawCanvas(const std::vector<std::vector<int>> &hists, const std::vector<APVAddress> &addr, int w, int h) { gStyle->SetOptStat(0); fRootCanvas->Clear(); fRootCanvas->Divide(w, h); int ii = 0; GenerateHistos(hists, addr); for(auto &i: vHContents) { fRootCanvas->cd(ii+1); i -> Draw(); ii++; } fRootCanvas->Modified(); fRootCanvas->Update(); } //////////////////////////////////////////////////////////////////////////////// // drawing interface, overloaded void QMainCanvas::DrawCanvas(const std::string &s, const std::vector<float> &c) { if(c.size() <= 0) return; static TH1I *h = 0; if(h == 0){ h = new TH1I("h", s.c_str(), c.size(), 0, c.size()); } else if((int)c.size() != h->GetNbinsX() ) { delete h; h = new TH1I("h", s.c_str(), c.size(), 0, c.size()); } h->Reset("M"); h->SetTitle(s.c_str()); for(unsigned i=0;i<c.size();i++) h->SetBinContent(i, c[i]); gStyle->SetOptStat(0); fRootCanvas -> Clear(); h->Draw(); fRootCanvas -> Modified(); fRootCanvas -> Update(); } //////////////////////////////////////////////////////////////////////////////// // root timer void QMainCanvas::handle_root_events() { gSystem->ProcessEvents(); } //////////////////////////////////////////////////////////////////////////////// // slot mouse press event void QMainCanvas::mousePressEvent(QMouseEvent *e) { switch(e->button()) { case Qt::LeftButton: emit ItemSelected(); break; case Qt::RightButton: emit ItemDeSelected(); break; case Qt::MidButton: break; default: break; } } //////////////////////////////////////////////////////////////////////////////// // get root canvas TCanvas * QMainCanvas::GetCanvas() { return fCanvas->GetCanvas(); } //////////////////////////////////////////////////////////////////////////////// // refresh void QMainCanvas::Refresh() { fCanvas->Refresh(); } //////////////////////////////////////////////////////////////////////////////// // slot paint event void QMainCanvas::paintEvent([[maybe_unused]] QPaintEvent *e) { Refresh(); } //////////////////////////////////////////////////////////////////////////////// // slot resize event void QMainCanvas::resizeEvent([[maybe_unused]] QResizeEvent *e) { Refresh(); } //////////////////////////////////////////////////////////////////////////////// // generate histos from vector void QMainCanvas::GenerateHistos(const std::vector<std::vector<int>> &data, const std::vector<APVAddress> &addr) { // delete previous events for(auto &i: vHContents) if(i) delete i; vHContents.clear(); // generate new pedestal auto get_histo = [&](const std::vector<int> &v, const APVAddress &addr) -> TH1I* { TH1I * h = new TH1I(Form("h_crate_%d_mpd_%d_adc_ch_%d", addr.crate_id, addr.mpd_id, addr.adc_ch), Form("h_crate_%d_mpd_%d_adc_ch_%d", addr.crate_id, addr.mpd_id, addr.adc_ch), v.size(), 0, v.size()); for(unsigned int i=0;i<v.size();i++) h->SetBinContent(i, v[i]); return h; }; for(unsigned int i=0;i<data.size();i++) vHContents.push_back(get_histo(data[i], addr[i])); }
25.005319
106
0.481174
[ "vector" ]
0b8b1cdfebbe30f81b726dbbdbb29ac7c2f22e61
3,480
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/graphics/CPoint.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/graphics/CPoint.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/graphics/CPoint.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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. //========================================================================= #include "Elastos.Droid.Content.h" #include "Elastos.Droid.Os.h" #include "elastos/droid/graphics/CPoint.h" #include "elastos/droid/ext/frameworkext.h" #include <elastos/core/StringBuilder.h> using Elastos::Core::StringBuilder; namespace Elastos { namespace Droid { namespace Graphics { CAR_OBJECT_IMPL(CPoint); CAR_INTERFACE_IMPL_2(CPoint, Object, IPoint, IParcelable); ECode CPoint::constructor() { mX = 0; mY = 0; return NOERROR; } ECode CPoint::constructor( /* [in] */ Int32 x, /* [in] */ Int32 y) { mX = x; mY = y; return NOERROR; } ECode CPoint::constructor( /* [in] */ IPoint* src) { mX = ((CPoint*)src)->mX; mY = ((CPoint*)src)->mY; return NOERROR; } ECode CPoint::Set( /* [in] */ Int32 x, /* [in] */ Int32 y) { mX = x; mY = y; return NOERROR; } ECode CPoint::Get( /* [out] */ Int32* x, /* [out] */ Int32* y) { if (x != NULL) *x = mX; if (y != NULL) *y = mY; return NOERROR; } ECode CPoint::Negate() { mX = -mX; mY = -mY; return NOERROR; } ECode CPoint::Offset( /* [in] */ Int32 dx, /* [in] */ Int32 dy) { mX += dx; mY += dy; return NOERROR; } ECode CPoint::Equals( /* [in] */ Int32 x, /* [in] */ Int32 y, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mX == x && mY == y; return NOERROR; } ECode CPoint::Equals( /* [in] */ IPoint* p, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = FALSE; Int32 x, y; p->Get(&x, &y); return Equals(x, y, result); } ECode CPoint::Equals( /* [in] */ IInterface* p, /* [out] */ Boolean* result) { return Equals(IPoint::Probe(p), result); } ECode CPoint::GetHashCode( /* [out] */ Int32* hash) { VALIDATE_NOT_NULL(hash); Int32 result = mX; result = 31 * result + mY; *hash = result; return NOERROR; } ECode CPoint::ToString( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); StringBuilder sb(28); sb += "Point("; sb += mX; sb += ", "; sb += mY; sb += ")"; sb.ToString(result); return NOERROR; } ECode CPoint::ReadFromParcel( /* [in] */ IParcel* source) { source->ReadInt32(&mX); source->ReadInt32(&mY); return NOERROR; } ECode CPoint::WriteToParcel( /* [out] */ IParcel* dest) { dest->WriteInt32(mX); dest->WriteInt32(mY); return NOERROR; } ECode CPoint::GetX( /* [out] */ Int32* x) { VALIDATE_NOT_NULL(x); *x = mX; return NOERROR; } ECode CPoint::GetY( /* [out] */ Int32* y) { VALIDATE_NOT_NULL(y); *y = mY; return NOERROR; } } // namespace Graphics } // namepsace Droid } // namespace Elastos
19.441341
75
0.567529
[ "object" ]
0b9171ad8047ddaef4eaf5c86ffd604bd04b671a
2,609
hpp
C++
third_party/mockturtle/mockturtle/algorithms/exorcism.hpp
drewrisinger/tweedledum
1c331a076fa137295193a10e0ed664603ae80c21
[ "MIT" ]
7
2020-03-13T17:08:01.000Z
2021-11-17T11:43:58.000Z
third_party/mockturtle/mockturtle/algorithms/exorcism.hpp
drewrisinger/tweedledum
1c331a076fa137295193a10e0ed664603ae80c21
[ "MIT" ]
2
2021-03-16T12:05:50.000Z
2021-03-16T13:06:47.000Z
third_party/mockturtle/mockturtle/algorithms/exorcism.hpp
drewrisinger/tweedledum
1c331a076fa137295193a10e0ed664603ae80c21
[ "MIT" ]
8
2020-02-13T18:05:55.000Z
2021-03-16T11:12:33.000Z
/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*! \file exorcism.hpp \brief Wrapper for ABC's exorcism \author Mathias Soeken */ #pragma once #include <vector> #include <eabc/exor.h> #include <kitty/constructors.hpp> #include <kitty/cube.hpp> #include <kitty/dynamic_truth_table.hpp> #include <kitty/esop.hpp> namespace abc::exorcism { extern int Abc_ExorcismMain( Vec_Wec_t * vEsop, int nIns, int nOuts, std::function<void(uint32_t, uint32_t)> const& onCube, int Quality, int Verbosity, int nCubesMax, int fUseQCost ); } namespace mockturtle { inline std::vector<kitty::cube> exorcism( std::vector<kitty::cube> const& esop, uint32_t num_vars ) { auto vesop = abc::exorcism::Vec_WecAlloc( esop.size() ); for ( auto const& cube : esop ) { auto vcube = abc::exorcism::Vec_WecPushLevel( vesop ); for ( auto i = 0u; i < num_vars; ++i ) { if ( !cube.get_mask( i ) ) continue; abc::exorcism::Vec_IntPush( vcube, cube.get_bit( i ) ? 2 * i : 2 * i + 1 ); } abc::exorcism::Vec_IntPush( vcube, -1 ); } std::vector<kitty::cube> exorcism_esop; abc::exorcism::Abc_ExorcismMain( vesop, num_vars, 1, [&]( uint32_t bits, uint32_t mask ) { exorcism_esop.emplace_back( bits, mask ); }, 2, 0, 4 * esop.size(), 0 ); abc::exorcism::Vec_WecFree( vesop ); return exorcism_esop; } inline std::vector<kitty::cube> exorcism( kitty::dynamic_truth_table const& func ) { return exorcism( kitty::esop_from_optimum_pkrm( func ), func.num_vars() ); } }
32.6125
185
0.71215
[ "vector" ]
0ba02f9da3ad2e0969a0e3dfb683442c9ba0180b
43,369
cpp
C++
src/ompl/geometric/planners/rrt/src/RRTstarConnect.cpp
rezamasha/ompl
f777209899a24702f081f83830956c6b6a62a9a8
[ "BSD-3-Clause" ]
null
null
null
src/ompl/geometric/planners/rrt/src/RRTstarConnect.cpp
rezamasha/ompl
f777209899a24702f081f83830956c6b6a62a9a8
[ "BSD-3-Clause" ]
null
null
null
src/ompl/geometric/planners/rrt/src/RRTstarConnect.cpp
rezamasha/ompl
f777209899a24702f081f83830956c6b6a62a9a8
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2019, University of Malaya * 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 Willow Garage 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. *********************************************************************/ /* Author: Reza Mashayekhi */ #include "ompl/geometric/planners/rrt/RRTstarConnect.h" #include "ompl/base/goals/GoalSampleableRegion.h" #include "ompl/base/objectives/PathLengthOptimizationObjective.h" #include "ompl/tools/config/SelfConfig.h" #include "ompl/util/String.h" #include "ompl/util/GeometricEquations.h" #include "ompl/base/samplers/InformedStateSampler.h" #include <algorithm> #include <boost/math/constants/constants.hpp> #include <limits> #include <vector> ompl::geometric::RRTstarConnect::RRTstarConnect(const base::SpaceInformationPtr &si) : base::Planner(si, "RRTstarConnect") { specs_.recognizedGoal = base::GOAL_SAMPLEABLE_REGION; specs_.directed = true; Planner::declareParam<double>("range", this, &RRTstarConnect::setRange, &RRTstarConnect::getRange, "0.:1.:10000."); Planner::declareParam<double>("rewire_factor", this, &RRTstarConnect::setRewireFactor, &RRTstarConnect::getRewireFactor, "1.0:0.01:2.0"); Planner::declareParam<bool>("use_k_nearest", this, &RRTstarConnect::setKNearest, &RRTstarConnect::getKNearest, "0,1"); Planner::declareParam<bool>("delay_collision_checking", this, &RRTstarConnect::setDelayCC, &RRTstarConnect::getDelayCC, "0,1"); Planner::declareParam<bool>("informed_sampling", this, &RRTstarConnect::setInformedSampling, &RRTstarConnect::getInformedSampling, "0,1"); Planner::declareParam<bool>("tree_pruning", this, &RRTstarConnect::setTreePruning, &RRTstarConnect::getTreePruning, "0,1"); Planner::declareParam<bool>("pruned_measure", this, &RRTstarConnect::setPrunedMeasure, &RRTstarConnect::getPrunedMeasure, "0,1"); bestConnectionPoint_ = std::make_pair<Motion *, Motion *>(nullptr, nullptr); connectionPoints_.clear(); distanceBetweenTrees_ = std::numeric_limits<double>::infinity(); addPlannerProgressProperty("iterations INTEGER", [this] { return numIterationsProperty(); }); addPlannerProgressProperty("best cost REAL", [this] { return bestCostProperty(); }); } ompl::geometric::RRTstarConnect::~RRTstarConnect() { freeMemory(); } void ompl::geometric::RRTstarConnect::setup() { Planner::setup(); tools::SelfConfig sc(si_, getName()); sc.configurePlannerRange(maxDistance_); if (!tStart_) tStart_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion *>(this)); if (!tGoal_) tGoal_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion *>(this)); tStart_->setDistanceFunction([this](const Motion *a, const Motion *b) { return distanceFunction(a, b); }); tGoal_->setDistanceFunction([this](const Motion *a, const Motion *b) { return distanceFunction(a, b); }); // Setup optimization objective // // If no optimization objective was specified, then default to // optimizing path length as computed by the distance() function // in the state space. if (pdef_) { if (pdef_->hasOptimizationObjective()) opt_ = pdef_->getOptimizationObjective(); else { OMPL_INFORM("%s: No optimization objective specified. Defaulting to optimizing path length for the allowed " "planning time.", getName().c_str()); opt_ = std::make_shared<base::PathLengthOptimizationObjective>(si_); // Store the new objective in the problem def'n pdef_->setOptimizationObjective(opt_); } // Set the bestCost_ and prunedCost_ as infinite bestCost_ = opt_->infiniteCost(); prunedCost_ = opt_->infiniteCost(); } else { OMPL_INFORM("%s: problem definition is not set, deferring setup completion...", getName().c_str()); setup_ = false; } // Calculate some constants: calculateRewiringLowerBounds(); } void ompl::geometric::RRTstarConnect::freeMemory() { std::vector<Motion *> motions; if (tStart_) { tStart_->list(motions); for (auto &motion : motions) { if (motion->state != nullptr) si_->freeState(motion->state); delete motion; } } if (tGoal_) { tGoal_->list(motions); for (auto &motion : motions) { if (motion->state != nullptr) si_->freeState(motion->state); delete motion; } } } void ompl::geometric::RRTstarConnect::clear() { setup_ = false; Planner::clear(); sampler_.reset(); infSampler_.reset(); freeMemory(); if (tStart_) tStart_->clear(); if (tGoal_) tGoal_->clear(); bestConnectionPoint_ = std::make_pair<Motion *, Motion *>(nullptr, nullptr); connectionPoints_.clear(); costs.clear(); incCosts.clear(); sortedCostIndices.clear(); valid.clear(); distanceBetweenTrees_ = std::numeric_limits<double>::infinity(); iterations_ = 0; bestCost_ = base::Cost(std::numeric_limits<double>::quiet_NaN()); prunedCost_ = base::Cost(std::numeric_limits<double>::quiet_NaN()); prunedMeasure_ = 0.0; goalMotions_.clear(); startMotions_.clear(); } ompl::geometric::RRTstarConnect::GrowState ompl::geometric::RRTstarConnect::growTree(TreeData &tree, TreeGrowingInfo &tgi, Motion *rmotion) { /* find closest state in the tree */ Motion *nmotion = tree->nearest(rmotion); /* assume we can reach the state we go towards */ bool reach = true; /* find state to add */ base::State *dstate = rmotion->state; double d = si_->distance(nmotion->state, rmotion->state); if (d > maxDistance_) { si_->getStateSpace()->interpolate(nmotion->state, rmotion->state, maxDistance_ / d, tgi.xstate); /* Check if we have moved at all. Due to some stranger state spaces (e.g., the constrained state spaces), * interpolate can fail and no progress is made. Without this check, the algorithm gets stuck in a loop as it * thinks it is making progress, when none is actually occurring. */ if (si_->equalStates(nmotion->state, tgi.xstate)) return TRAPPED; dstate = tgi.xstate; reach = false; } bool validMotion = tgi.start ? si_->checkMotion(nmotion->state, dstate) : si_->isValid(dstate) && si_->checkMotion(dstate, nmotion->state); if (!validMotion) { return TRAPPED; } Motion *motion = new Motion(si_); si_->copyState(motion->state, dstate); motion->parent = nmotion; motion->root = nmotion->root; motion->isConnectionPoint = false; motion->incCost = opt_->motionCost(nmotion->state, motion->state); motion->cost = opt_->combineCosts(nmotion->cost, motion->incCost); // tgi.xmotion = motion; // Find nearby neighbors of the new motion std::vector<Motion *> nbh; getNeighbors(tree, motion, nbh); rewireTest += nbh.size(); statesGenerated++; // cache for distance computations // // Our cost caches only increase in size, so they're only // resized if they can't fit the current neighborhood if (costs.size() < nbh.size()) { costs.resize(nbh.size()); incCosts.resize(nbh.size()); sortedCostIndices.resize(nbh.size()); } // cache for motion validity (only useful in a symmetric space) // // Our validity caches only increase in size, so they're // only resized if they can't fit the current neighborhood if (valid.size() < nbh.size()) valid.resize(nbh.size()); std::fill(valid.begin(), valid.begin() + nbh.size(), 0); // our functor for sorting nearest neighbors CostIndexCompare compareFn(costs, *opt_); // Finding the nearest neighbor to connect to // By default, neighborhood states are sorted by cost, and collision checking // is performed in increasing order of cost if (delayCC_) { // calculate all costs and distances for (std::size_t i = 0; i < nbh.size(); ++i) { incCosts[i] = opt_->motionCost(nbh[i]->state, motion->state); costs[i] = opt_->combineCosts(nbh[i]->cost, incCosts[i]); } // sort the nodes // // we're using index-value pairs so that we can get at // original, unsorted indices for (std::size_t i = 0; i < nbh.size(); ++i) sortedCostIndices[i] = i; std::sort(sortedCostIndices.begin(), sortedCostIndices.begin() + nbh.size(), compareFn); // collision check until a valid motion is found // // ASYMMETRIC CASE: it's possible that none of these // neighbors are valid. This is fine, because motion // already has a connection to the tree through // nmotion (with populated cost fields!). for (std::vector<std::size_t>::const_iterator i = sortedCostIndices.begin(); i != sortedCostIndices.begin() + nbh.size(); ++i) { if (nbh[*i] == nmotion || ((!useKNearest_ || si_->distance(nbh[*i]->state, motion->state) < maxDistance_) && (tgi.start ? si_->checkMotion(nbh[*i]->state, motion->state) : si_->isValid(motion->state) && si_->checkMotion(motion->state, nbh[*i]->state)))) { motion->incCost = incCosts[*i]; motion->cost = costs[*i]; motion->parent = nbh[*i]; valid[*i] = 1; break; } else valid[*i] = -1; } } else // if not delayCC { motion->incCost = opt_->motionCost(nmotion->state, motion->state); motion->cost = opt_->combineCosts(nmotion->cost, motion->incCost); // find which one we connect the new state to for (std::size_t i = 0; i < nbh.size(); ++i) { if (nbh[i] != nmotion) { incCosts[i] = opt_->motionCost(nbh[i]->state, motion->state); costs[i] = opt_->combineCosts(nbh[i]->cost, incCosts[i]); if (opt_->isCostBetterThan(costs[i], motion->cost)) { if ((!useKNearest_ || si_->distance(nbh[i]->state, motion->state) < maxDistance_) && (tgi.start ? si_->checkMotion(nbh[i]->state, motion->state) : si_->isValid(motion->state) && si_->checkMotion(motion->state, nbh[i]->state))) { motion->incCost = incCosts[i]; motion->cost = costs[i]; motion->parent = nbh[i]; valid[i] = 1; } else valid[i] = -1; } } else { incCosts[i] = motion->incCost; costs[i] = motion->cost; valid[i] = 1; } } } tree->add(motion); tgi.xmotion = motion; motion->parent->children.push_back(motion); // update existing motions for (std::size_t i = 0; i < nbh.size(); ++i) { if (nbh[i] != motion->parent) { base::Cost nbhIncCost; if (opt_->isSymmetric()) nbhIncCost = incCosts[i]; else nbhIncCost = opt_->motionCost(motion->state, nbh[i]->state); base::Cost nbhNewCost = opt_->combineCosts(motion->cost, nbhIncCost); if (opt_->isCostBetterThan(nbhNewCost, nbh[i]->cost)) { if (valid[i] == 0) { validMotion = (!useKNearest_ || si_->distance(nbh[i]->state, motion->state) < maxDistance_) && (tgi.start ? si_->checkMotion(motion->state, nbh[i]->state) : si_->isValid(motion->state) && si_->checkMotion(nbh[i]->state, motion->state)); } else { validMotion = (valid[i] == 1); } if (validMotion) { // Remove this node from its parent list removeFromParent(nbh[i]); // Add this node to the new parent nbh[i]->parent = motion; nbh[i]->incCost = nbhIncCost; nbh[i]->cost = nbhNewCost; nbh[i]->parent->children.push_back(nbh[i]); // Update the costs of the node's children updateChildCosts(nbh[i]); checkForSolution = true; } } } } return reach ? REACHED : ADVANCED; } ompl::base::PlannerStatus ompl::geometric::RRTstarConnect::solve(const base::PlannerTerminationCondition &ptc) { checkValidity(); auto *goal = dynamic_cast<base::GoalSampleableRegion *>(pdef_->getGoal().get()); if (goal == nullptr) { OMPL_ERROR("%s: Unknown type of goal", getName().c_str()); return base::PlannerStatus::UNRECOGNIZED_GOAL_TYPE; } while (const base::State *st = pis_.nextStart()) { auto *motion = new Motion(si_); si_->copyState(motion->state, st); motion->root = motion->state; tStart_->add(motion); startMotions_.push_back(motion); } // And assure that, if we're using an informed sampler, it's reset infSampler_.reset(); if (tStart_->size() == 0) { OMPL_ERROR("%s: Motion planning start tree could not be initialized!", getName().c_str()); return base::PlannerStatus::INVALID_START; } if (!goal->couldSample()) { OMPL_ERROR("%s: Insufficient states in sampleable goal region", getName().c_str()); return base::PlannerStatus::INVALID_GOAL; } // Allocate a sampler if necessary if (!sampler_ && !infSampler_) { allocSampler(); } OMPL_INFORM("%s: Starting planning with %d states already in datastructure", getName().c_str(), (int)(tStart_->size() + tGoal_->size())); TreeGrowingInfo tgi; tgi.xstate = si_->allocState(); Motion *approxsol = nullptr; double approxdif = std::numeric_limits<double>::infinity(); auto *rmotion = new Motion(si_); bool startTree = true; bool solved = false; rewireTest = 0; statesGenerated = 0; costs.clear(); incCosts.clear(); sortedCostIndices.clear(); if (bestConnectionPoint_.first && bestConnectionPoint_.second) OMPL_INFORM("%s: Starting planning with existing solution of cost %.5f", getName().c_str(), bestCost_); if (useKNearest_) OMPL_INFORM("%s: Initial k-nearest value of %u", getName().c_str(), (unsigned int)std::ceil(k_rrt_ * log((double)(tStart_->size() + tGoal_->size() + 1u)))); else OMPL_INFORM( "%s: Initial rewiring radius of %.2f", getName().c_str(), std::min(maxDistance_, r_rrt_ * std::pow(log((double)(tStart_->size() + tGoal_->size() + 1u)) / ((double)(tStart_->size() + tGoal_->size() + 1u)), 1 / (double)(si_->getStateDimension())))); while (!ptc) { iterations_++; TreeData &tree = startTree ? tStart_ : tGoal_; tgi.start = startTree; startTree = !startTree; TreeData &otherTree = startTree ? tStart_ : tGoal_; if (tGoal_->size() == 0 || pis_.getSampledGoalsCount() < tGoal_->size() / 2) { const base::State *st = tGoal_->size() == 0 ? pis_.nextGoal(ptc) : pis_.nextGoal(); if (st != nullptr) { auto *motion = new Motion(si_); si_->copyState(motion->state, st); motion->root = motion->state; tGoal_->add(motion); goalMotions_.push_back(motion); } if (tGoal_->size() == 0) { OMPL_ERROR("%s: Unable to sample any valid states for goal tree", getName().c_str()); break; } } /* sample random state */ if (!sampleUniform(rmotion->state)) continue; checkForSolution = false; GrowState gs = growTree(tree, tgi, rmotion); if (gs != TRAPPED) { /* remember which motion was just added */ Motion *addedMotion = tgi.xmotion; /* attempt to connect trees */ /* if reached, it means we used rstate directly, no need top copy again */ if (gs != REACHED) si_->copyState(rmotion->state, tgi.xstate); GrowState gsc = ADVANCED; tgi.start = startTree; while (gsc == ADVANCED) gsc = growTree(otherTree, tgi, rmotion); /* update distance between trees */ const double newDist = tree->getDistanceFunction()(addedMotion, otherTree->nearest(addedMotion)); if (newDist < distanceBetweenTrees_) { distanceBetweenTrees_ = newDist; } Motion *startMotion = startTree ? tgi.xmotion : addedMotion; Motion *goalMotion = startTree ? addedMotion : tgi.xmotion; /* if we connected the trees in a valid way (start and goal pair is valid)*/ if (gsc == REACHED && goal->isStartGoalPairValid(startMotion->root, goalMotion->root)) { startMotion->isConnectionPoint = true; goalMotion->isConnectionPoint = true; checkForSolution = true; connectionPoints_.push_back(std::pair<Motion *, Motion *>(startMotion, goalMotion)); solved = true; } else { if(!(bestConnectionPoint_.first && bestConnectionPoint_.second)) bestConnectionPoint_=std::pair<Motion *, Motion *>(startMotion, goalMotion); // We didn't reach the goal, but if we were extending the start // tree, then we can mark/improve the approximate path so far. if (!startTree) { // We were working from the startTree. double dist = 0.0; goal->isSatisfied(tgi.xmotion->state, &dist); if (dist < approxdif) { approxdif = dist; approxsol = tgi.xmotion; } } } if (checkForSolution) { bool updatedSolution = false; if (!(bestConnectionPoint_.first && bestConnectionPoint_.second) && !connectionPoints_.empty()) { // We have found our first solution, store it as the best. We only add one // connection point at a time, so there can only be one connection point at this moment. bestConnectionPoint_ = connectionPoints_.front(); bestCost_ = opt_->combineCosts(bestConnectionPoint_.first->cost, bestConnectionPoint_.second->cost); updatedSolution = true; OMPL_INFORM("%s: Found an initial solution with a cost of %.2f in %u iterations (%u " "vertices in both trees(%u in Start Tree and %u in Goal Tree))", getName().c_str(), bestCost_, iterations_, tStart_->size() + tGoal_->size(), tStart_->size(), tGoal_->size()); } else { // We already have a solution, iterate through the list of connection Points // and see if there's any improvement. for (auto &connectionPoint : connectionPoints_) { // Is this goal motion better than the (current) best? if ((opt_->combineCosts(connectionPoint.first->cost, connectionPoint.second->cost).value()) < bestCost_.value()) { bestConnectionPoint_ = connectionPoint; bestCost_ = opt_->combineCosts(connectionPoint.first->cost, connectionPoint.second->cost); updatedSolution = true; // Check if it satisfies the optimization objective, if it does, break the for loop if (opt_->isSatisfied(bestCost_)) { break; } } } } if (updatedSolution) { if (useTreePruning_) { pruneTrees(bestCost_); } } } } // terminate if a sufficient solution is found if (bestConnectionPoint_.first && bestConnectionPoint_.second && opt_->isSatisfied(bestCost_)) break; } si_->freeState(tgi.xstate); if (rmotion->state) si_->freeState(rmotion->state); delete rmotion; ptc.terminate(); bool solutionFound = false; if (approxsol && !solved) { solutionFound = true; Motion *solution = approxsol; std::vector<Motion *> mpath; while (solution != nullptr) { mpath.push_back(solution); solution = solution->parent; } auto path(std::make_shared<PathGeometric>(si_)); for (int i = mpath.size() - 1; i >= 0; --i) path->append(mpath[i]->state); // Add the solution path. base::PlannerSolution psol(path); psol.setPlannerName(getName()); // If we don't have a goal motion, the solution is approximate if (!(bestConnectionPoint_.first && bestConnectionPoint_.second)) psol.setApproximate(approxdif); // Does the solution satisfy the optimization objective? psol.setOptimized(opt_, approxsol->cost, opt_->isSatisfied(bestCost_)); pdef_->addSolutionPath(psol); } else if(bestConnectionPoint_.first && bestConnectionPoint_.second) { solutionFound = true; Motion *solution = bestConnectionPoint_.first; std::vector<Motion *> mpath1; while (solution != nullptr) { mpath1.push_back(solution); solution = solution->parent; } solution = bestConnectionPoint_.second; std::vector<Motion *> mpath2; while (solution != nullptr) { mpath2.push_back(solution); solution = solution->parent; } auto path(std::make_shared<PathGeometric>(si_)); path->getStates().reserve(mpath1.size() + mpath2.size()); for (int i = mpath1.size() - 1; i >= 0; --i) path->append(mpath1[i]->state); for (auto &i : mpath2) path->append(i->state); // Add the solution path. base::PlannerSolution psol(path); psol.setPlannerName(getName()); // If we don't have a goal motion, the solution is approximate if (!(bestConnectionPoint_.first && bestConnectionPoint_.second)) psol.setApproximate(approxdif); // Does the solution satisfy the optimization objective? psol.setOptimized(opt_, opt_->combineCosts(bestConnectionPoint_.first->cost, bestConnectionPoint_.second->cost), opt_->isSatisfied(bestCost_)); pdef_->addSolutionPath(psol); } OMPL_INFORM("%s: Created %u new states. All states in both trees %u (%u start + %u goal). \nChecked %u rewire options. %u connection points in graph. Final solution cost " "%.3f", getName().c_str(), statesGenerated, tStart_->size() + tGoal_->size(), tStart_->size(), tGoal_->size(), rewireTest, connectionPoints_.size(), bestCost_); return base::PlannerStatus(solutionFound, bestConnectionPoint_.first== nullptr && bestConnectionPoint_.second== nullptr); } void ompl::geometric::RRTstarConnect::removeFromParent(Motion *m) { for (auto it = m->parent->children.begin(); it != m->parent->children.end(); ++it) { if (*it == m) { m->parent->children.erase(it); break; } } } void ompl::geometric::RRTstarConnect::updateChildCosts(Motion *m) { for (std::size_t i = 0; i < m->children.size(); ++i) { m->children[i]->cost = opt_->combineCosts(m->cost, m->children[i]->incCost); updateChildCosts(m->children[i]); } } void ompl::geometric::RRTstarConnect::getNeighbors(TreeData &tree, Motion *motion, std::vector<Motion *> &nbh) const { auto cardDbl = static_cast<double>(tree->size() + 1u); if (useKNearest_) { //- k-nearest RRT* unsigned int k = std::ceil(k_rrt_ * log(cardDbl)); tree->nearestK(motion, k, nbh); } else { double r = std::min( maxDistance_, r_rrt_ * std::pow(log(cardDbl) / cardDbl, 1 / static_cast<double>(si_->getStateDimension()))); tree->nearestR(motion, r, nbh); } } void ompl::geometric::RRTstarConnect::getPlannerData(base::PlannerData &data) const { Planner::getPlannerData(data); std::vector<Motion *> motions; if (tStart_) tStart_->list(motions); for (auto &motion : motions) { if (motion->parent == nullptr) data.addStartVertex(base::PlannerDataVertex(motion->state, 1)); else { data.addEdge(base::PlannerDataVertex(motion->parent->state, 1), base::PlannerDataVertex(motion->state, 1)); } } motions.clear(); if (tGoal_) tGoal_->list(motions); for (auto &motion : motions) { if (motion->parent == nullptr) data.addGoalVertex(base::PlannerDataVertex(motion->state, 2)); else { // The edges in the goal tree are reversed to be consistent with start tree data.addEdge(base::PlannerDataVertex(motion->state, 2), base::PlannerDataVertex(motion->parent->state, 2)); } } // Add the edge connecting the two trees if(bestConnectionPoint_.first && bestConnectionPoint_.second) data.addEdge(data.vertexIndex(bestConnectionPoint_.first->state), data.vertexIndex(bestConnectionPoint_.second->state)); // Add some info. data.properties["approx goal distance REAL"] = ompl::toString(distanceBetweenTrees_); } int ompl::geometric::RRTstarConnect::pruneTrees(const base::Cost &pruneTreeCost) { // Variable // The percent improvement (expressed as a [0,1] fraction) in cost double fracBetter; // The number pruned int numPruned = 0; if (opt_->isFinite(prunedCost_)) { fracBetter = std::abs((pruneTreeCost.value() - prunedCost_.value()) / prunedCost_.value()); } else { fracBetter = 1.0; } if (fracBetter > pruneThreshold_) { numPruned = pruneTree(tStart_, bestCost_, true); numPruned += pruneTree(tGoal_, bestCost_, false); } return numPruned; } int ompl::geometric::RRTstarConnect::pruneTree(TreeData &tree, const base::Cost &pruneTreeCost, bool isTreeStart) { int numPruned = 0; // We are only pruning motions if they, AND all descendents, have a estimated cost greater than pruneTreeCost // The easiest way to do this is to find leaves that should be pruned and ascend up their ancestry until a // motion is found that is kept. // To avoid making an intermediate copy of the NN structure, we process the tree by descending down from the // start(s). // In the first pass, all Motions with a cost below pruneTreeCost, or Motion's with children with costs below // pruneTreeCost are added to the replacement NN structure, // while all other Motions are stored as either a 'leaf' or 'chain' Motion. After all the leaves are // disconnected and deleted, we check // if any of the the chain Motions are now leaves, and repeat that process until done. // This avoids (1) copying the NN structure into an intermediate variable and (2) the use of the expensive // NN::remove() method. // Variable // The queue of Motions to process: std::queue<Motion *, std::deque<Motion *>> motionQueue; // The list of leaves to prune std::queue<Motion *, std::deque<Motion *>> leavesToPrune; // The list of chain vertices to recheck after pruning std::list<Motion *> chainsToRecheck; tree->clear(); if (isTreeStart) { // Put all the starts into the tStart_ structure and their children into the queue: // We do this so that start states are never pruned. for (auto &startMotion : startMotions_) { // Add to the tStart_ tree->add(startMotion); // Add their children to the queue: addChildrenToList(&motionQueue, startMotion); } } else { // Put all the starts into the tGoal_ structure and their children into the queue: // We do this so that start states are never pruned. for (auto &goalMotion : goalMotions_) { // Add to the tGoal_ tree->add(goalMotion); // Add their children to the queue: addChildrenToList(&motionQueue, goalMotion); } } while (motionQueue.empty() == false) { // Test, can the current motion ever provide a better solution? if (keepCondition(motionQueue.front(), pruneTreeCost, isTreeStart)) { // Yes it can, so it definitely won't be pruned // Add it back into the NN structure tree->add(motionQueue.front()); // Add it's children to the queue addChildrenToList(&motionQueue, motionQueue.front()); } else { // No it can't, but does it have children? if (motionQueue.front()->children.empty() == false) { // Yes it does. // We can minimize the number of intermediate chain motions if we check their children // If any of them won't be pruned, then this motion won't either. This intuitively seems // like a nice balance between following the descendents forever. // Variable // Whether the children are definitely to be kept. bool keepAChild = false; // Find if any child is definitely not being pruned. for (unsigned int i = 0u; keepAChild == false && i < motionQueue.front()->children.size(); ++i) { // Test if the child can ever provide a better solution keepAChild = keepCondition(motionQueue.front()->children.at(i), pruneTreeCost, isTreeStart); } // Are we *definitely* keeping any of the children? if (keepAChild) { // Yes, we are, so we are not pruning this motion // Add it back into the NN structure. tree->add(motionQueue.front()); } else { // No, we aren't. This doesn't mean we won't though // Move this Motion to the temporary list chainsToRecheck.push_back(motionQueue.front()); } // Either way. add it's children to the queue addChildrenToList(&motionQueue, motionQueue.front()); } else { // No, so we will be pruning this motion: leavesToPrune.push(motionQueue.front()); } } // Pop the iterator, std::list::erase returns the next iterator motionQueue.pop(); } // We now have a list of Motions to definitely remove, and a list of Motions to recheck // Iteratively check the two lists until there is nothing to to remove while (leavesToPrune.empty() == false) { // First empty the current leaves-to-prune while (leavesToPrune.empty() == false) { // If this leaf is a goal, remove it from the goal set if (leavesToPrune.front()->isConnectionPoint == true) { if(isTreeStart) { // Warn if pruning the _best_ goal if (leavesToPrune.front() == bestConnectionPoint_.first) { OMPL_ERROR("%s: Pruning the best connection point.", getName().c_str()); } // Remove it // Find the connection point to remove for(auto cp : connectionPoints_) { if(cp.first == leavesToPrune.front()) { cp.second->isConnectionPoint = false; connectionPoints_.erase(std::remove(connectionPoints_.begin(), connectionPoints_.end(), cp),connectionPoints_.end()); break; } } } else { // Warn if pruning the _best_ goal if (leavesToPrune.front() == bestConnectionPoint_.second) { OMPL_ERROR("%s: Pruning the best connection point.", getName().c_str()); } // Remove it // Find the connection point to remove for(auto cp : connectionPoints_) { if(cp.second == leavesToPrune.front()) { cp.first->isConnectionPoint = false; connectionPoints_.erase(std::remove(connectionPoints_.begin(), connectionPoints_.end(), cp),connectionPoints_.end()); break; } } } } // Remove the leaf from its parent removeFromParent(leavesToPrune.front()); // Erase the actual motion // First free the state si_->freeState(leavesToPrune.front()->state); // then delete the pointer delete leavesToPrune.front(); // And finally remove it from the list, erase returns the next iterator leavesToPrune.pop(); // Update our counter ++numPruned; } // Now, we need to go through the list of chain vertices and see if any are now leaves auto mIter = chainsToRecheck.begin(); while (mIter != chainsToRecheck.end()) { // Is the Motion a leaf? if ((*mIter)->children.empty() == true) { // It is, add to the removal queue leavesToPrune.push(*mIter); // Remove from this queue, getting the next mIter = chainsToRecheck.erase(mIter); } else { // Is isn't, skip to the next ++mIter; } } } // Now finally add back any vertices left in chainsToReheck. // These are chain vertices that have descendents that we want to keep for (const auto &r : chainsToRecheck) // Add the motion back to the NN struct: tree->add(r); // All done pruning. // Update the cost at which we've pruned: prunedCost_ = pruneTreeCost; // And if we're using the pruned measure, the measure to which we've pruned if (usePrunedMeasure_) { prunedMeasure_ = infSampler_->getInformedMeasure(prunedCost_); if (useKNearest_ == false) { calculateRewiringLowerBounds(); } } // No else, prunedMeasure_ is the si_ measure by default. return numPruned; } void ompl::geometric::RRTstarConnect::addChildrenToList(std::queue<Motion *, std::deque<Motion *>> *motionList, Motion *motion) { for (auto &child : motion->children) { motionList->push(child); } } bool ompl::geometric::RRTstarConnect::keepCondition(const Motion *motion, const base::Cost &threshold, bool isTreeStart) const { // We keep if the cost-to-come-heuristic of motion is <= threshold, by checking // if !(threshold < heuristic), as if b is not better than a, then a is better than, or equal to, b if (isTreeStart && bestConnectionPoint_.first && motion == bestConnectionPoint_.first) { // If the threshold is the theoretical minimum, bestConnectionPoint_ will sometimes fail the test due to floating point precision. Avoid that. return true; } else if (!isTreeStart && bestConnectionPoint_.second && motion == bestConnectionPoint_.second) { return true; } return !opt_->isCostBetterThan(threshold, solutionHeuristic(motion, isTreeStart)); } ompl::base::Cost ompl::geometric::RRTstarConnect::solutionHeuristic(const Motion *motion, bool isTreeStart) const { base::Cost costToCome = motion->cost; if (isTreeStart) { if (useAdmissibleCostToCome_) { // Start with infinite cost costToCome = opt_->infiniteCost(); // Find the min from each start for (auto &startMotion : startMotions_) { costToCome = opt_->betterCost( costToCome, opt_->motionCost(startMotion->state, motion->state)); // lower-bounding cost from the start to the state } } else { costToCome = motion->cost; // current cost from the state to the goal } const base::Cost costToGo = opt_->costToGo(motion->state, pdef_->getGoal().get()); // lower-bounding cost from the state to the goal return opt_->combineCosts(costToCome, costToGo); // add the two costs } else { // The tree is goal tree if (useAdmissibleCostToCome_) { // Start with infinite cost costToCome = opt_->infiniteCost(); // Find the min from each goal for (auto &goalMotion : goalMotions_) { costToCome = opt_->betterCost(costToCome, opt_->motionCost(motion->state, goalMotion->state)); // lower-bounding cost from the goal to the state } } else { costToCome = motion->cost; // current cost from the state to the goal } // Find the min from each start base::Cost costToGo = opt_->infiniteCost(); for (auto &startMotion : startMotions_) { costToGo = opt_->betterCost(costToGo, opt_->motionCost(motion->state, startMotion->state)); // lower-bounding cost from the start to the state } return opt_->combineCosts(costToCome, costToGo); // add the two costs } } void ompl::geometric::RRTstarConnect::setTreePruning(const bool prune) { if (static_cast<bool>(opt_) == true) { if (opt_->hasCostToGoHeuristic() == false) { OMPL_INFORM("%s: No cost-to-go heuristic set. Informed techniques will not work well.", getName().c_str()); } } // If we just disabled tree pruning, but we wee using prunedMeasure, we need to disable that as it required myself if (prune == false && getPrunedMeasure() == true) { setPrunedMeasure(false); } // Store useTreePruning_ = prune; } void ompl::geometric::RRTstarConnect::setPrunedMeasure(bool informedMeasure) { if (static_cast<bool>(opt_) == true) { if (opt_->hasCostToGoHeuristic() == false) { OMPL_INFORM("%s: No cost-to-go heuristic set. Informed techniques will not work well.", getName().c_str()); } } // This option only works with informed sampling if (informedMeasure == true && (useInformedSampling_ == false || useTreePruning_ == false)) { OMPL_ERROR("%s: InformedMeasure requires InformedSampling and TreePruning.", getName().c_str()); } // Check if we're changed and update parameters if we have: if (informedMeasure != usePrunedMeasure_) { // Store the setting usePrunedMeasure_ = informedMeasure; // Update the prunedMeasure_ appropriately, if it has been configured. if (setup_ == true) { if (usePrunedMeasure_) { prunedMeasure_ = infSampler_->getInformedMeasure(prunedCost_); } else { prunedMeasure_ = si_->getSpaceMeasure(); } } // And either way, update the rewiring radius if necessary if (useKNearest_ == false) { calculateRewiringLowerBounds(); } } } void ompl::geometric::RRTstarConnect::setInformedSampling(bool informedSampling) { if (static_cast<bool>(opt_) == true) { if (opt_->hasCostToGoHeuristic() == false) { OMPL_INFORM("%s: No cost-to-go heuristic set. Informed techniques will not work well.", getName().c_str()); } } // If we just disabled tree pruning, but we are using prunedMeasure, we need to disable that as it required myself if (informedSampling == false && getPrunedMeasure() == true) { setPrunedMeasure(false); } // Check if we're changing the setting of informed sampling. If we are, we will need to create a new sampler, which // we only want to do if one is already allocated. if (informedSampling != useInformedSampling_) { // If we're disabled informedSampling, and prunedMeasure is enabled, we need to disable that if (informedSampling == false && usePrunedMeasure_ == true) { setPrunedMeasure(false); } // Store the value useInformedSampling_ = informedSampling; // If we currently have a sampler, we need to make a new one if (sampler_ || infSampler_) { // Reset the samplers sampler_.reset(); infSampler_.reset(); // Create the sampler allocSampler(); } } } void ompl::geometric::RRTstarConnect::allocSampler() { // Allocate the appropriate type of sampler. if (useInformedSampling_) { // We are using informed sampling, this can end-up reverting to rejection sampling in some cases OMPL_INFORM("%s: Using informed sampling.", getName().c_str()); infSampler_ = opt_->allocInformedStateSampler(pdef_, numSampleAttempts_); } else { // We are using a regular sampler sampler_ = si_->allocStateSampler(); } // No else // We are using a regular sampler sampler_ = si_->allocStateSampler(); } bool ompl::geometric::RRTstarConnect::sampleUniform(base::State *statePtr) { // Use the appropriate sampler if (useInformedSampling_) { // Attempt the focused sampler and return the result. // If bestCost is changing a lot by small amounts, this could // be prunedCost_ to reduce the number of times the informed sampling // transforms are recalculated. return infSampler_->sampleUniform(statePtr, bestCost_); } else { // Simply return a state from the regular sampler sampler_->sampleUniform(statePtr); // Always true return true; } } void ompl::geometric::RRTstarConnect::calculateRewiringLowerBounds() { const auto dimDbl = static_cast<double>(si_->getStateDimension()); // k_rrt > 2^(d + 1) * e * (1 + 1 / d). K-nearest RRT* k_rrt_ = rewireFactor_ * (std::pow(2, dimDbl + 1) * boost::math::constants::e<double>() * (1.0 + 1.0 / dimDbl)); // r_rrt > (2*(1+1/d))^(1/d)*(measure/ballvolume)^(1/d) // If we're not using the informed measure, prunedMeasure_ will be set to si_->getSpaceMeasure(); r_rrt_ = rewireFactor_ * std::pow(2 * (1.0 + 1.0 / dimDbl) * (prunedMeasure_ / unitNBallMeasure(si_->getStateDimension())), 1.0 / dimDbl); }
34.310918
175
0.61461
[ "vector" ]
243b061e10d077daa7878caab7872b5b0dd8d63f
5,334
cpp
C++
src/tests/ascent/t_ascent_hola.cpp
xuanhuang1/ascent
2a919cc1b28cbc1994321bcee47632376c96e1bb
[ "BSD-3-Clause" ]
null
null
null
src/tests/ascent/t_ascent_hola.cpp
xuanhuang1/ascent
2a919cc1b28cbc1994321bcee47632376c96e1bb
[ "BSD-3-Clause" ]
null
null
null
src/tests/ascent/t_ascent_hola.cpp
xuanhuang1/ascent
2a919cc1b28cbc1994321bcee47632376c96e1bb
[ "BSD-3-Clause" ]
2
2018-02-28T14:15:23.000Z
2018-07-05T18:30:07.000Z
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC. // // Produced at the Lawrence Livermore National Laboratory // // LLNL-CODE-716457 // // All rights reserved. // // This file is part of Ascent. // // For details, see: http://ascent.readthedocs.io/. // // Please also read ascent/LICENSE // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the disclaimer below. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the disclaimer (as noted below) in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, // LLC, THE U.S. DEPARTMENT OF ENERGY 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. // //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// //----------------------------------------------------------------------------- /// /// file: t_ascent_hola.cpp /// //----------------------------------------------------------------------------- #include "gtest/gtest.h" #include <ascent.hpp> #include <ascent_hola.hpp> #include "t_config.hpp" #include "t_utils.hpp" using namespace std; using namespace conduit; using ascent::Ascent; //----------------------------------------------------------------------------- TEST(ascent_hola, test_hola_relay_blueprint_mesh) { // the vtkm runtime is currently our only rendering runtime Node n; ascent::about(n); // only run this test if ascent was built with vtkm support if(n["runtimes/ascent/vtkm/status"].as_string() == "disabled") { ASCENT_INFO("Ascent support disabled, skipping test"); return; } // // Create example data // Node data, verify_info; conduit::blueprint::mesh::examples::braid("hexs", 10, 10, 10, data); EXPECT_TRUE(conduit::blueprint::mesh::verify(data,verify_info)); int cycle = 101; data["state/cycle"] = cycle; // make sure the _output dir exists string output_path = prepare_output_dir(); string output_file = "tout_hola_relay_blueprint_mesh"; // // Create the actions to export the dataset // conduit::Node actions; // add the extracts conduit::Node &add_extract = actions.append(); add_extract["action"] = "add_extracts"; add_extract["extracts/e1/type"] = "relay"; add_extract["extracts/e1/params/path"] = output_file; add_extract["extracts/e1/params/protocol"] = "blueprint/mesh/hdf5"; // // Run Ascent // Ascent ascent; Node ascent_opts; ascent_opts["messages"] = "verbose"; ascent.open(ascent_opts); ascent.publish(data); ascent.execute(actions); ascent.close(); // use hola to say hello to the data gain Node hola_data, hola_opts; char cyc_fmt_buff[64]; snprintf(cyc_fmt_buff, sizeof(cyc_fmt_buff), "%06d",cycle); ostringstream oss; oss << output_file << ".cycle_" << cyc_fmt_buff << ".root"; std::string output_root = oss.str(); hola_opts["root_file"] = output_root; ascent::hola("relay/blueprint/mesh", hola_opts, hola_data); string output_image = conduit::utils::join_file_path(output_path, "tout_hola_bp_test_render"); // remove old image before rendering remove_test_image(output_image); Ascent ascent2; ascent2.open(ascent_opts); // // Create rendering actions. // actions.reset(); conduit::Node &add_scene = actions.append(); add_scene["action"] = "add_scenes"; add_scene["scenes/scene1/plots/plt1/type"] = "pseudocolor"; add_scene["scenes/scene1/plots/plt1/field"] = "braid"; add_scene["scenes/scene1/image_prefix"] = output_file; ascent2.publish(hola_data); ascent2.execute(actions); ascent2.close(); std::string msg = "An example of using hola with a blueprint hdf5 file"; ASCENT_ACTIONS_DUMP(actions,output_file, msg); }
32.925926
79
0.619423
[ "mesh" ]
243b164bd41b2cf1d8971d25681b36b95d10239b
3,544
cpp
C++
third_party/WebKit/Source/modules/worklet/WorkletGlobalScope.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
third_party/WebKit/Source/modules/worklet/WorkletGlobalScope.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/modules/worklet/WorkletGlobalScope.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "modules/worklet/WorkletGlobalScope.h" #include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/frame/FrameConsole.h" #include "core/inspector/InspectorInstrumentation.h" #include "core/inspector/MainThreadDebugger.h" namespace blink { WorkletGlobalScope::WorkletGlobalScope(LocalFrame* frame, const KURL& url, const String& userAgent, PassRefPtr<SecurityOrigin> securityOrigin, v8::Isolate* isolate) : MainThreadWorkletGlobalScope(frame) , m_url(url) , m_userAgent(userAgent) , m_scriptController(WorkerOrWorkletScriptController::create(this, isolate)) { setSecurityOrigin(securityOrigin); } WorkletGlobalScope::~WorkletGlobalScope() { } void WorkletGlobalScope::dispose() { stopActiveDOMObjects(); ASSERT(m_scriptController); m_scriptController->willScheduleExecutionTermination(); m_scriptController->dispose(); m_scriptController.clear(); } v8::Local<v8::Object> WorkletGlobalScope::wrap(v8::Isolate*, v8::Local<v8::Object> creationContext) { // WorkletGlobalScope must never be wrapped with wrap method. The global // object of ECMAScript environment is used as the wrapper. RELEASE_NOTREACHED(); return v8::Local<v8::Object>(); } v8::Local<v8::Object> WorkletGlobalScope::associateWithWrapper(v8::Isolate*, const WrapperTypeInfo*, v8::Local<v8::Object> wrapper) { RELEASE_NOTREACHED(); // Same as wrap method. return v8::Local<v8::Object>(); } void WorkletGlobalScope::disableEval(const String& errorMessage) { m_scriptController->disableEval(errorMessage); } bool WorkletGlobalScope::isSecureContext(String& errorMessage, const SecureContextCheck privilegeContextCheck) const { // Until there are APIs that are available in worklets and that // require a privileged context test that checks ancestors, just do // a simple check here. if (getSecurityOrigin()->isPotentiallyTrustworthy()) return true; errorMessage = getSecurityOrigin()->isPotentiallyTrustworthyErrorMessage(); return false; } void WorkletGlobalScope::reportBlockedScriptExecutionToInspector(const String& directiveText) { InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText); } void WorkletGlobalScope::addConsoleMessage(ConsoleMessage* consoleMessage) { frame()->console().addMessage(consoleMessage); } void WorkletGlobalScope::logExceptionToConsole(const String& errorMessage, int scriptId, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack) { ConsoleMessage* consoleMessage = ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, columnNumber); consoleMessage->setScriptId(scriptId); consoleMessage->setCallStack(callStack); addConsoleMessage(consoleMessage); } KURL WorkletGlobalScope::virtualCompleteURL(const String& url) const { // Always return a null URL when passed a null string. // TODO(ikilpatrick): Should we change the KURL constructor to have this // behavior? if (url.isNull()) return KURL(); // Always use UTF-8 in Worklets. return KURL(m_url, url); } DEFINE_TRACE(WorkletGlobalScope) { visitor->trace(m_scriptController); ExecutionContext::trace(visitor); SecurityContext::trace(visitor); MainThreadWorkletGlobalScope::trace(visitor); } } // namespace blink
33.752381
186
0.764673
[ "object" ]
243cc53c00418763f477b4afc80155d68d961ec1
1,312
cpp
C++
src/Motor.cpp
ScaredStorm/SpaceGame
136df0e173b07ebc3f6a0b7c2370edeb7c120af8
[ "MIT" ]
null
null
null
src/Motor.cpp
ScaredStorm/SpaceGame
136df0e173b07ebc3f6a0b7c2370edeb7c120af8
[ "MIT" ]
null
null
null
src/Motor.cpp
ScaredStorm/SpaceGame
136df0e173b07ebc3f6a0b7c2370edeb7c120af8
[ "MIT" ]
null
null
null
#include "Motor.h" Motor::Motor(int x, int y) : Machine(x, y) { _type = MOTOR_BASIC; info.name = "MOTOR"; info.maxEnergy = 0; info.maxEnergyGeneration = 15; info.maxEnergyUsage = 10; info.maxFuel = (12 * (_type+1))*5; info.maxFuelUsage = 5; _maxCyl = 12 * (_type+1); } Motor::Motor(int x, int y, MotorType type) : Machine(x, y) , _type(type) { info.name = "MOTOR"; info.maxEnergy = 0; info.maxEnergyGeneration = 15; info.maxEnergyUsage = 10; info.maxFuel = (12 * (_type+1))*5; info.maxFuelUsage = 5; _maxCyl = 12 * (_type+1); } Motor::~Motor() { } void Motor::update() { } void Motor::render(SDL_Renderer *renderer, TextureManager &manager, Camera &camera) { manager.renderTexture("Motor", Vector2(_x - camera.getX(), _y - camera.getY()), Vector2(32, 32), renderer); } void Motor::handleInput(SDL_Event &e, Camera &cam) { } /*int Motor::getEnergyUsage() const { return _maxEnergyUsage; } int Motor::getFuelUsage() const { return _maxFuelUsage; } */ int Motor::getCylCount() const { return _totalCyl; } int Motor::getMaxCylCount() const { return _maxCyl; } void Motor::increaseCylCount(int inc) { if(_totalCyl < _maxCyl) _totalCyl++; } void Motor::decreaseCylCount(int dec) { if(_totalCyl > 0) _totalCyl--; }
15.807229
111
0.641006
[ "render" ]
24461419dc62c517244c421d390bbac17c0af6d9
10,975
hpp
C++
src/sdl1/SDLGraphics.hpp
LibreSprite/Dotto
3d057875fd0e33d2a72add44c316af9fdc5be7c8
[ "MIT" ]
151
2021-12-28T21:22:42.000Z
2022-03-30T13:53:28.000Z
src/sdl1/SDLGraphics.hpp
LibreSprite/Dotto
3d057875fd0e33d2a72add44c316af9fdc5be7c8
[ "MIT" ]
9
2021-12-29T13:20:00.000Z
2022-03-18T12:47:19.000Z
src/sdl1/SDLGraphics.hpp
Linux-Gamer/Dotto
ed722f0bbcbcb230b7c40977a5552cba81e5075d
[ "MIT" ]
18
2021-12-28T19:58:49.000Z
2022-03-31T16:38:14.000Z
// Copyright (c) 2021 LibreSprite Authors (cf. AUTHORS.md) // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #pragma once #include <SDL/SDL.h> #include <SDL/SDL_video.h> #include <common/match.hpp> #include <common/Rect.hpp> #include <common/Surface.hpp> #include <cstdint> #include <gui/Graphics.hpp> #include <gui/Texture.hpp> #include <log/Log.hpp> extern int SDL_SoftStretchAlpha(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect, SDL_Color *multiply); extern int SDL_BlitSurfaceMul(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect, SDL_Color *multiply); extern void SDL_FillRectAlpha(SDL_Surface *src, SDL_Rect *rect, SDL_Color *color, Uint8 a); class SDLTextureInfo : public Texture, public TextureInfo { public: SDL_Surface* surface = nullptr; U32 width = 0; U32 height = 0; F32 iwidth = 0; F32 iheight = 0; Rect dirtyRegion{0, 0, ~U32{}, ~U32{}}; void setDirty(const Rect& region) override { dirtyRegion.expand(region); } ~SDLTextureInfo() { if (surface) SDL_FreeSurface(surface); } }; class SDLGraphics : public Graphics, public std::enable_shared_from_this<SDLGraphics> { public: F32 iwidth, iheight; S32 width, height; SDL_Surface* screen; std::shared_ptr<SDLTextureInfo> activeTexture; SDLGraphics(SDL_Surface* screen) : screen{screen} {} void begin(Rect& globalRect, Color& clearColor) { clip = globalRect; width = globalRect.width; iwidth = 2.0f / width; height = globalRect.height; iheight = 2.0f / height; SDL_FillRect(screen, nullptr, SDL_MapRGBA(screen->format, clearColor.r, clearColor.g, clearColor.b, clearColor.a)); } void upload(Surface& surface, SDLTextureInfo* texture) { texture->dirtyRegion = Rect{}; if (texture->surface) { if (texture->surface->w != surface.width() || texture->surface->h != surface.height()) { SDL_FreeSurface(texture->surface); texture->surface = nullptr; } } if (!texture->surface) { texture->surface = SDL_CreateRGBSurfaceFrom(surface.data(), surface.width(), surface.height(), 32, surface.width() * sizeof(Surface::PixelType), 0xFF << Color::Rshift, 0xFF << Color::Gshift, 0xFF << Color::Bshift, 0xFF << Color::Ashift); } else { auto out = (Surface::PixelType*) texture->surface->pixels; auto in = surface.data(); for (U32 i=0, size = surface.width() * surface.height(); i < size; ++i) out[i] = in[i]; } texture->width = surface.width(); texture->iwidth = 1.0f / texture->width; texture->height = surface.height(); texture->iheight = 1.0f / texture->height; } struct Rectf { F32 x, y, w, h; F32 u0, v0, u1, v1; U8 r, g, b, a; bool flip; }; bool debug = false; void push(F32 z, const Rectf& rect) { F32 x1 = rect.x, y1 = rect.y, x2 = rect.x + rect.w, y2 = rect.y + rect.h, u0 = rect.u0, v0 = rect.v0, u1 = rect.u1, v1 = rect.v1; if (x1 >= clip.right() || x2 <= clip.x || y1 >= clip.bottom() || y2 <= clip.y) { if (debug) logI("Texture clipped away"); return; } if (x1 < clip.x) { if (rect.w) { u0 += (clip.x - x1) / rect.w; } x1 = clip.x; } if (x2 > clip.right()) { if (rect.w) { u1 -= (x2 - clip.right()) / rect.w; } x2 = clip.right(); } if (y1 < clip.y) { if (rect.h) { v0 += (clip.y - y1) / rect.h; } y1 = clip.y; } if (y2 > clip.bottom()) { if (rect.h) { v1 -= (y2 - clip.bottom()) / rect.h; } y2 = clip.bottom(); } if (debug) logI("Pushing ", x1, " ", y1, " => ", x2, " ", y2); // push({x1, y1, z, u0, v0, rect.r, rect.g, rect.b, rect.a, rect.flip}); // push({x1, y2, z, u0, v1, rect.r, rect.g, rect.b, rect.a, rect.flip}); // push({x2, y1, z, u1, v0, rect.r, rect.g, rect.b, rect.a, rect.flip}); // push({x1, y2, z, u0, v1, rect.r, rect.g, rect.b, rect.a, rect.flip}); // push({x2, y2, z, u1, v1, rect.r, rect.g, rect.b, rect.a, rect.flip}); // push({x2, y1, z, u1, v0, rect.r, rect.g, rect.b, rect.a, rect.flip}); SDL_Rect dest; dest.x = x1; dest.y = y1; dest.w = x2 - x1; dest.h = y2 - y1; if (activeTexture) { SDL_Rect src; src.x = u0 * activeTexture->width; src.y = v0 * activeTexture->height; src.w = (u1 - u0) * activeTexture->width; src.h = (v1 - v0) * activeTexture->height; if (src.h && src.w) { SDL_Color mul{ rect.r, rect.g, rect.b, rect.a }; SDL_Color* mulp = (rect.r != 0xFF || rect.g != 0xFF || rect.b != 0xFF || rect.a != 0xFF) ? &mul : nullptr; if (dest.w != src.w || dest.h != src.h) { SDL_SoftStretchAlpha(activeTexture->surface, &src, screen, &dest, mulp); } else if (mulp) { SDL_BlitSurfaceMul(activeTexture->surface, &src, screen, &dest, mulp); } else { SDL_BlitSurface(activeTexture->surface, &src, screen, &dest); } } } else { if (rect.a != 0xFF) { SDL_Color color{rect.r, rect.g, rect.b}; SDL_FillRectAlpha(screen, &dest, &color, rect.a); } else { SDL_FillRect(screen, &dest, SDL_MapRGB(screen->format, rect.r, rect.g, rect.b)); } } } void push(std::shared_ptr<SDLTextureInfo>& texture, const BlitSettings& settings) { debug = settings.debug; F32 x = settings.destination.x; F32 y = settings.destination.y; F32 z = settings.zIndex; F32 w = settings.destination.width; F32 h = settings.destination.height; U8 r = settings.multiply.r; U8 g = settings.multiply.g; U8 b = settings.multiply.b; U8 a = settings.multiply.a * alpha; if (a <= 0) return; if (!clip.overlaps(settings.destination)) { if (debug) logI("Killed by the clip"); return; } activeTexture = texture; F32 sW = settings.nineSlice.width; F32 sH = settings.nineSlice.height; S32 textureWidth = texture ? texture->width : 1; S32 textureHeight = texture ? texture->height : 1; F32 textureIwidth = texture ? texture->iwidth : 1; F32 textureIheight = texture ? texture->iheight : 1; if (sW == 0 && settings.nineSlice.x != 0) sW = textureWidth - settings.nineSlice.x * 2; if (sH == 0 && settings.nineSlice.y != 0) sH = textureHeight - settings.nineSlice.y * 2; if (sW <= 0 || sH <= 0) { push(z, { x, y, w, h, settings.source.x / F32(textureWidth), settings.source.y / F32(textureHeight), settings.source.right() / F32(textureWidth), settings.source.bottom() / F32(textureHeight), r, g, b, a, settings.flip }); } else { F32 sX = settings.nineSlice.x; F32 sY = settings.nineSlice.y; F32 nsX = sX * textureIwidth; F32 nsY = sY * textureIheight; F32 nsW = sW * textureIwidth; F32 nsH = sH * textureIheight; F32 rW = textureWidth - sW - sX; F32 rH = textureHeight - sH - sY; push(z, {x, y, sX, sY, 0.0f, 0.0f, nsX, nsY, r, g, b, a}); push(z, {x + sX, y, w - sX - rW, sY, nsX, 0.0f, nsX + nsW, nsY, r, g, b, a}); push(z, {x + w - rW, y, rW, sY, nsX + nsW, 0.0f, 1.0f, nsY, r, g, b, a}); y += sY; push(z, {x, y, sX, h-sY-rH, 0.0f, nsY, nsX, nsY + nsH, r, g, b, a}); push(z, {x + sX, y, w-sX-rW, h-sY-rH, nsX, nsY, nsX + nsW, nsY + nsH, r, g, b, a}); push(z, {x + w-rW, y, rW, h-sY-rH, nsX + nsW, nsY, 1.0f, nsY + nsH, r, g, b, a}); y += h - sY - rH; push(z, {x, y, sX, rH, 0.0f, nsY + nsH, nsX, 1.0f, r, g, b, a}); push(z, {x + sX, y, w - sX - rW, rH, nsX, nsY + nsH, nsX + nsW, 1.0f, r, g, b, a}); push(z, {x + w - rW, y, rW, rH, nsX + nsW, nsY + nsH, 1.0f, 1.0f, r, g, b, a}); } } Vector<fork_ptr<Texture>> textures; std::shared_ptr<SDLTextureInfo> getTexture(Surface& surface) { auto texture = surface.info().get<SDLTextureInfo>(this); if (!texture) { texture = std::make_shared<SDLTextureInfo>(); fork_ptr<Texture> ptr{std::static_pointer_cast<Texture>(texture)}; textures.push_back(ptr); surface.info().set(this, std::move(ptr)); } return texture; } void blit(const BlitSettings& settings) override { std::shared_ptr<SDLTextureInfo> texture; if (settings.surface) { auto& surface = *settings.surface; texture = getTexture(surface); if (!texture->dirtyRegion.empty()) { if (settings.debug) logI("Uploading surface"); upload(surface, texture.get()); } } else if (settings.multiply.a == 0) { return; // no texture + no color = no op } push(texture, settings); } Rect pushClipRect(const Rect& rect) override { auto copy = clip; clip.intersect(rect); return copy; } void setClipRect(const Rect& rect) override { clip = rect; } Surface* read() override { return nullptr; } void write() override { } };
34.190031
127
0.478178
[ "vector" ]
244c7d8e7ac320c2815100ea541fb876b3f34ce0
322
cpp
C++
26_Remove_Duplicates_From_Sorted_Array/solution.cpp
bkbowie/LeetCode
65a7e7eb16e68a2f5de1a85aa62e8235ff8fce21
[ "MIT" ]
null
null
null
26_Remove_Duplicates_From_Sorted_Array/solution.cpp
bkbowie/LeetCode
65a7e7eb16e68a2f5de1a85aa62e8235ff8fce21
[ "MIT" ]
null
null
null
26_Remove_Duplicates_From_Sorted_Array/solution.cpp
bkbowie/LeetCode
65a7e7eb16e68a2f5de1a85aa62e8235ff8fce21
[ "MIT" ]
null
null
null
class Solution { Public: int removeDuplicates(vector<int>& nums) { if ( nums.empty() ) return 0; int index = 0; for (int i = 0;i < nums.size();i++) { if (nums[index] != nums[i]) { nums[++index] = nums[i]; } } return index + 1; } };
20.125
45
0.428571
[ "vector" ]
244e1d009c4e5db14001308f72c9f576088d646d
1,595
hpp
C++
src/index/chm/Neighbors.hpp
Matej-Chmel/approximate-knn
4d29dc285f50fcdce1c3052472959f789c46cc70
[ "MIT" ]
null
null
null
src/index/chm/Neighbors.hpp
Matej-Chmel/approximate-knn
4d29dc285f50fcdce1c3052472959f789c46cc70
[ "MIT" ]
null
null
null
src/index/chm/Neighbors.hpp
Matej-Chmel/approximate-knn
4d29dc285f50fcdce1c3052472959f789c46cc70
[ "MIT" ]
null
null
null
#pragma once #include "Heap.hpp" namespace chm { /** * Seznam sousedů. */ class Neighbors { /** * Ukazatel na začátek seznamu. */ std::vector<uint>::iterator beginIter; /** * Ukazatel na buňku s počtem sousedů. */ std::vector<uint>::iterator count; /** * Ukazatel na konec seznamu. */ std::vector<uint>::iterator endIter; public: /** * Vrátí konstantní iterátor @ref beginIter. * @return Konstantní iterátor @ref beginIter. */ std::vector<uint>::const_iterator begin() const; /** * Vymaže seznam sousedů. */ void clear(); /** * Vrátí konstantní iterátor @ref endIter. * @return Konstantní iterátor @ref endIter. */ std::vector<uint>::const_iterator end() const; /** * Přidá vrcholy z haldy do seznamu. * @param[in] h Halda. */ void fillFrom(const FarHeap& h); /** * Přidá vrcholy z haldy do seznamu a uloží nejbližší vrchol ke zkoumanému prvku z haldy. * @param[in] h Halda. * @param[out] nearest Nejbližší vrchol. */ void fillFrom(const FarHeap& h, Node& nearest); /** * Vrátí identitu souseda na pozici @p i. * @param[in] i Pozice souseda. * @return Identita souseda. */ uint get(const size_t i) const; /** * Vrátí počet sousedů v seznamu. * @return Počet sousedů. */ uint len() const; /** * Konstruktor. * @param[in] count Ukazatel na buňku s počtem sousedů v seznamu. */ Neighbors(const std::vector<uint>::iterator& count); /** * Přidá souseda do seznamu. * @param[in] id Identita nového souseda. */ void push(const uint id); }; }
22.464789
91
0.628213
[ "vector" ]
244f369e10ee1034f9ee544fee63c27d3abdb295
2,135
cpp
C++
HDUOJ/4699/stack_dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
HDUOJ/4699/stack_dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
HDUOJ/4699/stack_dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <string> #include <cstring> #include <iomanip> #include <climits> #include <stack> #include <queue> #include <vector> #include <set> #include <map> #include <functional> #include <iterator> using namespace std; #define SIZE 1000010 long long int suffixSum[SIZE]; long long int dp[SIZE]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int qNum; while (cin >> qNum) { stack<int> leftStk, rightStk; suffixSum[0] = 0; dp[0] = INT_MIN; while (qNum--) { char opr; cin >> opr; if (opr == 'I') { // insert int val; cin >> val; leftStk.push(val); suffixSum[leftStk.size()] = suffixSum[leftStk.size() - 1] + val; dp[leftStk.size()] = max(dp[leftStk.size() - 1], suffixSum[leftStk.size()]); } else if (opr == 'D') { // delete if (leftStk.empty()) continue; leftStk.pop(); } else if (opr == 'L') { // move left if (leftStk.empty()) continue; int cnt = leftStk.top(); leftStk.pop(); rightStk.push(cnt); } else if (opr == 'R') { // move right if (rightStk.empty()) continue; int cnt = rightStk.top(); rightStk.pop(); leftStk.push(cnt); suffixSum[leftStk.size()] = suffixSum[leftStk.size() - 1] + cnt; dp[leftStk.size()] = max(dp[leftStk.size() - 1], suffixSum[leftStk.size()]); } else if (opr == 'Q') { // query max prefix sum int pos; cin >> pos; cout << dp[pos] << endl; } } } return 0; }
23.461538
92
0.422951
[ "vector" ]
2461cbae5e5d39f72d0d32483f821522b36a20db
1,882
cpp
C++
test/unit/math/rev/mat/fun/log_determinant_ldlt_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
test/unit/math/rev/mat/fun/log_determinant_ldlt_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
test/unit/math/rev/mat/fun/log_determinant_ldlt_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/rev/mat.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/mat/fun/util.hpp> #include <test/unit/math/rev/mat/util.hpp> #include <vector> TEST(AgradRevMatrix, log_determinant_ldlt_diff) { using stan::math::determinant; using stan::math::fabs; using stan::math::log; using stan::math::matrix_v; // expected from auto-diff/Eigen AVEC x1 = createAVEC(2, 1, 1, 3); matrix_v v1(2, 2); v1 << x1[0], x1[1], x1[2], x1[3]; AVAR det1 = log(fabs(v1.determinant())); std::vector<double> g1; det1.grad(x1, g1); stan::math::LDLT_factor<stan::math::var, -1, -1> ldlt_v; AVEC x2 = createAVEC(2, 1, 1, 3); matrix_v v2(2, 2); v2 << x2[0], x2[1], x2[2], x2[3]; ldlt_v.compute(v2); ASSERT_TRUE(ldlt_v.success()); AVAR det2 = log_determinant_ldlt(ldlt_v); std::vector<double> g2; det2.grad(x2, g2); EXPECT_FLOAT_EQ(det1.val(), det2.val()); EXPECT_EQ(g1.size(), g2.size()); for (size_t i = 0; i < g1.size(); ++i) EXPECT_FLOAT_EQ(g1[i], g2[i]); } TEST(AgradRevMatrix, log_determinant_ldlt) { using stan::math::matrix_v; stan::math::LDLT_factor<stan::math::var, -1, -1> ldlt_v; matrix_v v(2, 2); v << 1, 0, 0, 3; ldlt_v.compute(v); ASSERT_TRUE(ldlt_v.success()); AVAR f; AVEC v_vec = createAVEC(v(0, 0), v(0, 1), v(1, 0), v(1, 1)); VEC grad; f = log_determinant_ldlt(ldlt_v); f.grad(v_vec, grad); // derivative is: 1/det(A) * adj(A) EXPECT_FLOAT_EQ(std::log(3.0), f.val()); ASSERT_EQ(4U, grad.size()); EXPECT_FLOAT_EQ(1.0, grad[0]); EXPECT_FLOAT_EQ(0, grad[1]); EXPECT_FLOAT_EQ(0, grad[2]); EXPECT_FLOAT_EQ(1.0 / 3.0, grad[3]); } TEST(AgradRevMatrix, check_varis_on_stack) { stan::math::matrix_v v2(2, 2); v2 << 2, 1, 1, 3; stan::math::LDLT_factor<stan::math::var, -1, -1> ldlt_v; ldlt_v.compute(v2); test::check_varis_on_stack(stan::math::log_determinant_ldlt(ldlt_v)); }
27.676471
71
0.643996
[ "vector" ]
246ef9147f8198ea9f3e635e656fc2141b225f03
3,400
cpp
C++
Grip or Slip/Motor2D/j1SceneChange.cpp
DavidTello1/Development
c12abdc8902ea87f1139174945fc4109a7c77313
[ "MIT" ]
null
null
null
Grip or Slip/Motor2D/j1SceneChange.cpp
DavidTello1/Development
c12abdc8902ea87f1139174945fc4109a7c77313
[ "MIT" ]
null
null
null
Grip or Slip/Motor2D/j1SceneChange.cpp
DavidTello1/Development
c12abdc8902ea87f1139174945fc4109a7c77313
[ "MIT" ]
null
null
null
#include "p2Log.h" #include "j1App.h" #include "j1SceneChange.h" #include "j1Render.h" #include "j1Scene.h" #include "j1Window.h" #include "j1EntityController.h" #include "j1Player.h" #include "j1Map.h" #include "j1Gui.h" #include "Brofiler\Brofiler.h" #include <math.h> #include "SDL\include\SDL_render.h" j1SceneChange::j1SceneChange() { name.create("scenechange"); } j1SceneChange::~j1SceneChange() {} bool j1SceneChange::Awake(pugi::xml_node&) { LOG("SceneChange Awake"); bool ret = true; screen = { 0, 0, App->win->width*App->win->scale, App->win->height*App->win->scale }; return ret; } bool j1SceneChange::Start() { LOG("SceneChange Start"); SDL_SetRenderDrawBlendMode(App->render->renderer, SDL_BLENDMODE_BLEND); return true; } bool j1SceneChange::Update(float dt) { BROFILER_CATEGORY("SceneChange Update", Profiler::Color::Red); if (current_step == fade_step::none) { return true; } uint now = SDL_GetTicks() - start_time; float normalized = 1.0f < ((float)now / (float)total_time) ? 1.0f : ((float)now / (float)total_time); switch (current_step) { case fade_step::fade_to_black: { if (map == true) { if (now >= total_time) //screen->black & map->loaded { App->scene->currentMap = nextMap; LOG("%i", App->scene->currentMap); App->map->SwitchMaps(App->scene->map_names[nextMap]); App->entitycontroller->PlayerRestart(); total_time += total_time; start_time = SDL_GetTicks(); fading = false; current_step = fade_step::fade_from_black; } } else if (scene == true) { if (switchtimer.ReadSec() >= fadetime) { to_disable->Disable(); App->gui->CleanUp(); App->map->CleanUp(); App->entitycontroller->DeleteEntities(); if (to_disable == App->scene) { App->entitycontroller->Disable(); } App->gui->Start(); to_enable->Enable(); if (to_enable == App->scene) { App->entitycontroller->Enable(); } switchtimer.Start(); if (App->scenechange->ContinueGame) { App->LoadGame(); } current_step = fade_step::fade_from_black; } } }break; case fade_step::fade_from_black: { normalized = 1.0f - normalized; if (map == true) { if (now >= total_time) { current_step = fade_step::none; map = false; } } else if (scene == true) { if (switchtimer.ReadSec() >= fadetime) { current_step = fade_step::none; scene = false; } } }break; } SDL_SetRenderDrawColor(App->render->renderer, 0, 0, 0, (Uint8)(normalized * 255.0f)); SDL_RenderFillRect(App->render->renderer, &screen); return true; } bool j1SceneChange::ChangeMap(int newMap, float time) { bool ret = false; nextMap = newMap; map = true; if (current_step == fade_step::none) { current_step = fade_step::fade_to_black; start_time = SDL_GetTicks(); total_time = (Uint32)(time*0.5f*1000.0f); fading = true; ret = true; } return ret; } bool j1SceneChange::IsChanging() const { return current_step != fade_step::none; } bool j1SceneChange::SwitchScene(j1Module* SceneIn, j1Module* SceneOut) { bool ret = false; scene = true; if (current_step == fade_step::none) { current_step = fade_step::fade_to_black; switchtimer.Start(); to_enable = SceneIn; to_disable = SceneOut; ret = true; } return true; } bool j1SceneChange::IsSwitching() const { return (current_step != fade_step::none); }
18.888889
102
0.656176
[ "render" ]
247ae84cd7812999d14bdee043d06ad7519f4353
1,064
cpp
C++
leetcode/binary_search/peak_index.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
leetcode/binary_search/peak_index.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
leetcode/binary_search/peak_index.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
#include <doctest/doctest.h> #include <climits> #include <vector> // 852. Peak Index in a Mountain Array class Solution { public: int peakIndexInMountainArray(const std::vector<int>& A) { int left = 0; int right = A.size() - 1; while (left < right) { size_t mid = left + (right - left) / 2; auto v_l = mid > 0 ? A[mid - 1] : INT_MIN; auto v_r = mid < A.size() - 1 ? A[mid + 1] : INT_MIN; if (A[mid] > v_l && A[mid] > v_r) { return mid; } else if (A[mid] < v_l) { right = mid - 1; } else { left = mid + 1; } } return left; } }; TEST_CASE("Peak index") { Solution s; REQUIRE_EQ(s.peakIndexInMountainArray({0, 1, 0}), 1); REQUIRE_EQ(s.peakIndexInMountainArray({0, 2, 1, 0}), 1); REQUIRE_EQ(s.peakIndexInMountainArray({0, 1, 2, 0}), 2); REQUIRE_EQ(s.peakIndexInMountainArray({0, 1, 2, 1, 0}), 2); REQUIRE_EQ(s.peakIndexInMountainArray({0, 1, 2}), 2); REQUIRE_EQ(s.peakIndexInMountainArray({2, 1, 0}), 0); REQUIRE_EQ(s.peakIndexInMountainArray({1, 2}), 1); }
28
61
0.585526
[ "vector" ]
247c0836c0ccf4d5c382f007135d9e33cc3ae1dc
1,224
cpp
C++
src/vector.cpp
ebayboy/cpp_demos
b01df202c0285bf232900662d336505520d5d24d
[ "Apache-2.0" ]
null
null
null
src/vector.cpp
ebayboy/cpp_demos
b01df202c0285bf232900662d336505520d5d24d
[ "Apache-2.0" ]
null
null
null
src/vector.cpp
ebayboy/cpp_demos
b01df202c0285bf232900662d336505520d5d24d
[ "Apache-2.0" ]
null
null
null
/* vector usage */ #include <iostream> #include <vector> using namespace std; static void show_arr(vector <int> & arr) { int j; cout << "func:" << __func__ << endl; for (int j = 0; j < arr.size(); j++) { cout << arr[j] << endl; } cout << endl; } static void show_arr_with_it(vector <int> & arr) { cout << "func:" << __func__ << endl; vector <int>::iterator it; for (it = arr.begin(); it != arr.end(); it++) { cout << "*it: " << *it << endl; } cout << endl; } int main() { int a[4] = {1,2,3,4}; vector <int> arr; /* 0. ����Ԫ�ص����� */ for (int i = 0; i < sizeof(a)/sizeof(int); i++) { arr.push_back(a[i]); } /* 1. ͨ���±�ɾ��Ԫ�� */ for (int j = 0; j < arr.size(); j++) { if (arr[j] == 2) { cout << "del:" << arr[j] << endl; arr.erase(arr.begin() + j); break; } cout << arr[j] << endl; } /* 2. ͨ���±�չʾ */ show_arr(arr); /* 3. ͨ��������ɾ�� */ vector <int>::iterator it; for (it = arr.begin(); it != arr.end(); it++) { if (*it == 3) { arr.erase(it); } } /* 4. ͨ��������չʾ */ show_arr_with_it(arr); /* 5. insert 5 */ for (int i = 0; i < arr.size(); i++) { if (arr[i] == 1) { arr.insert(arr.begin() + i, 5); } } show_arr_with_it(arr); return 0; }
16.32
50
0.478758
[ "vector" ]
247c12cec55d46869db11e3a7354022812197aa3
832
cpp
C++
contest-1004-495/c-v3-cpp/main.cpp
easimonenko/solution-problems-from-codeforces
64251e0ba2c2ba619b0daf67f89f29b6dff8fd9f
[ "MIT" ]
1
2018-12-03T02:06:05.000Z
2018-12-03T02:06:05.000Z
contest-1004-495/c-v3-cpp/main.cpp
easimonenko/solution-problems-from-codeforces
64251e0ba2c2ba619b0daf67f89f29b6dff8fd9f
[ "MIT" ]
null
null
null
contest-1004-495/c-v3-cpp/main.cpp
easimonenko/solution-problems-from-codeforces
64251e0ba2c2ba619b0daf67f89f29b6dff8fd9f
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <set> #include <vector> using namespace std; void printv(vector<int> & v) { cout << v[0]; for_each(v.begin() + 1, v.end(), [](auto elem) { cout << ' ' << elem; }); cout << endl; } int main() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } long long ans = 0; vector<int> dp(n); set<int> r; dp[n - 1] = 1; r.insert(a[n - 1]); for (int i = n - 2; i >= 0; i--) { if (r.find(a[i]) != r.end()) { dp[i] = dp[i + 1]; } else { dp[i] = dp[i + 1] + 1; r.insert(a[i]); } } //printv(dp); set<int> l; for (int i = 0; i < n - 1; i++) { if (l.find(a[i]) == l.end()) { ans += dp[i + 1]; l.insert(a[i]); } } cout << ans << endl; return 0; }
15.407407
50
0.426683
[ "vector" ]
248091b15ca18bd992d43d804c14dbed940e1128
16,834
cc
C++
src/pb_tensor.cc
nskool/python_backend
2b98842559055b4d2837dd972e2392683c846079
[ "BSD-3-Clause" ]
null
null
null
src/pb_tensor.cc
nskool/python_backend
2b98842559055b4d2837dd972e2392683c846079
[ "BSD-3-Clause" ]
null
null
null
src/pb_tensor.cc
nskool/python_backend
2b98842559055b4d2837dd972e2392683c846079
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021-2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef TRITON_ENABLE_GPU #include <cuda.h> #endif // TRITON_ENABLE_GPU #ifdef TRITON_PB_STUB #include "pb_stub_utils.h" namespace py = pybind11; #endif #include "pb_tensor.h" namespace triton { namespace backend { namespace python { #ifdef TRITON_PB_STUB PbTensor::PbTensor(const std::string& name, py::array& numpy_array) : name_(name) { if (name == "") { throw PythonBackendException("Tensor name cannot be an empty string."); } dtype_ = numpy_to_triton_type(numpy_array.attr("dtype")); memory_type_ = TRITONSERVER_MEMORY_CPU; memory_type_id_ = 0; dl_managed_tensor_ = nullptr; bool is_contiguous = numpy_array.attr("data").attr("c_contiguous").cast<bool>(); if (!is_contiguous) { py::module numpy = py::module::import("numpy"); numpy_array = numpy.attr("ascontiguousarray")(numpy_array); } numpy_array_ = numpy_array; if (dtype_ == TRITONSERVER_TYPE_BYTES) { py::module triton_pb_utils = py::module::import("triton_python_backend_utils"); numpy_array_serialized_ = triton_pb_utils.attr("serialize_byte_tensor")(numpy_array); memory_ptr_ = numpy_array_serialized_.request().ptr; byte_size_ = numpy_array_serialized_.nbytes(); } else { memory_ptr_ = numpy_array_.request().ptr; byte_size_ = numpy_array_.nbytes(); } // Initialize tensor dimension size_t dims_count = numpy_array_.ndim(); const ssize_t* numpy_shape = numpy_array_.shape(); for (size_t i = 0; i < dims_count; i++) { dims_.push_back(numpy_shape[i]); } } PbTensor::PbTensor( const std::string& name, py::array& numpy_array, TRITONSERVER_DataType dtype) : name_(name) { if (name == "") { throw PythonBackendException("Tensor name cannot be an empty string."); } if (numpy_to_triton_type(numpy_array.attr("dtype")) != dtype) { numpy_array = numpy_array.attr("view")(triton_to_numpy_type(dtype)); } bool is_contiguous = numpy_array.attr("data").attr("c_contiguous").cast<bool>(); if (!is_contiguous) { py::module numpy = py::module::import("numpy"); numpy_array = numpy.attr("ascontiguousarray")(numpy_array); } numpy_array_ = numpy_array; if (dtype == TRITONSERVER_TYPE_BYTES) { py::module triton_pb_utils = py::module::import("triton_python_backend_utils"); numpy_array_serialized_ = triton_pb_utils.attr("serialize_byte_tensor")(numpy_array); memory_ptr_ = numpy_array_serialized_.request().ptr; byte_size_ = numpy_array_serialized_.nbytes(); } else { memory_ptr_ = numpy_array_.request().ptr; byte_size_ = numpy_array_.nbytes(); } memory_type_ = TRITONSERVER_MEMORY_CPU; dtype_ = dtype; // Initialize tensor dimension size_t dims_count = numpy_array_.ndim(); const ssize_t* numpy_shape = numpy_array_.shape(); for (size_t i = 0; i < dims_count; i++) { dims_.push_back(numpy_shape[i]); } memory_type_id_ = 0; dl_managed_tensor_ = nullptr; } #endif // TRITON_PB_STUB PbTensor::PbTensor( const std::string& name, const std::vector<int64_t>& dims, TRITONSERVER_DataType dtype, TRITONSERVER_MemoryType memory_type, int64_t memory_type_id, void* memory_ptr, uint64_t byte_size, DLManagedTensor* dl_managed_tensor) { if (name == "") { throw PythonBackendException("Tensor name cannot be an empty string."); } name_ = name; memory_ptr_ = memory_ptr; memory_type_ = memory_type; memory_type_id_ = memory_type_id; dtype_ = dtype; dims_ = dims; #ifdef TRITON_PB_STUB if (memory_type_ == TRITONSERVER_MEMORY_CPU || memory_type_ == TRITONSERVER_MEMORY_CPU_PINNED) { if (dtype != TRITONSERVER_TYPE_BYTES) { py::object numpy_array = py::array(triton_to_pybind_dtype(dtype_), dims_, (void*)memory_ptr_); numpy_array_ = numpy_array.attr("view")(triton_to_numpy_type(dtype_)); } else { py::object numpy_array = py::array( triton_to_pybind_dtype(TRITONSERVER_TYPE_UINT8), {byte_size}, (void*)memory_ptr_); py::module triton_pb_utils = py::module::import("triton_python_backend_utils"); numpy_array_ = triton_pb_utils.attr("deserialize_bytes_tensor")(numpy_array) .attr("reshape")(dims); } } else { numpy_array_ = py::none(); } #endif byte_size_ = byte_size; dl_managed_tensor_ = dl_managed_tensor; } bool PbTensor::IsCPU() const { if (memory_type_ == TRITONSERVER_MEMORY_CPU || memory_type_ == TRITONSERVER_MEMORY_CPU_PINNED) { return true; } else { return false; } } TRITONSERVER_MemoryType PbTensor::MemoryType() const { return memory_type_; } int64_t PbTensor::MemoryTypeId() const { return memory_type_id_; } uint64_t PbTensor::ByteSize() const { return byte_size_; } const std::vector<int64_t>& PbTensor::Dims() const { return dims_; } void PbTensor::SetMemory(std::unique_ptr<PbMemory>&& memory) { pb_memory_ = std::move(memory); memory_type_ = pb_memory_->MemoryType(); memory_type_id_ = pb_memory_->MemoryTypeId(); byte_size_ = pb_memory_->ByteSize(); memory_ptr_ = pb_memory_->DataPtr(); } #ifdef TRITON_PB_STUB void delete_unused_dltensor(PyObject* dlp) { if (PyCapsule_IsValid(dlp, "dltensor")) { DLManagedTensor* dl_managed_tensor = static_cast<DLManagedTensor*>(PyCapsule_GetPointer(dlp, "dltensor")); dl_managed_tensor->deleter(dl_managed_tensor); } } std::shared_ptr<PbTensor> PbTensor::FromNumpy(const std::string& name, py::array& numpy_array) { return std::make_shared<PbTensor>(name, numpy_array); } py::capsule PbTensor::ToDLPack() { if (dtype_ == TRITONSERVER_TYPE_BYTES) { throw PythonBackendException( "DLPack does not have support for string tensors."); } DLManagedTensor* dlpack_tensor = new DLManagedTensor; dlpack_tensor->dl_tensor.ndim = dims_.size(); dlpack_tensor->dl_tensor.byte_offset = 0; dlpack_tensor->dl_tensor.data = memory_ptr_; dlpack_tensor->dl_tensor.shape = &dims_[0]; dlpack_tensor->dl_tensor.strides = nullptr; dlpack_tensor->manager_ctx = this; dlpack_tensor->deleter = [](DLManagedTensor* m) { if (m->manager_ctx == nullptr) { return; } PbTensor* tensor = reinterpret_cast<PbTensor*>(m->manager_ctx); py::handle tensor_handle = py::cast(tensor); tensor_handle.dec_ref(); free(m); }; PbTensor* tensor = reinterpret_cast<PbTensor*>(this); py::handle tensor_handle = py::cast(tensor); // Increase the reference count by one to make sure that the DLPack // represenation doesn't become invalid when the tensor object goes out of // scope. tensor_handle.inc_ref(); dlpack_tensor->dl_tensor.device.device_id = memory_type_id_; dlpack_tensor->dl_tensor.dtype = triton_to_dlpack_type(dtype_); switch (memory_type_) { case TRITONSERVER_MEMORY_GPU: dlpack_tensor->dl_tensor.device.device_type = DLDeviceType::kDLCUDA; break; case TRITONSERVER_MEMORY_CPU: dlpack_tensor->dl_tensor.device.device_type = DLDeviceType::kDLCPU; break; case TRITONSERVER_MEMORY_CPU_PINNED: dlpack_tensor->dl_tensor.device.device_type = DLDeviceType::kDLCUDAHost; break; } return py::capsule( static_cast<void*>(dlpack_tensor), "dltensor", &delete_unused_dltensor); } #endif // TRITON_PB_STUB void PbTensor::DeleteDLPack() { if (dl_managed_tensor_ != nullptr) { dl_managed_tensor_->deleter(dl_managed_tensor_); dl_managed_tensor_ = nullptr; } } std::unique_ptr<PbMemory>& PbTensor::Memory() { return pb_memory_; } #ifdef TRITON_PB_STUB std::shared_ptr<PbTensor> PbTensor::FromDLPack(const std::string& name, const py::capsule& dlpack_tensor) { if (name == "") { throw PythonBackendException("Tensor name cannot be an empty string."); } DLManagedTensor* dl_managed_tensor = static_cast<DLManagedTensor*>(dlpack_tensor.get_pointer()); void* memory_ptr = dl_managed_tensor->dl_tensor.data; memory_ptr = reinterpret_cast<char*>(memory_ptr) + dl_managed_tensor->dl_tensor.byte_offset; int64_t* strides = dl_managed_tensor->dl_tensor.strides; int ndim = dl_managed_tensor->dl_tensor.ndim; std::vector<int64_t> dims( dl_managed_tensor->dl_tensor.shape, dl_managed_tensor->dl_tensor.shape + ndim); // Check if the input is contiguous and in C order if (strides != nullptr) { int64_t calculated_stride{1}; bool is_contiguous_c_order = true; for (size_t i = 1; i < dims.size(); i++) { if (strides[ndim - i] != calculated_stride) { is_contiguous_c_order = false; break; } calculated_stride *= dims[ndim - i]; } if (!is_contiguous_c_order) { throw PythonBackendException( "DLPack tensor is not contiguous. Only contiguous DLPack " "tensors that are stored in C-Order are supported."); } } TRITONSERVER_MemoryType memory_type; int64_t memory_type_id; switch (dl_managed_tensor->dl_tensor.device.device_type) { case DLDeviceType::kDLCUDA: memory_type = TRITONSERVER_MEMORY_GPU; memory_type_id = dl_managed_tensor->dl_tensor.device.device_id; break; case DLDeviceType::kDLCPU: memory_type = TRITONSERVER_MEMORY_CPU; memory_type_id = 0; break; case DLDeviceType::kDLCUDAHost: memory_type = TRITONSERVER_MEMORY_CPU; memory_type_id = 0; break; default: throw PythonBackendException( "DLDevice type " + std::to_string(dl_managed_tensor->dl_tensor.device.device_type) + " is not support by Python backend."); break; } TRITONSERVER_DataType dtype = dlpack_to_triton_type(dl_managed_tensor->dl_tensor.dtype); // Calculate tensor size. uint64_t byte_size = 1; for (auto& dim : dims) { byte_size *= dim; } byte_size *= (dl_managed_tensor->dl_tensor.dtype.bits + 7) / 8; PyCapsule_SetName(dlpack_tensor.ptr(), "used_dlpack"); return std::make_unique<PbTensor>( name, dims, dtype, memory_type, memory_type_id, memory_ptr, byte_size, dl_managed_tensor); } #endif // TRITON_PB_STUB PbTensor::~PbTensor() noexcept(false) { DeleteDLPack(); } const std::string& PbTensor::Name() const { return name_; } #ifdef TRITON_PB_STUB const py::array* PbTensor::AsNumpy() const { if (IsCPU()) { return &numpy_array_; } else { throw PythonBackendException( "Tensor is stored in GPU and cannot be converted to NumPy."); } } #endif // TRITON_PB_STUB void PbTensor::SaveToSharedMemory( std::unique_ptr<SharedMemoryManager>& shm_pool, bool copy_gpu) { if (!tensor_shm_.data_) { uint64_t byte_size; if (!pb_memory_) { byte_size = sizeof(TensorShm) + sizeof(int64_t) * dims_.size() + PbString::ShmStructSize(name_) + PbMemory::ShmStructSize(memory_type_, byte_size_); } else { byte_size = sizeof(TensorShm) + sizeof(int64_t) * dims_.size() + PbString::ShmStructSize(name_); } tensor_shm_ = shm_pool->Construct<char>(byte_size); tensor_shm_ptr_ = reinterpret_cast<TensorShm*>(tensor_shm_.data_.get()); tensor_shm_ptr_->dtype = dtype_; tensor_shm_ptr_->dims_count = dims_.size(); shm_handle_ = tensor_shm_.handle_; dims_shm_ptr_ = reinterpret_cast<int64_t*>( reinterpret_cast<char*>(tensor_shm_ptr_) + sizeof(TensorShm)); // Write the dimensions data to shared memory. for (size_t i = 0; i < dims_.size(); i++) { dims_shm_ptr_[i] = dims_[i]; } std::size_t name_offset = sizeof(TensorShm) + sizeof(int64_t) * dims_.size(); name_shm_ = PbString::Create( name_, reinterpret_cast<char*>(tensor_shm_ptr_) + name_offset, shm_handle_ + name_offset); std::size_t pb_memory_offset = name_offset + PbString::ShmStructSize(name_); if (!pb_memory_) { pb_memory_ = PbMemory::Create( memory_type_, memory_type_id_, byte_size_, reinterpret_cast<char*>(memory_ptr_), reinterpret_cast<char*>(tensor_shm_ptr_) + pb_memory_offset, shm_handle_ + pb_memory_offset, copy_gpu); tensor_shm_ptr_->memory = 0; } else { tensor_shm_ptr_->memory = pb_memory_->ShmHandle(); } memory_ptr_ = pb_memory_->DataPtr(); } } std::unique_ptr<PbTensor> PbTensor::LoadFromSharedMemory( std::unique_ptr<SharedMemoryManager>& shm_pool, bi::managed_external_buffer::handle_t tensor_handle, bool open_cuda_handle) { AllocatedSharedMemory<char> tensor_shm = shm_pool->Load<char>(tensor_handle); TensorShm* tensor_shm_ptr = reinterpret_cast<TensorShm*>(tensor_shm.data_.get()); size_t name_offset = sizeof(TensorShm) + sizeof(int64_t) * tensor_shm_ptr->dims_count; std::unique_ptr<PbString> name_shm = PbString::LoadFromSharedMemory( tensor_handle + name_offset, tensor_shm.data_.get() + name_offset); std::unique_ptr<PbMemory> pb_memory; if (tensor_shm_ptr->memory == 0) { std::size_t pb_memory_offset = name_offset + name_shm->Size(); pb_memory = PbMemory::LoadFromSharedMemory( pb_memory_offset, tensor_shm.data_.get() + pb_memory_offset, open_cuda_handle); } else { pb_memory = PbMemory::LoadFromSharedMemory( shm_pool, tensor_shm_ptr->memory, open_cuda_handle); } return std::unique_ptr<PbTensor>( new PbTensor(tensor_shm, name_shm, pb_memory)); } TRITONSERVER_DataType PbTensor::TritonDtype() const { return dtype_; } void* PbTensor::DataPtr() { return memory_ptr_; } bi::managed_external_buffer::handle_t PbTensor::ShmHandle() { return shm_handle_; } PbTensor::PbTensor( AllocatedSharedMemory<char>& tensor_shm, std::unique_ptr<PbString>& name_shm, std::unique_ptr<PbMemory>& pb_memory) : tensor_shm_(std::move(tensor_shm)), name_shm_(std::move(name_shm)), pb_memory_(std::move(pb_memory)) { tensor_shm_ptr_ = reinterpret_cast<TensorShm*>(tensor_shm_.data_.get()); dims_shm_ptr_ = reinterpret_cast<int64_t*>( reinterpret_cast<char*>(tensor_shm_ptr_) + sizeof(TensorShm)); name_ = name_shm_->String(); dims_ = std::vector<int64_t>( dims_shm_ptr_, dims_shm_ptr_ + tensor_shm_ptr_->dims_count); dtype_ = tensor_shm_ptr_->dtype; dl_managed_tensor_ = nullptr; byte_size_ = pb_memory_->ByteSize(); memory_ptr_ = pb_memory_->DataPtr(); memory_type_ = pb_memory_->MemoryType(); memory_type_id_ = pb_memory_->MemoryTypeId(); shm_handle_ = tensor_shm_.handle_; #ifdef TRITON_PB_STUB if (memory_type_ == TRITONSERVER_MEMORY_CPU || memory_type_ == TRITONSERVER_MEMORY_CPU_PINNED) { if (dtype_ != TRITONSERVER_TYPE_BYTES) { py::object numpy_array = py::array(triton_to_pybind_dtype(dtype_), dims_, (void*)memory_ptr_); numpy_array_ = numpy_array.attr("view")(triton_to_numpy_type(dtype_)); } else { py::object numpy_array = py::array( triton_to_pybind_dtype(TRITONSERVER_TYPE_UINT8), {byte_size_}, (void*)memory_ptr_); py::module triton_pb_utils = py::module::import("triton_python_backend_utils"); numpy_array_ = triton_pb_utils.attr("deserialize_bytes_tensor")(numpy_array) .attr("reshape")(dims_); } } else { numpy_array_ = py::none(); } #endif } }}} // namespace triton::backend::python
30.496377
80
0.706546
[ "object", "shape", "vector" ]
24830b021b4d133e304996b06e4364c178b768ec
457
hpp
C++
Mike-Dev/Task.hpp
manilonis/Christmas-Break-Project
f4fb80709bc11cad50dc08397fe68c3b7f9d2bd1
[ "MIT" ]
null
null
null
Mike-Dev/Task.hpp
manilonis/Christmas-Break-Project
f4fb80709bc11cad50dc08397fe68c3b7f9d2bd1
[ "MIT" ]
null
null
null
Mike-Dev/Task.hpp
manilonis/Christmas-Break-Project
f4fb80709bc11cad50dc08397fe68c3b7f9d2bd1
[ "MIT" ]
null
null
null
#include <string> #include "User.hpp" #include "Issue.hpp" #include <vector> using namespace std; class Task{ private: static int current_num; int id_num; string name; string description; User* assigned_to; User* assigned_by; vector<Issue*>* issues; public: Task(string, string, User*, User*); Task(string, string, User*, User*, vector<Issue*>*); int get_id(); string get_name(); string get_description(); User* get_assigned(int); ~Task(); };
19.041667
53
0.706783
[ "vector" ]
24891e5732a078be12a4e43286b5d2cfaa4ca556
1,864
hpp
C++
Ca3DE/Client/Graphs.hpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
Ca3DE/Client/Graphs.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
Ca3DE/Client/Graphs.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #ifndef CAFU_CLIENT_GRAPHS_HPP_INCLUDED #define CAFU_CLIENT_GRAPHS_HPP_INCLUDED namespace MatSys { class RenderMaterialT; } class GraphsT { public: float FPS[512]; // Frames Per Second unsigned short Heading[512]; // Heading unsigned short PosY[512]; unsigned short PosZ[512]; // Erzeugt ein neues GraphsT-Objekt. GraphsT(); ~GraphsT(); // Trägt für das Frame 'ClientFrameNr' für alle Graphen 0 ein. void ClearForFrame(unsigned long ClientFrameNr); // Zeichnet alle Graphen. void Draw(unsigned long ClientFrameNr, unsigned int fbWidth, unsigned int fbHeight) const; private: GraphsT(const GraphsT&); ///< Use of the Copy Constructor is not allowed. void operator = (const GraphsT&); ///< Use of the Assignment Operator is not allowed. MatSys::RenderMaterialT* m_RMatWireframe; ///< The render material for wire-frame rendering. // MatSys::RenderMaterialT* m_RMatWireframeOZ; ///< The render material for wire-frame rendering (with polygon z-offset, e.g. for outlines). // MatSys::RenderMaterialT* m_RMatFlatShaded; ///< The render material for flat shaded (single solid color) rendering. // MatSys::RenderMaterialT* m_RMatFlatShadedOZ; ///< The render material for flat shaded (single solid color) rendering (with polygon z-offset, e.g. for decals). // MatSys::RenderMaterialT* m_RMatOverlay; ///< The render material for selection overlays (added in a second pass). // MatSys::RenderMaterialT* m_RMatOverlayOZ; ///< The render material for selection overlays (added in a second pass) (with polygon z-offset, e.g. for decals). }; #endif
38.040816
166
0.694742
[ "render", "solid" ]
2490db29b7f7f8bc30ea592c05b9dc697984c40a
305
cpp
C++
C++/minimum-value-to-get-positive-step-by-step-sum.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/minimum-value-to-get-positive-step-by-step-sum.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/minimum-value-to-get-positive-step-by-step-sum.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n) // Space: O(1) class Solution { public: int minStartValue(vector<int>& nums) { int min_prefix = 0, prefix = 0; for (const auto& num : nums) { prefix += num; min_prefix = min(min_prefix, prefix); } return 1 - min_prefix; } };
20.333333
49
0.511475
[ "vector" ]
249149f5e728723c6b2faa41dce5f59482ee35d5
8,694
cpp
C++
vcgapps/OGF/image/algos/rasterizer.cpp
mattjr/structured
0cb4635af7602f2a243a9b739e5ed757424ab2a7
[ "Apache-2.0" ]
14
2015-01-11T02:53:04.000Z
2021-11-25T17:31:22.000Z
vcgapps/OGF/image/algos/rasterizer.cpp
skair39/structured
0cb4635af7602f2a243a9b739e5ed757424ab2a7
[ "Apache-2.0" ]
null
null
null
vcgapps/OGF/image/algos/rasterizer.cpp
skair39/structured
0cb4635af7602f2a243a9b739e5ed757424ab2a7
[ "Apache-2.0" ]
14
2015-07-21T04:47:52.000Z
2020-03-12T12:31:25.000Z
/* * GXML/Graphite: Geometry and Graphics Programming Library + Utilities * Copyright (C) 2000 Bruno Levy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact: Bruno Levy * * levy@loria.fr * * ISA Project * LORIA, INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * * Note that the GNU General Public License does not permit incorporating * the Software into proprietary programs. */ #include <OGF/image/algos/rasterizer.h> #include <OGF/image/types/image.h> namespace OGF { Rasterizer::Rasterizer(Image* target) { target_ = target ; ogf_assert(target_->color_encoding() == Image::RGBA) ; width_ = target_->width() ; height_ = target_->height() ; bytes_per_line_ = 4 * width_ ; left_ = new ScanLineExtremity[height_] ; right_ = new ScanLineExtremity[height_] ; graph_mem_ = target_->base_mem() ; } Rasterizer::~Rasterizer() { target_ = nil ; delete[] left_ ; left_ = nil ; delete[] right_ ; right_ = nil ; } void Rasterizer::begin_polygon() { current_polygon_index_ = 0 ; } void Rasterizer::vertex(const Point2d& p, const Color& c) { ogf_assert(current_polygon_index_ < MAX_POLYGON) ; Vertex& v = current_polygon_[current_polygon_index_] ; v.x = int(p.x() * (width_ - 1)) ; v.y = int(p.y() * (height_ - 1)) ; ogf_clamp(v.x, 0, width_ - 1) ; ogf_clamp(v.y, 0, height_ - 1) ; v.r = int(c.r() * 255.0) ; v.g = int(c.g() * 255.0) ; v.b = int(c.b() * 255.0) ; v.a = int(c.a() * 255.0) ; ogf_clamp(v.r, 0, 255) ; ogf_clamp(v.g, 0, 255) ; ogf_clamp(v.b, 0, 255) ; ogf_clamp(v.a, 0, 255) ; current_polygon_index_++ ; } void Rasterizer::end_polygon() { rasterize(current_polygon_, current_polygon_index_) ; } void Rasterizer::triangle( const Point2d& p0, const Color& c0, const Point2d& p1, const Color& c1, const Point2d& p2, const Color& c2 ) { begin_polygon() ; vertex(p0,c0) ; vertex(p1,c1) ; vertex(p2,c2) ; end_polygon() ; } static inline int nmg_sgn(int x) { return x > 0 ? 1 : (x < 0 ? -1 : 0) ; } void Rasterizer::rasterize(Vertex* v, int nb_vertices) { int clock_wise = 0 ; int miny = 100000; int maxy = -1; int i,j,u ; if(nb_vertices < 2) { return ; } // Step 1: Get clockwise, min and max y for(i=0; i<nb_vertices; i++) { int j = i+1; if(j == nb_vertices) { j = 0; } int k = j+1; if(k == nb_vertices) { k = 0; } int dx1 = v[i].x - v[j].x; int dy1 = v[i].y - v[j].y; int dx2 = v[k].x - v[j].x; int dy2 = v[k].y - v[j].y; clock_wise += dx1 * dy2 - dx2 * dy1; miny = ogf_min(miny,v[i].y); maxy = ogf_max(maxy,v[i].y); } clock_wise = (clock_wise > 0); if(miny == maxy) { return; } // Step 2: rasterize border int y,y1,y2,dy,sy; int x,x1,x2,dx,sx,ex; int r,r1,r2,dr,sr,er; int g,g1,g2,dg,sg,eg; int b,b1,b2,db,sb,eb; int a,a1,a2,da,sa,ea; for(i=0; i<nb_vertices; i++) { j = i+1; if(j==nb_vertices) { j = 0; } if(v[i].y == v[j].y) continue; y1 = v[i].y; y2 = v[j].y; dy = y2 - y1; sy = nmg_sgn(dy); dy *= sy; y = y1; x1 = v[i].x; x2 = v[j].x; dx = x2 - x1; sx = nmg_sgn(dx); dx *= sx; ex = (dx << 1) - dy; x = x1; r1 = v[i].r; r2 = v[j].r; dr = r2 - r1; sr = nmg_sgn(dr); dr *= sr; er = (dr << 1) - dy; r = r1; g1 = v[i].g; g2 = v[j].g; dg = g2 - g1; sg = nmg_sgn(dg); dg *= sg; eg = (dg << 1) - dy; g = g1; b1 = v[i].b; b2 = v[j].b; db = b2 - b1; sb = nmg_sgn(db); db *= sb; eb = (db << 1) - dy; b = b1; a1 = v[i].a; a2 = v[j].a; da = a2 - a1; sa = nmg_sgn(da); da *= sa; ea = (da << 1) - dy; a = a1; ScanLineExtremity* extr = (clock_wise ^ (y2 > y1)) ? right_ : left_ ; for(u=0; u <= dy; u++) { extr[y].x = x; extr[y].r = r; extr[y].g = g; extr[y].b = b; extr[y].a = a; y += sy; while(ex >= 0) { x += sx; ex -= dy << 1; } ex += dx << 1; while(er >= 0) { r += sr; er -= dy << 1; } er += dr << 1; while(eg >= 0) { g += sg; eg -= dy << 1; } eg += dg << 1; while(eb >= 0) { b += sb; eb -= dy << 1; } eb += db << 1; while(ea >= 0) { a += sa; ea -= dy << 1; } ea += da << 1; } } // Step 3: rasterize scanlines Memory::byte* graph_ptr0 = graph_mem_ + miny * bytes_per_line_ ; for(y=miny; y<=maxy; y++) { x1 = left_[y].x; x2 = right_[y].x; dx = x2 - x1 + 1; x = x1; Memory::byte* graph_ptr = graph_ptr0 + (x1 << 2) ; r1 = left_[y].r; r2 = right_[y].r; dr = r2 - r1; sr = nmg_sgn(dr); dr *= sr; er = (dr << 1) - dx; r = r1; g1 = left_[y].g; g2 = right_[y].g; dg = g2 - g1; sg = nmg_sgn(dg); dg *= sg; eg = (dg << 1) - dx; g = g1; b1 = left_[y].b; b2 = right_[y].b; db = b2 - b1; sb = nmg_sgn(db); db *= sb; eb = (db << 1) - dx; b = b1; a1 = left_[y].a; a2 = right_[y].a; da = a2 - a1; sa = nmg_sgn(da); da *= sa; ea = (da << 1) - dx; a = a1; for(x=x1; x <= x2; x++) { graph_ptr[0] = Memory::byte(r) ; graph_ptr[1] = Memory::byte(g) ; graph_ptr[2] = Memory::byte(b) ; graph_ptr[3] = Memory::byte(a) ; while(er >= 0) { r += sr; er -= dx << 1; } er += dr << 1; while(eg >= 0) { g += sg; eg -= dx << 1; } eg += dg << 1; while(eb >= 0) { b += sb; eb -= dx << 1; } eb += db << 1; while(ea >= 0) { a += sa; ea -= dx << 1; } ea += da << 1; graph_ptr += 4 ; } graph_ptr0 += bytes_per_line_ ; } } }
25.952239
77
0.398321
[ "geometry" ]
2492f860bc3e720682a9cae907906848d92ff6ff
6,449
hpp
C++
base/context.hpp
wangg12/libskylark
e8836190be854d0284d38772c48e110b3c6d5e51
[ "Apache-2.0" ]
2
2021-06-12T07:26:43.000Z
2021-06-12T07:26:47.000Z
base/context.hpp
cjiyer/libskylark
e8836190be854d0284d38772c48e110b3c6d5e51
[ "Apache-2.0" ]
null
null
null
base/context.hpp
cjiyer/libskylark
e8836190be854d0284d38772c48e110b3c6d5e51
[ "Apache-2.0" ]
null
null
null
#ifndef SKYLARK_CONTEXT_HPP #define SKYLARK_CONTEXT_HPP #include "config.h" #include "exception.hpp" #include "../utility/randgen.hpp" #include "boost/smart_ptr.hpp" #include "boost/property_tree/ptree.hpp" #include "boost/property_tree/json_parser.hpp" namespace skylark { namespace base { /** * A structure that holds basic information about the state of the * random number stream. */ struct context_t { /** * Initialize context with a seed. * @param[in] seed Random seed to be used for all computations. */ context_t (int seed, int counter=0) : _counter(counter), _seed(seed) {} #if 0 context_t (context_t&& ctxt) : _counter(std::move(ctxt._counter)), _seed(std::move(ctxt._seed)) {} context_t(const context_t& other) { _seed = other._seed; _counter = other._counter; } context_t& operator=(const context_t& other) { _seed = other._seed; _counter = other._counter; return *this; } #endif /** * Load context from a serialized JSON structure. * @param[in] filename of JSON structure encoding serialized state. */ context_t (const boost::property_tree::ptree& json) { _seed = json.get<int>("seed"); _counter = json.get<size_t>("counter"); } boost::property_tree::ptree to_ptree() const { boost::property_tree::ptree pt; pt.put("skylark_object_type", "context"); pt.put("skylark_version", VERSION); pt.put("seed", _seed); pt.put("counter", _counter); return pt; } /** * Returns a container of samples drawn from a distribution * to be accessed as an array. * @param[in] size The size of the container. * @param[in] distribution The distribution to draw samples from. * @return Random samples' container. * * @details This is the main facility for creating a "stream" of * samples of given size and distribution. size is needed for * reserving up-front a portion of the linear space of the 2^64 samples * that can be provided by a context with a fixed seed. * * @internal We currently use Random123 library, most specifically * Threefry4x64 counter-based generator, as wrapped by the uniform * random generator, MicroURNG. For each sample we instantiate * a MicroURNG instance. Each such instance needs 2 arrays of 4 uint64 * numbers each, namely a counter and a key: we successively increment only * the first uint64 component in counter (counter[0]) and fix key to be * the seed. This instance is then passed to the distribution. This * in turn calls operator () on the instance and increments counter[3] * accordingly (for multiple calls), thus ensuring the independence * of successive samples. operator () can either trigger a run of * the Threefry4x64 algorithm for creating a fresh result array * (also consisting of 4 uint64's) and use one or more of its components or * use those components from a previous run that are not processed yet. * * @caveat This should be used as a global operation to keep the * the internal state of the context synchronized. */ template <typename Distribution> skylark::utility::random_samples_array_t<Distribution> allocate_random_samples_array(size_t size, Distribution& distribution) { skylark::utility::random_samples_array_t<Distribution> random_samples_array(_counter, size, _seed, distribution); _counter += size; return random_samples_array; } /** * Returns a vector of samples drawn from a distribution. * @param[in] size The size of the vector. * @param[in] distribution The distribution to draw samples from. * @return Random samples' vector. */ template <typename Distribution > std::vector<typename Distribution::result_type> generate_random_samples_array(size_t size, Distribution& distribution) { skylark::utility::random_samples_array_t<Distribution> allocated_random_samples_array(_counter, size, _seed, distribution); _counter += size; std::vector<typename Distribution::result_type> random_samples_array; try { random_samples_array.resize(size); } catch (std::bad_alloc ba) { SKYLARK_THROW_EXCEPTION ( base::allocation_exception() << base::error_msg(ba.what()) ); } for(size_t i = 0; i < size; i++) { random_samples_array[i] = allocated_random_samples_array[i]; } return random_samples_array; } /** * Returns a container of random numbers to be accessed as an array. * @param[in] size The size of the container. * @return Random numbers' container. * * @caveat This should be used as a global operation to keep the * the internal state of the context synchronized. */ skylark::utility::random_array_t allocate_random_array(size_t size) { skylark::utility::random_array_t random_array(_counter, size, _seed); _counter += size; return random_array; } /** * Returns an integer random number. * @return Random integer number. * * @caveat This should be used as a global operation to keep the * the internal state of the context synchronized. */ int random_int() { skylark::utility::random_array_t random_array = allocate_random_array(1); int sample = random_array[0]; return sample; } size_t get_counter() { return _counter; } /** * Serializes the context to a JSON structure. * @param[out] JSON encoded state of the context. */ friend boost::property_tree::ptree& operator<<( boost::property_tree::ptree &sk, const context_t &data); private: /// Internal counter identifying the start of next stream of random numbers size_t _counter; /// The seed used for initializing the context int _seed; }; boost::property_tree::ptree& operator<<(boost::property_tree::ptree &sk, const context_t &data) { sk.put("sketch.context.seed", data._seed); sk.put("sketch.context.counter", data._counter); return sk; } } } /** namespace skylark::base */ #endif // SKYLARK_CONTEXT_HPP
34.672043
80
0.653435
[ "vector" ]
249d1b2845abcb288bf4e7ad21ac0ba9721c4e42
22,364
cpp
C++
dataurus/CheckSums.cpp
TheofilosBel/sigmod2018
61b3cab644f6143dfe6b6b81421e418ff9b81556
[ "MIT" ]
28
2018-04-10T19:14:13.000Z
2021-06-25T23:54:50.000Z
dataurus/CheckSums.cpp
geooo109/sigmod2018-1
61b3cab644f6143dfe6b6b81421e418ff9b81556
[ "MIT" ]
null
null
null
dataurus/CheckSums.cpp
geooo109/sigmod2018-1
61b3cab644f6143dfe6b6b81421e418ff9b81556
[ "MIT" ]
12
2018-04-10T19:15:38.000Z
2019-12-29T15:44:16.000Z
#include <cassert> #include <iostream> #include <string> #include <unordered_map> #include <algorithm> #include <functional> #include <utility> #include <vector> #include <pthread.h> #include "job_scheduler.h" // The job scheduler Class #include "Joiner.hpp" // Implements Joiner Functions #include "checksum_job.h" // Parallel Checksums 32 bit ver #include "checksum_job_64.h" // Parallel Checksums 64 bit ver using namespace std; #define CHECK_SUM_RANGE 20 // The self Join CheckSum on the Fly method table_t * Joiner::SelfJoinCheckSumOnTheFly(table_t *table, PredicateInfo *predicate_ptr, columnInfoMap & cmap, std::vector<SelectInfo> selections, string & result_str) { /* Get the 2 relation rows ids vectors in referances */ unsigned * row_ids_matrix = table->row_ids; /* Get the 2 relations */ Relation & relation_l = getRelation(predicate_ptr->left.relId); Relation & relation_r = getRelation(predicate_ptr->right.relId); /* Get their columns */ uint64_t *column_values_l = relation_l.columns[predicate_ptr->left.colId]; uint64_t *column_values_r = relation_r.columns[predicate_ptr->right.colId]; /* Fint the indexes of the raltions in the table's */ int index_l = -1; int index_r = -1; index_l = table->relations_bindings.find(predicate_ptr->left.binding)->second; index_r = table->relations_bindings.find(predicate_ptr->right.binding)->second; unsigned rows_number = table->tups_num; unsigned rels_number = table->rels_num; /* Crete a vector for the pairs Column, Index in relationR/S */ vector<struct checksumST> distinctPairs; struct checksumST st; /* take the distinct columns in a vector */ unordered_map<unsigned, unsigned>::iterator itr; unsigned index = 0; for (columnInfoMap::iterator it=cmap.begin(); it != cmap.end(); it++) { index = -1; itr = table->relations_bindings.find(it->first.binding); if (itr != table->relations_bindings.end()) { st.colId = it->first.colId; st.binding = it->first.binding; st.index = itr->second; st.values = getRelation(it->first.relId).columns[st.colId]; distinctPairs.push_back(st); } } // Range for chunking size_t range = CHECK_SUM_RANGE; /* Calculate check sums on the fly , if its the last query */ vector<uint64_t> sum(distinctPairs.size(), 0); vector<uint64_t*> sums(range); for (size_t i = 0; i < sums.size(); i++) { sums[i] = (uint64_t *) calloc (sum.size(), sizeof(uint64_t)); } struct selfJoinSum_arg a[range]; for (size_t i = 0; i < range; i++) { a[i].low = (i < rows_number % range) ? i * (rows_number / range) + i : i * (rows_number / range) + rows_number % range; a[i].high = (i < rows_number % range) ? a[i].low + rows_number / range + 1 : a[i].low + rows_number / range; a[i].column_values_l = column_values_l; a[i].column_values_r = column_values_r; a[i].row_ids_matrix = row_ids_matrix; a[i].index_l = index_l; a[i].index_r = index_r; a[i].relations_num = rels_number; a[i].priv_checsums = sums[i]; a[i].distinctPairs = &distinctPairs; job_scheduler.Schedule(new JobCheckSumSelfJoin(a[i])); } job_scheduler.Barrier(); /* Create the checksum */ for (size_t j = 0; j < sum.size(); j++) { for (size_t i = 0; i < sums.size(); i++) { sum[j] += sums[i][j]; } } /* Construct the checksums in the right way */ bool found = false; for (size_t i = 0; i < selections.size(); i++) { // Look up the check sum int the array for (size_t j = 0; j < distinctPairs.size(); j++) { if (selections[i].colId == distinctPairs[j].colId && selections[i].binding == distinctPairs[j].binding) { (sum[j] == 0) ? result_str += "NULL" : result_str += to_string(sum[j]); found = true; break; } } // Create the write check sum if (i != selections.size() - 1) { result_str += " "; } } return NULL; } // 32 bit version void Joiner::CheckSumOnTheFly(result_t * result, table_t * table_r, table_t * table_s, columnInfoMap & cmap, std::vector<SelectInfo> selections, string & result_str) { /* Crete a vector for the pairs Column, Index in relationR/S */ vector<struct checksumST> distinctPairs_in_R; vector<struct checksumST> distinctPairs_in_S; struct checksumST st; /* take the distinct columns in a vector */ unordered_map<unsigned, unsigned>::iterator itr; unsigned index = 0; for (columnInfoMap::iterator it=cmap.begin(); it != cmap.end(); it++) { index = -1; itr = table_r->relations_bindings.find(it->first.binding); if (itr != table_r->relations_bindings.end() ) { st.colId = it->first.colId; st.binding = it->first.binding; st.index = itr->second; st.values = getRelation(it->first.relId).columns[st.colId]; distinctPairs_in_R.push_back(st); } else { itr = table_s->relations_bindings.find(it->first.binding); (itr != table_s->relations_bindings.end()) ? (index = itr->second) : (index = -1); st.colId = it->first.colId; st.binding = it->first.binding; st.index = itr->second; st.values = getRelation(it->first.relId).columns[st.colId]; distinctPairs_in_S.push_back(st); } } size_t range = THREAD_NUM_1CPU; // always eqyal with threads of radix int jobs_num = 0; void * job_args = NULL; for (size_t th = 0; th < range; th++) { chainedtuplebuffer_t * cb = (chainedtuplebuffer_t *) result->resultlist[th].results; jobs_num += cb->numbufs; } vector<uint64_t> sum(distinctPairs_in_R.size() + distinctPairs_in_S.size(), 0); vector<uint64_t*> sums(jobs_num); for (size_t i = 0; i < sums.size(); i++) { sums[i] = (uint64_t *) calloc (sum.size(), sizeof(uint64_t)); } if (table_r->intermediate_res && table_s->intermediate_res) { //struct interInterTable_arg a[jobs_num]; tuplebuffer_t * tb; struct interInterSum_arg * ja = (struct interInterSum_arg *) malloc(sizeof(struct interInterSum_arg) * jobs_num); /* Loop all the buffers */ int idx = 0; for (int th = 0; th < range ; th++) { chainedtuplebuffer_t * cb = (chainedtuplebuffer_t *) result->resultlist[th].results; tb = cb->buf; for (int buff = 0; buff < cb->numbufs && result->resultlist[th].nresults != 0; buff++) { struct interInterSum_arg * a = ja + idx;//new interInterSum_arg; a->priv_checsums = sums[idx++]; a->distinctPairs_r = &distinctPairs_in_R; a->distinctPairs_s = &distinctPairs_in_S; a->rel_num_r = table_r->rels_num; a->rel_num_s = table_s->rels_num; a->rids_r = table_r->row_ids; a->rids_s = table_s->row_ids; a->size = (buff == 0) ? cb->writepos : CHAINEDBUFF_NUMTUPLESPERBUF; a->tb = tb; job_scheduler.Schedule(new JobCheckSumInterInter(*a)); tb = tb->next; } } job_args = (void *) ja; } else if (table_r->intermediate_res) { tuplebuffer_t * tb; struct interNoninterSum_arg * ja = (struct interNoninterSum_arg *) malloc(sizeof(struct interNoninterSum_arg) * jobs_num); /* Loop all the buffers */ int idx = 0; for (int th = 0; th < range ; th++) { chainedtuplebuffer_t * cb = (chainedtuplebuffer_t *) result->resultlist[th].results; tb = cb->buf; for (int buff = 0; buff < cb->numbufs && result->resultlist[th].nresults != 0; buff++) { struct interNoninterSum_arg * a = ja + idx; a->priv_checsums = sums[idx++]; a->distinctPairs_r = &distinctPairs_in_R; a->distinctPairs_s = &distinctPairs_in_S; a->rel_num_r = table_r->rels_num; a->rids_r = table_r->row_ids; a->size = (buff == 0) ? cb->writepos : CHAINEDBUFF_NUMTUPLESPERBUF; a->tb = tb; job_scheduler.Schedule(new JobCheckSumInterNonInter(*a)); tb = tb->next; } } job_args = (void *) ja; } else if (table_s->intermediate_res) { tuplebuffer_t * tb; struct noninterInterSum_arg * ja = (struct noninterInterSum_arg *) malloc(sizeof(struct noninterInterSum_arg) * jobs_num); /* Loop all the buffers */ int idx = 0; for (int th = 0; th < range ; th++) { chainedtuplebuffer_t * cb = (chainedtuplebuffer_t *) result->resultlist[th].results; tb = cb->buf; for (int buff = 0; buff < cb->numbufs && result->resultlist[th].nresults != 0; buff++) { struct noninterInterSum_arg * a = ja + idx;//new noninterInterSum_arg; a->priv_checsums = sums[idx++]; a->distinctPairs_r = &distinctPairs_in_R; a->distinctPairs_s = &distinctPairs_in_S; a->rel_num_s = table_s->rels_num; a->rids_s = table_s->row_ids; a->size = (buff == 0) ? cb->writepos : CHAINEDBUFF_NUMTUPLESPERBUF; a->tb = tb; job_scheduler.Schedule(new JobCheckSumNonInterInter(*a)); tb = tb->next; } } job_args = (void *) ja; } else { tuplebuffer_t * tb; struct noninterNoninterSum_arg * ja = (struct noninterNoninterSum_arg *) malloc(sizeof(struct noninterNoninterSum_arg) * jobs_num); /* Loop all the buffers */ int idx = 0; for (int th = 0; th < range ; th++) { chainedtuplebuffer_t * cb = (chainedtuplebuffer_t *) result->resultlist[th].results; tb = cb->buf; for (int buff = 0; buff < cb->numbufs && result->resultlist[th].nresults != 0; buff++) { struct noninterNoninterSum_arg * a = ja + idx;//new noninterNoninterSum_arg; a->priv_checsums = sums[idx++]; a->distinctPairs_r = &distinctPairs_in_R; a->distinctPairs_s = &distinctPairs_in_S; a->size = (buff == 0) ? cb->writepos : CHAINEDBUFF_NUMTUPLESPERBUF; a->tb = tb; job_scheduler.Schedule(new JobCheckSumNonInterNonInter(*a)); tb = tb->next; } } job_args = (void *) ja; } /* Barrier here */ job_scheduler.Barrier(); /* Create the checksum */ for (size_t j = 0; j < sum.size(); j++) { for (size_t i = 0; i < sums.size(); i++) { sum[j] += sums[i][j]; } } //delete_ /* Free args */ free(job_args); /* Construct the checksums in the right way */ bool found = false; for (size_t i = 0; i < selections.size(); i++) { // Check if checksum is cached for (size_t j = 0; j < distinctPairs_in_R.size(); j++) { if (selections[i].colId == distinctPairs_in_R[j].colId && selections[i].binding == distinctPairs_in_R[j].binding) { (sum[j] == 0) ? result_str += "NULL" : result_str += to_string(sum[j]); found = true; break; } } /* Search in the other */ for (size_t j = 0; j < distinctPairs_in_S.size() && found != true; j++) { if (selections[i].colId == distinctPairs_in_S[j].colId && selections[i].binding == distinctPairs_in_S[j].binding) { (sum[j] == 0) ? result_str += "NULL" : result_str += to_string(sum[j + distinctPairs_in_R.size()]); found = true; break; } } /* Flag for the next loop */ found = false; // Create the write check sum if (i != selections.size() - 1) { result_str += " "; } } // Frees for (size_t i = 0; i < range; i++) { chainedtuplebuffer_free((chainedtuplebuffer_t *) result->resultlist[i].results); } } //64 Bit version void Joiner::CheckSumOnTheFly_t64(result_t * result, table_t * table_r, table_t * table_s, columnInfoMap & cmap, std::vector<SelectInfo> selections, string & result_str) { /* Crete a vector for the pairs Column, Index in relationR/S */ vector<struct checksumST> distinctPairs_in_R; vector<struct checksumST> distinctPairs_in_S; struct checksumST st; /* take the distinct columns in a vector */ unordered_map<unsigned, unsigned>::iterator itr; unsigned index = 0; for (columnInfoMap::iterator it=cmap.begin(); it != cmap.end(); it++) { index = -1; itr = table_r->relations_bindings.find(it->first.binding); if (itr != table_r->relations_bindings.end() ) { st.colId = it->first.colId; st.binding = it->first.binding; st.index = itr->second; st.values = getRelation(it->first.relId).columns[st.colId]; distinctPairs_in_R.push_back(st); } else { itr = table_s->relations_bindings.find(it->first.binding); (itr != table_s->relations_bindings.end()) ? (index = itr->second) : (index = -1); st.colId = it->first.colId; st.binding = it->first.binding; st.index = itr->second; st.values = getRelation(it->first.relId).columns[st.colId]; distinctPairs_in_S.push_back(st); } } size_t range = THREAD_NUM_1CPU; // always eqyal with threads of radix int jobs_num = 0; void * job_args = NULL; for (size_t th = 0; th < range; th++) { chainedtuplebuffer64_t * cb = (chainedtuplebuffer64_t *) result->resultlist[th].results; jobs_num += cb->numbufs; } vector<uint64_t> sum(distinctPairs_in_R.size() + distinctPairs_in_S.size(), 0); vector<uint64_t*> sums(jobs_num); for (size_t i = 0; i < sums.size(); i++) { sums[i] = (uint64_t *) calloc (sum.size(), sizeof(uint64_t)); } if (table_r->intermediate_res && table_s->intermediate_res) { //struct interInterTable_arg64_t a[jobs_num]; tuplebuffer64_t * tb; struct interInterSum_arg64_t * ja = (struct interInterSum_arg64_t *) malloc(sizeof(struct interInterSum_arg64_t) * jobs_num); /* Loop all the buffers */ int idx = 0; for (int th = 0; th < range ; th++) { chainedtuplebuffer64_t * cb = (chainedtuplebuffer64_t *) result->resultlist[th].results; tb = cb->buf; for (int buff = 0; buff < cb->numbufs && result->resultlist[th].nresults != 0; buff++) { struct interInterSum_arg64_t * a = ja + idx;//new interInterSum_arg; a->priv_checsums = sums[idx++]; a->distinctPairs_r = &distinctPairs_in_R; a->distinctPairs_s = &distinctPairs_in_S; a->rel_num_r = table_r->rels_num; a->rel_num_s = table_s->rels_num; a->rids_r = table_r->row_ids; a->rids_s = table_s->row_ids; a->size = (buff == 0) ? cb->writepos : CHAINEDBUFF_NUMTUPLESPERBUF; a->tb = tb; job_scheduler.Schedule(new JobCheckSumInterInter_t64(*a)); tb = tb->next; } } job_args = (void *) ja; } else if (table_r->intermediate_res) { tuplebuffer64_t * tb; struct interNoninterSum_arg64_t * ja = (struct interNoninterSum_arg64_t *) malloc(sizeof(struct interNoninterSum_arg64_t) * jobs_num); /* Loop all the buffers */ int idx = 0; for (int th = 0; th < range ; th++) { chainedtuplebuffer64_t * cb = (chainedtuplebuffer64_t *) result->resultlist[th].results; tb = cb->buf; for (int buff = 0; buff < cb->numbufs && result->resultlist[th].nresults != 0; buff++) { struct interNoninterSum_arg64_t * a = ja + idx; a->priv_checsums = sums[idx++]; a->distinctPairs_r = &distinctPairs_in_R; a->distinctPairs_s = &distinctPairs_in_S; a->rel_num_r = table_r->rels_num; a->rids_r = table_r->row_ids; a->size = (buff == 0) ? cb->writepos : CHAINEDBUFF_NUMTUPLESPERBUF; a->tb = tb; job_scheduler.Schedule(new JobCheckSumInterNonInter_t64(*a)); tb = tb->next; } } job_args = (void *) ja; } else if (table_s->intermediate_res) { tuplebuffer64_t * tb; struct noninterInterSum_arg64_t * ja = (struct noninterInterSum_arg64_t *) malloc(sizeof(struct noninterInterSum_arg64_t) * jobs_num); /* Loop all the buffers */ int idx = 0; for (int th = 0; th < range ; th++) { chainedtuplebuffer64_t * cb = (chainedtuplebuffer64_t *) result->resultlist[th].results; tb = cb->buf; for (int buff = 0; buff < cb->numbufs && result->resultlist[th].nresults != 0; buff++) { struct noninterInterSum_arg64_t * a = ja + idx;//new noninterInterSum_arg64_t; a->priv_checsums = sums[idx++]; a->distinctPairs_r = &distinctPairs_in_R; a->distinctPairs_s = &distinctPairs_in_S; a->rel_num_s = table_s->rels_num; a->rids_s = table_s->row_ids; a->size = (buff == 0) ? cb->writepos : CHAINEDBUFF_NUMTUPLESPERBUF; a->tb = tb; job_scheduler.Schedule(new JobCheckSumNonInterInter_t64(*a)); tb = tb->next; } } job_args = (void *) ja; } else { tuplebuffer64_t * tb; struct noninterNoninterSum_arg64_t * ja = (struct noninterNoninterSum_arg64_t *) malloc(sizeof(struct noninterNoninterSum_arg64_t) * jobs_num); /* Loop all the buffers */ int idx = 0; for (int th = 0; th < range ; th++) { chainedtuplebuffer64_t * cb = (chainedtuplebuffer64_t *) result->resultlist[th].results; tb = cb->buf; for (int buff = 0; buff < cb->numbufs && result->resultlist[th].nresults != 0; buff++) { struct noninterNoninterSum_arg64_t * a = ja + idx;//new noninterNoninterSum_arg64_t; a->priv_checsums = sums[idx++]; a->distinctPairs_r = &distinctPairs_in_R; a->distinctPairs_s = &distinctPairs_in_S; a->size = (buff == 0) ? cb->writepos : CHAINEDBUFF_NUMTUPLESPERBUF; a->tb = tb; job_scheduler.Schedule(new JobCheckSumNonInterNonInter_t64(*a)); tb = tb->next; } } job_args = (void *) ja; } /* free cb maybe */ /* Barrier here */ job_scheduler.Barrier(); /* Create the checksum */ for (size_t j = 0; j < sum.size(); j++) { for (size_t i = 0; i < sums.size(); i++) { sum[j] += sums[i][j]; } } /* Free args */ free(job_args); /* Construct the checksums in the right way */ bool found = false; for (size_t i = 0; i < selections.size(); i++) { // Check if checksum is cached for (size_t j = 0; j < distinctPairs_in_R.size(); j++) { if (selections[i].colId == distinctPairs_in_R[j].colId && selections[i].binding == distinctPairs_in_R[j].binding) { (sum[j] == 0) ? result_str += "NULL" : result_str += to_string(sum[j]); found = true; break; } } /* Search in the other */ for (size_t j = 0; j < distinctPairs_in_S.size() && found != true; j++) { if (selections[i].colId == distinctPairs_in_S[j].colId && selections[i].binding == distinctPairs_in_S[j].binding) { (sum[j] == 0) ? result_str += "NULL" : result_str += to_string(sum[j + distinctPairs_in_R.size()]); found = true; break; } } /* Flag for the next loop */ found = false; // Create the write check sum if (i != selections.size() - 1) { result_str += " "; } } // Frees for (size_t i = 0; i < range; i++) { chainedtuplebuffer_free_t64((chainedtuplebuffer64_t *) result->resultlist[i].results); } }
42.925144
171
0.525622
[ "vector" ]
24a6d312ddd4086b828a62b24a146e3e4e6b654e
86,285
cpp
C++
src/CSVGObject.cpp
colinw7/CSVG
049419b4114fc6ff7f5b25163398f02c21a64bf6
[ "MIT" ]
5
2015-04-11T14:56:03.000Z
2021-12-14T10:12:36.000Z
src/CSVGObject.cpp
colinw7/CSVG
049419b4114fc6ff7f5b25163398f02c21a64bf6
[ "MIT" ]
3
2015-04-20T19:23:15.000Z
2021-09-03T20:03:30.000Z
src/CSVGObject.cpp
colinw7/CSVG
049419b4114fc6ff7f5b25163398f02c21a64bf6
[ "MIT" ]
3
2015-05-21T08:33:12.000Z
2020-05-13T15:45:11.000Z
#include <CSVGObject.h> #include <CSVGFilter.h> #include <CSVGGroup.h> #include <CSVGStop.h> #include <CSVGMask.h> #include <CSVGClipPath.h> #include <CSVGBuffer.h> #include <CSVGTitle.h> #include <CSVG.h> #include <CSVGLog.h> #include <CFontMgr.h> #include <CEncode64.h> #include <CRegExp.h> #include <CFileUtil.h> #include <CStrParse.h> namespace { static uint s_ObjectInd; uint nextInd() { ++s_ObjectInd; return s_ObjectInd; } } CSVGObject:: CSVGObject(CSVG &svg) : svg_ (svg), ind_ (nextInd()), stroke_ (svg), fill_ (svg), viewportFill_(svg), clip_ (svg), fontDef_ (svg) { init(); animation_.setParent(const_cast<CSVGObject *>(this)); transform_.reset(); } CSVGObject:: CSVGObject(const CSVGObject &obj) : svg_ (obj.svg_), id_ (obj.id_), classes_ (obj.classes_), parent_ (obj.parent_), ind_ (nextInd()), opacity_ (obj.opacity_), text_ (obj.text_), stroke_ (obj.stroke_), fill_ (obj.fill_), overflow_ (obj.overflow_), visibility_ (obj.visibility_), display_ (obj.display_), currentColor_ (obj.currentColor_), viewportFill_ (obj.viewportFill_), clip_ (obj.clip_), fontDef_ (obj.fontDef_), textAnchor_ (obj.textAnchor_), textDecoration_ (obj.textDecoration_), letterSpacing_ (obj.letterSpacing_), wordSpacing_ (obj.wordSpacing_), nameValues_ (obj.nameValues_), styleValues_ (obj.styleValues_), transform_ (obj.transform_), enableBackground_ (obj.enableBackground_), enableBackgroundRect_ (obj.enableBackgroundRect_), externalResourcesRequired_(obj.externalResourcesRequired_), objects_ (), animation_ (), filter_ (obj.filter_), filtered_ (obj.filtered_), mask_ (obj.mask_), masked_ (obj.masked_), clipPath_ (obj.clipPath_), clipped_ (obj.clipped_), marker_ (obj.marker_), viewBox_ (obj.viewBox_), bbox_ (obj.bbox_), selected_ (obj.selected_), inside_ (obj.inside_), xmlTag_ (obj.xmlTag_), outBuffer_ (obj.outBuffer_) { init(); animation_.setParent(const_cast<CSVGObject *>(this)); // add children for (const auto &o : obj.children()) { auto *child = o->dup(); addChildObject(child); } } CSVGObject:: ~CSVGObject() { for (auto &o : objects_) delete o; } void CSVGObject:: init() { skipNames_.insert("id"); skipNames_.insert("viewBox"); skipNames_.insert("transform"); } void CSVGObject:: setParent(CSVGObject *parent) { parent_ = parent; } int CSVGObject:: getDepth() const { return (getParent() ? getParent()->getDepth() + 1 : 0); } std::string CSVGObject:: autoName() { // TODO: Move to SVG, name per depth using IdMap = std::map<std::string, int>; static IdMap idMap; auto typeName = getObjType().getName(); auto p = idMap.find(typeName); if (p == idMap.end()) p = idMap.insert(p, IdMap::value_type(typeName, 1)); setId(CStrUtil::strprintf("%s%d", typeName.c_str(), (*p).second)); ++(*p).second; return getId(); } std::string CSVGObject:: getHierId(bool autoName) const { std::string id; if (getParent() && getParent() != svg_.getRoot()) id = getParent()->getHierId(autoName); if (id != "") id += "/"; id += getId(autoName); return id; } std::string CSVGObject:: getText() const { return text_.getValue(""); } void CSVGObject:: setText(const std::string &str) { // if (! hasText()) // std::cerr << "Option does not support text '" + str + "'\n"; std::string str1 = CStrUtil::stripSpaces(str); if (str1.empty()) return; text_ = str1; } #if 0 void CSVGObject:: setOpacity(const std::string &opacityDef) { double opacity; bool inherit; if (! svg_.decodeOpacityString(opacityDef, opacity, inherit)) { CSVGLog() << "Bad opacity value " << opacityDef; return; } setOpacity(opacity); } #endif void CSVGObject:: updateStroke(const CSVGStroke &stroke, bool recurse) { stroke_.update(stroke); if (recurse) { for (auto &c : children()) c->updateStroke(stroke, recurse); } } void CSVGObject:: updateFill(const CSVGFill &fill, bool recurse) { fill_.update(fill); if (recurse) { for (auto &c : children()) c->updateFill(fill, recurse); } } //------ CSVGStroke CSVGObject:: getFlatStroke() const { CSVGStroke stroke(svg_); if (! stroke_.isSet()) { auto *parent = getParent(); if (parent) return parent->getFlatStroke(); else return stroke; } auto color = getFlatStrokeColor(); if (color.isValid()) stroke.setColor(color.getValue()); else stroke.resetColor(); //--- auto opacity = getFlatStrokeOpacity(); if (opacity.isValid()) stroke.setOpacity(opacity.getValue()); else stroke.resetOpacity(); //--- auto rule = getFlatStrokeRule(); if (rule.isValid()) stroke.setRule(rule.getValue()); else stroke.resetRule(); //--- auto url = getFlatStrokeUrl(); if (url.isValid()) stroke.setUrl(url.getValue()); else stroke.resetUrl(); //--- auto obj = getFlatStrokeFillObject(); if (obj.isValid()) stroke.setFillObject(obj.getValue()); else stroke.resetFillObject(); //--- auto width = getFlatStrokeWidth(); if (width.isValid()) stroke.setWidth(width.getValue()); else stroke.resetWidth(); //--- auto dash = getFlatStrokeDashArray(); if (dash.isValid()) stroke.setDashArray(dash.getValue()); else stroke.resetDashArray(); //--- auto offset = getFlatStrokeDashOffset(); if (offset.isValid()) stroke.setDashOffset(offset.getValue()); else stroke.resetDashOffset(); //--- auto lineCap = getFlatStrokeLineCap(); if (lineCap.isValid()) stroke.setLineCap(lineCap.getValue()); else stroke.resetLineCap(); //--- auto lineJoin = getFlatStrokeLineJoin(); if (lineJoin.isValid()) stroke.setLineJoin(lineJoin.getValue()); else stroke.resetLineJoin(); //--- auto mlimit = getFlatStrokeMiterLimit(); if (mlimit.isValid()) stroke.setMiterLimit(mlimit.getValue()); else stroke.resetMiterLimit(); return stroke; } COptValT<CSVGObject::Color> CSVGObject:: getFlatStrokeColor() const { // if color set use it if (stroke_.getColorValid()) return COptValT<Color>(stroke_.getColor()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getColorValid()) return COptValT<Color>(parent->stroke_.getColor()); parent = parent->getParent(); } return COptValT<Color>(); } COptValT<CSVGObject::Opacity> CSVGObject:: getFlatStrokeOpacity() const { // if opacity set use it if (stroke_.getOpacityValid()) return COptValT<Opacity>(stroke_.getOpacity()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getOpacityValid()) return COptValT<Opacity>(parent->stroke_.getOpacity()); parent = parent->getParent(); } return COptValT<Opacity>(); } COptValT<CSVGObject::FillType> CSVGObject:: getFlatStrokeRule() const { if (stroke_.getRuleValid()) return COptValT<FillType>(stroke_.getRule()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getRuleValid()) return COptValT<FillType>(parent->getFlatStrokeRule()); parent = parent->getParent(); } return COptValT<FillType>(); } COptString CSVGObject:: getFlatStrokeUrl() const { if (stroke_.getUrlValid()) return COptString(stroke_.getUrl()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getUrlValid()) return parent->getFlatStrokeUrl(); parent = parent->getParent(); } return COptString(); } COptValT<CSVGObject*> CSVGObject:: getFlatStrokeFillObject() const { if (stroke_.getFillObjectValid()) return COptValT<CSVGObject*>(stroke_.getFillObject()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getFillObjectValid()) return COptValT<CSVGObject*>(parent->getFlatStrokeFillObject()); parent = parent->getParent(); } return COptValT<CSVGObject*>(); } COptValT<CSVGObject::Width> CSVGObject:: getFlatStrokeWidth() const { if (stroke_.getWidthValid()) return COptValT<Width>(stroke_.getWidth()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getWidthValid()) return COptValT<Width>(parent->getFlatStrokeWidth()); parent = parent->getParent(); } return COptValT<Width>(); } COptValT<CSVGObject::DashArray> CSVGObject:: getFlatStrokeDashArray() const { if (stroke_.getDashArrayValid()) return COptValT<DashArray>(stroke_.getDashArray()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getDashArrayValid()) return COptValT<DashArray>(parent->getFlatStrokeDashArray()); parent = parent->getParent(); } return COptValT<DashArray>(); } COptValT<CSVGObject::DashOffset> CSVGObject:: getFlatStrokeDashOffset() const { if (stroke_.getDashOffsetValid()) return COptValT<DashOffset>(stroke_.getDashOffset()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getDashOffsetValid()) return COptValT<DashOffset>(parent->getFlatStrokeDashOffset()); parent = parent->getParent(); } return COptValT<DashOffset>(); } COptValT<CSVGObject::LineCap> CSVGObject:: getFlatStrokeLineCap() const { if (stroke_.getLineCapValid()) return COptValT<LineCap>(stroke_.getLineCap()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getLineCapValid()) return COptValT<LineCap>(parent->getFlatStrokeLineCap()); parent = parent->getParent(); } return COptValT<LineCap>(); } COptValT<CSVGObject::LineJoin> CSVGObject:: getFlatStrokeLineJoin() const { if (stroke_.getLineJoinValid()) return COptValT<LineJoin>(stroke_.getLineJoin()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getLineJoinValid()) return COptValT<LineJoin>(parent->getFlatStrokeLineJoin()); parent = parent->getParent(); } return COptValT<LineJoin>(); } COptValT<CSVGObject::MiterLimit> CSVGObject:: getFlatStrokeMiterLimit() const { if (stroke_.getMiterLimitValid()) return COptValT<MiterLimit>(stroke_.getMiterLimit()); auto *parent = getParent(); while (parent) { if (parent->stroke_.getMiterLimitValid()) return COptValT<MiterLimit>(parent->getFlatStrokeMiterLimit()); parent = parent->getParent(); } return COptValT<MiterLimit>(); } //------ CSVGFill CSVGObject:: getFlatFill() const { CSVGFill fill(svg_); auto color = getFlatFillColor(); if (color.isValid()) fill.setColor(color.getValue()); else fill.resetColor(); //--- auto opacity = getFlatFillOpacity(); if (opacity.isValid()) fill.setOpacity(opacity.getValue()); else fill.resetOpacity(); //--- auto rule = getFlatFillRule(); if (rule.isValid()) fill.setRule(rule.getValue()); else fill.resetRule(); //--- auto url = getFlatFillUrl(); if (url.isValid()) fill.setUrl(url.getValue()); else fill.resetUrl(); //--- auto obj = getFlatFillFillObject(); if (obj.isValid()) fill.setFillObject(obj.getValue()); else fill.resetFillObject(); return fill; } COptValT<CSVGObject::Color> CSVGObject:: getFlatFillColor() const { // if color set use it if (fill_.getColorValid() && ! fill_.getColor().isInherit()) return COptValT<Color>(fill_.getColor()); auto *parent = getParent(); while (parent) { if (parent->fill_.getColorValid()) return COptValT<Color>(parent->fill_.getColor()); parent = parent->getParent(); } return COptValT<Color>(); } COptValT<CSVGObject::Opacity> CSVGObject:: getFlatFillOpacity() const { // if opacity set use it if (fill_.getOpacityValid() && ! fill_.getOpacity().isInherit()) return COptValT<Opacity>(fill_.getOpacity()); auto *parent = getParent(); while (parent) { if (parent->fill_.getOpacityValid()) return COptValT<Opacity>(parent->fill_.getOpacity()); parent = parent->getParent(); } return COptValT<Opacity>(); } COptValT<CSVGObject::FillType> CSVGObject:: getFlatFillRule() const { // if opacity set use it if (fill_.getRuleValid() && ! fill_.getRule().isInherit()) return COptValT<FillType>(fill_.getRule()); auto *parent = getParent(); while (parent) { if (parent->fill_.getRuleValid()) return COptValT<FillType>(parent->fill_.getRule()); parent = parent->getParent(); } return COptValT<FillType>(); } COptString CSVGObject:: getFlatFillUrl() const { // if opacity set use it if (fill_.getUrlValid()) return COptString(fill_.getUrl()); auto *parent = getParent(); while (parent) { if (parent->fill_.getUrlValid()) return COptString(parent->fill_.getUrl()); parent = parent->getParent(); } return COptString(); } COptValT<CSVGObject *> CSVGObject:: getFlatFillFillObject() const { // if opacity set use it if (fill_.getFillObjectValid()) return COptValT<CSVGObject *>(fill_.getFillObject()); auto *parent = getParent(); while (parent) { if (parent->fill_.getFillObjectValid()) return COptValT<CSVGObject *>(parent->fill_.getFillObject()); parent = parent->getParent(); } return COptValT<CSVGObject *>(); } CSVGFontDef CSVGObject:: getFlatFontDef() const { auto fontFamily = getFlatFontFamily(); auto fontSize = getFlatFontSize(); auto fontStyles = getFlatFontStyle(); CSVGFontDef fontDef(svg_); if (fontFamily.isValid()) fontDef.setFamily(fontFamily.getValue()); if (fontSize.isValid()) fontDef.setSize(fontSize.getValue()); fontDef.setStyle(fontStyles); return fontDef; } COptValT<CSVGObject::FontFamily> CSVGObject:: getFlatFontFamily() const { if (fontDef_.hasFamily()) return COptValT<FontFamily>(fontDef_.getFamily()); auto *parent = getParent(); while (parent) { if (parent->fontDef_.hasFamily()) return parent->getFlatFontFamily(); parent = parent->getParent(); } return COptValT<FontFamily>(FontFamily("serif")); } CFontStyles CSVGObject:: getFlatFontStyle() const { if (fontDef_.hasStyle()) return fontDef_.getStyle(); auto *parent = getParent(); while (parent) { if (parent->fontDef_.hasStyle()) return parent->getFlatFontStyle(); parent = parent->getParent(); } return CFontStyles(CFONT_STYLE_NORMAL); } COptValT<CSVGObject::FontSize> CSVGObject:: getFlatFontSize() const { if (fontDef_.hasSize()) return COptValT<FontSize>(fontDef_.getSize()); auto *parent = getParent(); while (parent) { if (parent->fontDef_.hasSize()) return parent->getFlatFontSize(); parent = parent->getParent(); } return COptValT<FontSize>(FontSize(CScreenUnits(12))); } // [[ <family-name> | <generic-family> ],]* [<family-name> | <generic-family>] | inherit void CSVGObject:: setFontFamily(const FontFamily &family) { fontDef_.setFamily(family); } void CSVGObject:: setFontSize(const FontSize &size) { fontDef_.setSize(size); } // normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit void CSVGObject:: setFontWeight(const std::string &weight) { fontDef_.setWeight(weight); } // normal | italic | oblique | inherit void CSVGObject:: setFontStyle(const std::string &style) { fontDef_.setStyle(style); } void CSVGObject:: setFontStyle(CFontStyle s) { fontDef_.setStyle(s); } CRGBA CSVGObject:: colorToRGBA(const Color &color) const { CSVGColor c; if (! color.isInherit()) c = color.getValue(); // inherit, none if (color.isInherit() || c.isNone()) { if (getParent()) return getParent()->colorToRGBA(color); else return CRGBA(0, 0, 0); } if (c.isRGBA()) return c.rgba(); if (c.isCurrent()) return getFlatCurrentColor(); return CRGBA(0, 0, 0, 0); } CRGBA CSVGObject:: getFlatCurrentColor() const { if (hasCurrentColor()) { auto color = currentColor(); if (color.isRGBA()) return color.rgba(); } if (getParent()) return getParent()->getFlatCurrentColor(); return CRGBA(0, 0, 0); } //--- CMatrixStack2D CSVGObject:: getFlatTransform() const { if (getParent()) { auto matrix = getParent()->getFlatTransform(); matrix.append(getTransform()); return matrix; } else return getTransform(); } CMatrixStack2D CSVGObject:: getTransformTo(CSVGObject *parent) const { auto *parent1 = getParent(); if (parent1 && parent != parent1) { auto matrix = parent1->getTransformTo(parent); matrix.append(getTransform()); return matrix; } else return getTransform(); } void CSVGObject:: untransform() { if (hasChildren()) { auto t = getTransform(); for (auto &c : children()) { auto t1 = c->getTransform(); t1.append(t); c->setTransform(t1); } setTransform(CMatrixStack2D()); } } //--- void CSVGObject:: setStyle(const std::string &style) { // Syntax: // name_value = <name> ':' <value> // name_value_list = <name_value> | <name_value> ';' <name_value_list> CStrParse parse(style); while (! parse.eof()) { parse.skipSpace(); if (parse.isChar(';')) { parse.skipChar(); continue; } //--- // get name (non-space) to next colon (TODO: quoted ?) std::string name; while (! parse.eof() && ! parse.isSpace() && ! parse.isChar(':')) name += parse.readChar(); parse.skipSpace(); //--- // get value std::string value; if (parse.isChar(':')) { parse.skipChar(); parse.skipSpace(); if (parse.isChar('\'') || parse.isChar('"')) { // get quoted value (TODO: escaping ok ?) (void) parse.readString(value, /*strip_quotes*/true); } else { // get non-quoted value (non-space) to next semi colon while (! parse.eof() && ! parse.isSpace() && ! parse.isChar(';')) value += parse.readChar(); } } if (name != "") processStyleNameValue(name, value); else CSVGLog() << "Missing name for style value '" << value << "' for " << getTagName(); } #if 0 std::vector<std::string> words; CStrUtil::addFields(style, words, ";"); uint num_words = words.size(); for (uint i = 0; i < num_words; ++i) { std::vector<std::string> words1; words[i] = CStrUtil::stripSpaces(words[i]); if (words[i] == "") continue; CStrUtil::addFields(words[i], words1, ":"); uint num_words1 = words1.size(); if (num_words1 != 2) { CSVGLog() << "Invalid style name/value format '" << words[i] << "' for " << getTagName(); continue; } auto name = CStrUtil::stripSpaces(words1[0]); auto value = CStrUtil::stripSpaces(words1[1]); processStyleNameValue(name, value); } #endif } void CSVGObject:: processStyleNameValue(const std::string &name, const std::string &value) { if (! processPaintOption (name, value) && ! processColorOption (name, value) && ! processFontOption (name, value) && ! processTextContentOption(name, value) && ! processOpacityOption (name, value) && ! processMarkerOption (name, value) && ! processGradientOption (name, value) && ! processGraphicsOption (name, value) && ! processClipOption (name, value) && ! processMaskOption (name, value) && ! processTextOption (name, value) && ! processFilterOption (name, value) && ! processCSSOption (name, value) && ! processContainerOption (name, value)) { if (! svg_.isQuiet()) CSVGLog() << "Invalid style option " << name << ":" << value << " for " << getTagName(); } } void CSVGObject:: setSelected(bool selected, bool hier) { selected_ = selected; if (hier) { for (auto &c : children()) c->setSelected(selected, hier); } } //--- bool CSVGObject:: handleOption(const std::string &name, const std::string &value) { setNameValue(name, value); return processOption(name, value); } bool CSVGObject:: processOption(const std::string &optName, const std::string &optValue) { if (! processSubOption(optName, optValue)) { if (! svg_.isQuiet()) CSVGLog() << "Unhandled option " << optName << " for " << getTagName(); return true; // don't propagate warning } return true; } bool CSVGObject:: processSubOption(const std::string &optName, const std::string &optValue) { if (processCoreOption (optName, optValue)) return true; if (processConditionalOption (optName, optValue)) return true; if (processStyleOption (optName, optValue)) return true; if (processPaintOption (optName, optValue)) return true; if (processColorOption (optName, optValue)) return true; if (processOpacityOption (optName, optValue)) return true; if (processGraphicsOption (optName, optValue)) return true; if (processMarkerOption (optName, optValue)) return true; if (processClipOption (optName, optValue)) return true; if (processMaskOption (optName, optValue)) return true; if (processFilterOption (optName, optValue)) return true; if (processGradientOption (optName, optValue)) return true; if (processGraphicalEventsOption(optName, optValue)) return true; if (processCursorOption (optName, optValue)) return true; if (processExternalOption (optName, optValue)) return true; if (processFontOption (optName, optValue)) return true; if (processTextContentOption (optName, optValue)) return true; if (processContainerOption (optName, optValue)) return true; if (processViewportOption (optName, optValue)) return true; std::string str; CBBox2D bbox; CMatrixStack2D transform; // Other properties if (svg_.transformOption(optName, optValue, "transform", transform)) setTransform(transform); else if (svg_.bboxOption(optName, optValue, "viewBox", bbox)) viewBox_ = bbox; // xmlns else if (CRegExpUtil::parse(optName, "xmlns:.*")) { //notHandled(optName, optValue); } else if (CRegExpUtil::parse(optName, "sodipodi:.*")) { //notHandled(optName, optValue); } else if (CRegExpUtil::parse(optName, "inkscape:.*")) { //notHandled(optName, optValue); } else { return false; } return true; } bool CSVGObject:: processCoreOption(const std::string &optName, const std::string &optValue) { std::string str; // Core Attributes if (svg_.stringOption(optName, optValue, "id", str)) setId(str); else if (svg_.stringOption(optName, optValue, "class", str)) { std::vector<std::string> classes; CStrUtil::addWords(str, classes, " "); setClasses(classes); } else if (svg_.stringOption(optName, optValue, "xml:base", str)) notHandled(optName, optValue); else if (svg_.stringOption(optName, optValue, "xml:lang", str)) notHandled(optName, optValue); else if (svg_.stringOption(optName, optValue, "xml:space", str)) /* default or preserve */; else if (svg_.stringOption(optName, optValue, "xml:id", str)) setId(str); else return false; return true; } bool CSVGObject:: processConditionalOption(const std::string &optName, const std::string &optValue) { std::string str; // Conditional Attributes if (svg_.stringOption(optName, optValue, "requiredFeatures", str)) { setId(str); } else if (svg_.stringOption(optName, optValue, "requiredExtensions", str)) { //setNameValue("requiredExtensions", str); } else if (svg_.stringOption(optName, optValue, "requiredFonts", str)) { //setNameValue("requiredFonts", str); } else if (svg_.stringOption(optName, optValue, "requiredFormats", str)) { //setNameValue("requiredFormats", str); } else if (svg_.stringOption(optName, optValue, "systemLanguage", str)) { //setNameValue("systemLanguage", str); } else return false; return true; } bool CSVGObject:: processStyleOption(const std::string &optName, const std::string &optValue) { std::string str; // Style Attributes if (svg_.stringOption(optName, optValue, "style", str)) setStyle(str); else if (svg_.stringOption(optName, optValue, "class", str)) { // duplicate ? std::vector<std::string> classes; CStrUtil::addWords(str, classes, " "); setClasses(classes); } else return false; return true; } bool CSVGObject:: processPaintOption(const std::string &optName, const std::string &optValue) { std::string str; // Paint Attributes if (svg_.stringOption(optName, optValue, "fill", str)) setFillColor(str); else if (svg_.stringOption(optName, optValue, "fill-rule", str)) setFillRule(str); else if (svg_.stringOption(optName, optValue, "stroke", str)) setStrokeColor(str); else if (svg_.stringOption(optName, optValue, "stroke-dasharray", str)) setStrokeDashArray(str); else if (svg_.stringOption(optName, optValue, "stroke-dashoffset", str)) setStrokeDashOffset(str); else if (svg_.stringOption(optName, optValue, "stroke-linecap", str)) setStrokeLineCap(str); else if (svg_.stringOption(optName, optValue, "stroke-linejoin", str)) setStrokeLineJoin(str); else if (svg_.stringOption(optName, optValue, "stroke-miterlimit", str)) setStrokeMiterLimit(str); else if (svg_.stringOption(optName, optValue, "stroke-width", str)) setStrokeWidth(str); else if (svg_.stringOption(optName, optValue, "overflow", str)) setOverflow(str); else if (svg_.stringOption(optName, optValue, "visibility", str)) // TODO: duplicate setVisibility(str); // visible | hidden | collapse | inherit else if (svg_.stringOption(optName, optValue, "display", str)) // TODO: duplicate setDisplay(str); // inline | block | list-item| run-in | compact | marker else return false; return true; } bool CSVGObject:: processColorOption(const std::string &optName, const std::string &optValue) { std::string str; CSVGColor color; bool inherit; // Color Attributes if (svg_.colorOption(optName, optValue, "color", color, inherit)) { setCurrentColor(color); } else if (svg_.stringOption(optName, optValue, "color-interpolation", str)) { //setNameValue("color-interpolation", str); } else if (svg_.stringOption(optName, optValue, "color-rendering", str)) { // auto | optimizeSpeed | optimizeQuality | inherit //setNameValue("color-rendering", str); } else if (svg_.colorOption(optName, optValue, "solid-color", color, inherit)) { notHandled(optName, optValue); } else return false; return true; } bool CSVGObject:: processColorProfileOption(const std::string &optName, const std::string &optValue) { std::string str; // Color Profile if (svg_.stringOption(optName, optValue, "color-profile", str)) { //setNameValue("color-profile", str); } else return false; return true; } bool CSVGObject:: processFilterColorOption(const std::string &optName, const std::string &optValue) { std::string str; // Filter Color if (svg_.stringOption(optName, optValue, "color-interpolation-filters", str)) { //setNameValue("color-interpolation-filters", str); } else return false; return true; } bool CSVGObject:: processOpacityOption(const std::string &optName, const std::string &optValue) { std::string str; double real; bool inherit; // Opacity Attributes if (svg_.opacityOption(optName, optValue, "opacity", real, inherit)) setOpacity(! inherit ? Opacity(real) : Opacity::makeInherit()); else if (svg_.stringOption(optName, optValue, "fill-opacity", str)) setFillOpacity(str); else if (svg_.stringOption(optName, optValue, "stroke-opacity", str)) setStrokeOpacity(str); else if (svg_.opacityOption(optName, optValue, "solid-opacity", real, inherit)) notHandled(optName, optValue); else return false; return true; } bool CSVGObject:: processGraphicsOption(const std::string &optName, const std::string &optValue) { std::string str; // Graphics Attributes if (svg_.stringOption(optName, optValue, "display", str)) // inline | block | list-item | run-in | compact | marker | table | inline-table | // table-row-group | table-header-group | table-footer-group | table-row | // table-column-group | table-column | table-cell | table-caption | none | inherit setDisplay(str); else if (svg_.stringOption(optName, optValue, "image-rendering", str)) { // auto | optimizeSpeed | optimizeQuality | inherit //setNameValue("image-rendering", str); } else if (svg_.stringOption(optName, optValue, "pointer-events", str)) { // visiblePainted | visibleFill | visibleStroke | visible | painted | fill | // stroke | all | none | inherit //setNameValue("pointer-events", str); } else if (svg_.stringOption(optName, optValue, "shape-rendering", str)) { // auto | optimizeSpeed | crispEdges | geometricPrecision | inherit //setNameValue("shape-rendering", str); } else if (svg_.stringOption(optName, optValue, "text-rendering", str)) { // TODO: duplicate // auto | optimizeSpeed | optimizeLegibility | geometricPrecision | inherit //setNameValue("text-rendering", str); } else if (svg_.stringOption(optName, optValue, "buffered-rendering", str)) { // auto | dynamic | static | inherit //setNameValue("buffered-rendering", str); } else if (svg_.stringOption(optName, optValue, "visibility", str)) { setVisibility(str); // visible | hidden | collapse | inherit } else if (svg_.stringOption(optName, optValue, "vector-effect", str)) { // non-scaling-stroke | none | inherit //setNameValue("vector-effect", str); } else return false; return true; } bool CSVGObject:: processMarkerOption(const std::string &optName, const std::string &optValue) { std::string str; CSVGObject* obj; // Marker if (svg_.urlOption(optName, optValue, "marker", &obj)) { // no shortcut "marker" for group (other grouping svg) auto *group = dynamic_cast<CSVGGroup *>(this); if (! group) { setMarkerStart(obj); setMarkerMid (obj); setMarkerEnd (obj); } } else if (svg_.urlOption(optName, optValue, "marker-start", &obj)) setMarkerStart(obj); else if (svg_.urlOption(optName, optValue, "marker-mid", &obj)) setMarkerMid(obj); else if (svg_.urlOption(optName, optValue, "marker-end", &obj)) setMarkerEnd(obj); else return false; return true; } bool CSVGObject:: processClipOption(const std::string &optName, const std::string &optValue) { std::string str; CSVGObject* obj; if (svg_.urlOption(optName, optValue, "clip-path", &obj)) clipPath_ = dynamic_cast<CSVGClipPath *>(obj); else if (svg_.stringOption(optName, optValue, "clip-rule", str)) { setClipRule(str); } else return false; return true; } bool CSVGObject:: processPresentationOption(const std::string &optName, const std::string &optValue) { std::string str; if (processContainerOption (optName, optValue)) return true; if (processViewportOption (optName, optValue)) return true; if (processTextOption (optName, optValue)) return true; if (processTextContentOption (optName, optValue)) return true; if (processFontOption (optName, optValue)) return true; if (processPaintOption (optName, optValue)) return true; if (processColorOption (optName, optValue)) return true; if (processOpacityOption (optName, optValue)) return true; if (processGraphicsOption (optName, optValue)) return true; if (processMarkerOption (optName, optValue)) return true; if (processColorProfileOption(optName, optValue)) return true; if (processGradientOption (optName, optValue)) return true; if (processClipOption (optName, optValue)) return true; if (processMaskOption (optName, optValue)) return true; if (processFilterOption (optName, optValue)) return true; if (processFilterColorOption (optName, optValue)) return true; if (processCursorOption (optName, optValue)) return true; // Presentation if (svg_.stringOption(optName, optValue, "flood-color", str)) { //setNameValue("flood-color", str); } else if (svg_.stringOption(optName, optValue, "flood-opacity", str)) { //setNameValue("flood-opacity", str); } else if (svg_.stringOption(optName, optValue, "lighting-color", str)) { //setNameValue("lighting-color", str); } else return false; return true; } bool CSVGObject:: processMaskOption(const std::string &optName, const std::string &optValue) { CSVGObject *obj; if (svg_.urlOption(optName, optValue, "mask", &obj)) mask_ = dynamic_cast<CSVGMask *>(obj); else return false; return true; } bool CSVGObject:: processFilterOption(const std::string &optName, const std::string &optValue) { CSVGObject *obj; // Filter Attributes if (svg_.urlOption(optName, optValue, "filter", &obj)) filter_ = dynamic_cast<CSVGFilter *>(obj); else return false; return true; } bool CSVGObject:: processViewportOption(const std::string &optName, const std::string &optValue) { std::string str; CSVGColor color; double real; bool inherit; if (svg_.stringOption(optName, optValue, "clip", str)) { //setNameValue("clip", str); } else if (svg_.stringOption(optName, optValue, "overflow", str)) setOverflow(str); else if (svg_.colorOption(optName, optValue, "viewport-fill", color, inherit)) setViewportFillColor(! inherit ? Color(color) : Color::makeInherit()); else if (svg_.opacityOption(optName, optValue, "viewport-fill-opacity", real, inherit)) setViewportFillOpacity(! inherit ? Opacity(real) : Opacity::makeInherit()); else return false; return true; } bool CSVGObject:: processGradientOption(const std::string &optName, const std::string &optValue) { std::string str; // Gradient Properties if (svg_.stringOption(optName, optValue, "stop-color", str)) { auto *stop = dynamic_cast<CSVGStop *>(this); if (stop) stop->processOption(optName, optValue); else notHandled(optName, optValue); } else if (svg_.stringOption(optName, optValue, "stop-opacity", str)) { auto *stop = dynamic_cast<CSVGStop *>(this); if (stop) stop->processOption(optName, optValue); else notHandled(optName, optValue); } else return false; return true; } bool CSVGObject:: processContainerOption(const std::string &optName, const std::string &optValue) { std::string str; // Container Properties if (svg_.stringOption(optName, optValue, "enable-background", str)) { CStrParse parse(str); parse.skipSpace(); std::string word; parse.readNonSpace(word); if (word == "accumulate") enableBackground_ = CSVGEnableBackground::ACCUMULATE; else if (word == "new") enableBackground_ = CSVGEnableBackground::NEW; parse.skipSpace(); double x1, y1, x2, y2; if (parse.readReal(&x1) && parse.readReal(&y1) && parse.readReal(&x2) && parse.readReal(&y2)) enableBackgroundRect_ = CBBox2D(x1, y1, x2, y2); } else return false; return true; } bool CSVGObject:: processGraphicalEventsOption(const std::string &optName, const std::string &optValue) { std::string str; if (svg_.stringOption(optName, optValue, "onfocusin" , str)) { //setNameValue("onfocusin", str); } else if (svg_.stringOption(optName, optValue, "onfocusout" , str)) { //setNameValue("onfocusout", str); } else if (svg_.stringOption(optName, optValue, "onactivate" , str)) { //setNameValue("onactivate", str); } else if (svg_.stringOption(optName, optValue, "onclick" , str)) { //setNameValue("onclick", str); } else if (svg_.stringOption(optName, optValue, "onmousedown", str)) { //setNameValue("onmousedown", str); } else if (svg_.stringOption(optName, optValue, "onmouseup" , str)) { //setNameValue("onmouseup", str); } else if (svg_.stringOption(optName, optValue, "onmouseover", str)) { //setNameValue("onmouseover", str); } else if (svg_.stringOption(optName, optValue, "onmousemove", str)) { //setNameValue("onmousemove", str); } else if (svg_.stringOption(optName, optValue, "onmouseout" , str)) { //setNameValue("onmouseout", str); } else if (svg_.stringOption(optName, optValue, "onload" , str)) { //setNameValue("onload", str); } else return false; return true; } bool CSVGObject:: processDocumentEventsOption(const std::string &optName, const std::string &optValue) { std::string str; if (svg_.stringOption(optName, optValue, "onunload", str)) notHandled(optName, optValue); else if (svg_.stringOption(optName, optValue, "onabort", str)) notHandled(optName, optValue); else if (svg_.stringOption(optName, optValue, "onerror", str)) notHandled(optName, optValue); else if (svg_.stringOption(optName, optValue, "onresize", str)) notHandled(optName, optValue); else if (svg_.stringOption(optName, optValue, "onscroll", str)) notHandled(optName, optValue); else if (svg_.stringOption(optName, optValue, "onzoom", str)) notHandled(optName, optValue); else return false; return true; } bool CSVGObject:: processAnimationEventsOption(const std::string &optName, const std::string &optValue) { std::string str; if (svg_.stringOption(optName, optValue, "onbegin", str)) { //setNameValue("onbegin", str); } else if (svg_.stringOption(optName, optValue, "onend", str)) { //setNameValue("onend", str); } else if (svg_.stringOption(optName, optValue, "onrepeat", str)) { //setNameValue("onrepeat", str); } else if (svg_.stringOption(optName, optValue, "onload", str)) { //setNameValue("onload", str); } else return false; return true; } bool CSVGObject:: processCursorOption(const std::string &optName, const std::string &optValue) { std::string str; if (svg_.stringOption(optName, optValue, "cursor", str)) notHandled(optName, optValue); else return false; return true; } bool CSVGObject:: processExternalOption(const std::string &optName, const std::string &optValue) { bool b; if (svg_.booleanOption(optName, optValue, "externalResourcesRequired", b)) setExternalResourcesRequired(b); else return false; return true; } bool CSVGObject:: processFontOption(const std::string &optName, const std::string &optValue) { std::string str; CScreenUnits length; bool inherit; // Font properties if (svg_.stringOption(optName, optValue, "font", str)) parseFont(str); else if (svg_.fontFamilyOption(optName, optValue, "font-family", str, inherit)) setFontFamily(! inherit ? FontFamily(str) : FontFamily::makeInherit()); else if (svg_.fontSizeOption(optName, optValue, "font-size", length, inherit)) setFontSize(! inherit ? FontSize(length) : FontSize::makeInherit()); else if (svg_.stringOption(optName, optValue, "font-size-adjust", str)) { //setNameValue("font-size-adjust", str); } else if (svg_.stringOption(optName, optValue, "font-stretch", str)) { //setNameValue("font-stretch", str); } else if (svg_.stringOption(optName, optValue, "font-style", str)) { setFontStyle(str); } // normal | small-caps | inherit else if (svg_.stringOption(optName, optValue, "font-variant", str)) { //setNameValue("font-variant", str); } else if (svg_.stringOption(optName, optValue, "font-weight", str)) { setFontWeight(str); } else if (svg_.stringOption(optName, optValue, "line-increment", str)) { //setNameValue("line-increment", str); } else if (svg_.stringOption(optName, optValue, "text-align", str)) { //setNameValue("text-align", str); } else if (svg_.stringOption(optName, optValue, "display-align", str)) { //setNameValue("display-align", str); } else if (svg_.stringOption(optName, optValue, "line-height", str)) { //setNameValue("line-height", str); } else if (svg_.stringOption(optName, optValue, "-inkscape-font-specification", str)) { //setNameValue("-inkscape-font-specification", str); } else return false; return true; } bool CSVGObject:: parseFont(const std::string &str) { CStrParse parse(str); parse.skipSpace(); if (parse.isDigit()) { std::string word; parse.readNonSpace(word); auto length = svg_.decodeLengthValue(word); if (! length.isValid()) { CSVGLog() << "Illegal font length value '" << word << "'"; return false; } parse.skipSpace(); parse.readNonSpace(word); std::vector<std::string> words; CStrUtil::addFields(word, words, ","); if (! words.empty()) setFontFamily(FontFamily(words[0])); } else { //CSVGLog() << "Invalid font string '" << str << "'"; //return false; setFontFamily(FontFamily(str)); } return true; } bool CSVGObject:: processTextOption(const std::string &optName, const std::string &optValue) { std::string str; // Text properties if (svg_.stringOption(optName, optValue, "writing-mode", str)) setWritingMode(str); else return false; return true; } bool CSVGObject:: processTextContentOption(const std::string &optName, const std::string &optValue) { std::string str; CScreenUnits length; // Text content propeties if (svg_.stringOption(optName, optValue, "alignment-baseline", str)) { //setNameValue("alignment-baseline", str); } else if (svg_.stringOption(optName, optValue, "baseline-shift", str)) { setTextBaselineShift(str); } else if (svg_.stringOption(optName, optValue, "dominant-baseline", str)) { //setNameValue("dominant-baseline", str); } else if (svg_.stringOption(optName, optValue, "glyph-orientation-horizontal", str)) { setHGlyphOrient(str); } else if (svg_.stringOption(optName, optValue, "glyph-orientation-vertical", str)) { setVGlyphOrient(str); } else if (svg_.stringOption(optName, optValue, "kerning", str)) { //setNameValue("kerning", str); } else if (svg_.stringOption(optName, optValue, "text-anchor", str)) { setTextAnchor(str); } else if (svg_.stringOption(optName, optValue, "direction", str)) { // ltr | rtl | inherit //setNameValue("direction", str); } else if (svg_.letterSpacingOption(optName, optValue, "letter-spacing", length)) { letterSpacing_ = length; } else if (svg_.stringOption(optName, optValue, "text-decoration", str)) { setTextDecoration(str); } else if (svg_.stringOption(optName, optValue, "text-rendering", str)) { // auto | optimizeSpeed | optimizeLegibility | geometricPrecision | inherit //setNameValue("text-rendering", str); } // normal | embed | bidi-override | inherit else if (svg_.stringOption(optName, optValue, "unicode-bidi", str)) { //setNameValue("unicode-bidi", str); } else if (svg_.wordSpacingOption(optName, optValue, "word-spacing", length)) { wordSpacing_ = length; } else return false; return true; } bool CSVGObject:: processCSSOption(const std::string &optName, const std::string &optValue) { std::string str; if (svg_.stringOption(optName, optValue, "background-color", str)) { //setNameValue("background-color", str); } else if (svg_.stringOption(optName, optValue, "mix-blend-mode", str)) { //setNameValue("mix-blend-mode", str); } else if (svg_.stringOption(optName, optValue, "isolation", str)) { //setNameValue("isolation", str); } else return false; return true; } void CSVGObject:: notHandled(const std::string &optName, const std::string &optValue) { if (! svg_.isQuiet()) CSVGLog() << "Option " << optName << ":" << optValue << " not handled " << "for " << getTagName(); } //--- void CSVGObject:: setNameValue(const std::string &name, const std::string &value) { nameValues_[name] = value; } bool CSVGObject:: hasNameValue(const std::string &name) const { auto p = nameValues_.find(name); return (p != nameValues_.end()); } COptString CSVGObject:: getNameValue(const std::string &name) const { COptString str; if (name == "className") { auto classes = getClasses(); if (! classes.empty()) str = classes.front(); } else if (name == "viewBox") { auto bbox = getViewBox(); str = CStrUtil::toString(bbox.getXMin()) + ", " + CStrUtil::toString(bbox.getYMin()) + ", " + CStrUtil::toString(bbox.getWidth()) + ", " + CStrUtil::toString(bbox.getHeight()); } else if (name == "transform") { str = getTransform().toString(); } else if (name == "externalResourcesRequired") { str = (isExternalResourcesRequired() ? "true" : "false"); } else { auto p = nameValues_.find(name); if (p != nameValues_.end()) str = (*p).second; } return str; } COptReal CSVGObject:: getRealNameValue(const std::string &name) const { auto str = getNameValue(name); if (! str.isValid()) return COptReal(); double r; if (! CStrUtil::toReal(str.getValue(), &r)) return COptReal(); return COptReal(r); } COptInt CSVGObject:: getIntegerNameValue(const std::string &name) const { auto str = getNameValue(name); if (! str.isValid()) return COptInt(); long i; if (! CStrUtil::toInteger(str.getValue(), &i)) return COptInt(); return COptInt(i); } //--- void CSVGObject:: setStyleValue(const std::string &name, const std::string &value) { styleValues_[name] = value; //--- std::string lname = CStrUtil::toLower(name); if (lname == "fill") fill_.setColor(value); else if (lname == "fill-opacity") fill_.setOpacity(value); else if (lname == "stroke") stroke_.setColor(value); else if (lname == "stroke-width") stroke_.setWidth(value); else if (lname == "stroke-dasharray") stroke_.setDashArray(value); else if (lname == "marker-start") { std::string id; CSVGObject *obj; if (svg_.decodeUrlObject(value, id, &obj)) marker_.setStart(obj); else CSVGLog() << "Illegal url value '" << id << "' for " << name; } else if (lname == "marker-mid") { std::string id; CSVGObject *obj; if (svg_.decodeUrlObject(value, id, &obj)) marker_.setMid(obj); else CSVGLog() << "Illegal url value '" << id << "' for " << name; } else if (lname == "marker-end") { std::string id; CSVGObject *obj; if (svg_.decodeUrlObject(value, id, &obj)) marker_.setEnd(obj); else CSVGLog() << "Illegal url value '" << id << "' for " << name; } else if (lname == "marker") { std::string id; CSVGObject *obj; if (svg_.decodeUrlObject(value, id, &obj)) { marker_.setStart(obj); marker_.setMid (obj); marker_.setEnd (obj); } else CSVGLog() << "Illegal url value '" << id << "' for " << name; } else if (lname == "font-family") { // TODO CSVGLog() << "Unhandled style font-family: " << value; } else if (lname == "font-weight") { // TODO CSVGLog() << "Unhandled style font-weight: " << value; } else if (lname == "font-style") { // TODO CSVGLog() << "Unhandled style font-style: " << value; } else if (lname == "src") { // TODO CSVGLog() << "Unhandled style src: " << value; } else CSVGLog() << "Unhandled style name: " << name << ":" << value; } bool CSVGObject:: hasStyleValue(const std::string &name) const { auto p = styleValues_.find(name); return (p != styleValues_.end()); } COptString CSVGObject:: getStyleValue(const std::string &name) const { COptString str; auto p = nameValues_.find(name); if (p != nameValues_.end()) str = (*p).second; return str; } //--- bool CSVGObject:: interpValue(const std::string &name, const std::string &from, const std::string &to, double x, std::string &ystr) const { if (name == "fill") { CSVGColor fromColor; bool fromInherit; if (! svg_.decodeColorString(from, fromColor, fromInherit)) return false; CSVGColor toColor; bool toInherit; if (! svg_.decodeColorString(to, toColor, toInherit)) { CSVGLog() << "Invalid color '" << to << "'"; return false; } auto c = fromColor.rgba()*(1 - x) + toColor.rgba()*x; ystr = CStrUtil::strprintf("rgb(%d,%d,%d)", c.getRedI(), c.getGreenI(), c.getBlueI()); return true; } else if (from == to) { ystr = from; return true; } else { double fromVal = 0; uint fromPos = 0; if (! CStrUtil::readReal(from, &fromPos, &fromVal)) { CSVGLog() << "Invalid real '" << from << "'"; return false; } double toVal = 0; uint toPos = 0; if (! CStrUtil::readReal(to, &toPos, &toVal)) return false; double y = CMathUtil::map(x, 0, 1, fromVal, toVal); ystr = std::to_string(y); return true; } } double CSVGObject:: pathLength() const { return getPartList().getLength(); } bool CSVGObject:: pointAtLength(double l, CPoint2D &p, double &a, int &pi) const { double s = l/pathLength(); double xi, yi; if (! getPartList().interp(s, &xi, &yi, &a, &pi)) return false; p = CPoint2D(xi, yi); return true; } void CSVGObject:: setOverflow(const std::string &str) { bool inherit = false; CSVGOverflowType overflow = CSVGOverflowType::VISIBLE; if (str == "visible") overflow = CSVGOverflowType::VISIBLE; else if (str == "hidden" ) overflow = CSVGOverflowType::HIDDEN; else if (str == "scroll" ) overflow = CSVGOverflowType::SCROLL; else if (str == "auto" ) overflow = CSVGOverflowType::AUTO; else if (str == "inherit") inherit = true; else notHandled("overflow", str); overflow_ = (! inherit ? Overflow(overflow) : Overflow::makeInherit()); } void CSVGObject:: setTextBaselineShift(const std::string &str) { //setNameValue("baseline-shift", str); if (str == "super") fontDef_.setSuperscript(true); else if (str == "sub" ) fontDef_.setSubscript(true); else notHandled("baseline-shift", str); } // start | middle | end | inherit void CSVGObject:: setTextAnchor(const std::string &str) { if (str == "start" ) textAnchor_ = TextAnchor(CHALIGN_TYPE_LEFT); else if (str == "middle" ) textAnchor_ = TextAnchor(CHALIGN_TYPE_CENTER); else if (str == "end" ) textAnchor_ = TextAnchor(CHALIGN_TYPE_RIGHT); else if (str == "inherit") textAnchor_ = TextAnchor::makeInherit(); else notHandled("text-anchor", str); } CHAlignType CSVGObject:: getFlatTextAnchor() const { if (textAnchor_.isValid()) return textAnchor_.getValue().getValue(); auto *parent = getParent(); while (parent) { if (parent->textAnchor_.isValid()) return parent->getFlatTextAnchor(); parent = parent->getParent(); } return CHALIGN_TYPE_LEFT; } CSVGObject * CSVGObject:: getFlatMarkerStart() const { auto *marker = marker_.getStart(); if (marker) return marker; return nullptr; } CSVGObject * CSVGObject:: getFlatMarkerMid() const { auto *marker = marker_.getMid(); if (marker) return marker; if (getParent()) return getParent()->getFlatMarkerMid(); return nullptr; } CSVGObject * CSVGObject:: getFlatMarkerEnd() const { auto *marker = marker_.getEnd(); if (marker) return marker; if (getParent()) return getParent()->getFlatMarkerEnd(); return nullptr; } void CSVGObject:: setTextDecoration(const std::string &str) { if (str == "underline") { textDecoration_ = CSVGTextDecoration::UNDERLINE; fontDef_.setUnderline(true); } else if (str == "overline") { textDecoration_ = CSVGTextDecoration::OVERLINE; fontDef_.setOverline(true); } else if (str == "line-through") { textDecoration_ = CSVGTextDecoration::LINE_THROUGH; fontDef_.setLineThrough(true); } else notHandled("text-decoration", str); } //--- void CSVGObject:: ungroupObject() { auto *parent = getParent(); if (! parent) return; auto transform = getTransform(); parent->deleteChildObject(this); for (const auto &c : children()) { auto transform1 = c->getTransform(); transform1.prepend(transform); c->setTransform(transform1); parent->addChildObject(c); } } void CSVGObject:: addChildObject(CSVGObject *object) { object->setParent(this); if (object->isAnimated()) animation_.addObject(object); else objects_.push_back(object); } void CSVGObject:: deleteChildObject(CSVGObject *object) { object->setParent(nullptr); if (object->isAnimated()) animation_.removeObject(object); else objects_.remove(object); } CSVGObject * CSVGObject:: child(int i) const { int i1 = 0; for (auto &c : children()) { if (i1 == i) return c; ++i1; } return nullptr; } bool CSVGObject:: getAllChildren(ObjectArray &objects) const { for (const auto &c : children()) objects.push_back(c); for (const auto &c : children()) c->getAllChildren(objects); return ! objects.empty(); } bool CSVGObject:: getAllChildrenOfType(CSVGObjTypeId id, ObjectArray &objects) const { getChildrenOfType(id, objects); for (const auto &c : children()) c->getAllChildrenOfType(id, objects); return ! objects.empty(); } bool CSVGObject:: getChildrenOfType(CSVGObjTypeId id, ObjectArray &objects) const { for (const auto &c : children()) if (c->isObjType(id)) objects.push_back(c); return ! objects.empty(); } bool CSVGObject:: getAllChildrenOfId(const std::string &id, ObjectArray &objects) const { getChildrenOfId(id, objects); for (const auto &c : children()) c->getAllChildrenOfId(id, objects); return ! objects.empty(); } bool CSVGObject:: getHierChildrenOfId(const std::string &id, ObjectArray &objects) const { if (id == "") return false; std::vector<std::string> words; CStrUtil::addFields(id, words, "/"); if (words.size() == 1) getChildrenOfId(id, objects); else { ObjectArray parentObjects; getChildrenOfId(words[0], parentObjects); auto childId = CStrUtil::toString(words, 1, -1, "/"); for (const auto &parentObj : parentObjects) parentObj->getHierChildrenOfId(childId, objects); } return ! objects.empty(); } bool CSVGObject:: getChildrenOfId(const std::string &id, ObjectArray &objects) const { for (const auto &c : children()) if (c->getId() == id) objects.push_back(c); return ! objects.empty(); } bool CSVGObject:: drawObject() { svg_.updateBusy(); //------ if (! isHierDrawable()) return false; if (getDisplay() == "none") return false; bool drawn = false; //------ // draw to new temp background if (enableBackground() == CSVGEnableBackground::NEW) { auto *bgBuffer = svg_.getBuffer("BackgroundImage"); auto *tempBgBuffer1 = svg_.getBuffer(getUniqueName() + "_BackgroundImage1"); if (tempBgBuffer1->isDrawing()) tempBgBuffer1->stopDraw(); bool oldBgDrawing = bgBuffer->isDrawing(); if (oldBgDrawing) bgBuffer->stopDraw(); tempBgBuffer1->setImageBuffer(bgBuffer); bgBuffer->clear(); if (oldBgDrawing) bgBuffer->startDraw(); } //------ // get current buffer auto *oldBuffer = svg_.getCurrentBuffer(); auto *currentBuffer = oldBuffer; //------ // save object image to temporary buffer if debug or filter bool saveImage = false; if (svg_.getDebugObjImage()) { saveImage = true; if (! isDrawable() && ! hasChildren()) saveImage = false; } if (getOpacityValid()) saveImage = true; bool isFiltered = (hasFilter() && getFiltered()); if (svg_.getIgnoreFilter()) isFiltered = false; if (isFiltered) saveImage = true; bool isMasked = (getMask() && getMasked()); if (isMasked) saveImage = true; CSVGBuffer *saveBuffer = nullptr; //--- // set buffer to temporary buffer if (saveImage) { CBBox2D bbox; saveBuffer = svg_.pushBuffer("_" + getUniqueName()); if (isFiltered) { auto *filter = getFilter(); filter->getRegion(this, bbox); saveBuffer->updateBBoxSize(bbox); } saveBuffer->clear(); auto *block = dynamic_cast<CSVGBlock *>(this); if (bbox.isSet()) saveBuffer->setBBox(bbox); if (block) svg_.beginDrawBuffer(saveBuffer, svg_.offset(), svg_.xscale(), svg_.yscale()); else if (bbox.isSet()) { auto *root = svg_.getRoot(); auto pixelBox = root->calcPixelBox(); auto viewBox = root->calcViewBox(); auto offset = CPoint2D(0, 0); double xs = 1; double ys = 1; auto preserveAspect = svg_.blockPreserveAspect(); viewBox.setXMax(std::max(viewBox.getXMax(), bbox.getXMax())); viewBox.setYMax(std::max(viewBox.getYMax(), bbox.getYMax())); svg_.beginDrawBuffer(saveBuffer, pixelBox, viewBox, offset, xs, ys, preserveAspect); } else svg_.beginDrawBuffer(saveBuffer, CPoint2D(0, 0), 1, 1); currentBuffer = saveBuffer; } //------ // set current transform auto transform = oldBuffer->transform(); CMatrixStack2D transform1(transform); transform1.append(getTransform()); //if (! isFiltered) currentBuffer->setTransform(transform1); if (getOpacityValid() && ! getOpacity().isInherit()) currentBuffer->setOpacity(getOpacity().getValue()); //------ // draw object if (drawSubObject()) drawn = true; //------ // restore transform //if (! isFiltered) currentBuffer->setTransform(transform); //------ // if object image saved to temporary buffer add to old buffer if (saveImage) { svg_.endDrawBuffer(saveBuffer); //--- if (drawn) { if (isFiltered) { // filtered image draw in local coords so need to place // image at expected position #if 1 double x1 = 0, y1 = 0, x2 = 0, y2 = 0; transform .multiplyPoint(0, 0, &x1, &y1); transform1.multiplyPoint(0, 0, &x2, &y2); double dx = x2 - x1; double dy = y2 - y1; saveBuffer->setOrigin(CPoint2D(dx, dy)); double px, py; svg_.lengthToPixel(dx, dy, &px, &py); #else double x = 0, y = 0; transform1.multiplyPoint(0, 0, &x, &y); saveBuffer->setOrigin(CPoint2D(x, y)); double px, py; svg_.lengthToPixel(x, y, &px, &py); #endif bool oldDrawing = oldBuffer->isDrawing(); if (oldDrawing) oldBuffer->stopDraw(); px = 0; py = 0; oldBuffer->addImageBuffer(px, py, saveBuffer); if (oldDrawing) oldBuffer->startDraw(); } else { bool oldDrawing = oldBuffer->isDrawing(); if (oldDrawing) oldBuffer->stopDraw(); oldBuffer->addImageBuffer(saveBuffer); if (oldDrawing) oldBuffer->startDraw(); } } //--- svg_.popBuffer(); } //--- // add new background to original if (enableBackground() == CSVGEnableBackground::NEW) { auto *bgBuffer = svg_.getBuffer("BackgroundImage"); auto *tempBgBuffer1 = svg_.getBuffer(getUniqueName() + "_BackgroundImage1"); auto *tempBgBuffer2 = svg_.getBuffer(getUniqueName() + "_BackgroundImage2"); bool oldBgDrawing = bgBuffer->isDrawing(); if (oldBgDrawing) bgBuffer->stopDraw(); tempBgBuffer2->setImageBuffer(bgBuffer); bgBuffer->clear(); bgBuffer->addImageBuffer(tempBgBuffer1); bgBuffer->addImageBuffer(tempBgBuffer2); if (oldBgDrawing) bgBuffer->startDraw(); } //--- return drawn; } bool CSVGObject:: drawSubObject(bool forceDraw) { bool visible = isVisible(); bool childVisible = (! visible ? anyChildVisible(visible) : true); if (! visible && ! childVisible) return false; //------ bool drawn = false; auto *oldBuffer = svg_.getCurrentBuffer(); // set stroke //CSVGTempStroke tempStroke(*this); //CSVGTempFont tempFont (*this); svg_.pushStyle(this); drawInit(); //------ // draw clip path if specified bool isClipped = (getClipPath() && getClipped()); if (isClipped) getClipPath()->drawPath(this); //------ // draw object (virtual) if (visible) { if (isDrawable() || isFilter()) { svg_.pushDrawObject(this); draw(); drawn = true; svg_.popDrawObject(); } } //------ // draw children for (const auto &c : children()) { if (! forceDraw && ! c->isDrawable()) continue; if (c->drawObject()) drawn = true; } //------ // apply filter bool isFiltered = (hasFilter() && getFiltered()); if (svg_.getIgnoreFilter()) isFiltered = false; if (isFiltered) { auto *filter = getFilter(); // init filter if (filter) { filter->setObject(this); filter->initDraw(oldBuffer); CBBox2D filterBBox; if (filter->getRegion(this, filterBBox)) filter->setContentsBBox(filterBBox); // draw filter if (filter->drawSubObject(true)) drawn = true; //-- filter->termDraw(oldBuffer); } } //--- if (isClipped) oldBuffer->initClip(); //--- // mask if defined bool isMasked = (getMask() && getMasked()); if (isMasked) getMask()->drawMask(this); //------ drawTerm(); svg_.popStyle(); return drawn; } bool CSVGObject:: isHierVisible(bool defValue) const { if (! hasVisibility()) { if (getParent()) return getParent()->isHierVisible(); return defValue; } else return isVisible(defValue); } bool CSVGObject:: anyChildVisible(bool defValue) const { for (const auto &c : children()) { if (c->isVisible(defValue)) return true; } for (const auto &c : children()) { if (c->anyChildVisible(defValue)) return true; } return defValue; } bool CSVGObject:: isVisible(bool defValue) const { // visible | hidden | collapse | inherit if (hasVisibility()) { if (getVisibility() == "visible") return true; else if (getVisibility() == "hidden" || getVisibility() == "collapse") return false; } return defValue; } void CSVGObject:: setVisible(bool b) { if (! b) visibility_ = "hidden"; else visibility_.setInvalid(); } CSVGBuffer * CSVGObject:: toBufferImage() { // TODO: use toNamedBufferImage, optional filter ? CBBox2D bbox; if (! getBBox(bbox)) return nullptr; auto *imageBuffer = svg_.pushBuffer("_" + getUniqueName() + "_image"); imageBuffer->clear(); // draw object to buffer svg_.beginDrawBuffer(imageBuffer, bbox); //buffer->setup(bbox); (void) drawSubObject(true); svg_.endDrawBuffer(imageBuffer); svg_.popBuffer(); return imageBuffer; } CSVGBuffer * CSVGObject:: toNamedBufferImage(const std::string &bufferName) { CBBox2D bbox; if (! getBBox(bbox)) return nullptr; COptValT<CSVGFilter*> saveFilter; std::swap(saveFilter, filter_); auto *imageBuffer = svg_.pushBuffer(bufferName); imageBuffer->clear(); svg_.beginDrawBuffer(imageBuffer, bbox); (void) drawSubObject(true); svg_.endDrawBuffer(imageBuffer); svg_.popBuffer(); std::swap(saveFilter, filter_); return imageBuffer; } void CSVGObject:: moveTo(const CPoint2D &point) { CBBox2D bbox; if (! getBBox(bbox)) return; auto m = getFlatTransform(); auto bbox1 = svg_.transformBBox(m, bbox); bbox1.moveTo(point); auto bbox2 = svg_.untransformBBox(m, bbox1); auto d = CVector2D(bbox.getMin(), bbox2.getMin()); moveDelta(d); } void CSVGObject:: moveBy(const CVector2D &delta) { CBBox2D bbox; if (! getBBox(bbox)) return; auto m = getFlatTransform(); auto bbox1 = svg_.transformBBox(m, bbox); bbox1.moveBy(delta); auto bbox2 = svg_.untransformBBox(m, bbox1); auto d = CVector2D(bbox.getMin(), bbox2.getMin()); moveDelta(d); } void CSVGObject:: moveDelta(const CVector2D &) { if (isDrawable()) CSVGLog() << "moveDelta: not implemented"; } void CSVGObject:: resizeTo(const CSize2D &s) { CBBox2D bbox; if (! getFlatTransformedBBox(bbox)) return; double sx = s.getWidth ()/bbox.getWidth (); double sy = s.getHeight()/bbox.getHeight(); scaleBy(sx, sy); } void CSVGObject:: rotateBy(double da) { CBBox2D bbox; if (! getBBox(bbox)) return; auto c = bbox.getCenter(); CMatrixStack2D m; m.translate(c.x, c.y); m.rotate(da); m.translate(-c.x, -c.y); m.append(getTransform()); setTransform(m); } void CSVGObject:: rotateAt(double a, const CPoint2D &c) { CMatrixStack2D m; m.rotate(a, c); m.append(getTransform()); setTransform(m); } void CSVGObject:: scaleBy(double s) { CMatrixStack2D m; m.scale(s, s); m.append(getTransform()); setTransform(m); } void CSVGObject:: scaleBy(double xs, double ys) { CMatrixStack2D m; m.scale(xs, ys); m.append(getTransform()); setTransform(m); } bool CSVGObject:: getBBox(CBBox2D &bbox) const { if (! hasViewBox()) { bbox = CBBox2D(); CBBox2D bbox1; if (getChildrenBBox(bbox1)) bbox += bbox1; } else bbox = getViewBox(); return bbox.isSet(); } bool CSVGObject:: getParentViewBox(CBBox2D &bbox) const { if (hasViewBox()) { bbox = getViewBox(); return true; } if (! getParent()) return false; return getParent()->getParentViewBox(bbox); } bool CSVGObject:: getTransformedBBox(CBBox2D &bbox) const { auto m = getTransform(); if (! getBBox(bbox)) return false; bbox = svg_.transformBBox(m, bbox); return true; } bool CSVGObject:: getFlatTransformedBBox(CBBox2D &bbox) const { auto m = getFlatTransform(); if (! getBBox(bbox)) { if (! getParent()) return false; return getParent()->getFlatTransformedBBox(bbox); } bbox = svg_.transformBBox(m, bbox); return true; } CBBox2D CSVGObject:: getDrawBBox() const { CBBox2D bbox; if (hasViewBox()) bbox = getViewBox(); else { if (! getParentViewBox(bbox)) bbox = CBBox2D(0, 0, 100, 100); } return bbox; } bool CSVGObject:: inside(const CPoint2D &pos) const { if (! isHierDrawable()) return false; CBBox2D bbox; if (! getFlatTransformedBBox(bbox)) return false; return bbox.inside(pos); } bool CSVGObject:: getSize(CSize2D &size) const { double w = getXMax() - getXMin(); double h = getYMax() - getYMin(); size = CSize2D(w, h); return true; } double CSVGObject:: getXMin() const { CBBox2D bbox; if (getBBox(bbox)) return bbox.getXMin(); return 0.0; } double CSVGObject:: getYMin() const { CBBox2D bbox; if (getBBox(bbox)) return bbox.getYMin(); return 0.0; } double CSVGObject:: getXMax() const { CBBox2D bbox; if (getBBox(bbox)) return bbox.getXMax(); return 1.0; } double CSVGObject:: getYMax() const { CBBox2D bbox; if (getBBox(bbox)) return bbox.getYMax(); return 1.0; } bool CSVGObject:: getChildrenBBox(CBBox2D &bbox) const { CBBox2D bbox1; for (const auto &c : children()) { if (c->getTransformedBBox(bbox1)) bbox.add(bbox1); } return bbox.isSet(); } void CSVGObject:: tick(double dt) { for (const auto &c : children()) c->tick(dt); animation_.tick(dt); } void CSVGObject:: setTime(double t) { for (const auto &c : children()) c->setTime(t); animation_.setTime(t); } std::string CSVGObject:: getId(bool autoName) const { auto id = id_.getValue(""); if (id == "" && autoName) id = const_cast<CSVGObject *>(this)->autoName(); return id; } void CSVGObject:: setId(const std::string &id) { id_ = id; svg_.setObjectById(id, this); } void CSVGObject:: setClasses(const std::vector<std::string> &classes) { classes_ = classes; } //--- bool CSVGObject:: getTitle(std::string &str) const { std::vector<CSVGObject *> children; getChildrenOfType(CSVGObjTypeId::TITLE, children); for (const auto *child : children) { const auto *title = dynamic_cast<const CSVGTitle *>(child); if (! title) continue; str = title->getText(); return true; } return false; } void CSVGObject:: setTitle(const std::string &str) { std::vector<CSVGObject *> children; getChildrenOfType(CSVGObjTypeId::TITLE, children); for (auto *child : children) { auto *title = dynamic_cast<CSVGTitle *>(child); if (! title) continue; title->setText(str); return; } auto *title = svg_.createTitle(); title->setText(str); addChildObject(title); } //--- bool CSVGObject:: decodeXLink(const std::string &str, CSVGObject **object, CSVGBuffer **buffer) { if (object) *object = nullptr; if (buffer) *buffer = nullptr; //--- // check for inline image data uint len = str.size(); if (len >= 5 && str.substr(0, 5) == "data:") { // get format uint pos = 5; std::string format; while (pos < len && str[pos] != ',') format += str[pos++]; if (pos >= len) { // error ? return false; } ++pos; if (format == "image/png;base64" || format == "image/jpeg;base64") { // image string to buffer std::string filename; if (format == "image/png;base64") filename = ".svg.png"; else filename = ".svg.jpeg"; decodeStringToFile(str.substr(pos), filename); auto *imgBuffer = getXLinkBuffer(); imgBuffer->setImageFile(filename); if (buffer) *buffer = imgBuffer; return true; } else if (format == "image/svg+xml;base64") { // SVG string to buffer std::string filename(".svg.svg"); decodeStringToFile(str.substr(pos), filename); auto type = CFileUtil::getTextType(filename); if (type == CFILE_TYPE_TEXT_GZIP) { std::string gzfilename = filename + ".gz"; rename(filename.c_str(), gzfilename.c_str()); std::string cmd = "/bin/gzip -d " + gzfilename; system(cmd.c_str()); } // draw SVG file to image at current scale auto *svg = svg_.dup(); svg->setRenderer(svg_.getRenderer()); svg->init(); svg->read(filename); CSize2D size; getSize(size); svg->getRoot()->setSize(size); auto *imgBuffer = getXLinkBuffer(); int w = svg->getIWidth(); int h = svg->getIHeight(); svg->drawToBuffer(imgBuffer, w, h, svg_.offset(), svg_.xscale(), svg_.yscale()); if (buffer) *buffer = imgBuffer; delete svg; return true; } else if (format == "text/javascript;base64") { // Javascript string to buffer std::string filename(".svg.js"); decodeStringToFile(str.substr(pos), filename); auto type = CFileUtil::getTextType(filename); if (type == CFILE_TYPE_TEXT_GZIP) { std::string gzfilename = filename + ".gz"; rename(filename.c_str(), gzfilename.c_str()); std::string cmd = "/bin/gzip -d " + gzfilename; system(cmd.c_str()); } // load javascript svg_.setScriptFile(".svg.js"); return true; } else { CSVGLog() << "Unhandled images format '" + format + "'"; return true; // don't propagate warning } } //--- // get link name std::string::size_type pos = str.find('#'); if (pos != std::string::npos) { CSVGObject *object1 = nullptr; std::string lhs = str.substr(0, pos); std::string rhs = str.substr(pos + 1); // Handle file: <filename>#<id> if (lhs != "") { // read file auto *block = svg_.createBlock(); svg_.read(lhs, block); // get object from id if (rhs != "") object1 = svg_.lookupObjectById(rhs); else object1 = block; } // handle id: <id> else { object1 = svg_.lookupObjectById(rhs); } if (! object1) { //CSVGLog() << "Object '" << rhs << "' does not exist"; //return true; // don't propagate warning return false; } if (object) *object = object1; } // handle file else { // check valid CFile file(str); if (! file.exists()) { CSVGLog() << "File '" << str << "' does not exist"; return true; // don't propagate warning } if (! file.isRegular()) { CSVGLog() << "File '" << str << "' is not a regular file"; return true; // don't propagate warning } // get type from contents/suffix auto type = CFileUtil::getType(&file); if (type == CFILE_TYPE_INODE_REG && file.getSuffix() == "svg") type = CFILE_TYPE_IMAGE_SVG; // handle image file if (type & CFILE_TYPE_IMAGE) { // svg image if (type == CFILE_TYPE_IMAGE_SVG) { // draw SVG file to image at current scale auto *svg = svg_.dup(); svg->setRenderer(svg_.getRenderer()); svg->init(); svg->read(file.getPath()); CSize2D size; getSize(size); svg->getRoot()->setSize(size); auto *imgBuffer = getXLinkBuffer(); int w = svg->getIWidth(); int h = svg->getIHeight(); svg->drawToBuffer(imgBuffer, w, h, svg_.offset(), svg_.xscale(), svg_.yscale()); if (buffer) *buffer = imgBuffer; } // image file (png, jpeg, ...) else { auto *imgBuffer = getXLinkBuffer(); imgBuffer->setImageFile(str); if (buffer) *buffer = imgBuffer; } } // handle svg file else if (type == CFILE_TYPE_TEXT_HTML) { // read svg file auto *block = svg_.createBlock(); svg_.read(str, block); if (object) *object = block; } else { CSVGLog() << "Unknown type of file for '" << str << "'"; return true; // don't propagate warning } } return true; } bool CSVGObject:: decodeStringToFile(const std::string &str, const std::string &filename) { std::string str1 = CEncode64Inst->decode(str); CFile file(filename); file.write(str1); file.flush(); file.close(); return true; } CSVGBuffer * CSVGObject:: getXLinkBuffer() { return svg_.getBuffer(getUniqueName() + "_xlink"); } bool CSVGObject:: getObjectsAtPoint(const CPoint2D &p, ObjectArray &objects) const { ObjectArray objects1; if (inside(p)) objects1.push_back(const_cast<CSVGObject *>(this)); for (const auto &c : children()) c->getObjectsAtPoint(p, objects1); using DepthObjects = std::map<int, ObjectArray>; DepthObjects depthObjects; for (const auto &obj : objects1) depthObjects[-obj->getDepth()].push_back(obj); for (const auto &pd : depthObjects) for (const auto &obj : pd.second) objects.push_back(obj); return ! objects.empty(); } void CSVGObject:: handleEvent(CSVGEventType type, const std::string &id, const std::string &data, bool propagate) { if (id == "" || id == this->getId()) execEvent(type); if (type == CSVGEventType::MOUSE_OVER || type == CSVGEventType::MOUSE_OUT) { if (! isHierDrawable()) propagate = false; } if (propagate) { for (const auto &c : children()) c->handleEvent(type, id, data); } if (! animation_.objects().empty()) animation_.handleEvent(type, id, data); } void CSVGObject:: execEvent(CSVGEventType type) { auto execNamedEvent = [&](const std::string &name) { if (hasNameValue(name)) svg_.execJsEvent(this, getNameValue(name).getValue()); }; if (type == CSVGEventType::LOAD) execNamedEvent("onload"); else if (type == CSVGEventType::MOUSE_OVER) execNamedEvent("onmouseover"); else if (type == CSVGEventType::MOUSE_OUT) execNamedEvent("onmouseout"); else if (type == CSVGEventType::CLICK) execNamedEvent("onclick"); else if (type == CSVGEventType::BEGIN) execNamedEvent("onbegin"); else if (type == CSVGEventType::END) execNamedEvent("onend"); } std::string CSVGObject:: toString(bool hier) const { std::stringstream ss; print(ss, hier); return ss.str(); } void CSVGObject:: print(std::ostream &os, bool hier) const { if (hier) { auto s = getText(); os << "<" << getTagName(); printValues(os); if (hasChildren()) { os << ">\n"; if (s != "") os << s << "\n"; printChildren(os, hier); os << "</" << getTagName() << ">\n"; } else if (s != "") { os << ">" << s; os << "</" << getTagName() << ">\n"; } else os << "/>\n"; } else os << getTagName() << ": '" << getId() << "'"; } void CSVGObject:: printFlat(std::ostream &os, bool force, int depth) const { auto id = getObjTypeId(); if (id == CSVGObjTypeId::BLOCK) { os << "<svg"; printValues(os, /*flat*/ false); // true ? os << ">\n"; } if (hasChildren()) { bool startTag = false; if (id == CSVGObjTypeId::GROUP && ! getId().empty()) startTag = true; if (id == CSVGObjTypeId::DEFS) startTag = true; if (id == CSVGObjTypeId::TEXT) startTag = true; if (! canFlatten() && ! getId().empty()) startTag = true; if (startTag) { for (int i = 0; i < depth; ++i) os << " "; os << "<" << getTagName(); printValues(os, /*flat*/true); os << ">\n"; } for (const auto &c : children()) { if (force || propagateFlat()) { if (startTag) c->printFlat(os, force, depth + 1); else c->printFlat(os, force, depth); } else c->print(os, /*hier*/true); } if (startTag) { for (int i = 0; i < depth; ++i) os << " "; os << "</" << getTagName() << ">\n"; } } else { if (id == CSVGObjTypeId::GROUP || id == CSVGObjTypeId::DEFS) return; for (int i = 0; i < depth; ++i) os << " "; std::string s = getText(); os << "<" << getTagName(); printValues(os, /*flat*/true); if (s != "") { os << ">" << s; os << "</" << getTagName() << ">\n"; } else os << "/>\n"; } if (id == CSVGObjTypeId::BLOCK) { os << "</svg>\n"; } } void CSVGObject:: printValues(std::ostream &os, bool flat) const { printNameValue (os, "id" , id_ ); printNameValues(os, "class", classes_); if (hasViewBox()) { auto viewBox = getViewBox(); os << " viewBox=\"" << viewBox.getXMin() << " " << viewBox.getYMin() << " " << viewBox.getWidth() << " " << viewBox.getHeight() << "\""; } printTransform(os, flat); printFilter(os); printStyle(os, flat); printTextContent(os); for (const auto &nv : nameValues_) { auto &name = nv.first; auto pn = skipNames_.find(name); if (pn != skipNames_.end()) continue; os << " " << name << "=\"" << nv.second << "\""; } } bool CSVGObject:: hasChildren(bool includeAnimated) const { if (includeAnimated) return (! children().empty() || ! animation_.objects().empty()); else return ! children().empty(); } bool CSVGObject:: hasAnimation() const { if (! animation_.objects().empty()) return true; for (const auto &c : children()) if (c->hasAnimation()) return true; return false; } void CSVGObject:: printChildren(std::ostream &os, bool hier) const { for (const auto &c : children()) c->print(os, hier); for (const auto &o : animation_.objects()) o->print(os, hier); } void CSVGObject:: printFilter(std::ostream &os) const { if (hasFilter()) { auto *filter = getFilter(); if (filter) os << " filter=\"url(#" << filter->getId() << ")\""; else os << " filter=\"url(none)\""; } } void CSVGObject:: printStyle(std::ostream &os, bool flat) const { auto str = styleString(flat); if (str.length()) os << " style=\"" << str << "\""; } std::string CSVGObject:: styleString(bool flat) const { std::stringstream ss; bool output = false; if (hasFontDef()) { std::stringstream ss1; printFontDef(ss1); if (ss1.str().size()) { ss << ss1.str(); output = true; } } if (getOpacityValid()) { if (output) ss << " "; ss << "opacity:" << getOpacity() << ";"; output = true; } if (flat || hasStroke()) { std::stringstream ss1; printStroke(ss1, flat); if (ss1.str().size()) { if (output) ss << " "; ss << ss1.str(); output = true; } } if (flat || hasFill()) { std::stringstream ss1; printFill(ss1, flat); if (ss1.str().size()) { if (output) ss << " "; ss << ss1.str(); output = true; } } if (getMarkerStart()) { if (output) ss << " "; ss << "marker-start:url(#" << getMarkerStart()->getId() << ");"; } if (getMarkerMid()) { if (output) ss << " "; ss << "marker-mid:url(#" << getMarkerMid()->getId() << ");"; } if (getMarkerEnd()) { if (output) ss << " "; ss << "marker-end:url(#" << getMarkerEnd()->getId() << ");"; } if (hasLetterSpacing()) { if (output) ss << " "; ss << "letter-spacing:" << getLetterSpacing() << ";"; output = true; } if (hasWordSpacing()) { if (output) ss << " "; ss << "word-spacing:" << getWordSpacing() << ";"; output = true; } if (getClipPath()) { if (output) ss << " "; ss << "clip-path:url(#" << getClipPath()->getId() << ");"; output = true; } if (getMask()) { if (output) ss << " "; ss << "mask:url(#" << getMask()->getId() << ");"; output = true; } if (hasVisibility()) { if (output) ss << " "; ss << "visibility:" << getVisibility() << ";"; output = true; } return ss.str(); } void CSVGObject:: printStroke(std::ostream &os, bool flat) const { if (flat) { auto stroke = getFlatStroke(); stroke.print(os); } else { const auto &stroke = getStroke(); stroke.print(os); } } void CSVGObject:: printFill(std::ostream &os, bool flat) const { if (flat) { auto fill = getFlatFill(); fill.print(os); } else { const auto &fill = getFill(); fill.print(os); } } void CSVGObject:: printTextContent(std::ostream &os) const { if (textAnchor_.isValid()) { os << " text-anchor=\""; if (textAnchor_.getValue().isInherit()) os << "inherit"; else { auto value = textAnchor_.getValue().getValue(); if (value == CHALIGN_TYPE_LEFT ) os << "start"; else if (value == CHALIGN_TYPE_CENTER) os << "middle"; else if (value == CHALIGN_TYPE_RIGHT ) os << "end"; else assert(false); } os << "\""; } } void CSVGObject:: printFontDef(std::ostream &os) const { fontDef_.print(os); } void CSVGObject:: printTransform(std::ostream &os, bool flat) const { if (! flat) { if (! transform_.isEmpty()) { os << " transform=\""; printTransform(os, transform_); os << "\""; } } else { if (! hasChildren()) { auto transform = getFlatTransform(); if (! transform.isEmpty()) { os << " transform=\""; printTransform(os, transform); os << "\""; } } } } void CSVGObject:: printTransform(std::ostream &os, const CMatrixStack2D &m) const { if (m.isEmpty()) return; bool output = false; for (const auto &t : m.transformStack()) { switch (t.type()) { case CMatrixTransformType::TRANSLATE: { if (output) os << " "; os << "translate(" << t.dx() << " " << t.dy() << ")"; output = true; break; } case CMatrixTransformType::SCALE1: case CMatrixTransformType::SCALE2: { if (output) os << " "; if (t.type() == CMatrixTransformType::SCALE1) os << "scale(" << t.xscale() << ")"; else os << "scale(" << t.xscale() << " " << t.yscale() << ")"; output = true; break; } case CMatrixTransformType::ROTATE: case CMatrixTransformType::ROTATE_ORIGIN: { if (output) os << " "; if (t.type() == CMatrixTransformType::ROTATE) os << "rotate(" << CMathGen::RadToDeg(t.angle()) << ")"; else os << "rotate(" << CMathGen::RadToDeg(t.angle()) << " " << t.xo() << " " << t.yo() << ")"; output = true; break; } case CMatrixTransformType::SKEWX: { if (output) os << " "; os << "skewX(" << CMathGen::RadToDeg(t.angle()) << ")"; output = true; break; } case CMatrixTransformType::SKEWY: { if (output) os << " "; os << "skewY(" << CMathGen::RadToDeg(t.angle()) << ")"; output = true; break; } default: { if (output) os << " "; os << "matrix("; const double *v = t.values(); for (int i = 0; i < 6; ++i) { if (i > 0) os << " "; // SVG is ((a c e) (b d f) (0 0 1)) if (i == 1 || i == 2) os << v[3 - i]; else os << v[i]; } os << ")"; output = true; break; } } } } void CSVGObject:: printNameParts(std::ostream &os, const std::string &name, const CSVGPathPartList &parts) const { if (! parts.empty()) { os << " " << name << "=\"" << parts << "\""; } } void CSVGObject:: printNameCoordUnits(std::ostream &os, const std::string &name, const COptValT<CSVGCoordUnits> &units) const { if (units.isValid()) os << " " << name << "=\"" << CSVG::encodeUnitsString(units.getValue()) << "\""; } void CSVGObject:: printNamePercent(std::ostream &os, const std::string &name, const COptValT<CScreenUnits> &units) const { if (units.isValid()) { if (units.getValue().units() == CScreenUnits::Units::RATIO) os << " " << name << "=\"" << units.getValue().ratioValue() << "\""; else os << " " << name << "=\"" << units.getValue() << "\""; } } void CSVGObject:: accept(CSVGVisitor *visitor) { visitor->visit(this); }
20.612757
99
0.621858
[ "object", "shape", "vector", "transform", "solid" ]
24c10190591e3c0dff51782cee0f28fc96d4d098
7,438
cpp
C++
src/Acceleration/bvh.cpp
bittencourt-lucas/pbr-code
03776f90683a06a326b6f3b7ae6ea453d7eb4737
[ "MIT" ]
null
null
null
src/Acceleration/bvh.cpp
bittencourt-lucas/pbr-code
03776f90683a06a326b6f3b7ae6ea453d7eb4737
[ "MIT" ]
null
null
null
src/Acceleration/bvh.cpp
bittencourt-lucas/pbr-code
03776f90683a06a326b6f3b7ae6ea453d7eb4737
[ "MIT" ]
null
null
null
#include "bvh.h" BVH::BVH( const std::vector< Primitive::PrimitiveUniquePtr > &primitives ) : primitives_( primitives ) { if ( primitives_.size() > 0 ) { std::deque< PrimitiveAABBArea > s( primitives_.size() ); primitive_id_.resize( primitives_.size() ); BoundingBox root_aabb; for( std::size_t i = 0; i < primitives_.size(); i++ ) { BoundingBox aabb = primitives_[i]->getAABB(); // compute the AABB area for the root node if ( !i ) root_aabb = aabb; else root_aabb = root_aabb + aabb; s[i].primitive_id_ = i; s[i].centroid_ = aabb.centroid_; s[i].aabb_ = aabb; } splitNode( &root_node_, s, 0, s.size() - 1, root_aabb.getArea() ); } } BVH::~BVH( void ) { if ( root_node_ ) { delete root_node_; root_node_ = nullptr; } } bool BVH::intersect( const Ray &ray, IntersectionRecord &intersection_record) const { return traverse( root_node_, ray, intersection_record); } double BVH::SAH( std::size_t s1_size, double s1_area, std::size_t s2_size, double s2_area, double s_area ) { return 2.0 * cost_intersec_aabb_ + ( ( s1_area / s_area ) * s1_size * cost_intersec_tri_ ) + ( ( s2_area / s_area ) * s2_size * cost_intersec_tri_ ); } /* BVH construction based on the algorithm presented in the paper: * * "Ray Tracing Deformable Scenes Using Dynamic Bounding Volume Hierarchies". * Ingo Wald, Solomon Boulos, and Peter Shirley * ACM Transactions on Graphics. * Volume 26 Issue 1, 2007. */ void BVH::splitNode( BVHNode **node, std::deque< PrimitiveAABBArea > &s, std::size_t first, std::size_t last, double s_area ) { (*node) = new BVHNode(); (*node)->first_ = first; (*node)->last_ = last; (*node)->left_ = nullptr; (*node)->right_ = nullptr; std::deque< PrimitiveAABBArea > s_aux; double best_cost = cost_intersec_tri_ * ( last + 1 - first ); int best_axis = -1; int best_event = -1; for ( int axis = 1; axis <= 3; axis++ ) { switch( axis ) { case 1: std::sort( s.begin() + first, s.begin() + last + 1, Comparator::sortInX ); break; case 2: std::sort( s.begin() + first, s.begin() + last + 1, Comparator::sortInY ); break; case 3: std::sort( s.begin() + first, s.begin() + last + 1, Comparator::sortInZ ); break; } s_aux = std::deque< PrimitiveAABBArea >( s.begin() + first, s.begin() + last + 1 ); for ( std::size_t i = first; i <= last; i++ ) { if ( i == first ) { s[i].left_area_ = std::numeric_limits< double >::infinity(); s_aux[0].left_aabb_ = s_aux[0].aabb_; } else { s[i].left_area_ = s_aux[ i - first - 1 ].left_aabb_.getArea(); s_aux[ i - first ].left_aabb_ = s_aux[ i - first ].aabb_ + s_aux[ i - first - 1 ].left_aabb_; } } for ( long int i = last; i >= static_cast< long int >( first ); i-- ) { if ( i == static_cast< long int >( last ) ) { s[i].right_area_ = std::numeric_limits< double >::infinity(); s_aux[ last - first ].right_aabb_ = s_aux[ last - first ].aabb_; } else { s[i].right_area_ = s_aux[ i - first + 1 ].right_aabb_.getArea(); s_aux[ i - first ].right_aabb_ = s_aux[ i - first ].aabb_ + s_aux[ i - first + 1 ].right_aabb_; } double this_cost = SAH( i - first + 1, s[ ( i + 1 ) % ( s.size() + 1 ) ].left_area_, // Fixes an indexing problem from the original paper. last - i, s[i].right_area_, s_area ); if ( this_cost < best_cost ) { best_cost = this_cost; best_event = i; best_axis = axis; } } } if ( best_axis == -1 ) // This is a leaf node { primitives_inserted_ += last - first + 1; std::stringstream progress_stream; progress_stream << "\r BVH building progress ............: " << std::fixed << std::setw( 6 ) << std::setprecision( 2 ) << 100.0 * static_cast< float >( primitives_inserted_ ) / primitives_.size() << "%"; std::clog << progress_stream.str(); for ( long unsigned int i = first; i <= last; i++ ) { primitive_id_[i] = s[i].primitive_id_; if ( i == first ) (*node)->aabb_ = s[i].aabb_; else (*node)->aabb_ = (*node)->aabb_ + s[i].aabb_; } } else // This is an inner node { // Make inner node with best_axis / best_event switch( best_axis ) { case 1: std::sort( s.begin() + first, s.begin() + last + 1, Comparator::sortInX ); break; case 2: std::sort( s.begin() + first, s.begin() + last + 1, Comparator::sortInY ); break; case 3: std::sort( s.begin() + first, s.begin() + last + 1, Comparator::sortInZ ); break; } splitNode( &(*node)->left_, s, first, best_event, s_area ); splitNode( &(*node)->right_, s, best_event + 1, last, s_area ); (*node)->aabb_ = (*node)->left_->aabb_ + (*node)->right_->aabb_; } } // TODO: test for null child before recursive call. bool BVH::traverse( const BVHNode *node, const Ray &ray, IntersectionRecord &intersection_record) const { bool primitive_intersect = false; if ( node ) { if ( node->aabb_.intersect( ray ) ) { if ( ( !node->left_ ) && ( !node->right_ ) ) // is a leaf node { IntersectionRecord tmp_intersection_record; for ( std::size_t primitive_id = node->first_; primitive_id <= node->last_; primitive_id++ ) { if ( primitives_[primitive_id_[primitive_id]]->intersect( ray, tmp_intersection_record ) ) { if ( ( tmp_intersection_record.t_ < intersection_record.t_ ) && ( tmp_intersection_record.t_ > 0.0 ) ) { intersection_record = tmp_intersection_record; primitive_intersect = true; } } } } else { if ( traverse( node->left_, ray, intersection_record) ) primitive_intersect = true; if ( traverse( node->right_, ray, intersection_record) ) primitive_intersect = true; } } } return primitive_intersect; }
32.060345
135
0.475531
[ "vector" ]
24c1a56372a4b6eb274c1efd955ba09f514f8874
13,382
cc
C++
src/http.cc
1computerguy/mercury
193bf6432e4f53f1253965f5ca8634bd6ca69136
[ "BSD-2-Clause" ]
null
null
null
src/http.cc
1computerguy/mercury
193bf6432e4f53f1253965f5ca8634bd6ca69136
[ "BSD-2-Clause" ]
null
null
null
src/http.cc
1computerguy/mercury
193bf6432e4f53f1253965f5ca8634bd6ca69136
[ "BSD-2-Clause" ]
null
null
null
/* * http.c */ #include <unordered_map> #include "asn1/bytestring.h" #include "http.h" #include "json_object.h" #include "match.h" void http_request::parse(struct datum &p) { /* parse request line */ method.parse_up_to_delim(p, ' '); p.skip(1); uri.parse_up_to_delim(p, ' '); p.skip(1); protocol.parse_up_to_delim(p, '\r'); p.skip(2); /* parse headers */ headers.parse(p); return; } void http_headers::print_matching_names(struct json_object &o, std::list<std::pair<struct datum, std::string>> &name_list) const { unsigned char crlf[2] = { '\r', '\n' }; unsigned char csp[2] = { ':', ' ' }; if (this->is_not_readable()) { return; } struct datum p{this->data, this->data_end}; // create copy, to leave object unmodified while (parser_get_data_length(&p) > 0) { if (parser_match(&p, crlf, sizeof(crlf), NULL) == status_ok) { break; /* at end of headers */ } struct datum keyword{p.data, NULL}; if (parser_skip_upto_delim(&p, csp, sizeof(csp)) == status_err) { return; } keyword.data_end = p.data; const char *header_name = NULL; for (const auto &name : name_list) { if (name.first.case_insensitive_match(keyword)) { header_name = (const char *)name.second.c_str(); } } const uint8_t *value_start = p.data; if (parser_skip_upto_delim(&p, crlf, sizeof(crlf)) == status_err) { return; } const uint8_t *value_end = p.data - 2; if (header_name) { o.print_key_json_string(header_name, value_start, value_end - value_start); } } } inline void to_lower(std::basic_string<uint8_t> &str, struct datum d) { if (d.is_not_readable()) { return; } while (d.data < d.data_end) { str.push_back(tolower(*d.data++)); } } void http_headers::fingerprint(struct buffer_stream &buf, std::unordered_map<std::basic_string<uint8_t>, bool> &name_dict) const { unsigned char crlf[2] = { '\r', '\n' }; unsigned char csp[2] = { ':', ' ' }; struct datum p{this->data, this->data_end}; // create copy, to leave object unmodified while (parser_get_data_length(&p) > 0) { if (parser_match(&p, crlf, sizeof(crlf), NULL) == status_ok) { break; /* at end of headers */ } struct datum name{p.data, NULL}; if (parser_skip_upto_delim(&p, csp, sizeof(csp)) == status_err) { return; } name.data_end = p.data; bool include_name = false; bool include_value = false; std::basic_string<uint8_t> name_lowercase; to_lower(name_lowercase, name); auto pair = name_dict.find(name_lowercase); if (pair != name_dict.end()) { include_name = true; include_value = pair->second; } if (parser_skip_upto_delim(&p, crlf, sizeof(crlf)) == status_err) { return; } const uint8_t *name_end = p.data - 2; if (include_name) { if (include_value) { buf.write_char('('); buf.raw_as_hex(name.data, name_end - name.data); // write {name, value} buf.write_char(')'); } else { buf.write_char('('); buf.raw_as_hex(name.data, name.data_end - name.data - 2); // write {name} buf.write_char(')'); } } } } void http_request::write_json(struct json_object &record, bool output_metadata) { // construct a list of http header names to be printed out // uint8_t ua[] = { 'u', 's', 'e', 'r', '-', 'a', 'g', 'e', 'n', 't', ':', ' ' }; struct datum user_agent{ua, ua+sizeof(ua)}; std::pair<struct datum, std::string> user_agent_name{user_agent, "user_agent"}; uint8_t h[] = { 'h', 'o', 's', 't', ':', ' ' }; struct datum host{h, h+sizeof(h)}; std::pair<struct datum, std::string> host_name{host, "host"}; uint8_t xff[] = { 'x', '-', 'f', 'o', 'r', 'w', 'a', 'r', 'd', 'e', 'd', '-', 'f', 'o', 'r', ':', ' ' }; struct datum xff_parser{xff, xff+sizeof(xff)}; std::pair<struct datum, std::string> x_forwarded_for{xff_parser, "x_forwarded_for"}; uint8_t v[] = { 'v', 'i', 'a', ':', ' ' }; struct datum v_parser{v, v+sizeof(v)}; std::pair<struct datum, std::string> via{v_parser, "via"}; uint8_t u[] = { 'u', 'p', 'g', 'r', 'a', 'd', 'e', ':', ' ' }; struct datum u_parser{u, u+sizeof(u)}; std::pair<struct datum, std::string> upgrade_pair{u_parser, "upgrade"}; std::list<std::pair<struct datum, std::string>> names_to_print{user_agent_name, host_name, x_forwarded_for, via, upgrade_pair}; if (this->is_not_empty()) { struct json_object http{record, "http"}; struct json_object http_request{http, "request"}; if (output_metadata) { http_request.print_key_json_string("method", method); http_request.print_key_json_string("uri", uri); http_request.print_key_json_string("protocol", protocol); // http.print_key_json_string("headers", headers.data, headers.length()); // headers.print_host(http, "host"); // run the list of http headers to be printed out against // all headers, and print the values corresponding to each // of the matching names // headers.print_matching_names(http_request, names_to_print); http_request.print_key_value("fingerprint", *this); } else { // output only the user-agent std::list<std::pair<struct datum, std::string>> ua_only{user_agent_name}; headers.print_matching_names(http_request, ua_only); } http_request.close(); http.close(); } } void http_response::parse(struct datum &p) { /* process request line */ version.parse_up_to_delim(p, ' '); p.skip(1); status_code.parse_up_to_delim(p, ' '); p.skip(1); status_reason.parse_up_to_delim(p, '\r'); p.skip(2); /* parse headers */ headers.parse(p); return; } void http_response::write_json(struct json_object &record) { // construct a list of http header names to be printed out // uint8_t ct[] = { 'c', 'o', 'n', 't', 'e', 'n', 't', '-', 't', 'y', 'p', 'e', ':', ' ' }; struct datum content_type{ct, ct+sizeof(ct)}; std::pair<struct datum, std::string> content_type_pair{content_type, "content_type"}; uint8_t cl[] = { 'c', 'o', 'n', 't', 'e', 'n', 't', '-', 'l', 'e', 'n', 'g', 't', 'h', ':', ' ' }; struct datum content_length{cl, cl+sizeof(cl)}; std::pair<struct datum, std::string> content_length_pair{content_length, "content_length"}; uint8_t srv[] = { 's', 'e', 'r', 'v', 'e', 'r', ':', ' ' }; struct datum server{srv, srv+sizeof(srv)}; std::pair<struct datum, std::string> server_pair{server, "server"}; uint8_t v[] = { 'v', 'i', 'a', ':', ' ' }; struct datum v_parser{v, v+sizeof(v)}; std::pair<struct datum, std::string> via_pair{v_parser, "via"}; std::list<std::pair<struct datum, std::string>> names_to_print{server_pair, content_type_pair, content_length_pair, via_pair}; struct json_object http{record, "http"}; struct json_object http_response{http, "response"}; http_response.print_key_json_string("version", version.data, version.length()); http_response.print_key_json_string("status_code", status_code.data, status_code.length()); http_response.print_key_json_string("status_reason", status_reason.data, status_reason.length()); //http.print_key_json_string("headers", response.headers.data, response.headers.length()); // run the list of http headers to be printed out against // all headers, and print the values corresponding to each // of the matching names // headers.print_matching_names(http_response, names_to_print); http_response.print_key_value("fingerprint", *this); http_response.close(); http.close(); } void http_request::operator()(struct buffer_stream &b) const { if (is_not_empty() == false) { b.write_char('\"'); b.write_char('\"'); return; } b.write_char('\"'); b.write_char('('); b.raw_as_hex(method.data, method.data_end - method.data); b.write_char(')'); b.write_char('('); b.raw_as_hex(protocol.data, protocol.data_end - protocol.data); b.write_char(')'); std::unordered_map<std::basic_string<uint8_t>, bool> http_static_keywords = { { { 'a', 'c', 'c', 'e', 'p', 't', ':', ' ' }, true }, { { 'a', 'c', 'c', 'e', 'p', 't', '-', 'e', 'n', 'c', 'o', 'd', 'i', 'n', 'g', ':', ' '}, true }, { { 'c', 'o', 'n', 'n', 'e', 'c', 't', 'i', 'o', 'n', ':', ' ' }, true }, { { 'd', 'n', 't', ':', ' ' }, true }, { { 'd', 'p', 'r', ':', ' ' }, true }, { { 'u', 'p', 'g', 'r', 'a', 'd', 'e', '-', 'i', 'n', 's', 'e', 'c', 'u', 'r', 'e', '-', 'r', 'e', 'q', 'u', 'e', 's', 't', 's', ':', ' ' }, true }, { { 'x', '-', 'r', 'e', 'q', 'u', 'e', 's', 't', 'e', 'd', '-', 'w', 'i', 't', 'h', ':', ' ' }, true }, { { 'a', 'c', 'c', 'e', 'p', 't', '-', 'c', 'h', 'a', 'r', 's', 'e', 't', ':', ' ' }, false }, { { 'a', 'c', 'c', 'e', 'p', 't', '-', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e', ':', ' ' }, false }, { { 'a', 'u', 't', 'h', 'o', 'r', 'i', 'z', 'a', 't', 'i', 'o', 'n', ':', ' ' }, false }, { { 'c', 'a', 'c', 'h', 'e', '-', 'c', 'o', 'n', 't', 'r', 'o', 'l', ':', ' ' }, false }, { { 'h', 'o', 's', 't', ':', ' ' }, false }, { { 'i', 'f', '-', 'm', 'o', 'd', 'i', 'f', 'i', 'e', 'd', '-', 's', 'i', 'n', 'c', 'e', ':', ' ' }, false }, { { 'k', 'e', 'e', 'p', '-', 'a', 'l', 'i', 'v', 'e', ':', ' ' }, false }, { { 'u', 's', 'e', 'r', '-', 'a', 'g', 'e', 'n', 't', ':', ' ' }, false }, { { 'x', '-', 'f', 'l', 'a', 's', 'h', '-', 'v', 'e', 'r', 's', 'i', 'o', 'n', ':', ' ' }, false }, { { 'x', '-', 'p', '2', 'p', '-', 'p', 'e', 'e', 'r', 'd', 'i', 's', 't', ':', ' ' }, false } }; headers.fingerprint(b, http_static_keywords); b.write_char('\"'); } void http_response::operator()(struct buffer_stream &buf) const { if (is_not_empty() == false) { buf.write_char('\"'); buf.write_char('\"'); return; } buf.write_char('\"'); buf.write_char('('); buf.raw_as_hex(version.data, version.data_end - version.data); buf.write_char(')'); buf.write_char('('); buf.raw_as_hex(status_code.data, status_code.data_end - status_code.data); buf.write_char(')'); buf.write_char('('); buf.raw_as_hex(status_reason.data, status_reason.data_end - status_reason.data); buf.write_char(')'); std::unordered_map<std::basic_string<uint8_t>, bool> http_static_keywords = { { (uint8_t *)"access-control-allow-credentials: ", true }, { (uint8_t *)"access-control-allow-headers: ", true }, { (uint8_t *)"access-control-allow-methods: ", true }, { (uint8_t *)"access-control-expose-headers: ", true }, { (uint8_t *)"cache-control: ", true }, { (uint8_t *)"code: ", true }, { (uint8_t *)"connection: ", true }, { (uint8_t *)"content-language: ", true }, { (uint8_t *)"content-transfer-encoding: ", true }, { (uint8_t *)"p3p: ", true }, { (uint8_t *)"pragma: ", true }, { (uint8_t *)"reason: ", true }, { (uint8_t *)"server: ", true }, { (uint8_t *)"strict-transport-security: ", true }, { (uint8_t *)"version: ", true }, { (uint8_t *)"x-aspnetmvc-version: ", true }, { (uint8_t *)"x-aspnet-version: ", true }, { (uint8_t *)"x-cid: ", true }, { (uint8_t *)"x-ms-version: ", true }, { (uint8_t *)"x-xss-protection: ", true }, { (uint8_t *)"appex-activity-id: ", false }, { (uint8_t *)"cdnuuid: ", false }, { (uint8_t *)"cf-ray: ", false }, { (uint8_t *)"content-range: ", false }, { (uint8_t *)"content-type: ", false }, { (uint8_t *)"date: ", false }, { (uint8_t *)"etag: ", false }, { (uint8_t *)"expires: ", false }, { (uint8_t *)"flow_context: ", false }, { (uint8_t *)"ms-cv: ", false }, { (uint8_t *)"msregion: ", false }, { (uint8_t *)"ms-requestid: ", false }, { (uint8_t *)"request-id: ", false }, { (uint8_t *)"vary: ", false }, { (uint8_t *)"x-amz-cf-pop: ", false }, { (uint8_t *)"x-amz-request-id: ", false }, { (uint8_t *)"x-azure-ref-originshield: ", false }, { (uint8_t *)"x-cache: ", false }, { (uint8_t *)"x-cache-hits: ", false }, { (uint8_t *)"x-ccc: ", false }, { (uint8_t *)"x-diagnostic-s: ", false }, { (uint8_t *)"x-feserver: ", false }, { (uint8_t *)"x-hw: ", false }, { (uint8_t *)"x-msedge-ref: ", false }, { (uint8_t *)"x-ocsp-responder-id: ", false }, { (uint8_t *)"x-requestid: ", false }, { (uint8_t *)"x-served-by: ", false }, { (uint8_t *)"x-timer: ", false }, { (uint8_t *)"x-trace-context: ", false } }; headers.fingerprint(buf, http_static_keywords); buf.write_char('\"'); }
39.474926
156
0.523539
[ "object" ]
24cdecb7e184efed355f90f37ffd1416b4a77bdf
1,481
hpp
C++
quantum_system.hpp
ORNL-QCI/sabot
c33edfc8a4461c67580e8a3cc8454a5a61347412
[ "BSD-3-Clause" ]
1
2020-06-18T23:10:20.000Z
2020-06-18T23:10:20.000Z
quantum_system.hpp
ORNL-QCI/sabot
c33edfc8a4461c67580e8a3cc8454a5a61347412
[ "BSD-3-Clause" ]
null
null
null
quantum_system.hpp
ORNL-QCI/sabot
c33edfc8a4461c67580e8a3cc8454a5a61347412
[ "BSD-3-Clause" ]
1
2020-06-18T23:10:22.000Z
2020-06-18T23:10:22.000Z
#ifndef _QUANTUM_SYSTEM_HPP #define _QUANTUM_SYSTEM_HPP #include <common.hpp> #include "state/state_type.hpp" /** * \brief A discrete quantum system. * * A system has a state type object and a noise type object which holds relevent * parameters. We use move semantics. */ struct quantum_system { public: using id_t = std::uint_fast64_t; /** * \brief Initialization constructor. */ quantum_system(const char* stateType) : stateType(state::state_type_factory::instantiate(stateType)) { } /** * \brief Copy constructor disabled. */ quantum_system(const quantum_system&) = delete; /** * \brief Move constructor. */ quantum_system(quantum_system&& system) { stateType = system.stateType; system.stateType = 0; } /** * \brief Assignment operator disabled. */ quantum_system& operator=(const quantum_system&) = delete; /** * \brief Move assignment operator. */ quantum_system& operator=(quantum_system&& system) { std::swap(stateType, system.stateType); return *this; } /** * \brief Destructor. */ ~quantum_system() { if(stateType != 0) { delete stateType; } } /** * \brief Get a pointer to the state type object. */ inline state::state_type& state_type() const { return *stateType; } private: /** * \brief The type of state the quantum channel can handle. * * This also contains the list of states, since the type of element is dynamic. */ state::state_type* stateType; }; #endif
19.233766
80
0.680621
[ "object" ]
24d2cf4e878e470ecb03b5f4f40f116abe8ea32c
13,580
cpp
C++
Disposition/src/EditorLayer.cpp
Tomzopo/parabol
2e11a78ba11726c01af2cd320f0a6769f221758f
[ "Apache-2.0" ]
null
null
null
Disposition/src/EditorLayer.cpp
Tomzopo/parabol
2e11a78ba11726c01af2cd320f0a6769f221758f
[ "Apache-2.0" ]
null
null
null
Disposition/src/EditorLayer.cpp
Tomzopo/parabol
2e11a78ba11726c01af2cd320f0a6769f221758f
[ "Apache-2.0" ]
null
null
null
#include "EditorLayer.h" #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/matrix_decompose.hpp> #include "Parabol/Scene/SceneSerializer.h" #include "Parabol/Utils/PlatformUtils.h" namespace Parabol { EditorLayer::EditorLayer() : Layer("Disposition_Editor"), m_CameraController(16.0f / 9.0f, true) { } void EditorLayer::OnAttach() { FramebufferSpecification spec; spec.Width = 1280; spec.Height = 720; m_FrameBuffer = FrameBuffer::Create(spec); NewScene(); } void EditorLayer::OnDetach() { } void EditorLayer::OnUpdate(Timestep ts) { FramebufferSpecification spec = m_FrameBuffer->GetSpecification(); if (m_ViewportSize.width > 0.0f && m_ViewportSize.height > 0.0f && // framebuffer must have a size (spec.Width != static_cast<uint32_t>(m_ViewportSize.width) || spec.Height != static_cast<uint32_t>(m_ViewportSize.height))) { m_FrameBuffer->Resize((uint32_t) m_ViewportSize.width, (uint32_t) m_ViewportSize.height); m_CameraController.OnResize(m_ViewportSize.width, m_ViewportSize.height); m_EditorCamera.SetViewportSize(m_ViewportSize.width, m_ViewportSize.height); m_ActiveScene->OnViewportResize(static_cast<uint32_t>(m_ViewportSize.width), static_cast<uint32_t>(m_ViewportSize.height)); } if (m_ViewportFocused) m_CameraController.OnUpdate(ts); m_EditorCamera.OnUpdate(ts); Renderer2D::ResetStats(); m_FrameBuffer->Bind(); RenderCommand::SetClearColor({0.1f, 0.1f, 0.1f, 1.0f}); RenderCommand::Clear(); m_ActiveScene->OnUpdateEditor(ts, m_EditorCamera); m_FrameBuffer->Unbind(); } void EditorLayer::OnImGuiRender() { static bool dockspace_open = true; static bool opt_fullscreen_persistent = true; bool opt_fullscreen = opt_fullscreen_persistent; static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, // because it would be confusing to have two docking targets within each others. ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; if (opt_fullscreen) { const ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->WorkPos); ImGui::SetNextWindowSize(viewport->WorkSize); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background // and handle the pass-thru hole, so we ask Begin() to not render a background. if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) window_flags |= ImGuiWindowFlags_NoBackground; // Important: note that we proceed even if Begin() returns false (aka window is collapsed). // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, // all active windows docked into it will lose their parent and become undocked. // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. static bool opt_padding = false; if (!opt_padding) ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace Demo", &dockspace_open, window_flags); if (!opt_padding) ImGui::PopStyleVar(); if (opt_fullscreen) ImGui::PopStyleVar(2); // Submit the DockSpace ImGuiIO& io = ImGui::GetIO(); ImGuiStyle& style = ImGui::GetStyle(); float minWinSizeX = style.WindowMinSize.x; float minWinSizeY = style.WindowMinSize.y; style.WindowMinSize.x = 385.0f; style.WindowMinSize.y = 250.0f; if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); } style.WindowMinSize.x = minWinSizeX; style.WindowMinSize.y = minWinSizeY; if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("New Scene", "Ctrl+N")) { NewScene(); } if (ImGui::MenuItem("Open Scene", "Ctrl+O")) { OpenScene(); } ImGui::Separator(); if (ImGui::MenuItem("Save", "Ctrl+S")) { SaveScene(); } if (ImGui::MenuItem("Save As...", "Ctrl+Shift+S")) { SaveSceneAs(); } ImGui::Separator(); if (ImGui::MenuItem("Exit")) Application::Get().Close(); ImGui::EndMenu(); } ImGui::EndMenuBar(); } ImGui::End(); m_SceneHierarchyPanel.OnImGuiRender(); ImGui::Begin("Settings"); { auto stats = Renderer2D::GetStats(); ImGui::Text("Renderer2D Stats:"); ImGui::Text("Draw Calls: %d", stats.DrawCalls); ImGui::Text("Quads: %d", stats.QuadCount); ImGui::Text("Vertices: %d", stats.GetTotalVertexCount()); ImGui::Text("Indices: %d", stats.GetTotalIndexCount()); } ImGui::End(); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2{0, 0}); ImGui::Begin("Scene"); m_ViewportFocused = ImGui::IsWindowFocused(); m_ViewportHovered = ImGui::IsWindowHovered(); Application::Get().GetImGuiLayer()->BlockEvents(!m_ViewportFocused && !m_ViewportHovered); ImVec2 viewportSize = ImGui::GetContentRegionAvail(); m_ViewportSize = {viewportSize.x, viewportSize.y}; uint32_t textureID = m_FrameBuffer->GetColorAttachmentRendererID(); ImGui::Image((void*) textureID, ImVec2{m_ViewportSize.width, m_ViewportSize.height}, ImVec2{0, 1}, ImVec2{1, 0}); // ImGuizmo's Entity selected_entity = m_SceneHierarchyPanel.GetSelectedEntity(); if (selected_entity && m_GuizmoType.has_value()) { // Camera auto camera_entity_opt = m_ActiveScene->GetPrimaryCameraEntity(); if (camera_entity_opt.has_value()) { // Camera const glm::mat4& camera_projection = m_EditorCamera.GetProjection(); glm::mat4 camera_view = m_EditorCamera.GetViewMatrix(); //Runtime camera // auto camera_entity = camera_entity_opt.value(); // const auto& camera = camera_entity.GetComponent<CameraComponent>().Camera; // const glm::mat4& camera_projection = camera.GetProjection(); // glm::mat4 camera_view = glm::inverse(camera_entity.GetComponent<TransformComponent>().GetTransform()); ImGuizmo::SetOrthographic(false); ImGuizmo::SetDrawlist(); auto window_width = static_cast<float>(ImGui::GetWindowWidth()); auto window_height = static_cast<float>(ImGui::GetWindowHeight()); ImGuizmo::SetRect(ImGui::GetWindowPos().x, ImGui::GetWindowPos().y, window_width, window_height); // Entity auto& tc = selected_entity.GetComponent<TransformComponent>(); glm::mat4 transform = tc.GetTransform(); // Snapping bool snap = Input::IsKeyPressed(Key::LeftControl); float snap_value = (m_GuizmoType == ImGuizmo::OPERATION::TRANSLATE) || (m_GuizmoType == ImGuizmo::OPERATION::SCALE) ? 0.5f : 5.0f; float snap_values[3] = {snap_value, snap_value, snap_value}; // ImGuizmo::Manipulate(glm::value_ptr(camera_view), glm::value_ptr(camera_projection), m_GuizmoType.value(), ImGuizmo::MODE::LOCAL, glm::value_ptr(transform), nullptr, snap ? snap_values : nullptr); if (ImGuizmo::IsUsing()) { glm::vec3 translation, skew, scale; glm::quat rotation; glm::vec4 perspective; glm::decompose(transform, scale, rotation, translation, skew, perspective); tc.Translation = translation; tc.Rotation = eulerAngles(rotation); tc.Scale = scale; } } } ImGui::PopStyleVar(); ImGui::End(); } void EditorLayer::OnEvent(Event& event) { m_CameraController.OnEvent(event); m_EditorCamera.OnEvent(event); EventDispatcher dispatcher(event); dispatcher.Dispatch<KeyPressedEvent>(PB_BIND_EVENT_FN(EditorLayer::OnKeyPressed)); } bool EditorLayer::OnKeyPressed(KeyPressedEvent& event) { if (event.GetRepeatCount() > 0) return false; // TODO Hotkey system bool control = Input::IsKeyPressed(Key::LeftControl) || Input::IsKeyPressed(Key::RightControl); bool shift = Input::IsKeyPressed(Key::LeftShift) || Input::IsKeyPressed(Key::RightShift); switch (event.GetKeyCode()) { // File shortcuts case Key::N: { if (control) NewScene(); break; } case Key::O: { if (control) OpenScene(); break; } case Key::S: { if (control && shift) SaveSceneAs(); else if (control) SaveScene(); break; } // Gizmo shortcuts case Key::Q: { if(!ImGuizmo::IsUsing()) m_GuizmoType = std::nullopt; break; } case Key::W: { if(!ImGuizmo::IsUsing()) m_GuizmoType = ImGuizmo::OPERATION::TRANSLATE; break; } case Key::E: { if(!ImGuizmo::IsUsing()) m_GuizmoType = ImGuizmo::OPERATION::ROTATE; break; } case Key::R: { if(!ImGuizmo::IsUsing()) m_GuizmoType = ImGuizmo::OPERATION::SCALE; break; } default:break; } return false; } void EditorLayer::NewScene() { m_ActiveScene = CreateRc<Scene>(); m_EditorCamera = EditorCamera(30.0f, 1.778f, 0.1f, 1000.0f); m_ActiveScene->OnViewportResize(static_cast<uint32_t>(m_ViewportSize.width), static_cast<uint32_t>(m_ViewportSize.height)); m_SceneHierarchyPanel.SetContext(m_ActiveScene); m_ActiveScene_Filepath = std::nullopt; } void EditorLayer::OpenScene() { auto filepath = FileDialogs::OpenFile("Parabol Scene " "(*.parabol)\0" "*.parabol\0"); if (filepath.has_value()) { m_ActiveScene = CreateRc<Scene>(); m_SceneHierarchyPanel.SetContext(m_ActiveScene); SceneSerializer serializer(m_ActiveScene); serializer.Deserialize(*filepath); m_ActiveScene_Filepath = std::string(*filepath); } } void EditorLayer::OpenScene(const std::filesystem::path& path) { if (path.extension().string() != ".parabol") { LOG_WARN("Could not load {0} - not a scene file", path.filename().string()); return; } auto new_scene = CreateRc<Scene>(); SceneSerializer serializer(new_scene); if (serializer.Deserialize(path.string())) { m_ActiveScene = new_scene; m_ActiveScene->OnViewportResize(static_cast<uint32_t>(m_ViewportSize.width), static_cast<uint32_t>(m_ViewportSize.height)); m_SceneHierarchyPanel.SetContext(m_ActiveScene); m_ActiveScene_Filepath = path.string(); } } void EditorLayer::SaveScene() { if (m_ActiveScene_Filepath.has_value()) { SceneSerializer serializer(m_ActiveScene); serializer.Serialize(m_ActiveScene_Filepath.value()); } else SaveSceneAs(); } void EditorLayer::SaveSceneAs() { auto filepath = FileDialogs::SaveFile("Parabol Scene " "(*.parabol)\0" "*.parabol\0"); if (filepath.has_value()) { SceneSerializer serializer(m_ActiveScene); serializer.Serialize(*filepath); m_ActiveScene_Filepath = std::string(*filepath); } } }
40.058997
146
0.579676
[ "render", "transform" ]
24d528ce4596a9d9a09512a993b4d525fece54bd
2,572
cpp
C++
PyCommon/externalLibs/BaseLib/motion/Retarget_JH/MATHCLASS/transf.cpp
hpgit/HumanFoot
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
[ "Apache-2.0" ]
4
2017-04-15T09:16:10.000Z
2018-04-19T09:28:54.000Z
PyCommon/externalLibs/BaseLib/motion/Retarget_JH/MATHCLASS/transf.cpp
hpgit/HumanFoot
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
[ "Apache-2.0" ]
null
null
null
PyCommon/externalLibs/BaseLib/motion/Retarget_JH/MATHCLASS/transf.cpp
hpgit/HumanFoot
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
[ "Apache-2.0" ]
1
2021-07-26T15:13:55.000Z
2021-07-26T15:13:55.000Z
#include "mathclass.h" namespace jhm { // Identity Transform transf identity_transf( scaling(1), vector(0,0,0) ); // Inquiry Function transf transf::inverse() const { matrix a = m.inverse(); return transf( a, (-v)*a ); } transf inverse( transf const& t ) { return t.inverse(); } // generator transf scale_transf( m_real s ) { matrix m = scaling( s ); vector v( 0.0, 0.0, 0.0 ); return transf( m, v ); } transf scale_transf( m_real sx, m_real sy, m_real sz ) { matrix m = scaling( sx, sy, sz ); vector v( 0.0, 0.0, 0.0 ); return transf( m, v ); } transf rotate_transf( m_real angle, vector const& axis ) { matrix m = rotation( angle, axis ); vector v( 0.0, 0.0, 0.0 ); return transf( m, v ); } transf reflect_transf( vector const& axis ) { matrix m = reflection( axis ); vector v( 0.0, 0.0, 0.0 ); return transf( m, v ); } transf translate_transf( vector const& axis ) { return transf( scaling( 1.0 ), axis ); } transf translate_transf( m_real x, m_real y, m_real z ) { return transf( scaling( 1.0 ), vector(x,y,z) ); } transf coordinate_transf( position const& new_o, unit_vector const& new_x, unit_vector const& new_y ) { position o( 0.0, 0.0, 0.0 ); vector x_axis( 1.0, 0.0, 0.0 ); vector y_axis( 0.0, 1.0, 0.0 ); vector z_axis( 0.0, 0.0, 1.0 ); transf t1 = translate_transf( o - new_o ); vector v1 = new_x; v1.set_x( 0.0 ); m_real theta = ACOS( (v1 % z_axis) / len(v1) ); transf t2 = rotate_transf( theta, x_axis ); vector v2 = new_x; vector v3 = v2 * t2 * t1; theta = ACOS( (v3 % x_axis) / len(v3) ); transf t3 = rotate_transf( theta, y_axis ); vector v4 = new_y; vector v5 = v4 * t3 * t2 * t1; theta = ACOS( (v5 % y_axis) / len(v5) ); transf t4 = rotate_transf( theta, x_axis ); return t4 * t3 * t2 * t1; } std::ostream& operator<<( std::ostream& os, transf const& a ) { os << a.getAffine() << " + " << a.getTranslation(); return os; } std::istream& operator>>( std::istream& is, transf& a ) { static char buf[256]; //is >> a.m >> "+" >> a.v; is >> a.m >> buf >> a.v; return is; } transf interpolate( m_real t, transf const& a, transf const& b ) { matrix m = interpolate( t, a.getAffine(), b.getAffine() ); vector v = interpolate( t, a.getTranslation(), b.getTranslation() ); return transf( m, v ); } }
21.256198
70
0.550544
[ "vector", "transform" ]
24d9762712b66e12d8ef6a07e60280ac4b367433
2,421
hxx
C++
main/sw/source/ui/docvw/ShadowOverlayObject.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sw/source/ui/docvw/ShadowOverlayObject.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sw/source/ui/docvw/ShadowOverlayObject.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SHADOWOVERLAYOBJECT_HXX #define _SHADOWOVERLAYOBJECT_HXX #include <svx/sdr/overlay/overlayobject.hxx> class SwView; namespace sw { namespace sidebarwindows { enum ShadowState { SS_NORMAL, SS_VIEW, SS_EDIT }; class ShadowOverlayObject: public sdr::overlay::OverlayObjectWithBasePosition { protected: // geometry creation for OverlayObject virtual drawinglayer::primitive2d::Primitive2DSequence createOverlayObjectPrimitive2DSequence(); private: basegfx::B2DPoint maSecondPosition; ShadowState mShadowState; ShadowOverlayObject( const basegfx::B2DPoint& rBasePos, const basegfx::B2DPoint& rSecondPosition, Color aBaseColor, ShadowState aState ); virtual ~ShadowOverlayObject(); public: void SetShadowState(ShadowState aState); inline ShadowState GetShadowState() {return mShadowState;} inline const basegfx::B2DPoint& GetSecondPosition() const { return maSecondPosition; } void SetSecondPosition( const basegfx::B2DPoint& rNew ); void SetPosition( const basegfx::B2DPoint& rPoint1, const basegfx::B2DPoint& rPoint2 ); static ShadowOverlayObject* CreateShadowOverlayObject( SwView& rDocView ); static void DestroyShadowOverlayObject( ShadowOverlayObject* pShadow ); }; } } // end of namespace sw::sidebarwindows #endif
33.164384
104
0.668732
[ "geometry" ]
24da04c2fa569de6401ca6d96bfa42f7fdc1f840
1,794
cpp
C++
src/sycomore/Pulse.cpp
aTrotier/sycomore
32e438d3a90ca0a9d051bb6acff461e06079116d
[ "MIT" ]
14
2019-11-06T09:23:09.000Z
2022-01-11T19:08:36.000Z
src/sycomore/Pulse.cpp
aTrotier/sycomore
32e438d3a90ca0a9d051bb6acff461e06079116d
[ "MIT" ]
2
2020-12-01T15:48:27.000Z
2020-12-04T15:19:37.000Z
src/sycomore/Pulse.cpp
aTrotier/sycomore
32e438d3a90ca0a9d051bb6acff461e06079116d
[ "MIT" ]
2
2020-08-12T04:36:36.000Z
2021-05-27T13:17:34.000Z
#include "Pulse.h" #include <algorithm> #include <cmath> #include <numeric> #include <vector> #include "sycomore/Grid.h" #include "sycomore/sycomore.h" #include "sycomore/units.h" namespace sycomore { Pulse ::Pulse(Quantity const & angle, Quantity const & phase) { this->set_angle(angle); this->set_phase(phase); } Quantity const & Pulse ::get_angle() const { return this->_angle; } void Pulse ::set_angle(Quantity const & q) { if(q.dimensions == Angle) { this->_angle = q; } else { std::ostringstream message; message << "Invalid angle dimensions: " << q.dimensions; throw std::runtime_error(message.str()); } } Quantity const & Pulse ::get_phase() const { return this->_phase; } void Pulse ::set_phase(Quantity const & q) { if(q.dimensions == Angle) { this->_phase = q; } else { std::ostringstream message; message << "Invalid phase dimensions: " << q.dimensions; throw std::runtime_error(message.str()); } } Pulse::RotationMatrix Pulse ::rotation_matrix() const { using namespace units; Real const c_alpha = std::cos(this->_angle.convert_to(rad)); Real const s_alpha = std::sin(this->_angle.convert_to(rad)); Complex const e_i_phi{ std::cos(this->_phase.convert_to(rad)), std::sin(this->_phase.convert_to(rad))}; RotationMatrix m({0,0}, {3,3}, 0); m[{0, 0}] = 0.5 * (1. + c_alpha); m[{0, 1}] = Complex{0, -s_alpha} * e_i_phi / std::sqrt(2.); m[{0, 2}] = 0.5 * (1. - c_alpha) * std::pow(e_i_phi, 2); m[{1, 0}] = -std::conj(m[{0, 1}]); m[{1, 1}] = c_alpha; m[{1, 2}] = -m[{0, 1}]; m[{2, 0}] = std::conj(m[{0, 2}]); m[{2, 1}] = -m[{1, 0}]; m[{2, 2}] = m[{0, 0}]; return m; } }
18.884211
64
0.574136
[ "vector" ]
24e277911e913f4918d15a973b5d461d2bd0bb63
5,879
cpp
C++
ray/Board.cpp
guille0/space-chess
3e8a3c8c8b91fbcbc00fbb4b35596a3b2ad1a37c
[ "MIT" ]
17
2019-08-02T16:52:14.000Z
2021-09-21T15:32:14.000Z
ray/Board.cpp
guille0/space-chess
3e8a3c8c8b91fbcbc00fbb4b35596a3b2ad1a37c
[ "MIT" ]
1
2020-01-02T07:44:22.000Z
2020-01-02T07:44:22.000Z
ray/Board.cpp
guille0/space-chess
3e8a3c8c8b91fbcbc00fbb4b35596a3b2ad1a37c
[ "MIT" ]
4
2019-11-10T17:52:39.000Z
2022-02-25T14:55:48.000Z
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <limits> #include "AI.h" #include "Moves.h" #include "Board.h" namespace chess { // Board Board::Board () {} Board::Board(long* t_beginning, int t_maxZ, int t_maxY, int t_maxX, int t_turn, bool t_pawn2step) : m_beginning(t_beginning), m_maxZ(t_maxZ), m_maxY(t_maxY), m_maxX(t_maxX), m_turn(t_turn), m_pawn2step(t_pawn2step) {} Board::~Board() {} Board Board::copy(bool t_change_turn) { if (t_change_turn) { return Board(m_beginning, m_maxZ, m_maxY, m_maxX, m_turn*-1, m_pawn2step); } return Board(m_beginning, m_maxZ, m_maxY, m_maxX, m_turn, m_pawn2step); } // Getters and setters void Board::set(int t_x, int t_y, int t_z, int t_value) { m_beginning[t_x+t_y*m_maxX+t_z*(m_maxX*m_maxY)] = t_value; } int Board::get(int t_x, int t_y, int t_z) { return m_beginning[t_x+t_y*m_maxX+t_z*(m_maxX*m_maxY)]; } int Board::getCheck() { return m_check; } int Board::getTurn() { return m_turn; } void Board::setTurn(int t_turn) { m_turn = t_turn; } void Board::changeTurn() { m_turn = m_turn*-1; } int Board::getPawn2step() { return m_pawn2step; } int Board::getMaxX() { return m_maxX; } int Board::getMaxY() { return m_maxY; } int Board::getMaxZ() { return m_maxZ; } // Calculates the value of the board double Board::getValue() { double boardValue = 0; // Count black & white pieces for (int z=0; z<m_maxZ; z++) { for (int y=0; y<m_maxY; y++) { for (int x=0; x<m_maxX; x++) { // The weights prioritize squares on the center of the board if (get(x,y,z) > 0) { boardValue += m_piecesValue[get(x,y,z)-1]; boardValue += (addWeights(x, m_maxX) + addWeights(y, m_maxY) + addWeights(z, m_maxZ)); } else if (get(x,y,z) < 0) { boardValue -= m_piecesValue[abs(get(x,y,z))-1]; boardValue -= (addWeights(x, m_maxX) + addWeights(y, m_maxY) + addWeights(z, m_maxZ)); } } } } return boardValue; } // Returns the board turned into a string for printing std::string Board::toString() { std::string str = ""; for (int z=0; z<m_maxZ; z++) { for (int y=0; y<m_maxY; y++) { for (int x=0; x<m_maxX; x++) { if (get(x,y,z) >= 0) { str += " "; } str += std::to_string(get(x,y,z)); } str += "\n"; } str += "\n"; } str += "TURN IS: "; str += std::to_string(m_turn); return str; } // Returns a vector of all the possible moves a player can make std::vector<std::pair<std::vector<int>,std::vector<int>>> Board::possibleMoves(int t_turn) { std::vector<std::vector<int>> pieces; for (int z=0; z<m_maxZ; z++) { for (int y=0; y<m_maxY; y++) { for (int x=0; x<m_maxX; x++) { if (get(x,y,z)*t_turn > 0) { pieces.push_back(std::vector<int> {x, y, z, get(x,y,z)}); } } } } std::vector<std::pair<std::vector<int>,std::vector<int>>> totalMoves; for (auto piece : pieces) { // Get the moves for this piece std::vector<std::pair<std::vector<int>,std::vector<int>>> moves = pieceMoves(piece, t_turn); // Shove it into all the moves that can be made totalMoves.insert(std::end(totalMoves), std::begin(moves), std::end(moves)); } return totalMoves; } // Returns all the moves a certain piece can make {{piece}, {move}} std::vector<std::pair<std::vector<int>,std::vector<int>>> Board::pieceMoves(std::vector<int> t_piece, int t_turn) { const int x = t_piece[0]; const int y = t_piece[1]; const int z = t_piece[2]; // pieceType = pawn, rook, queen, etc. // (1,2,3,4,5,6,7,-1,-2,-3,-4,-5,-6,-7) const int pieceType = t_piece[3]; std::vector<std::pair<std::vector<int>,std::vector<int>>> moves; moves::Moves Movement(this, t_turn, x, y, z); switch (abs(pieceType)) { case 1: { moves = Movement.pawnMoves(); break; } case 2: { moves = Movement.rookMoves(); break; } case 3: { moves = Movement.knightMoves(); break; } case 4: { moves = Movement.bishopMoves(); break; } case 5: { moves = Movement.queenMoves(); break; } case 6: { moves = Movement.kingMoves(); break; } case 7: { moves = Movement.unicornMoves(); break; } } // Whether this player has a check on the enemy on this turn if (m_check == false && Movement.getCheck() == true) { m_check = true; } return moves; } std::vector<std::pair<std::vector<int>,std::vector<int>>> Board::allowedMoves(std::vector<std::pair<std::vector<int>,std::vector<int>>> piecesAndMoves, int t_turn) { std::vector<std::pair<std::vector<int>,std::vector<int>>> finalMoves; for (auto pieceAndMove : piecesAndMoves) { const std::vector<int> piece = pieceAndMove.first; const std::vector<int> move = pieceAndMove.second; // Copy this board Board newBoard = this->copy(); // Save the variables so we can undo the move const int pieceType = newBoard.get(piece[0], piece[1], piece[2]); const int pieceType2 = newBoard.get(move[0], move[1], move[2]); // Move the piece newBoard.set(move[0], move[1], move[2], pieceType); newBoard.set(piece[0], piece[1], piece[2], 0); // See all the possible moves for the other player, to see if he could attack the king newBoard.possibleMoves(t_turn*-1); // Reset movements newBoard.set(move[0], move[1], move[2], pieceType2); newBoard.set(piece[0], piece[1], piece[2], pieceType); if (newBoard.getCheck() == false) { finalMoves.push_back(pieceAndMove); } } return finalMoves; } // Simple weights that prioritize squares on the center of the board double addWeights (double dim, double maxDim) { dim = 0.5+dim-maxDim/2; dim = std::abs(dim)/maxDim; return -dim; } }
26.363229
97
0.609287
[ "vector" ]
24e2ab5b97b6eab0d32344c1d49aba7d4b6d7d2a
32,811
hpp
C++
storage/CSBTreeIndexSubBlock.hpp
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
31
2016-01-20T05:43:46.000Z
2022-02-07T09:14:06.000Z
storage/CSBTreeIndexSubBlock.hpp
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
221
2016-01-20T18:25:10.000Z
2016-06-26T02:58:12.000Z
storage/CSBTreeIndexSubBlock.hpp
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
17
2016-01-20T04:00:21.000Z
2019-03-12T02:41:25.000Z
/** * Copyright 2011-2015 Quickstep Technologies LLC. * Copyright 2015-2016 Pivotal Software, Inc. * Copyright 2016, Quickstep Research Group, Computer Sciences Department, * University of Wisconsin—Madison. * * 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. **/ #ifndef QUICKSTEP_STORAGE_CSBTREE_INDEX_SUB_BLOCK_HPP_ #define QUICKSTEP_STORAGE_CSBTREE_INDEX_SUB_BLOCK_HPP_ #include <cstddef> #include <cstdint> #include <exception> #include <memory> #include <vector> #include "catalog/CatalogTypedefs.hpp" #include "expressions/predicate/PredicateCost.hpp" #include "storage/IndexSubBlock.hpp" #include "storage/StorageBlockInfo.hpp" #include "storage/StorageConstants.hpp" #include "storage/SubBlockTypeRegistryMacros.hpp" #include "types/operations/comparisons/Comparison.hpp" #include "types/operations/comparisons/ComparisonID.hpp" #include "utility/BitVector.hpp" #include "utility/Macros.hpp" #include "utility/PtrVector.hpp" namespace quickstep { class CSBTreeIndexSubBlock; class CatalogRelationSchema; class ComparisonPredicate; class IndexSubBlockDescription; class TupleIdSequence; class TupleStorageSubBlock; class Type; class TypedValue; QUICKSTEP_DECLARE_SUB_BLOCK_TYPE_REGISTERED(CSBTreeIndexSubBlock); namespace csbtree_internal { class CompositeEntryReference; class CompressedEntryReference; class EntryReference; class PredicateEvaluationForwarder; // Hack which provides the UncheckedComparator interface, but compares // composite keys. // TODO(chasseur): Template this to avoid virtual calls. class CompositeKeyLessComparator : public UncheckedComparator { public: CompositeKeyLessComparator(const CSBTreeIndexSubBlock &owner, const CatalogRelationSchema &relation); ~CompositeKeyLessComparator() { } bool compareTypedValues(const TypedValue &left, const TypedValue &right) const { FATAL_ERROR("Can not use CompositeKeyLessComparator to compare TypedValue."); } inline bool compareDataPtrs(const void *left, const void *right) const { return compareDataPtrsInl(left, right); } bool compareDataPtrsInl(const void *left, const void *right) const; bool compareTypedValueWithDataPtr(const TypedValue &left, const void *right) const { FATAL_ERROR("Can not use CompositeKeyLessComparator to compare TypedValue."); } bool compareDataPtrWithTypedValue(const void *left, const TypedValue &right) const { FATAL_ERROR("Can not use CompositeKeyLessComparator to compare TypedValue."); } private: const CSBTreeIndexSubBlock &owner_; PtrVector<UncheckedComparator> attribute_comparators_; }; } // namespace csbtree_internal /** \addtogroup Storage * @{ */ /** * @brief Exception thrown when the key for a CSBTreeIndexSubBlock is too large * to fit more than one key in a node of the CSB+-tree. **/ class CSBTreeKeyTooLarge : public std::exception { public: virtual const char* what() const throw() { return "CSBTreeKeyTooLarge: Attempted to create a CSBTreeIndexSubBlock " "with an index key which is too large to fit more than 1 key in " "a node."; } }; /** * @brief An IndexSubBlock which implements a full CSB+-tree with linear scan * intra-node search. * @warning This IndexSubBlock only supports fixed-length attributes, and the * total key length must be small enough to fit at least 2 keys in a * node. **/ class CSBTreeIndexSubBlock : public IndexSubBlock { public: CSBTreeIndexSubBlock(const TupleStorageSubBlock &tuple_store, const IndexSubBlockDescription &description, const bool new_block, void *sub_block_memory, const std::size_t sub_block_memory_size); ~CSBTreeIndexSubBlock() override { } /** * @brief Determine whether an IndexSubBlockDescription is valid for this * type of IndexSubBlock. * * @param relation The relation an index described by description would * belong to. * @param description A description of the parameters for this type of * IndexSubBlock, which will be checked for validity. * @return Whether description is well-formed and valid for this type of * IndexSubBlock belonging to relation (i.e. whether an IndexSubBlock * of this type, belonging to relation, can be constructed according * to description). **/ static bool DescriptionIsValid(const CatalogRelationSchema &relation, const IndexSubBlockDescription &description); /** * @brief Estimate the average number of bytes (including any applicable * overhead) used to index a single tuple in this type of * IndexSubBlock. Used by StorageBlockLayout::finalize() to divide * block memory amongst sub-blocks. * @warning description must be valid. DescriptionIsValid() should be called * first if necessary. * * @param relation The relation tuples belong to. * @param description A description of the parameters for this type of * IndexSubBlock. * @return The average/ammortized number of bytes used to index a single * tuple of relation in an IndexSubBlock of this type described by * description. **/ static std::size_t EstimateBytesPerTuple(const CatalogRelationSchema &relation, const IndexSubBlockDescription &description); /** * @brief Estimate the total number of bytes (including any applicable * overhead) occupied by this IndexSubBlock within the StorageBlock. * This function is to be used by those indicies whose occupied size * in the block does not depend on the number of tuples being indexed. * @warning description must be valid. DescriptionIsValid() should be called * first if necessary. * @note This function will be invoked by StorageBlockLayout::finalize() * if and only when EstimateBytesPerTuple() returns a zero size. * * @param relation The relation tuples belong to. * @param description A description of the parameters for this type of * IndexSubBlock. * @return The total number of bytes occupied by this IndexSubBlock within * the StorageBlock. **/ static std::size_t EstimateBytesPerBlock(const CatalogRelationSchema &relation, const IndexSubBlockDescription &description); IndexSubBlockType getIndexSubBlockType() const override { return kCSBTree; } bool supportsAdHocAdd() const override { return initialized_; } bool supportsAdHocRemove() const override { return true; } bool addEntry(const tuple_id tuple) override; bool bulkAddEntries(const TupleIdSequence &tuples) override; void removeEntry(const tuple_id tuple) override; void bulkRemoveEntries(const TupleIdSequence &tuples) override; predicate_cost_t estimatePredicateEvaluationCost( const ComparisonPredicate &predicate) const override; /** * @note Currently this version only supports simple comparisons of a literal * value with a non-composite key. **/ TupleIdSequence* getMatchesForPredicate(const ComparisonPredicate &predicate, const TupleIdSequence *filter) const override; bool rebuild() override; private: // Information stored at the beginning of every node in the tree. struct NodeHeader { std::uint16_t num_keys; bool is_leaf; // 'node_group_reference' is the child for internal nodes, the right // sibling group for the last node in a group of leaf nodes, and // kNodeGroupNextLeaf for other leaf nodes. The very rightmost node // at the leaf level has this set to kNodeGroupNone. int node_group_reference; }; // Used by internalInsertHelper() and leafInsertHelper() to communicate // information about node and group splits to higher levels in the tree. struct InsertReturnValue { InsertReturnValue() : split_node_least_key(NULL), new_node_group_id(kNodeGroupNone), left_split_group_smaller(false) { } const void *split_node_least_key; int new_node_group_id; bool left_split_group_smaller; }; static const int kNodeGroupNone; // -1 static const int kNodeGroupNextLeaf; // -2 // Used in InsertReturnValue to indicate index is full (needed to allocate // new node groups, but not enough were free). static const int kNodeGroupFull; // -3 // Initialize this block's internal metadata and structure. Usually called by // the constructor, unless the key may be compressed, in which case it is // called by rebuild(). bool initialize(const bool new_block); // Get the number of the node group containing the root node for the tree. inline int getRootNodeGroupNumber() const { return *static_cast<const int*>(sub_block_memory_); } // Set the number of the node group containing the root node for the tree. inline void setRootNodeGroupNumber(const int node_group_number) { *static_cast<int*>(sub_block_memory_) = node_group_number; } // Get the location of the node designated by 'node_number' in the group // with 'node_group_number'. inline void* getNode(const int node_group_number, const std::uint16_t node_number) const { DEBUG_ASSERT(node_group_number >= 0); return static_cast<char*>(node_groups_start_) + node_group_number * node_group_size_bytes_ + node_number * kCSBTreeNodeSizeBytes; } // Get the root node of the tree. inline void* getRootNode() const { return getNode(getRootNodeGroupNumber(), 0); } // Get the right-sibling of the leaf node '*node', which may be in another // group. If '*node' is the very right-most leaf, returns NULL. inline void* getRightSiblingOfLeafNode(const void *node) const { DEBUG_ASSERT(static_cast<const NodeHeader*>(node)->is_leaf); const int sibling_reference = static_cast<const NodeHeader*>(node)->node_group_reference; if (sibling_reference == kNodeGroupNextLeaf) { return const_cast<char*>(static_cast<const char*>(node) + kCSBTreeNodeSizeBytes); } else if (sibling_reference >= 0) { return getNode(sibling_reference, 0); } else { DEBUG_ASSERT(sibling_reference == kNodeGroupNone); return NULL; } } // Remove all entries and reset this to an empty index. void clearIndex(); // Makes a copy of a composite key from 'tuple' in 'tuple_store_'. Caller is // responsible for freeing the memory allocated. void* makeKeyCopy(const tuple_id tuple) const; // Returns a pointer to the least key in the sub-tree anchored at '*node'. const void* getLeastKey(const void *node) const; // Return the first leaf node under *node which may contain *key. If // duplicate keys are present, it may be necessary to use // getRightSiblingOfLeafNode() to find the actual desired leaf. template <typename LiteralLessKeyComparatorT, typename KeyLessLiteralComparatorT> void* findLeaf( const void *node, const void *literal, const LiteralLessKeyComparatorT &literal_less_key_comparator, const KeyLessLiteralComparatorT &key_less_literal_comparator) const; // Get the very first leaf node in the tree. void* getLeftmostLeaf() const; // Attempt to insert the entry (compressed_code, tuple) in the index. // 'CodeType' is the compressed type of the code (either uint8_t, uint16_t, // or uint32_t). template <typename CodeType> InsertReturnValue compressedKeyAddEntryHelper(const tuple_id tuple, const std::uint32_t compressed_code); // Insert the entry (*key, tuple) into the appropriate leaf descendent of // '*node'. 'node_group_allocation_requirement' is the number of node group // splits of ancestors of '*node' and '*node' itself which would be necessary // if the node group containing '*node' were split. '*node' will have an // entry added if a child splits. If *node's child node group splits, '*node' // will be split, and '*split_node_first_key' in the return value will point // to the first key in the right split node. If a split occurs and the node // group '*node' belongs to is full, then the node group will be split, and // 'new_node_group_id' in the return value will be set to the ID of the // newly-created right split node group. Also, in cases where a node group // split occured and node group splits are asymmetric (i.e. // max_keys_internal_ + 1 is odd), left_split_group_smaller will be set to // indicate whether the left or right half of the split initially had one // less node than the other (the value of left_split_group_smaller should be // used by the caller to determine how to split *node's parent). The caller // is responsible for updating the ancestors of '*node' to reflect any splits // that occur. // // If node group splits are necessary to insert the new entry, but there are // not enough free node groups, then '*node' and its descendents will be // unmodified and 'new_node_group_id' in the return value will be set to // kNodeGroupFull. // // Note that this method may fail in some cases where tightly packing the // index by calling rebuild() would allow the index to accomodate the new // entry. template <typename ComparatorT> InsertReturnValue internalInsertHelper(const int node_group_allocation_requirement, const tuple_id tuple, const void *key, const ComparatorT &key_comparator, const NodeHeader *parent_node_header, void *node); // Insert the entry (*key, tuple) into '*node', which is a child of the node // at '*parent_node_header'. If '*node' is full and it is possible to split, // then '*node' will be split and the new entry will be inserted into the // appropriate node, and '*split_node_first_key' in the return value will // point to the first key in the right split node. If the node group which // '*node' belongs to is also full, and there are enough free nodes to // satisfy 'node_group_allocation_requirement', then the node group is split // to make room for the additional node, and 'new_node_group_id' in the // return value is set to the newly-created right split node group's ID. // Also, in cases where a node group split occured and node group splits are // asymmetric (i.e. max_keys_internal_ + 1 is odd), left_split_group_smaller // will be set to indicate whether the left or right half of the split // initially had one less node than the other (the value of // left_split_group_smaller should be used by the caller to determine how to // split *node's parent). The caller is responsible for updating the // ancestors of '*node' to reflect any splits that occur. // // If node group splits are necessary to insert the new entry, but there are // not enough free node groups, then '*node' will be unmodified and // 'new_node_group_id' in the return value will be set to kNodeGroupFull. // // Note that this method may fail in some cases where tightly packing the // index by calling rebuild() would allow the index to accomodate the new // entry. template <typename ComparatorT> InsertReturnValue leafInsertHelper(const int node_group_allocation_requirement, const tuple_id tuple, const void *key, const ComparatorT &key_comparator, const NodeHeader *parent_node_header, void *node); // Insert the entry (*key, tuple) into the appropriate position in the tree, // starting from the root node. Essentially just calls internalInsertHelper() // or leafInsertHelper() as appropriate on the root node. template <typename ComparatorT> inline InsertReturnValue rootInsertHelper(const tuple_id tuple, const void *key, const ComparatorT &key_comparator); // Split the child node group of '*parent_node_header' by invoking // splitNodeGroup(). '**node' is the node whose split necessitated splitting // the group. If node group splits are asymmetric, the split will be done // such that after '**node' is split the split groups will be balanced. The // 'new_node_group_id' and 'left_split_group_smaller' fields of // '*caller_return_value' will be filled in by this method. '*node' will be // adjusted to point to the location of the node after the group is split. // Returns the location of the end of the group which contains '**node' after // the split or, in the special case where '**node' should be split across // the two groups by calling splitNodeAcrossGroups(), returns NULL. const void* splitNodeGroupHelper(const NodeHeader *parent_node_header, void **node, InsertReturnValue *caller_return_value); // Split the child node group of '*parent_node_header' in half. The node // group must be full, and there must be an available free node group in // 'node_group_used_bitmap_'. In the case where group splits are asymmetric // (i.e. the number of nodes is odd), the left split group will have one less // node than the right split group if 'left_smaller' is true, otherwise the // right split group will have one less node than the left. If // 'will_split_node_across_groups' is true, then left_smaller must be false, // and the nodes of the right split group will be shifted right by one, // leaving the first node of the right split group uninitialized (the caller // should subsequently overwrite it by splitting the last node of the left // split group across the two groups). Returns the number of the right split // node group. Does not actually split the parent node (caller should do so). int splitNodeGroup(const NodeHeader *parent_node_header, const bool left_smaller, const bool will_split_node_across_groups); // Split '*node' in half. '*node' itself must be full, and the node group // '*node' belongs to must be non-full. '*group_end' is the current end of // nodes in the group. If 'right_child_node_group' is kNodeGroupNone, then // '*node' must be a leaf, otherwise '*node' must be an internal node and the // child node group of the right split node is set to // 'right_child_node_group'. Returns a pointer to the least key in the // subtree rooted at the right split node. In the case where node splits are // asymmetric (i.e. the number of keys is odd), the left split node will have // one less key than the right split node if 'left_smaller' is true, // otherwise the right split node will have one less key than the left. // // There is a special case when '*node' is an internal node and // 'child_was_split_across_groups' is true. In this case, both halves of the // split are completely constructed based on the values initially in '*node', // and the caller should NOT subsequently insert a key into one of the split // nodes. const void* splitNodeInGroup(void *node, const void *group_end, const int right_child_node_group, const bool left_smaller, const bool child_was_split_across_groups); // Splits '*node' such that the right half of the split is inserted as the // first node in the group designated by 'destination_group_number'. If // 'right_child_node_group' is kNodeGroupNone, then '*node' must be a leaf, // otherwise '*node' must be an internal node and the child node group of the // right split node is set to 'right_child_node_group'. Returns a pointer to // the least key in the subtree rooted at the right split node. In the case // where node splits are asymmetric (i.e. the number of keys is odd), the // left split node will have one less key than the right split node if // 'left_smaller' is true, otherwise the right split node will have one less // key than the left. // // This method should ONLY be called after splitNodeGroup(..., false, true) // is called. It assumes that '*node' is the last node in its group, and that // the destination node group has its existing nodes shifted right by one, so // that the right split node can be written directly into the zeroth position // in the destination group. This method will behave incorrectly if the // caller violates these assumptions. // // There is a special case when '*node' is an internal node and // 'child_was_split_across_groups' is true. In this case, both halves of the // split are completely constructed based on the values initially in '*node', // and the caller should NOT subsequently insert a key into one of the split // nodes. const void* splitNodeAcrossGroups(void *node, const int destination_group_number, const int right_child_node_group, const bool left_smaller, const bool child_was_split_across_groups); // Insert the entry (*key, tuple) into '*node'. '*node' must be non-full. template <typename ComparatorT> void insertEntryInLeaf(const tuple_id tuple, const void *key, const ComparatorT &key_comparator, void *node); // Remove the entry (compressed_code, tuple) from the index. 'CodeType' is // the compressed type of the code (either uint8_t, uint16_t, or uint32_t). template <typename CodeType> void compressedKeyRemoveEntryHelper(const tuple_id tuple, const std::uint32_t compressed_code); // Remove the entry (*key, tuple) from '*node'. If the entry does not exist // in '*node', but the last key in '*node' matches '*key', then this method // will be recursively called with the right-sibling of '*node'. template <typename ComparatorT> void removeEntryFromLeaf(const tuple_id tuple, const void *key, const ComparatorT &key_comparator, void *node); // Helper method for getMatchesForPredicate(). Generates a TupleIdSequence of // all tuples which match a predicate of the form 'key comp right_literal'. // This version is for uncompressed keys. TupleIdSequence* evaluateComparisonPredicateOnUncompressedKey( const ComparisonID comp, const TypedValue &right_literal, const Type &right_literal_type) const; // Helper method for getMatchesForPredicate(). Generates a TupleIdSequence of // all tuples which match a predicate of the form 'key comp right_literal'. // This version is for compressed keys. TupleIdSequence* evaluateComparisonPredicateOnCompressedKey( ComparisonID comp, const TypedValue &right_literal, const Type &right_literal_type) const; // Helper method which calls the appropriate predicate-evaluation method // below based on 'comp'. template <typename LiteralLessKeyComparatorT, typename KeyLessLiteralComparatorT> TupleIdSequence* evaluatePredicate( ComparisonID comp, const void *literal, const LiteralLessKeyComparatorT &literal_less_key_comparator, const KeyLessLiteralComparatorT &key_less_literal_comparator) const; // Helper method for evaluateComparisonPredicateOnUncompressedKey() and // evaluateComparisonPredicateOnCompressedKey(). Generates a TupleIdSequence // of all tuples which have a key equal to '*literal' according to // 'literal_less_key_comparator' and 'key_less_literal_comparator'. template <typename LiteralLessKeyComparatorT, typename KeyLessLiteralComparatorT> TupleIdSequence* evaluateEqualPredicate( const void *literal, const LiteralLessKeyComparatorT &literal_less_key_comparator, const KeyLessLiteralComparatorT &key_less_literal_comparator) const; // Helper method for evaluateComparisonPredicateOnUncompressedKey() and // evaluateComparisonPredicateOnCompressedKey(). Generates a TupleIdSequence // of all tuples which have a key not equal to '*literal' according to // 'literal_less_key_comparator' and 'key_less_literal_comparator'. template <typename LiteralLessKeyComparatorT, typename KeyLessLiteralComparatorT> TupleIdSequence* evaluateNotEqualPredicate( const void *literal, const LiteralLessKeyComparatorT &literal_less_key_comparator, const KeyLessLiteralComparatorT &key_less_literal_comparator) const; // Helper method for evaluateComparisonPredicateOnUncompressedKey() and // evaluateComparisonPredicateOnCompressedKey(). Generates a TupleIdSequence // of all tuples which have a key less than '*literal' according to // 'literal_less_key_comparator' and 'key_less_literal_comparator'. If // 'include_equal' is true, the sequence will also include tuples whose keys // are equal to '*literal'. template <typename LiteralLessKeyComparatorT, typename KeyLessLiteralComparatorT, bool include_equal> TupleIdSequence* evaluateLessPredicate( const void *literal, const LiteralLessKeyComparatorT &literal_less_key_comparator, const KeyLessLiteralComparatorT &key_less_literal_comparator) const; // Helper method for evaluateComparisonPredicateOnUncompressedKey() and // evaluateComparisonPredicateOnCompressedKey(). Generates a TupleIdSequence // of all tuples which have a key greater than '*literal' according to // 'literal_less_key_comparator' and 'key_less_literal_comparator'. If // 'include_equal' is true, the sequence will also include tuples whose keys // are equal to '*literal'. template <typename LiteralLessKeyComparatorT, typename KeyLessLiteralComparatorT, bool include_equal> TupleIdSequence* evaluateGreaterPredicate( const void *literal, const LiteralLessKeyComparatorT &literal_less_key_comparator, const KeyLessLiteralComparatorT &key_less_literal_comparator) const; // Check if there are enough node groups in this CSBTreeIndexSubBlock to // build a complete index of all tuple_store_'s tuples. bool rebuildSpaceCheck() const; // Rebuild the leaf nodes of the index from tuple_store_'s tuples. Requires // that the index be empty (i.e. that clearIndex() has been called) and that // there are enough node groups in this CSBTreeIndexSubBlock to hold all // entries (i.e. that rebuildSpaceCheck() returns true). All node groups used // to store leaf nodes will be added to '*used_node_groups', including the // initial root. Returns the number of nodes in the rightmost leaf node group // (all other leaf node groups will be full). std::uint16_t rebuildLeaves(std::vector<int> *used_node_groups); // Helper method for rebuildLeaves(). Actually constructs leaf nodes for all // of the entries in '*entry_references'. Templated on 'EntryReferenceT' so // that it may be used with both EntryReference and CompressedEntryReference. template <class EntryReferenceT> std::uint16_t buildLeavesFromEntryReferences( std::vector<EntryReferenceT> *entry_references, std::vector<int> *used_node_groups); // Helper method for rebuildLeaves(). Fill in '*entry_references' with an // entry for every tuple in 'tuple_store_' with a non-NULL key, and sort // '*entry_references' into key order. This version is for the case where the // key is non-composite. void generateEntryReferencesFromTypedValues( std::vector<csbtree_internal::EntryReference> *entry_references) const; // Helper method for rebuildLeaves(). Fill in '*entry_references' with an // entry for every tuple in 'tuple_store_' with a non-NULL key, and sort // '*entry_references' into key order. This version is for the case where the // key is non-composite and compressed. void generateEntryReferencesFromCompressedCodes( std::vector<csbtree_internal::CompressedEntryReference> *entry_references) const; // Helper method for rebuildLeaves(). Fill in '*entry_references' with an // entry for every tuple in 'tuple_store_' with a non-NULL key, and sort // '*entry_references' into key order. This version is for the case where the // key is composite. void generateEntryReferencesFromCompositeKeys( std::vector<csbtree_internal::CompositeEntryReference> *entry_references) const; // Rebuild an internal level of the index, above 'child_node_groups'. // 'last_child_num_nodes' is the number of nodes in the rightmost child // node groups (all other node child node groups should be full). All node // groups in the rebuilt internal level will be added to '*used_node_groups'. // Returns the number of nodes in the rightmost node group of the rebuilt // level (all other node groups will be full). When this method adds only // one node group to '*used_node_groups' and returns 1, rebuilding is // finished and the sole element in '*used_node_groups' should be used as the // new root. std::uint16_t rebuildInternalLevel(const std::vector<int> &child_node_groups, std::uint16_t last_child_num_nodes, std::vector<int> *used_node_groups); // Moves nodes from the group designated by 'full_node_group_number' to the // beginning of the group designated by 'underfull_node_group_number', which // contains 'underfull_num_nodes'. Existing nodes in the underfull node group // are shifted right. The full node group must be full, and // 'underfull_num_nodes' must be less than large_half_num_children_. After // rebalancing, the underfull node group will contain exactly // large_half_num_children_ nodes, and this method returns the number of // nodes remaining in the previously full node group. std::uint16_t rebalanceNodeGroups(const int full_node_group_number, const int underfull_node_group_number, const std::uint16_t underfull_num_nodes); // Create an internal node at '*node' whose child is the node group with // 'child_node_group_number' and has 'num_children' children. 'num_children' // must be at least 2. void makeInternalNode(const int child_node_group_number, const std::uint16_t num_children, void *node); // Allocates a new node group and marks it as used. int allocateNodeGroup(); // Deallocates a node group so that it can be reused. void deallocateNodeGroup(const int node_group_number); bool initialized_; bool key_may_be_compressed_; bool key_is_compressed_; bool key_is_composite_; bool key_is_nullable_; const Type *key_type_; // NULL for composite key. std::vector<attribute_id> indexed_attribute_ids_; std::vector<std::size_t> indexed_attribute_offsets_; std::size_t key_length_bytes_; std::size_t key_tuple_id_pair_length_bytes_; std::unique_ptr<csbtree_internal::CompositeKeyLessComparator> composite_key_comparator_; std::uint16_t max_keys_internal_; std::uint16_t small_half_num_children_; std::uint16_t large_half_num_children_; std::uint16_t max_keys_leaf_; std::uint16_t small_half_num_keys_leaf_; std::uint16_t large_half_num_keys_leaf_; void *node_groups_start_; std::size_t node_group_size_bytes_; std::unique_ptr<BitVector<false>> node_group_used_bitmap_; int next_free_node_group_; int num_free_node_groups_; friend class CSBTreeIndexSubBlockTest; friend class CSBTreePrettyPrinter; friend class csbtree_internal::CompositeKeyLessComparator; friend class csbtree_internal::PredicateEvaluationForwarder; DISALLOW_COPY_AND_ASSIGN(CSBTreeIndexSubBlock); }; /** @} */ } // namespace quickstep #endif // QUICKSTEP_STORAGE_CSBTREE_INDEX_SUB_BLOCK_HPP_
47.007163
93
0.715217
[ "vector" ]
0089ed5f8b18417809e614eb4198fb74bd7d2d9e
6,137
cpp
C++
Source/API/D3D12/UtilsD3D12.cpp
KawBuma/Buma3D
73b1c7a99c979492f072d4ead89f2d357d5e048a
[ "MIT" ]
5
2020-11-25T05:05:13.000Z
2022-02-09T09:35:21.000Z
Source/API/D3D12/UtilsD3D12.cpp
KawBuma/Buma3D
73b1c7a99c979492f072d4ead89f2d357d5e048a
[ "MIT" ]
5
2020-11-11T09:52:59.000Z
2021-12-15T13:27:37.000Z
Source/API/D3D12/UtilsD3D12.cpp
KawBuma/Buma3D
73b1c7a99c979492f072d4ead89f2d357d5e048a
[ "MIT" ]
null
null
null
#include "Buma3DPCH.h" #include "UtilsD3D12.h" namespace buma3d { namespace util { BMRESULT GetBMResultFromHR(HRESULT _hr) { if (SUCCEEDED(_hr)) return BMRESULT_SUCCEED; BMRESULT result{}; switch (_hr) { case E_INVALIDARG: // An invalid parameter was passed to the returning function. result = BMRESULT_FAILED_INVALID_PARAMETER; break; case E_OUTOFMEMORY: // Direct3D could not allocate sufficient memory to complete the call. result = BMRESULT_FAILED_OUT_OF_SYSTEM_MEMORY; break; case DXGI_ERROR_DEVICE_REMOVED: // The video card has been physically removed from the system, or a driver upgrade for the video card has occurred. The application should destroy and recreate the device. For help debugging the problem, call ID3D10Device::GetDeviceRemovedReason. result = BMRESULT_FAILED_DEVICE_REMOVED; break; case DXGI_ERROR_WAIT_TIMEOUT: // The time-out interval elapsed before the next desktop frame was available. result = BMRESULT_SUCCEED_TIMEOUT;// エラー版TIMEOUTを用意すべき? break; case DXGI_ERROR_UNSUPPORTED: // The requested functionality is not supported by the device or the driver. result = BMRESULT_FAILED_NOT_SUPPORTED; break; // NOTE: 定数が見つからない。エラーの値も定義なし。 //case D3D12_ERROR_FILE_NOT_FOUND : // The file was not found. //case D3D12_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS: // There are too many unique instances of a particular type of state object. //case D3D12_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS : // There are too many unique instances of a particular type of view object. case D3D12_ERROR_ADAPTER_NOT_FOUND : // The blob provided does not match the adapter that the device was created on. case D3D12_ERROR_DRIVER_VERSION_MISMATCH : // The blob provided was created for a different version of the driver, and must be re-created. case E_FAIL : // Attempted to create a device with the debug layer enabled and the layer is not installed. case E_NOTIMPL : // The method call isn't implemented with the passed parameter combination. case S_FALSE : // Alternate success value, indicating a successful but nonstandard completion (the precise meaning depends on context). case DXGI_ERROR_ACCESS_DENIED : // You tried to use a resource to which you did not have the required access privileges. This error is most typically caused when you write to a shared resource with read-only access. case DXGI_ERROR_ACCESS_LOST : // The desktop duplication interface is invalid. The desktop duplication interface typically becomes invalid when a different type of image is displayed on the desktop. case DXGI_ERROR_ALREADY_EXISTS : // The desired element already exists. This is returned by DXGIDeclareAdapterRemovalSupport if it is not the first time that the function is called. case DXGI_ERROR_CANNOT_PROTECT_CONTENT : // DXGI can't provide content protection on the swap chain. This error is typically caused by an older driver, or when you use a swap chain that is incompatible with content protection. case DXGI_ERROR_DEVICE_HUNG : // The application's device failed due to badly formed commands sent by the application. This is an design-time issue that should be investigated and fixed. case DXGI_ERROR_DEVICE_RESET : // The device failed due to a badly formed command. This is a run-time issue; The application should destroy and recreate the device. case DXGI_ERROR_DRIVER_INTERNAL_ERROR : // The driver encountered a problem and was put into the device removed state. case DXGI_ERROR_FRAME_STATISTICS_DISJOINT : // An event (for example, a power cycle) interrupted the gathering of presentation statistics. case DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE : // The application attempted to acquire exclusive ownership of an output, but failed because some other application (or device within the application) already acquired ownership. case DXGI_ERROR_INVALID_CALL : // The application provided invalid parameter data; this must be debugged and fixed before the application is released. case DXGI_ERROR_MORE_DATA : // The buffer supplied by the application is not big enough to hold the requested data. case DXGI_ERROR_NAME_ALREADY_EXISTS : // The supplied name of a resource in a call to IDXGIResource1::CreateSharedHandle is already associated with some other resource. case DXGI_ERROR_NONEXCLUSIVE : // A global counter resource is in use, and the Direct3D device can't currently use the counter resource. case DXGI_ERROR_NOT_CURRENTLY_AVAILABLE : // The resource or request is not currently available, but it might become available later. case DXGI_ERROR_NOT_FOUND : // When calling IDXGIObject::GetPrivateData, the GUID passed in is not recognized as one previously passed to IDXGIObject::SetPrivateData or IDXGIObject::SetPrivateDataInterface. When calling IDXGIFactory::EnumAdapters or IDXGIAdapter::EnumOutputs, the enumerated ordinal is out of range. case DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED : // Reserved case DXGI_ERROR_REMOTE_OUTOFMEMORY : // Reserved case DXGI_ERROR_RESTRICT_TO_OUTPUT_STALE : // The DXGI output (monitor) to which the swap chain content was restricted is now disconnected or changed. case DXGI_ERROR_SDK_COMPONENT_MISSING : // The operation depends on an SDK component that is missing or mismatched. case DXGI_ERROR_SESSION_DISCONNECTED : // The Remote Desktop Services session is currently disconnected. case DXGI_ERROR_WAS_STILL_DRAWING : // The GPU was busy at the moment when a call was made to perform an operation, and did not execute or schedule the operation. default: result = BMRESULT_FAILED; break; } return result; } }// namespace util }// namespace buma3d
77.683544
340
0.732117
[ "object" ]
0093370f7395992293c1b203fb819b2963fb8881
477
cpp
C++
Game/Src/Graphics/SpriteRendering/SpriteRendere.cpp
Cgunnar/SpeederGame
262660ab4b9c5ec4293e5b7be1148c0cc80166cb
[ "MIT" ]
null
null
null
Game/Src/Graphics/SpriteRendering/SpriteRendere.cpp
Cgunnar/SpeederGame
262660ab4b9c5ec4293e5b7be1148c0cc80166cb
[ "MIT" ]
null
null
null
Game/Src/Graphics/SpriteRendering/SpriteRendere.cpp
Cgunnar/SpeederGame
262660ab4b9c5ec4293e5b7be1148c0cc80166cb
[ "MIT" ]
null
null
null
#include "pch.hpp" #include "SpriteRendere.h" #include "LowLvlGfx.h" using namespace DirectX; void SpriteRendere::Init() { m_spriteBatch = std::make_unique<SpriteBatch>(LowLvlGfx::Context().Get()); } void SpriteRendere::Draw(std::vector<Sprite> sprites) { Resolution res = LowLvlGfx::GetResolution(); m_spriteBatch->Begin(); for (auto& s : sprites) { s.Draw(*m_spriteBatch, res); } m_spriteBatch->End(); LowLvlGfx::Context()->OMSetDepthStencilState(nullptr, 0); }
20.73913
75
0.721174
[ "vector" ]
00a20fb77736df592846fa56457a53b5509a4a2b
609
cpp
C++
Codeforces/Solutions/1365B.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
null
null
null
Codeforces/Solutions/1365B.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
null
null
null
Codeforces/Solutions/1365B.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
null
null
null
// Problem Code: 1365B #include <iostream> #include <vector> #include <set> using namespace std; string trouble_sort(int n, vector<int>& a, vector<int>& b) { bool sorted = true; set<int> types = {b[0]}; for (int i = 1; i < n; i++) { types.insert(b[i]); sorted &= a[i - 1] <= a[i]; } if (!sorted && types.size() == 1) return "No"; return "Yes"; } int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n), b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; cout << trouble_sort(n, a, b) << endl; } return 0; }
16.459459
60
0.515599
[ "vector" ]
00a2b3b7b3f8ce37acc940e267dad207363f3735
31,072
cpp
C++
applications/mne_analyze/libs/anShared/Model/fiffrawviewmodel.cpp
gabrielbmotta/mne-cpp
f3e68a4d2e33369dfe637591c055e34000c73a46
[ "BSD-3-Clause" ]
null
null
null
applications/mne_analyze/libs/anShared/Model/fiffrawviewmodel.cpp
gabrielbmotta/mne-cpp
f3e68a4d2e33369dfe637591c055e34000c73a46
[ "BSD-3-Clause" ]
null
null
null
applications/mne_analyze/libs/anShared/Model/fiffrawviewmodel.cpp
gabrielbmotta/mne-cpp
f3e68a4d2e33369dfe637591c055e34000c73a46
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file fiffrawviewmodel.cpp * @author Lorenz Esch <lesch@mgh.harvard.edu>; * Lars Debor <Lars.Debor@tu-ilmenau.de>; * Simon Heinke <Simon.Heinke@tu-ilmenau.de>; * Gabriel Motta <gbmotta@mgh.harvard.edu> * @version dev * @date October, 2018 * * @section LICENSE * * Copyright (C) 2018, Lorenz Esch, Lars Debor, Simon Heinke, Gabriel Motta. 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 MNE-CPP authors 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. * * * @brief FiffRawViewModel class definition. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "fiffrawviewmodel.h" #include "../Utils/metatypes.h" #include <fiff/fiff.h> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QtConcurrent/QtConcurrent> #include <QElapsedTimer> #include <QFile> #include <QBrush> #include <QFileDialog> //============================================================================================================= // Eigen INCLUDES //============================================================================================================= //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace ANSHAREDLIB; using namespace FIFFLIB; //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= FiffRawViewModel::FiffRawViewModel(QObject *pParent) : AbstractModel(pParent) { qInfo() << "[FiffRawViewModel::FiffRawViewModel] Default constructor called !"; } //============================================================================================================= FiffRawViewModel::FiffRawViewModel(const QString &sFilePath, qint32 iVisibleWindowSize, qint32 iPreloadBufferSize, QObject *pParent) : AbstractModel(pParent) , m_dDx(1.0) , m_iSamplesPerBlock(1024) , m_iVisibleWindowSize(iVisibleWindowSize) , m_iPreloadBufferSize(std::max(2, iPreloadBufferSize)) , m_iTotalBlockCount(m_iVisibleWindowSize + 2 * m_iPreloadBufferSize) , m_iFiffCursorBegin(-1) , m_bStartOfFileReached(true) , m_bEndOfFileReached(false) , m_blockLoadFutureWatcher() , m_bCurrentlyLoading(false) , m_iDistanceTimerSpacer(1000) , m_iScrollPos(0) , m_bDispAnn(true) , m_pAnnotationModel(QSharedPointer<AnnotationModel>::create(this)) { // connect data reloading: this will be run concurrently connect(&m_blockLoadFutureWatcher, &QFutureWatcher<int>::finished, [this]() { postBlockLoad(m_blockLoadFutureWatcher.future().result()); }); m_file.setFileName(sFilePath); initFiffData(m_file); updateEndStartFlags(); //m_pAnnotationModel = QSharedPointer<AnnotationModel>(new AnnotationModel(this)); } //============================================================================================================= FiffRawViewModel::FiffRawViewModel(const QString &sFilePath, const QByteArray& byteLoadedData, qint32 iVisibleWindowSize, qint32 iPreloadBufferSize, QObject *pParent) : AbstractModel(pParent) , m_dDx(1.0) , m_iSamplesPerBlock(1024) , m_iVisibleWindowSize(iVisibleWindowSize) , m_iPreloadBufferSize(std::max(2, iPreloadBufferSize)) , m_iTotalBlockCount(m_iVisibleWindowSize + 2 * m_iPreloadBufferSize) , m_iFiffCursorBegin(-1) , m_bStartOfFileReached(true) , m_bEndOfFileReached(false) , m_blockLoadFutureWatcher() , m_bCurrentlyLoading(false) , m_iDistanceTimerSpacer(1000) , m_iScrollPos(0) , m_bDispAnn(true) , m_pAnnotationModel(QSharedPointer<AnnotationModel>::create(this)) { Q_UNUSED(sFilePath) // connect data reloading: this will be run concurrently connect(&m_blockLoadFutureWatcher, &QFutureWatcher<int>::finished, [this]() { postBlockLoad(m_blockLoadFutureWatcher.future().result()); }); m_byteLoadedData = byteLoadedData; m_buffer.setData(m_byteLoadedData); initFiffData(m_buffer); updateEndStartFlags(); //m_pAnnotationModel = QSharedPointer<AnnotationModel>(new AnnotationModel(this)); } //============================================================================================================= FiffRawViewModel::~FiffRawViewModel() { } //============================================================================================================= void FiffRawViewModel::initFiffData(QIODevice& p_IODevice) { // build FiffIO m_pFiffIO = QSharedPointer<FiffIO>::create(p_IODevice); if(m_pFiffIO->m_qlistRaw.empty()) { qWarning() << "[FiffRawViewModel::loadFiffData] File does not contain any Fiff data"; return; } // load channel infos for(qint32 i=0; i < m_pFiffIO->m_qlistRaw[0]->info.nchan; ++i) m_ChannelInfoList.append(m_pFiffIO->m_qlistRaw[0]->info.chs[i]); // load FiffInfo m_pFiffInfo = FiffInfo::SPtr(new FiffInfo(m_pFiffIO->m_qlistRaw[0]->info)); // build datastructure that is to be filled with data from the file MatrixXd data, times; // Fiff file is not empty, set cursor somewhere into Fiff file m_iFiffCursorBegin = m_pFiffIO->m_qlistRaw[0]->first_samp; int start = m_iFiffCursorBegin; m_iSamplesPerBlock = m_pFiffInfo->sfreq; // for some reason the read_raw_segment function works with inclusive upper bound int end = start + (m_iSamplesPerBlock * m_iTotalBlockCount) - 1; // read in all blocks, use the already prepared list m_lData if(m_pFiffIO->m_qlistRaw[0]->read_raw_segment(data, times, start, end)) { // qDebug() << "[FiffRawmodel::loadFiffData] Successfully read a block "; } else { qWarning() << "[FiffRawViewModel::loadFiffData] Could not read samples " << start << " to " << end; return; } // append a matrix pair for each block for(int i = 0; i < m_iTotalBlockCount; ++i) { m_lData.push_back(QSharedPointer<QPair<MatrixXd, MatrixXd> >::create(qMakePair(data.block(0, i*m_iSamplesPerBlock, data.rows(), m_iSamplesPerBlock), times.block(0, i*m_iSamplesPerBlock, times.rows(), m_iSamplesPerBlock)))); } qInfo() << "[FiffRawViewModel::initFiffData] Loaded " << m_lData.size() << " blocks"; // need to close the file manually p_IODevice.close(); } //============================================================================================================= QVariant FiffRawViewModel::data(const QModelIndex &index, int role) const { // early filtering of unimplemented display roles if (role == Qt::BackgroundRole) { return QVariant(QBrush(m_colBackground)); } if (role != Qt::DisplayRole) { qWarning() << "[FiffRawViewModel::data] Role " << role << " not implemented yet !"; return QVariant(); } if (index.isValid()) { // channel names if(index.column() == 0) { return QVariant(m_ChannelInfoList[index.row()].ch_name); } // whole data else if (index.column() == 1) { QVariant result; switch (role) { case Qt::DisplayRole: { // in order to avoid extensive copying of data, we simply give out smartpointers to the matrices (wrapped inside the ChannelData container) // wait until its save to access data (that is if no data insertion is going on right now) m_dataMutex.lock(); // wrap in ChannelData container and then wrap into QVariant result.setValue(ChannelData(m_lData, index.row())); m_dataMutex.unlock(); return result; } } } // whether channel is marked as bad else if(index.column() == 2) { return QVariant(m_pFiffInfo->bads.contains(m_pFiffInfo->ch_names[index.row()])); } else { qWarning() << "[FiffRawViewModel::data] Column " << index.column() << " not implemented !"; return QVariant(); } } qWarning() << "[FiffRawViewModel::data] Warning, non of the presumed cases took effect"; return QVariant(); } //============================================================================================================= bool FiffRawViewModel::saveToFile(const QString& sPath) { #ifdef WASMBUILD QFileInfo fileInfo (sPath); QBuffer* bufferOut = new QBuffer; if(m_pFiffIO->m_qlistRaw.size() > 0) { m_pFiffIO->write_raw(*bufferOut, 0); // Wee need to call the QFileDialog here instead of the data load extension since we need access to the QByteArray QFileDialog::saveFileContent(bufferOut->data(), fileInfo.fileName()); return true; } //bufferOut->deleteLater(); return false; #else QFile fFileOut(sPath); if(m_pFiffIO->m_qlistRaw.size() > 0) { return m_pFiffIO->write_raw(fFileOut, 0); } return false; #endif } //============================================================================================================= QVariant FiffRawViewModel::headerData(int section, Qt::Orientation orientation, int role) const { if(role != Qt::DisplayRole && role != Qt::TextAlignmentRole) return QVariant(); if(orientation == Qt::Vertical) { QModelIndex chname = createIndex(section,0); switch(role) { case Qt::DisplayRole: return QVariant(data(chname).toString()); } } return QVariant(); } //============================================================================================================= Qt::ItemFlags FiffRawViewModel::flags(const QModelIndex &index) const { // TODO implement stuff return QAbstractItemModel::flags(index); } //============================================================================================================= QModelIndex FiffRawViewModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); return createIndex(row, column); } //============================================================================================================= QModelIndex FiffRawViewModel::parent(const QModelIndex &index) const { Q_UNUSED(index); // TODO implement stuff return QModelIndex(); } //============================================================================================================= int FiffRawViewModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); if(m_ChannelInfoList.empty() == false) return m_ChannelInfoList.size(); return 0; } //============================================================================================================= int FiffRawViewModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); // TODO implement stuff return 3; } //============================================================================================================= bool FiffRawViewModel::hasChildren(const QModelIndex &parent) const { Q_UNUSED(parent); // TODO implement stuff return false; } //============================================================================================================= void FiffRawViewModel::updateScrollPosition(qint32 newScrollPosition) { qDebug() << "m_iSamplesPerBlock" << m_iSamplesPerBlock; qDebug() << "m_iTotalBlockCount" << m_iTotalBlockCount; QElapsedTimer timer; timer.start(); // check if we are currently loading something in the background. This is a rudimentary solution. if (m_bCurrentlyLoading) { qInfo() << "[FiffRawViewModel::updateScrollPosition] Background operation still pending, try again later..."; return; } m_iScrollPos = newScrollPosition; qint32 targetCursor = (newScrollPosition / m_dDx) + absoluteFirstSample() ; if (targetCursor < m_iFiffCursorBegin + (m_iPreloadBufferSize - 1) * m_iSamplesPerBlock && m_bStartOfFileReached == false) { // time to move the loaded window. Calculate distance in blocks qint32 sampleDist = (m_iFiffCursorBegin + (m_iPreloadBufferSize - 1) * m_iSamplesPerBlock) - targetCursor; qint32 blockDist = (qint32) ceil(((double) sampleDist) / ((double) m_iSamplesPerBlock)); if (blockDist >= m_iTotalBlockCount) { // we must "jump" to the new cursor ... m_iFiffCursorBegin = std::max(absoluteFirstSample(), m_iFiffCursorBegin - blockDist * m_iSamplesPerBlock); // ... and load the whole model anew //startBackgroundOperation(&FiffRawViewModel::loadLaterBlocks, m_iTotalBlockCount); postBlockLoad(loadEarlierBlocks(m_iTotalBlockCount)); updateScrollPosition(newScrollPosition); } else { // there are some blocks in the intersection of the old and the new window that can stay in the buffer: // simply load earlier blocks //startBackgroundOperation(&FiffRawViewModel::loadEarlierBlocks, blockDist); postBlockLoad(loadEarlierBlocks(blockDist)); } } else if (targetCursor + (m_iVisibleWindowSize * m_iSamplesPerBlock) >= m_iFiffCursorBegin + ((m_iPreloadBufferSize + 1) + m_iVisibleWindowSize) * m_iSamplesPerBlock && m_bEndOfFileReached == false) { // time to move the loaded window. Calculate distance in blocks qint32 sampleDist = targetCursor + (m_iVisibleWindowSize * m_iSamplesPerBlock) - (m_iFiffCursorBegin + ((m_iPreloadBufferSize + 1) + m_iVisibleWindowSize) * m_iSamplesPerBlock); qint32 blockDist = (qint32) ceil(((double) sampleDist) / ((double) m_iSamplesPerBlock)); if (blockDist >= m_iTotalBlockCount) { // we must "jump" to the new cursor ... m_iFiffCursorBegin = std::min(absoluteLastSample() - m_iTotalBlockCount * m_iSamplesPerBlock, m_iFiffCursorBegin + blockDist * m_iSamplesPerBlock); // ... and load the whole model anew //startBackgroundOperation(&FiffRawViewModel::loadLaterBlocks, m_iTotalBlockCount); postBlockLoad(loadLaterBlocks(m_iTotalBlockCount)); updateScrollPosition(newScrollPosition); } else { // there are some blocks in the intersection of the old and the new window that can stay in the buffer: // simply load later blocks //startBackgroundOperation(&FiffRawViewModel::loadLaterBlocks, blockDist); postBlockLoad(loadLaterBlocks(blockDist)); } } qDebug() << "[FiffRawViewModel::updateScrollPosition] timer.elapsed()" << timer.elapsed(); } //============================================================================================================= void FiffRawViewModel::startBackgroundOperation(int (FiffRawViewModel::*loadFunction)(int), int iBlocksToLoad) { m_bCurrentlyLoading = true; QFuture<int> future = QtConcurrent::run(this, loadFunction, iBlocksToLoad); m_blockLoadFutureWatcher.setFuture(future); } //============================================================================================================= int FiffRawViewModel::loadEarlierBlocks(qint32 numBlocks) { // check if start of file was reached: int leftSamples = (m_iFiffCursorBegin - numBlocks * m_iSamplesPerBlock) - absoluteFirstSample(); if (leftSamples <= 0) { //qInfo() << "[FiffRawViewModel::loadEarlierBlocks] Reached start of file !"; // see how many blocks we still can load int maxNumBlocks = (m_iFiffCursorBegin - absoluteFirstSample()) / m_iSamplesPerBlock; //qInfo() << "[FiffRawViewModel::loadEarlierBlocks] Loading " << maxNumBlocks << " earlier blocks instead of requested " << numBlocks; if (maxNumBlocks != 0) { numBlocks = maxNumBlocks; } else { // nothing to be done, cant load any more blocks // return 0, meaning that this was a loading of earlier blocks return 0; } } // we expect m_lNewData to be empty: if (m_lNewData.empty() == false) { qInfo() << "[FiffRawViewModel::loadEarlierBlocks] FATAL, temporary data storage non empty !"; return -1; } // build data structures to be filled from file MatrixXd data, times; // initialize start and end indices int start = m_iFiffCursorBegin - (numBlocks * m_iSamplesPerBlock); int end = m_iFiffCursorBegin - 1; // read data, use the already prepared list m_lNewData QElapsedTimer timer; timer.start(); if(m_pFiffIO->m_qlistRaw[0]->read_raw_segment(data, times, start, end)) { // qDebug() << "[FiffRawViewModel::loadFiffData] Successfully read a block "; } else { qWarning() << "[FiffRawViewModel::loadEarlierBlocks] Could not read block "; return -1; } qDebug() << "[FiffRawViewModel::loadEarlierBlocks] read_raw_segment timer.elapsed()" << timer.elapsed(); for(int i = 0; i < numBlocks; ++i) { m_lNewData.push_front(QSharedPointer<QPair<MatrixXd, MatrixXd> >::create(qMakePair(data.block(0, i*m_iSamplesPerBlock, data.rows(), m_iSamplesPerBlock), times.block(0, i*m_iSamplesPerBlock, times.rows(), m_iSamplesPerBlock)))); } // adjust fiff cursor m_iFiffCursorBegin = start; //qDebug() << "[FiffRawViewModel::loadEarlierBlocks] |TIME| " << ((float) timer.elapsed()) / ((float) numBlocks) << " (per block) [FiffRawViewModel::loadEarlierBlocks]"; // return 0, meaning that this was a loading of earlier blocks return 0; } //============================================================================================================= int FiffRawViewModel::loadLaterBlocks(qint32 numBlocks) { // check if end of file is reached: int leftSamples = absoluteLastSample() - (m_iFiffCursorBegin + (m_iTotalBlockCount + numBlocks) * m_iSamplesPerBlock); if (leftSamples < 0) { qInfo() << "[FiffRawViewModel::loadLaterBlocks] Reached end of file !"; // see how many blocks we still can load int maxNumBlocks = (absoluteLastSample() - (m_iFiffCursorBegin + m_iTotalBlockCount * m_iSamplesPerBlock)) / m_iSamplesPerBlock; //qInfo() << "[FiffRawViewModel::loadLaterBlocks] Loading " << maxNumBlocks << " later blocks instead of requested " << numBlocks; if (maxNumBlocks != 0) { numBlocks = maxNumBlocks; } else { // nothing to be done, cant load any more blocks // return 1, meaning that this was a loading of later blocks return 1; } } // we expect m_lNewData to be empty: if (m_lNewData.empty() == false) { qCritical() << "[FiffRawViewModel::loadLaterBlocks] FATAL, temporary data storage non empty !"; return -1; } // build data structures to be filled from file MatrixXd data, times; // initialize start and end indices int start = m_iFiffCursorBegin + m_iTotalBlockCount * m_iSamplesPerBlock; int end = start + (m_iSamplesPerBlock * numBlocks) - 1; // read data, use the already prepaired list m_lNewData QElapsedTimer timer; timer.start(); if(m_pFiffIO->m_qlistRaw[0]->read_raw_segment(data, times, start, end)) { // qDebug() << "[FiffRawViewModel::loadFiffData] Successfully read a block "; } else { qWarning() << "[FiffRawViewModel::loadLaterBlocks] Could not read block "; return -1; } qDebug() << "[FiffRawViewModel::loadLaterBlocks] read_raw_segment timer.elapsed()" << timer.elapsed(); for(int i = 0; i < numBlocks; ++i) { m_lNewData.push_back(QSharedPointer<QPair<MatrixXd, MatrixXd> >::create(qMakePair(data.block(0, i*m_iSamplesPerBlock, data.rows(), m_iSamplesPerBlock), times.block(0, i*m_iSamplesPerBlock, times.rows(), m_iSamplesPerBlock)))); } // adjust fiff cursor m_iFiffCursorBegin += numBlocks * m_iSamplesPerBlock; //qInfo() << "[FiffRawViewModel::loadLaterBlocks] |TIME| " << ((float) timer.elapsed()) / ((float) numBlocks) << " (per block) [FiffRawViewModel::loadLaterBlocks]"; // return 1, meaning that this was a loading of later blocks return 1; } //============================================================================================================= void FiffRawViewModel::postBlockLoad(int result) { QElapsedTimer timer; timer.start(); switch(result){ case -1: qWarning() << "[FiffRawViewModel::postBlockLoad] QFuture returned an error: " << result; break; case 0: { // insertion of earlier blocks int iNewBlocks = m_lNewData.size(); m_dataMutex.lock(); for (int i = 0; i < iNewBlocks; ++i) { m_lData.push_front(m_lNewData.front()); m_lNewData.pop_front(); // @TODO check if this really frees the associated memory m_lData.pop_back(); } m_dataMutex.unlock(); //qInfo() << "[FiffRawViewModel::postBlockLoad] |TIME| " << timer.elapsed() << " [FiffRawViewModel::postBlockLoad]"; emit newBlocksLoaded(); break; } case 1: { // insertion of later blocks int iNewBlocks = m_lNewData.size(); m_dataMutex.lock(); for (int i = 0; i < iNewBlocks; ++i) { m_lData.push_back(m_lNewData.front()); m_lNewData.pop_front(); m_lData.pop_front(); } m_dataMutex.unlock(); emit newBlocksLoaded(); break; } default: qCritical() << "[FiffRawViewModel::postBlockLoad] FATAL Non-intended return value: " << result; } updateEndStartFlags(); m_bCurrentlyLoading = false; emit dataChanged(createIndex(0,0), createIndex(rowCount(), columnCount())); } //============================================================================================================= void FiffRawViewModel::updateEndStartFlags() { m_bStartOfFileReached = m_iFiffCursorBegin == absoluteFirstSample(); m_bEndOfFileReached = (m_iFiffCursorBegin + m_iTotalBlockCount * m_iSamplesPerBlock) == absoluteLastSample(); } //============================================================================================================= FIFFLIB::FiffInfo* FiffRawViewModel::getFiffInfo() const { return m_pFiffInfo.data(); } //============================================================================================================= void FiffRawViewModel::setScaling(const QMap< qint32,float >& p_qMapChScaling) { beginResetModel(); m_qMapChScaling = p_qMapChScaling; endResetModel(); } //============================================================================================================= qint32 FiffRawViewModel::getKind(const qint32 &index) const { return m_ChannelInfoList.at(index).kind; } //============================================================================================================= qint32 FiffRawViewModel::getUnit(const qint32 &index) const { return m_ChannelInfoList.at(index).unit; } //============================================================================================================= void FiffRawViewModel::setBackgroundColor(const QColor& color) { m_colBackground = color; } //============================================================================================================= void FiffRawViewModel::setWindowSize(const int& iNumSeconds, const int& iColWidth, const int& iScrollPos) { beginResetModel(); m_iVisibleWindowSize = iNumSeconds; m_iPreloadBufferSize = m_iVisibleWindowSize; m_iTotalBlockCount = m_iVisibleWindowSize + 2 * m_iPreloadBufferSize; //reload data to accomodate new size updateDisplayData(); //Update m_dDx basedon new size setDataColumnWidth(iColWidth); endResetModel(); } //============================================================================================================= void FiffRawViewModel::distanceTimeSpacerChanged(const int& iNewValue) { if(iNewValue <= 0) { m_iDistanceTimerSpacer = 1000; } else { m_iDistanceTimerSpacer = iNewValue; } } //============================================================================================================= float FiffRawViewModel::getNumberOfTimeSpacers() const { return (float)(1000 / m_iDistanceTimerSpacer); } //============================================================================================================= void FiffRawViewModel::updateDisplayData() { m_lData.clear(); MatrixXd data, times; m_iFiffCursorBegin = m_pFiffIO->m_qlistRaw[0]->first_samp; int start = m_iFiffCursorBegin; m_iSamplesPerBlock = m_pFiffInfo->sfreq; // for some reason the read_raw_segment function works with inclusive upper bound int end = start + (m_iSamplesPerBlock * m_iTotalBlockCount) - 1; // read in all blocks, use the already prepared list m_lData if(m_pFiffIO->m_qlistRaw[0]->read_raw_segment(data, times, start, end)) { // qDebug() << "[FiffRawmodel::loadFiffData] Successfully read a block "; } else { qWarning() << "[FiffRawViewModel::loadFiffData] Could not read samples " << start << " to " << end; return; } // append a matrix pair for each block for(int i = 0; i < m_iTotalBlockCount; ++i) { m_lData.push_back(QSharedPointer<QPair<MatrixXd, MatrixXd> >::create(qMakePair(data.block(0, i*m_iSamplesPerBlock, data.rows(), m_iSamplesPerBlock), times.block(0, i*m_iSamplesPerBlock, times.rows(), m_iSamplesPerBlock)))); } } //============================================================================================================= int FiffRawViewModel::getTimeMarks(int iIndex) const { // qDebug() << "getTimeMarks" << m_pAnnotationModel->getAnnotation(iIndex); return m_pAnnotationModel->getAnnotation(iIndex); } //============================================================================================================= int FiffRawViewModel::getTimeListSize() const { // qDebug() << "getTimeListSize" << m_pAnnotationModel->getNumberOfAnnotations(); return m_pAnnotationModel->getNumberOfAnnotations(); } //============================================================================================================= int FiffRawViewModel::getSampleScrollPos() const { return m_iScrollPos; } //============================================================================================================= int FiffRawViewModel::getWindowSizeBlocks() const { return m_iVisibleWindowSize + m_iPreloadBufferSize; } //============================================================================================================= void FiffRawViewModel::toggleDispAnn(const int& iToggleDisp) { m_bDispAnn = (iToggleDisp ? true : false); } //============================================================================================================= bool FiffRawViewModel::shouldDisplayAnn() const { return (m_bDispAnn && getTimeListSize()); } //============================================================================================================= void FiffRawViewModel::setAnnotationModel(QSharedPointer<AnnotationModel> pModel) { m_pAnnotationModel = pModel; } //============================================================================================================= QSharedPointer<AnnotationModel> FiffRawViewModel::getAnnotationModel() const { return m_pAnnotationModel; } //============================================================================================================= void FiffRawViewModel::addTimeMark(int iLastClicked) { m_pAnnotationModel->setSamplePos(iLastClicked); m_pAnnotationModel->insertRow(0, QModelIndex()); }
38.598758
185
0.538877
[ "model" ]
00a5f8499ac83471a1880d9855564fe74bb00788
1,431
cpp
C++
Algorithms/0970.PowerfulIntegers/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0970.PowerfulIntegers/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0970.PowerfulIntegers/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
#include <unordered_set> #include <vector> #include "gtest/gtest.h" namespace { class Solution { public: std::vector<int> powerfulIntegers(int x, int y, int bound) const { std::vector<int> xPows(generatePowers(x, bound)); std::vector<int> yPows(generatePowers(y, bound)); std::unordered_set<int> knownResults; std::vector<int> result; for (int xPow : xPows) { for (int yPow : yPows) { int sum = xPow + yPow; if (sum > bound) break; if (knownResults.count(sum) == 0) { result.push_back(sum); knownResults.insert(sum); } } } return result; } private: std::vector<int> generatePowers(int number, int bound) const { if (number == 1) return {1}; std::vector<int> powers; int power = 1; while (power <= bound) { powers.push_back(power); power *= number; } return powers; } }; } namespace PowerfulIntegersTask { TEST(PowerfulIntegersTaskTests, Examples) { const Solution solution; ASSERT_EQ(std::vector<int>({2, 4, 10, 3, 5, 7, 9}), solution.powerfulIntegers(2, 3, 10)); ASSERT_EQ(std::vector<int>({2, 6, 4, 8, 10, 14}), solution.powerfulIntegers(3, 5, 15)); } }
22.714286
93
0.51782
[ "vector" ]
00abdded315d88a3dea744e046da109962111a91
3,416
cpp
C++
src/objectimpl.cpp
MacroGu/log4cxx_gcc_4_8
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
[ "Apache-2.0" ]
1
2016-10-06T20:09:32.000Z
2016-10-06T20:09:32.000Z
src/objectimpl.cpp
MacroGu/log4cxx_gcc_4_8
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
[ "Apache-2.0" ]
null
null
null
src/objectimpl.cpp
MacroGu/log4cxx_gcc_4_8
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2003,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/config.h> #ifdef HAVE_MS_THREAD #include <windows.h> #endif #include <log4cxx/helpers/objectimpl.h> #include <log4cxx/helpers/criticalsection.h> #include <log4cxx/helpers/event.h> #include <log4cxx/helpers/thread.h> using namespace log4cxx::helpers; class EventList { protected: EventList(Event * event) : event(event), next(0) { } public: static void removeAll(EventList * list) { EventList * item = list; while (item != 0) { item = removeHead(item); } } static EventList * removeHead(EventList * list) { EventList * next = list->next; delete list; return next; } static EventList * append(EventList * list, Event * event) { if (list == 0) { return new EventList(event); } else { EventList * current = list; EventList * next = list->next; while (next != 0) { current = next; next = next->next; } current->next = new EventList(event); return list; } } Event * event; EventList * next; }; ObjectImpl::ObjectImpl() : ref(0), eventList(0) { } ObjectImpl::~ObjectImpl() { } void ObjectImpl::addRef() const { Thread::InterlockedIncrement(&ref); } void ObjectImpl::releaseRef() const { if (Thread::InterlockedDecrement(&ref) == 0) { delete this; } } void ObjectImpl::lock() const { cs.lock(); } void ObjectImpl::unlock() const { cs.unlock(); } void ObjectImpl::wait() const { if (cs.getOwningThread() != Thread::getCurrentThreadId()) { if (cs.getOwningThread() == 0) { throw IllegalMonitorStateException(_T("Object not locked")); } else { throw IllegalMonitorStateException(_T("Object not locked by this thread")); } } Event event(false, false); eventList = EventList::append((EventList *)eventList, &event); cs.unlock(); try { event.wait(); } catch(Exception&) { cs.lock(); eventList = EventList::removeHead((EventList *)eventList); return; } cs.lock(); } void ObjectImpl::notify() const { if (cs.getOwningThread() != Thread::getCurrentThreadId()) { if (cs.getOwningThread() == 0) { throw IllegalMonitorStateException(_T("Object not locked")); } else { throw IllegalMonitorStateException(_T("Object not locked by this thread")); } } if (eventList != 0) { ((EventList *)eventList)->event->set(); eventList = EventList::removeHead((EventList *)eventList); } } void ObjectImpl::notifyAll() const { if (cs.getOwningThread() != Thread::getCurrentThreadId()) { if (cs.getOwningThread() == 0) { throw IllegalMonitorStateException(_T("Object not locked")); } else { throw IllegalMonitorStateException(_T("Object not locked by this thread")); } } while (eventList != 0) { ((EventList *)eventList)->event->set(); eventList = EventList::removeHead((EventList *)eventList); } }
18.565217
78
0.671546
[ "object" ]
00ad97d5de4831b53509298312310635783273f1
4,393
hpp
C++
src/graphlab/gpu/gpu_scope.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
1
2018-08-01T06:32:58.000Z
2018-08-01T06:32:58.000Z
src/graphlab/gpu/gpu_scope.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/graphlab/gpu/gpu_scope.hpp
iivek/graphlab-cmu-mirror
028321757ea979e6a0859687e37933be375153eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2009 Carnegie Mellon University. * 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. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ #ifndef GRAPHLAB_GPU_SCOPE_HPP #define GRAPHLAB_GPU_SCOPE_HPP #include <graphlab/graph/graph.hpp> namespace graphlab { /** * This defines a general scope type */ template<typename GPUProgram> class gpu_scope { public: typedef typename GPUProgram::vertex_data_type vertex_data_type; typedef typename GPUProgram::edge_data_type edge_data_type; public: __device__ gpu_scope() { } /** * \brief Returns the vertex id of the base vertex in this scope. * * This method is used by the update function to get the base * vertex of the scope. The base vertex is the vertex that the * update function is being applied to. */ __device__ vertex_id_t vertex() { } /** Get the number of vertices */ __device__ size_t num_vertices() { } /** * \brief edge lookup from source target pair to edge id. * * This is used to get structural information from the graph. If * the edge is not present this method will fail. */ __device__ edge_id_t edge(vertex_id_t source, vertex_id_t target) const { } /** * \brief test whether an edge is present * * This method tests whether the edge exists. If the edge exists * this method returns true. */ __device__ bool edge_exists(vertex_id_t source, vertex_id_t target) const { } /** * \brief Get the reverse edge. * * Get the reverse edge id. If no such edge exists this method * will fail. */ __device__ edge_id_t reverse_edge(edge_id_t eid) const { } /** * \brief get all in edges to the base vertex of this scope. * * This method returns an immutable vector of edge ids sorted in * order of <source id, dest id> pairs. */ __device__ edge_list in_edge_ids() const { } /** * \brief get all in edge ids to the vertex argument * * This method returns an immutable vector of edge ids sorted in * order of <source id, dest id> pairs. */ __device_ edge_list in_edge_ids(vertex_id_t v) const { } /** * \brief get all out edge ids to the base vertex of this scope * * This method returns an immutable vector of edge ids sorted in * order of <source id, dest id> pairs. */ __device__ edge_list out_edge_ids() const { } /** * \brief get all out ede ids to the vertex argument. * * This method returns an immutable vector of edge ids sorted in * order of <source id, dest id> pairs. */ __device__ edge_list out_edge_ids(vertex_id_t v) const { } //! Get the source vertex of the edge id argument __device__ vertex_id_t source(edge_id_t edge_id) const { } //! get the target vertex of the edge id argument __device__ vertex_id_t target(edge_id_t edge_id) const { } /** Get a reference to the vertex data */ __device__ vertex_data_type& vertex_data() { } __device__ const vertex_data_type& const_vertex_data() const { } /// Direct calls to access edge data __device__ edge_data_type& edge_data(edge_id_t eid) { } __device__ const edge_data_type& const_edge_data(edge_id_t eid) const { } __device__ const vertex_data_type& neighbor_vertex_data(vertex_id_t vertex) const { } __device__ const vertex_data_type& const_neighbor_vertex_data(vertex_id_t vertex) const { } __device__ vertex_data_type& neighbor_vertex_data(vertex_id_t vertex) { } }; // end of ext_locked_scope } // end of graphlab namespace #endif
26.95092
82
0.65832
[ "vector" ]
00b10dbabe209649e5ba9d291cb5b29ef3ad6e6c
632
cpp
C++
recipes/tinyobjloader/all/test_package/test_package_2.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
562
2019-09-04T12:23:43.000Z
2022-03-29T16:41:43.000Z
recipes/tinyobjloader/all/test_package/test_package_2.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
9,799
2019-09-04T12:02:11.000Z
2022-03-31T23:55:45.000Z
recipes/tinyobjloader/all/test_package/test_package_2.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
1,126
2019-09-04T11:57:46.000Z
2022-03-31T16:43:38.000Z
#include <tiny_obj_loader.h> #include <vector> #include <iostream> int main (void) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string warn; std::string err; bool ret = tinyobj::LoadObj( &attrib, &shapes, &materials, &warn, &err, "cube.obj"); if (!warn.empty()) { std::cout << "WARN: " << warn << std::endl; } if (!err.empty()) { std::cerr << "ERR: " << err << std::endl; } if (!ret) { std::cerr << "Failed to load/parse .obj" << std::endl; return 1; } return 0; }
21.066667
63
0.544304
[ "vector" ]
00c3c6aec9771c8e468df3122dad0fca1eb921f7
1,647
hpp
C++
17/water_simulation.hpp
ComicSansMS/AdventOfCode2018
936ebf5dad7a0317ed3db0f58a16d88c4a00eabb
[ "Unlicense" ]
null
null
null
17/water_simulation.hpp
ComicSansMS/AdventOfCode2018
936ebf5dad7a0317ed3db0f58a16d88c4a00eabb
[ "Unlicense" ]
null
null
null
17/water_simulation.hpp
ComicSansMS/AdventOfCode2018
936ebf5dad7a0317ed3db0f58a16d88c4a00eabb
[ "Unlicense" ]
null
null
null
#ifndef ADVENT_OF_CODE_17_WATER_SIMULATION_HPP_INCLUDE_GUARD #define ADVENT_OF_CODE_17_WATER_SIMULATION_HPP_INCLUDE_GUARD #include <functional> #include <iosfwd> #include <optional> #include <string_view> #include <tuple> #include <vector> struct Vec2 { int x; int y; Vec2(int xx, int yy) :x(xx), y(yy) {} Vec2(Vec2 const&) = default; Vec2& operator=(Vec2 const&) = default; }; inline bool operator==(Vec2 const& lhs, Vec2 const& rhs) { return (lhs.x == rhs.x) && (lhs.y == rhs.y); } namespace std { template<> struct hash<Vec2> { typedef Vec2 argument_type; typedef std::size_t result_type; result_type operator()(argument_type const& v) const noexcept { return (static_cast<std::size_t>(v.x) << static_cast<std::size_t>(16)) | static_cast<std::size_t>(v.y); } }; } struct Limit { Vec2 min; Vec2 max; }; enum class Field { Empty = 0, Clay, Water_Flowing, Water_Still }; enum class Status { FoundPosition, FloorMissing }; struct Simulation { Limit m_limits; Vec2 m_source; std::vector<Field> m_field; Field& getField(Vec2 const& pos); Field getField(Vec2 const& pos) const; bool spawn(Vec2 const& spawn_source); std::optional<Vec2> flowDown(Vec2 const& start_pos); std::tuple<Status, Vec2> flowLeft(Vec2 const& start_pos); std::tuple<Status, Vec2> flowRight(Vec2 const& start_pos); }; Simulation parseInput(std::string_view input); std::ostream& operator<<(std::ostream& os, Simulation const& sim); bool spawnWater(Simulation& sim); std::tuple<int64_t, int64_t> simulateFlow(Simulation& sim); #endif
20.848101
111
0.67881
[ "vector" ]
00d10ae37ed2787952d57b019641affbb4770a56
410
cpp
C++
CodeForces/KefaandFirstSteps.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/KefaandFirstSteps.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/KefaandFirstSteps.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } priority_queue<int> count; int temp = 1; if (n > 1) { for (int i = 1; i < n; i++) { if (a[i] >= a[i - 1]) { temp++; count.push(temp); } else { temp = 1; count.push(temp); } } cout << count.top(); } else { cout << temp; } }
14.137931
31
0.463415
[ "vector" ]
00d14adda72d3339f6d6582e1cc73a7960042c3a
1,454
cpp
C++
source/aoc/src/aoc2019/d01/solver.cpp
daduraro/aoc
9029de9d6e703fa1b20a466c1286b74ce9a7b23c
[ "BSD-2-Clause" ]
1
2019-12-06T11:29:14.000Z
2019-12-06T11:29:14.000Z
source/aoc/src/aoc2019/d01/solver.cpp
daduraro/aoc
9029de9d6e703fa1b20a466c1286b74ce9a7b23c
[ "BSD-2-Clause" ]
null
null
null
source/aoc/src/aoc2019/d01/solver.cpp
daduraro/aoc
9029de9d6e703fa1b20a466c1286b74ce9a7b23c
[ "BSD-2-Clause" ]
null
null
null
#include "aoc/solver.h" #include <iostream> #include <string> #include <vector> #include <array> #include <algorithm> #include <numeric> #include <iterator> #include <limits> #include <type_traits> #include <memory> #include <cassert> namespace { using namespace aoc; constexpr std::size_t YEAR = 2019; constexpr std::size_t DAY = 1; using input_t = std::vector<std::size_t>; auto resultA(const input_t& in) noexcept -> std::size_t { return std::accumulate(in.begin(), in.end(), std::size_t(0), [](auto acc, auto x) { return acc + (x/3) - 2; }); } auto resultB(const input_t& in) noexcept -> std::size_t { return (std::size_t) std::accumulate(in.begin(), in.end(), std::intmax_t(0), [](auto acc, std::intmax_t x) { x = x / 3 - 2; while (x >= 0) { acc += x; x = x / 3 - 2; } return acc; }); } input_t parse_input(std::istream& is) { input_t in; using input_it = std::istream_iterator<std::size_t>; std::copy(input_it(is), input_it(), std::back_inserter(in)); if (!is.eof()) throw parse_exception{"failed to parse input"}; return in; } } namespace aoc { template<> auto create_solver<YEAR, DAY>() noexcept -> std::unique_ptr<solver_interface> { return create_solver<YEAR, DAY>(parse_input, resultA, resultB); } }
25.964286
116
0.572902
[ "vector" ]
00d61a25e62909931d7906ed264455cef4406dda
422
hpp
C++
eat/eat.hpp
arabian9ts/easy-git
5e0fe3e6bcc604c251c45c73fe2f1cead038d83c
[ "MIT" ]
2
2017-10-10T06:18:48.000Z
2018-04-26T05:55:39.000Z
eat/eat.hpp
arabian9ts/easy-git
5e0fe3e6bcc604c251c45c73fe2f1cead038d83c
[ "MIT" ]
null
null
null
eat/eat.hpp
arabian9ts/easy-git
5e0fe3e6bcc604c251c45c73fe2f1cead038d83c
[ "MIT" ]
null
null
null
// // eat.hpp // eat // // Created by arabian9ts on 2017/03/22. // Copyright © 2017年 arabian9ts. All rights reserved. // #ifndef eat_h #define eat_h #include <string> #include <stdio.h> #include <list> #include <vector> #include <algorithm> #include <sys/stat.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <unistd.h> #include <map> #include <boost/algorithm/string.hpp> #endif /* eat_h */
15.62963
54
0.684834
[ "vector" ]
00da60552209dfa21ba4e6f9d4af64e108f9ab62
9,593
cpp
C++
SD/Tema1/Sortari.cpp
andrei-micuda/teme-fmi
d31c032c45e0e910d75fc05faab3681d421aac7c
[ "MIT" ]
1
2020-06-07T09:45:17.000Z
2020-06-07T09:45:17.000Z
SD/Tema1/Sortari.cpp
micu01/teme-fmi
d31c032c45e0e910d75fc05faab3681d421aac7c
[ "MIT" ]
null
null
null
SD/Tema1/Sortari.cpp
micu01/teme-fmi
d31c032c45e0e910d75fc05faab3681d421aac7c
[ "MIT" ]
2
2020-04-09T19:27:36.000Z
2020-06-28T17:45:14.000Z
#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <chrono> using namespace std; using namespace std::chrono; ifstream in("sortari.in"); ofstream out("sortari.out"); //Utility Functions void PrintArray(vector<long long>& v); void FilePrintArray(vector<long long>& v); int NrOfDigits(long long x); bool CheckSort(vector<long long>& v, vector<long long>& sorted); long long BFPRT(vector<long long>& v, int st, int dr); //pivot picking algorithm for QuickSort int Partition(vector<long long>& v, int st, int dr); //partition algorithm for QuickSort void Merge(vector<long long>& v, int st, int dr); //merge algorithm for MergeSort //Sorting Algorithms void InsertionSort(vector<long long>& v); void BubbleSort(vector<long long>& v); void RadixSortBase10(vector<long long>& v); void RadixSortBase256(vector<long long>& v); void QuickSortBFPRT(vector<long long>& v, int st, int dr); void QuickSortMedianOfThree(vector<long long>& v, int st, int dr); void MergeSort(vector<long long>& v, int st, int dr); int main() { int tests; in >> tests; for (int k = 0; k < tests; k++) { int n; long long mn, mx; in >> n >> mn >> mx; out << "TEST CASE " << k + 1 << '\n'; vector<long long> v, tmp, sorted; for (int i = 0; i < n; i++) { long long x; in >> x; v.push_back(x); tmp.push_back(x); sorted.push_back(x); } out << "SIZE: 10^" << NrOfDigits(n) - 1 << '\n'; if (mn < 0) out << "MIN: -10^" << NrOfDigits(mn) - 1 << '\n'; else if (mn > 0) out << "MIN: 10^" << NrOfDigits(mn) - 1 << '\n'; else out << "MIN: 0\n"; if (mx > 0) out << "MAX: 10^" << NrOfDigits(mx) - 1 << '\n'; else if (mx < 0) out << "MAX: -10^" << NrOfDigits(mx) - 1 << '\n'; else out << "MAX: 0\n"; //STL Sort auto start = high_resolution_clock::now(); sort(sorted.begin(), sorted.end()); auto stop = high_resolution_clock::now(); duration<double, std::milli> fp_ms = stop - start; out << "STL Sort: " << fp_ms.count() / 1000 << "s\n"; //Insertion Sort start = high_resolution_clock::now(); InsertionSort(tmp); stop = high_resolution_clock::now(); fp_ms = stop - start; out << "Insertion Sort: " << fp_ms.count() / 1000 << "s " << (CheckSort(tmp, sorted) ? "OK\n" : "NOT OK\n"); //Bubble Sort for (int i = 0; i < n; i++) tmp[i] = v[i]; start = high_resolution_clock::now(); BubbleSort(tmp); stop = high_resolution_clock::now(); fp_ms = stop - start; out << "Bubble Sort: " << fp_ms.count() / 1000 << "s " << (CheckSort(tmp, sorted) ? "OK\n" : "NOT OK\n"); //Merge Sort for (int i = 0; i < n; i++) tmp[i] = v[i]; start = high_resolution_clock::now(); MergeSort(tmp, 0, tmp.size() - 1); stop = high_resolution_clock::now(); fp_ms = stop - start; out << "Merge Sort: " << fp_ms.count() / 1000 << "s " << (CheckSort(tmp, sorted) ? "OK\n" : "NOT OK\n"); //Quick Sort BFPRT for (int i = 0; i < n; i++) tmp[i] = v[i]; start = high_resolution_clock::now(); QuickSortBFPRT(tmp, 0, tmp.size() - 1); stop = high_resolution_clock::now(); fp_ms = stop - start; out << "Quick Sort BFPRT: " << fp_ms.count() / 1000 << "s " << (CheckSort(tmp, sorted) ? "OK\n" : "NOT OK\n"); //Quick Sort Median Of Three for (int i = 0; i < n; i++) tmp[i] = v[i]; start = high_resolution_clock::now(); QuickSortMedianOfThree(tmp, 0, tmp.size() - 1); stop = high_resolution_clock::now(); fp_ms = stop - start; out << "Quick Sort MedianOfThree: " << fp_ms.count() / 1000 << "s " << (CheckSort(tmp, sorted) ? "OK\n" : "NOT OK\n"); //Radix Sort Base 10 for (int i = 0; i < n; i++) tmp[i] = v[i]; start = high_resolution_clock::now(); RadixSortBase10(tmp); stop = high_resolution_clock::now(); fp_ms = stop - start; out << "Radix Sort(base 10): " << fp_ms.count() / 1000 << "s " << (CheckSort(tmp, sorted) ? "OK\n" : "NOT OK\n"); //Radix Sort Base 256 for (int i = 0; i < n; i++) tmp[i] = v[i]; start = high_resolution_clock::now(); RadixSortBase256(tmp); stop = high_resolution_clock::now(); fp_ms = stop - start; out << "Radix Sort(base 256): " << fp_ms.count() / 1000 << "s " << (CheckSort(tmp, sorted) ? "OK\n" : "NOT OK\n"); out << '\n'; } return 0; } void PrintArray(vector<long long>& v) { for (int i = 0; i < v.size(); i++) cout << v[i] << ' '; cout << '\n'; } void FilePrintArray(vector<long long>& v) { for (int i = 0; i < v.size(); i++) out << v[i] << ' '; out << '\n'; } int NrOfDigits(long long x) { int digits = 0; while(x) { digits++; x /= 10; } return digits; } bool CheckSort(vector<long long>& v, vector<long long>& sorted) { for (int i = 0; i < v.size(); i++) { if (v[i] != sorted[i]) return false; } return true; } long long BFPRT(vector<long long>& v, int st, int dr) { if (dr - st + 1 <= 5) { vector<long long> u; for (int i = st; i <= dr; i++) u.push_back(v[i]); InsertionSort(u); return u[u.size() / 2]; } vector<long long> u(5), mediane; for (int i = st; i <= dr; i += 5) { int j = 0; for (j = 0; j < 5 && i + j <= dr; j++) { u[j] = v[i + j]; } //daca o sublista (ultima) are mai putin de 5 elemente, le eliminam pe cele care ramasesera in vector din sublista anterioara if (j < 5) u.resize(j); InsertionSort(u); mediane.push_back(u[u.size() / 2]); } return BFPRT(mediane, 0, mediane.size() - 1); } int MedianOfThree(vector<long long>& v, int st, int dr) { int a = v[st], b = v[(st + dr) / 2], c = v[dr]; if ((a > b) != (a > c)) return st; else if ((b > a) != (b > c)) return (st+dr)/2; else return dr; } int Partition(vector<long long>& v, int st, int dr) { int i = st - 1; for (int j = st; j < dr; j++) { if (v[j] < v[dr]) { i++; swap(v[i], v[j]); } } swap(v[i + 1], v[dr]); return i + 1; } void Merge(vector<long long>& v, int st, int dr) { int m = (st + dr) / 2; int i = st, j = m + 1; vector<long long> u; while (i <= m && j <= dr) { if (v[i] < v[j]) u.push_back(v[i++]); else u.push_back(v[j++]); } while (i <= m) u.push_back(v[i++]); while (j <= dr) u.push_back(v[j++]); for (i = st; i <= dr; i++) v[i] = u[i - st]; } void InsertionSort(vector<long long>& v) { if (v.size() > 10000) { return; } for (int i = 1; i < v.size(); i++) { long long curr = v[i]; int j = i - 1; while (j >= 0 && v[j] > curr) { v[j + 1] = v[j]; j--; } v[j + 1] = curr; } } void BubbleSort(vector<long long>& v) { if (v.size() > 10000 || v.size() < 1) { return; } bool ok = 0; while (!ok) { ok = 1; for (int i = 0; i < v.size() - 1; i++) { if (v[i] > v[i + 1]) { swap(v[i], v[i + 1]); ok = 0; } } } } void RadixSortBase10(vector<long long>& v) { //aflam numarul minimul din vector int n = v.size(); if (n < 1) return; long long mn = v[0], mx = v[0]; for (int i = 0; i < n; i++) { if (v[i] < mn) mn = v[i]; } //daca vectorul contine elemente negative, scadem minimul pentru a sorta un vector doar de elemente pozitive if (mn < 0) { for (int i = 0; i < n; i++) v[i] -= mn; } for (int i = 0; i < n; i++) { if (v[i] > mx) mx = v[i]; } int pasi = NrOfDigits(mx); vector<long long> liste[10]; unsigned long long pow10 = 1; for (int k = 0; k < pasi; k++) { for (int i = 0; i < n; i++) { int cif_curr = (v[i] % (pow10 * 10)) / pow10; liste[cif_curr].push_back(v[i]); } //mutam valorile din liste inapoi in vector int l = 0; for (int i = 0; i < 10; i++) { for (int j = 0; j < liste[i].size(); j++) v[l++] = liste[i][j]; liste[i].clear(); } pow10 *= 10; } //daca vectorul continea initial valori negative, adaugam minimul acestora pentru a obtine valorile initiale din vector if (mn < 0) { for (int i = 0; i < n; i++) v[i] += mn; } } void RadixSortBase256(vector<long long>& v) { //aflam minimul din vector int n = v.size(); if (n < 1) return; long long mn = v[0]; for (int i = 0; i < n; i++) { if (v[i] < mn) mn = v[i]; } //daca vectorul contine elemente negative, scadem minimul pentru a sorta un vector doar de elemente pozitive if (mn < 0) { for (int i = 0; i < n; i++) v[i] -= mn; } vector<long long> liste[256]; for (int i = 0; i < n; i++) { liste[(v[i] & 255)].push_back(v[i]); } //mutam valorile din liste inapoi in vector int k = 0; for (int i = 0; i < 256; i++) { for (int j = 0; j < liste[i].size(); j++) v[k++] = liste[i][j]; liste[i].clear(); } int bits = 8; for (int j = 0; j < 7; j++) { for (int i = 0; i < n; i++) { liste[((v[i] >> bits) & 255)].push_back(v[i]); } //mutam valorile din liste inapoi in vector k = 0; for (int i = 0; i < 256; i++) { for (int j = 0; j < liste[i].size(); j++) v[k++] = liste[i][j]; liste[i].clear(); } bits += 8; } //daca vectorul continea initial valori negative, adaugam minimul acestora pentru a obtine valorile initiale din vector if (mn < 0) { for (int i = 0; i < n; i++) v[i] += mn; } } void QuickSortBFPRT(vector<long long>& v, int st, int dr) { if (st < dr) { int pivot = st; long long pivot_val = BFPRT(v, st, dr); while (v[pivot] != pivot_val) pivot++; swap(v[pivot], v[dr]); pivot = Partition(v, st, dr); QuickSortBFPRT(v, st, pivot - 1); QuickSortBFPRT(v, pivot + 1, dr); } } void QuickSortMedianOfThree(vector<long long>& v, int st, int dr) { if (st < dr) { int pivot = MedianOfThree(v, st, dr); swap(v[pivot], v[dr]); pivot = Partition(v, st, dr); QuickSortMedianOfThree(v, st, pivot - 1); QuickSortMedianOfThree(v, pivot + 1, dr); } } void MergeSort(vector<long long>& v, int st, int dr) { if (st >= dr) return; int m = (st + dr) / 2; MergeSort(v, st, m); MergeSort(v, m + 1, dr); Merge(v, st, dr); }
27.022535
127
0.565725
[ "vector" ]
00dab16f05206eaf4f98945aad15da452bdfba87
14,055
cc
C++
src/perfetto_cmd/pbtxt_to_pb_unittest.cc
azeng369/perfetto
024ea24c78533030a3faec9a5583af3175f07712
[ "Apache-2.0" ]
null
null
null
src/perfetto_cmd/pbtxt_to_pb_unittest.cc
azeng369/perfetto
024ea24c78533030a3faec9a5583af3175f07712
[ "Apache-2.0" ]
4
2021-02-13T21:42:44.000Z
2021-09-03T05:54:02.000Z
src/perfetto_cmd/pbtxt_to_pb_unittest.cc
azeng369/perfetto
024ea24c78533030a3faec9a5583af3175f07712
[ "Apache-2.0" ]
1
2021-11-03T18:22:40.000Z
2021-11-03T18:22:40.000Z
/* * Copyright (C) 2018 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. */ #include "src/perfetto_cmd/pbtxt_to_pb.h" #include <memory> #include <string> #include "test/gtest_and_gmock.h" #include "perfetto/tracing/core/data_source_config.h" #include "perfetto/tracing/core/trace_config.h" #include "protos/perfetto/config/ftrace/ftrace_config.gen.h" #include "protos/perfetto/config/test_config.gen.h" namespace perfetto { namespace { using ::testing::StrictMock; using ::testing::Contains; using ::testing::ElementsAre; class MockErrorReporter : public ErrorReporter { public: MockErrorReporter() {} ~MockErrorReporter() = default; MOCK_METHOD4(AddError, void(size_t line, size_t column_start, size_t column_end, const std::string& message)); }; TraceConfig ToProto(const std::string& input) { StrictMock<MockErrorReporter> reporter; std::vector<uint8_t> output = PbtxtToPb(input, &reporter); EXPECT_FALSE(output.empty()); TraceConfig config; config.ParseFromArray(output.data(), output.size()); return config; } void ToErrors(const std::string& input, MockErrorReporter* reporter) { std::vector<uint8_t> output = PbtxtToPb(input, reporter); } TEST(PbtxtToPb, OneField) { TraceConfig config = ToProto(R"( duration_ms: 1234 )"); EXPECT_EQ(config.duration_ms(), 1234u); } TEST(PbtxtToPb, TwoFields) { TraceConfig config = ToProto(R"( duration_ms: 1234 file_write_period_ms: 5678 )"); EXPECT_EQ(config.duration_ms(), 1234u); EXPECT_EQ(config.file_write_period_ms(), 5678u); } TEST(PbtxtToPb, Enum) { TraceConfig config = ToProto(R"( compression_type: COMPRESSION_TYPE_DEFLATE )"); EXPECT_EQ(config.compression_type(), 1); } TEST(PbtxtToPb, LastCharacters) { EXPECT_EQ(ToProto(R"( duration_ms: 123;)") .duration_ms(), 123u); EXPECT_EQ(ToProto(R"( duration_ms: 123 )") .duration_ms(), 123u); EXPECT_EQ(ToProto(R"( duration_ms: 123#)") .duration_ms(), 123u); EXPECT_EQ(ToProto(R"( duration_ms: 123 )") .duration_ms(), 123u); EXPECT_EQ(ToProto(R"( compression_type: COMPRESSION_TYPE_DEFLATE;)") .compression_type(), 1); EXPECT_EQ(ToProto(R"( compression_type: COMPRESSION_TYPE_DEFLATE )") .compression_type(), 1); EXPECT_EQ(ToProto(R"( compression_type: COMPRESSION_TYPE_DEFLATE#)") .compression_type(), 1); EXPECT_EQ(ToProto(R"( compression_type: COMPRESSION_TYPE_DEFLATE )") .compression_type(), 1); } TEST(PbtxtToPb, Semicolons) { TraceConfig config = ToProto(R"( duration_ms: 1234; file_write_period_ms: 5678; )"); EXPECT_EQ(config.duration_ms(), 1234u); EXPECT_EQ(config.file_write_period_ms(), 5678u); } TEST(PbtxtToPb, NestedMessage) { TraceConfig config = ToProto(R"( buffers: { size_kb: 123 } )"); ASSERT_EQ(config.buffers().size(), 1u); EXPECT_EQ(config.buffers()[0].size_kb(), 123u); } TEST(PbtxtToPb, SplitNested) { TraceConfig config = ToProto(R"( buffers: { size_kb: 1 } duration_ms: 1000; buffers: { size_kb: 2 } )"); ASSERT_EQ(config.buffers().size(), 2u); EXPECT_EQ(config.buffers()[0].size_kb(), 1u); EXPECT_EQ(config.buffers()[1].size_kb(), 2u); EXPECT_EQ(config.duration_ms(), 1000u); } TEST(PbtxtToPb, MultipleNestedMessage) { TraceConfig config = ToProto(R"( buffers: { size_kb: 1 } buffers: { size_kb: 2 } )"); ASSERT_EQ(config.buffers().size(), 2u); EXPECT_EQ(config.buffers()[0].size_kb(), 1u); EXPECT_EQ(config.buffers()[1].size_kb(), 2u); } TEST(PbtxtToPb, NestedMessageCrossFile) { TraceConfig config = ToProto(R"( data_sources { config { ftrace_config { drain_period_ms: 42 } } } )"); protos::gen::FtraceConfig ftrace_config; ASSERT_TRUE(ftrace_config.ParseFromString( config.data_sources()[0].config().ftrace_config_raw())); ASSERT_EQ(ftrace_config.drain_period_ms(), 42u); } TEST(PbtxtToPb, Booleans) { TraceConfig config = ToProto(R"( write_into_file: false; deferred_start: true; )"); EXPECT_EQ(config.write_into_file(), false); EXPECT_EQ(config.deferred_start(), true); } TEST(PbtxtToPb, Comments) { TraceConfig config = ToProto(R"( write_into_file: false # deferred_start: true; buffers# 1 # 2 :# 3 # 4 {# 5 # 6 fill_policy# 7 # 8 :# 9 # 10 RING_BUFFER# 11 # 12 ;# 13 # 14 } # 15 # 16 )"); EXPECT_EQ(config.write_into_file(), false); EXPECT_EQ(config.deferred_start(), false); } TEST(PbtxtToPb, Enums) { TraceConfig config = ToProto(R"( buffers: { fill_policy: RING_BUFFER } )"); const auto kRingBuffer = TraceConfig::BufferConfig::RING_BUFFER; EXPECT_EQ(config.buffers()[0].fill_policy(), kRingBuffer); } TEST(PbtxtToPb, AllFieldTypes) { TraceConfig config = ToProto(R"( data_sources { config { for_testing { dummy_fields { field_uint32: 1; field_uint64: 2; field_int32: 3; field_int64: 4; field_fixed64: 5; field_sfixed64: 6; field_fixed32: 7; field_sfixed32: 8; field_double: 9.9; field_float: 10.10; field_sint64: 11; field_sint32: 12; field_string: "13"; field_bytes: "14"; } } } } )"); const auto& fields = config.data_sources()[0].config().for_testing().dummy_fields(); ASSERT_EQ(fields.field_uint32(), 1u); ASSERT_EQ(fields.field_uint64(), 2u); ASSERT_EQ(fields.field_int32(), 3); ASSERT_EQ(fields.field_int64(), 4); ASSERT_EQ(fields.field_fixed64(), 5u); ASSERT_EQ(fields.field_sfixed64(), 6); ASSERT_EQ(fields.field_fixed32(), 7u); ASSERT_EQ(fields.field_sfixed32(), 8); ASSERT_DOUBLE_EQ(fields.field_double(), 9.9); ASSERT_FLOAT_EQ(fields.field_float(), 10.10f); ASSERT_EQ(fields.field_sint64(), 11); ASSERT_EQ(fields.field_sint32(), 12); ASSERT_EQ(fields.field_string(), "13"); ASSERT_EQ(fields.field_bytes(), "14"); } TEST(PbtxtToPb, LeadingDots) { TraceConfig config = ToProto(R"( data_sources { config { for_testing { dummy_fields { field_double: .1; field_float: .2; } } } } )"); const auto& fields = config.data_sources()[0].config().for_testing().dummy_fields(); ASSERT_DOUBLE_EQ(fields.field_double(), .1); ASSERT_FLOAT_EQ(fields.field_float(), .2f); } TEST(PbtxtToPb, NegativeNumbers) { TraceConfig config = ToProto(R"( data_sources { config { for_testing { dummy_fields { field_int32: -1; field_int64: -2; field_fixed64: -3; field_sfixed64: -4; field_fixed32: -5; field_sfixed32: -6; field_double: -7.7; field_float: -8.8; field_sint64: -9; field_sint32: -10; } } } } )"); const auto& fields = config.data_sources()[0].config().for_testing().dummy_fields(); ASSERT_EQ(fields.field_int32(), -1); ASSERT_EQ(fields.field_int64(), -2); ASSERT_EQ(fields.field_fixed64(), static_cast<uint64_t>(-3)); ASSERT_EQ(fields.field_sfixed64(), -4); ASSERT_EQ(fields.field_fixed32(), static_cast<uint32_t>(-5)); ASSERT_EQ(fields.field_sfixed32(), -6); ASSERT_DOUBLE_EQ(fields.field_double(), -7.7); ASSERT_FLOAT_EQ(fields.field_float(), -8.8f); ASSERT_EQ(fields.field_sint64(), -9); ASSERT_EQ(fields.field_sint32(), -10); } TEST(PbtxtToPb, EofEndsNumeric) { TraceConfig config = ToProto(R"(duration_ms: 1234)"); EXPECT_EQ(config.duration_ms(), 1234u); } TEST(PbtxtToPb, EofEndsIdentifier) { TraceConfig config = ToProto(R"(enable_extra_guardrails: true)"); EXPECT_EQ(config.enable_extra_guardrails(), true); } TEST(PbtxtToPb, ExampleConfig) { TraceConfig config = ToProto(R"( buffers { size_kb: 100024 fill_policy: RING_BUFFER } data_sources { config { name: "linux.ftrace" target_buffer: 0 ftrace_config { buffer_size_kb: 512 # 4 (page size) * 128 drain_period_ms: 200 ftrace_events: "binder_lock" ftrace_events: "binder_locked" atrace_categories: "gfx" } } } data_sources { config { name: "linux.process_stats" target_buffer: 0 } } data_sources { config { name: "linux.inode_file_map" target_buffer: 0 inode_file_config { scan_delay_ms: 1000 scan_interval_ms: 1000 scan_batch_size: 500 mount_point_mapping: { mountpoint: "/data" scan_roots: "/data/app" } } } } producers { producer_name: "perfetto.traced_probes" shm_size_kb: 4096 page_size_kb: 4 } duration_ms: 10000 )"); EXPECT_EQ(config.duration_ms(), 10000u); EXPECT_EQ(config.buffers()[0].size_kb(), 100024u); EXPECT_EQ(config.data_sources()[0].config().name(), "linux.ftrace"); EXPECT_EQ(config.data_sources()[0].config().target_buffer(), 0u); EXPECT_EQ(config.producers()[0].producer_name(), "perfetto.traced_probes"); } TEST(PbtxtToPb, Strings) { TraceConfig config = ToProto(R"( data_sources { config { ftrace_config { ftrace_events: "binder_lock" ftrace_events: "foo/bar" ftrace_events: "foo\\bar" ftrace_events: "newline\nnewline" ftrace_events: "\"quoted\"" ftrace_events: "\a\b\f\n\r\t\v\\\'\"\?" } } } )"); protos::gen::FtraceConfig ftrace_config; ASSERT_TRUE(ftrace_config.ParseFromString( config.data_sources()[0].config().ftrace_config_raw())); const auto& events = ftrace_config.ftrace_events(); EXPECT_THAT(events, Contains("binder_lock")); EXPECT_THAT(events, Contains("foo/bar")); EXPECT_THAT(events, Contains("foo\\bar")); EXPECT_THAT(events, Contains("newline\nnewline")); EXPECT_THAT(events, Contains("\"quoted\"")); EXPECT_THAT(events, Contains("\a\b\f\n\r\t\v\\\'\"\?")); } TEST(PbtxtToPb, UnknownField) { MockErrorReporter reporter; EXPECT_CALL(reporter, AddError(2, 5, 11, "No field named \"not_a_label\" in proto TraceConfig")); ToErrors(R"( not_a_label: false )", &reporter); } TEST(PbtxtToPb, UnknownNestedField) { MockErrorReporter reporter; EXPECT_CALL( reporter, AddError( 4, 5, 16, "No field named \"not_a_field_name\" in proto DataSourceConfig")); ToErrors(R"( data_sources { config { not_a_field_name { } } } )", &reporter); } TEST(PbtxtToPb, BadBoolean) { MockErrorReporter reporter; EXPECT_CALL(reporter, AddError(2, 22, 3, "Expected 'true' or 'false' for boolean field " "write_into_file in proto TraceConfig instead " "saw 'foo'")); ToErrors(R"( write_into_file: foo; )", &reporter); } TEST(PbtxtToPb, MissingBoolean) { MockErrorReporter reporter; EXPECT_CALL(reporter, AddError(3, 3, 0, "Unexpected end of input")); ToErrors(R"( write_into_file: )", &reporter); } TEST(PbtxtToPb, RootProtoMustNotEndWithBrace) { MockErrorReporter reporter; EXPECT_CALL(reporter, AddError(2, 5, 0, "Unmatched closing brace")); ToErrors(R"( } )", &reporter); } TEST(PbtxtToPb, SawNonRepeatedFieldTwice) { MockErrorReporter reporter; EXPECT_CALL( reporter, AddError(3, 5, 15, "Saw non-repeating field 'write_into_file' more than once")); ToErrors(R"( write_into_file: true; write_into_file: true; )", &reporter); } TEST(PbtxtToPb, WrongTypeBoolean) { MockErrorReporter reporter; EXPECT_CALL(reporter, AddError(2, 18, 4, "Expected value of type uint32 for field duration_ms in " "proto TraceConfig instead saw 'true'")); ToErrors(R"( duration_ms: true; )", &reporter); } TEST(PbtxtToPb, WrongTypeNumber) { MockErrorReporter reporter; EXPECT_CALL(reporter, AddError(2, 14, 3, "Expected value of type message for field buffers in " "proto TraceConfig instead saw '100'")); ToErrors(R"( buffers: 100; )", &reporter); } TEST(PbtxtToPb, NestedMessageDidNotTerminate) { MockErrorReporter reporter; EXPECT_CALL(reporter, AddError(2, 15, 0, "Nested message not closed")); ToErrors(R"( buffers: {)", &reporter); } TEST(PbtxtToPb, BadEscape) { MockErrorReporter reporter; EXPECT_CALL(reporter, AddError(5, 23, 2, "Unknown string escape in ftrace_events in " "proto FtraceConfig: '\\p'")); ToErrors(R"( data_sources { config { ftrace_config { ftrace_events: "\p" } } })", &reporter); } TEST(PbtxtToPb, BadEnumValue) { MockErrorReporter reporter; EXPECT_CALL(reporter, AddError(1, 18, 3, "Unexpected value 'FOO' for enum field " "compression_type in proto TraceConfig")); ToErrors(R"(compression_type: FOO)", &reporter); } // TODO(hjd): Add these tests. // TEST(PbtxtToPb, WrongTypeString) // TEST(PbtxtToPb, OverflowOnIntegers) // TEST(PbtxtToPb, NegativeNumbersForUnsignedInt) // TEST(PbtxtToPb, UnterminatedString) { // TEST(PbtxtToPb, NumberIsEof) // TEST(PbtxtToPb, OneOf) } // namespace } // namespace perfetto
25.098214
80
0.640413
[ "vector" ]
00dec619497639be18aa84479b7b513193f46a68
126
cpp
C++
Dataset/JC/valid/linkedlist/cpp/1363.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/JC/valid/linkedlist/cpp/1363.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/JC/valid/linkedlist/cpp/1363.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <functional> #include <algorithm> using namespace std; class LinkedList{ };
11.454545
21
0.738095
[ "vector" ]
00e4526392dbd7994ecddaf7d43795e019e571c7
19,934
cc
C++
hybridbackend/cpp/tensorflow/cuda/cast.cu.cc
fuhailin/HybridBackend
113383c5870b7180fa67c194208a27f76bdbf3f0
[ "Apache-2.0" ]
38
2021-12-01T06:54:36.000Z
2022-03-23T11:23:21.000Z
hybridbackend/cpp/tensorflow/cuda/cast.cu.cc
fuhailin/HybridBackend
113383c5870b7180fa67c194208a27f76bdbf3f0
[ "Apache-2.0" ]
15
2021-12-01T09:15:26.000Z
2022-03-28T02:49:21.000Z
hybridbackend/cpp/tensorflow/cuda/cast.cu.cc
fuhailin/HybridBackend
113383c5870b7180fa67c194208a27f76bdbf3f0
[ "Apache-2.0" ]
8
2021-12-02T01:16:14.000Z
2022-01-28T04:51:16.000Z
/* Copyright 2021 Alibaba Group Holding Limited. 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. ==============================================================================*/ #if HYBRIDBACKEND_TENSORFLOW #if GOOGLE_CUDA #define EIGEN_USE_GPU #include <tensorflow/core/framework/register_types.h> #include <tensorflow/core/framework/tensor.h> #include <tensorflow/core/public/version.h> #include <thrust/device_ptr.h> #include <thrust/device_vector.h> #include "hybridbackend/cpp/tensorflow/cuda/cast.h" #include "hybridbackend/cpp/tensorflow/cuda/device_functions.h" #include "hybridbackend/cpp/tensorflow/cuda/stream.h" namespace tensorflow { namespace hybridbackend { using GPUDevice = Eigen::GpuDevice; namespace functor { __global__ void CastFp32ToFp16(const float* d_in, __half* d_out, const size_t size) { for (size_t idx : CudaGridRangeX(size)) { d_out[idx] = __float2half(d_in[idx]); } } template <> void Cast<float, Eigen::half>::operator()(const Tensor& in, Tensor* out, OpKernelContext* ctx, cudaStream_t* stream) { const size_t size = in.NumElements(); if (TF_PREDICT_FALSE(size <= 0)) { return; } const float* d_input = in.flat<float>().data(); __half* d_output = reinterpret_cast<__half*>(out->flat<Eigen::half>().data()); CudaLaunch(CastFp32ToFp16, size, 0, ctx->eigen_device<GPUDevice>(), stream, d_input, d_output, size); } template struct Cast<float, Eigen::half>; __global__ void CastFp16ToFp32(const __half* d_in, float* d_out, const size_t size) { for (size_t idx : CudaGridRangeX(size)) { d_out[idx] = __half2float(d_in[idx]); } } template <> void Cast<Eigen::half, float>::operator()(const Tensor& in, Tensor* out, OpKernelContext* ctx, cudaStream_t* stream) { const size_t size = in.NumElements(); if (TF_PREDICT_FALSE(size <= 0)) { return; } const __half* d_input = reinterpret_cast<const __half*>(in.flat<Eigen::half>().data()); float* d_output = out->flat<float>().data(); CudaLaunch(CastFp16ToFp32, size, 0, ctx->eigen_device<GPUDevice>(), stream, d_input, d_output, size); } template struct Cast<Eigen::half, float>; __global__ void GroupCastFp32ToFp16(const size_t total_max_in_size, const size_t max_in_size, const float** dd_in, __half** dd_out, const int32* d_size) { for (int32 idx : CudaGridRangeX(total_max_in_size)) { const int32 s = idx / max_in_size; const int32 sidx = idx % max_in_size; if (sidx < ldg(d_size + s)) { dd_out[s][sidx] = __float2half(dd_in[s][sidx]); } } } template <> void GroupCast<float, Eigen::half>::operator()(const std::vector<Tensor>& in, std::vector<Tensor>* out, OpKernelContext* ctx, cudaStream_t* stream) { const int64 num_inputs = in.size(); auto d = ctx->eigen_device<GPUDevice>(); auto* ctx_stream = ctx->op_device_context()->stream(); CudaStream ctx_cu_stream = CudaStream(ctx_stream); CudaStream cu_stream = CudaStream(stream); AllocatorAttributes host_alloc_attrs; host_alloc_attrs.set_on_host(true); host_alloc_attrs.set_gpu_compatible(true); Tensor h_size_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &h_size_t, host_alloc_attrs)); Tensor d_size_t; OP_REQUIRES_OK( ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &d_size_t)); int32* h_size = h_size_t.flat<int32>().data(); int32* d_size = d_size_t.flat<int32>().data(); const int32 buffer_size = static_cast<int32>((sizeof(float*) + sizeof(Eigen::half*)) * num_inputs); Tensor h_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &h_buffer_t, host_alloc_attrs)); Tensor d_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &d_buffer_t)); int8* h_buffer = h_buffer_t.flat<int8>().data(); int8* d_buffer = d_buffer_t.flat<int8>().data(); const float** hd_in = reinterpret_cast<const float**>(h_buffer); const float** dd_in = reinterpret_cast<const float**>(d_buffer); __half** hd_out = reinterpret_cast<__half**>(h_buffer + sizeof(float*) * num_inputs); __half** dd_out = reinterpret_cast<__half**>(h_buffer + sizeof(float*) * num_inputs); size_t max_in_size = 0; for (size_t i = 0; i < num_inputs; ++i) { const size_t size = in[i].NumElements(); h_size[i] = size; hd_in[i] = in[i].flat<float>().data(); hd_out[i] = reinterpret_cast<__half*>(out->at(i).flat<Eigen::half>().data()); if (size > max_in_size) { max_in_size = size; } } ctx_cu_stream.ThenCopyToDevice(d_size, h_size, sizeof(int32) * num_inputs); ctx_cu_stream.ThenCopyToDevice(d_buffer, h_buffer, buffer_size); cu_stream.ThenWaitFor(ctx_cu_stream); auto total_max_in_size = num_inputs * max_in_size; CudaLaunch(GroupCastFp32ToFp16, total_max_in_size, 0, d, stream, total_max_in_size, max_in_size, dd_in, dd_out, d_size); } template <> void GroupCast<float, Eigen::half>::operator()(const std::vector<Tensor>& in, std::vector<Tensor*>* out, OpKernelContext* ctx, cudaStream_t* stream) { const int64 num_inputs = in.size(); auto d = ctx->eigen_device<GPUDevice>(); auto* ctx_stream = ctx->op_device_context()->stream(); CudaStream ctx_cu_stream = CudaStream(ctx_stream); CudaStream cu_stream = CudaStream(stream); AllocatorAttributes host_alloc_attrs; host_alloc_attrs.set_on_host(true); host_alloc_attrs.set_gpu_compatible(true); Tensor h_size_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &h_size_t, host_alloc_attrs)); Tensor d_size_t; OP_REQUIRES_OK( ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &d_size_t)); int32* h_size = h_size_t.flat<int32>().data(); int32* d_size = d_size_t.flat<int32>().data(); const int32 buffer_size = static_cast<int32>((sizeof(float*) + sizeof(Eigen::half*)) * num_inputs); Tensor h_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &h_buffer_t, host_alloc_attrs)); Tensor d_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &d_buffer_t)); int8* h_buffer = h_buffer_t.flat<int8>().data(); int8* d_buffer = d_buffer_t.flat<int8>().data(); const float** hd_in = reinterpret_cast<const float**>(h_buffer); const float** dd_in = reinterpret_cast<const float**>(d_buffer); __half** hd_out = reinterpret_cast<__half**>(h_buffer + sizeof(float*) * num_inputs); __half** dd_out = reinterpret_cast<__half**>(h_buffer + sizeof(float*) * num_inputs); size_t max_in_size = 0; for (size_t i = 0; i < num_inputs; ++i) { const size_t size = in[i].NumElements(); h_size[i] = size; hd_in[i] = in[i].flat<float>().data(); hd_out[i] = reinterpret_cast<__half*>(out->at(i)->flat<Eigen::half>().data()); if (size > max_in_size) { max_in_size = size; } } ctx_cu_stream.ThenCopyToDevice(d_size, h_size, sizeof(int32) * num_inputs); ctx_cu_stream.ThenCopyToDevice(d_buffer, h_buffer, buffer_size); cu_stream.ThenWaitFor(ctx_cu_stream); auto total_max_in_size = num_inputs * max_in_size; CudaLaunch(GroupCastFp32ToFp16, total_max_in_size, 0, d, stream, total_max_in_size, max_in_size, dd_in, dd_out, d_size); } template <> void GroupCast<float, Eigen::half>::operator()(const std::vector<Tensor*>& in, std::vector<Tensor*>* out, OpKernelContext* ctx, cudaStream_t* stream) { const int64 num_inputs = in.size(); auto d = ctx->eigen_device<GPUDevice>(); auto* ctx_stream = ctx->op_device_context()->stream(); CudaStream ctx_cu_stream = CudaStream(ctx_stream); CudaStream cu_stream = CudaStream(stream); AllocatorAttributes host_alloc_attrs; host_alloc_attrs.set_on_host(true); host_alloc_attrs.set_gpu_compatible(true); Tensor h_size_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &h_size_t, host_alloc_attrs)); Tensor d_size_t; OP_REQUIRES_OK( ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &d_size_t)); int32* h_size = h_size_t.flat<int32>().data(); int32* d_size = d_size_t.flat<int32>().data(); const int32 buffer_size = static_cast<int32>((sizeof(float*) + sizeof(Eigen::half*)) * num_inputs); Tensor h_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &h_buffer_t, host_alloc_attrs)); Tensor d_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &d_buffer_t)); int8* h_buffer = h_buffer_t.flat<int8>().data(); int8* d_buffer = d_buffer_t.flat<int8>().data(); const float** hd_in = reinterpret_cast<const float**>(h_buffer); const float** dd_in = reinterpret_cast<const float**>(d_buffer); __half** hd_out = reinterpret_cast<__half**>(h_buffer + sizeof(float*) * num_inputs); __half** dd_out = reinterpret_cast<__half**>(h_buffer + sizeof(float*) * num_inputs); size_t max_in_size = 0; for (size_t i = 0; i < num_inputs; ++i) { const size_t size = in[i]->NumElements(); h_size[i] = size; hd_in[i] = in[i]->flat<float>().data(); hd_out[i] = reinterpret_cast<__half*>(out->at(i)->flat<Eigen::half>().data()); if (size > max_in_size) { max_in_size = size; } } ctx_cu_stream.ThenCopyToDevice(d_size, h_size, sizeof(int32) * num_inputs); ctx_cu_stream.ThenCopyToDevice(d_buffer, h_buffer, buffer_size); cu_stream.ThenWaitFor(ctx_cu_stream); auto total_max_in_size = num_inputs * max_in_size; CudaLaunch(GroupCastFp32ToFp16, total_max_in_size, 0, d, stream, total_max_in_size, max_in_size, dd_in, dd_out, d_size); } template struct GroupCast<float, Eigen::half>; __global__ void GroupCastFp16ToFp32(const size_t total_max_in_size, const size_t max_in_size, const __half** dd_in, float** dd_out, const int32* d_size) { for (int32 idx : CudaGridRangeX(total_max_in_size)) { const int32 s = idx / max_in_size; const int32 sidx = idx % max_in_size; if (sidx < ldg(d_size + s)) { dd_out[s][sidx] = __half2float(dd_in[s][sidx]); } } } template <> void GroupCast<Eigen::half, float>::operator()(const std::vector<Tensor>& in, std::vector<Tensor>* out, OpKernelContext* ctx, cudaStream_t* stream) { const int64 num_inputs = in.size(); auto d = ctx->eigen_device<GPUDevice>(); auto* ctx_stream = ctx->op_device_context()->stream(); CudaStream ctx_cu_stream = CudaStream(ctx_stream); CudaStream cu_stream = CudaStream(stream); AllocatorAttributes host_alloc_attrs; host_alloc_attrs.set_on_host(true); host_alloc_attrs.set_gpu_compatible(true); Tensor h_size_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &h_size_t, host_alloc_attrs)); Tensor d_size_t; OP_REQUIRES_OK( ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &d_size_t)); int32* h_size = h_size_t.flat<int32>().data(); int32* d_size = d_size_t.flat<int32>().data(); const int32 buffer_size = static_cast<int32>((sizeof(float*) + sizeof(Eigen::half*)) * num_inputs); Tensor h_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &h_buffer_t, host_alloc_attrs)); Tensor d_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &d_buffer_t)); int8* h_buffer = h_buffer_t.flat<int8>().data(); int8* d_buffer = d_buffer_t.flat<int8>().data(); const __half** hd_in = reinterpret_cast<const __half**>(h_buffer); const __half** dd_in = reinterpret_cast<const __half**>(d_buffer); float** hd_out = reinterpret_cast<float**>(h_buffer + sizeof(Eigen::half*) * num_inputs); float** dd_out = reinterpret_cast<float**>(d_buffer + sizeof(Eigen::half*) * num_inputs); size_t max_in_size = 0; for (size_t i = 0; i < num_inputs; ++i) { const size_t size = in[i].NumElements(); h_size[i] = size; hd_in[i] = reinterpret_cast<const __half*>(in[i].flat<Eigen::half>().data()); hd_out[i] = out->at(i).flat<float>().data(); if (size > max_in_size) { max_in_size = size; } } ctx_cu_stream.ThenCopyToDevice(d_size, h_size, sizeof(int32) * num_inputs); ctx_cu_stream.ThenCopyToDevice(d_buffer, h_buffer, buffer_size); cu_stream.ThenWaitFor(ctx_cu_stream); auto total_max_in_size = num_inputs * max_in_size; CudaLaunch(GroupCastFp16ToFp32, total_max_in_size, 0, d, stream, total_max_in_size, max_in_size, dd_in, dd_out, d_size); } template <> void GroupCast<Eigen::half, float>::operator()(const std::vector<Tensor>& in, std::vector<Tensor*>* out, OpKernelContext* ctx, cudaStream_t* stream) { const int64 num_inputs = in.size(); auto d = ctx->eigen_device<GPUDevice>(); auto* ctx_stream = ctx->op_device_context()->stream(); CudaStream ctx_cu_stream = CudaStream(ctx_stream); CudaStream cu_stream = CudaStream(stream); AllocatorAttributes host_alloc_attrs; host_alloc_attrs.set_on_host(true); host_alloc_attrs.set_gpu_compatible(true); Tensor h_size_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &h_size_t, host_alloc_attrs)); Tensor d_size_t; OP_REQUIRES_OK( ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &d_size_t)); int32* h_size = h_size_t.flat<int32>().data(); int32* d_size = d_size_t.flat<int32>().data(); const int32 buffer_size = static_cast<int32>((sizeof(float*) + sizeof(Eigen::half*)) * num_inputs); Tensor h_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &h_buffer_t, host_alloc_attrs)); Tensor d_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &d_buffer_t)); int8* h_buffer = h_buffer_t.flat<int8>().data(); int8* d_buffer = d_buffer_t.flat<int8>().data(); const __half** hd_in = reinterpret_cast<const __half**>(h_buffer); const __half** dd_in = reinterpret_cast<const __half**>(d_buffer); float** hd_out = reinterpret_cast<float**>(h_buffer + sizeof(Eigen::half*) * num_inputs); float** dd_out = reinterpret_cast<float**>(d_buffer + sizeof(Eigen::half*) * num_inputs); size_t max_in_size = 0; for (size_t i = 0; i < num_inputs; ++i) { const size_t size = in[i].NumElements(); h_size[i] = size; hd_in[i] = reinterpret_cast<const __half*>(in[i].flat<Eigen::half>().data()); hd_out[i] = out->at(i)->flat<float>().data(); if (size > max_in_size) { max_in_size = size; } } ctx_cu_stream.ThenCopyToDevice(d_size, h_size, sizeof(int32) * num_inputs); ctx_cu_stream.ThenCopyToDevice(d_buffer, h_buffer, buffer_size); cu_stream.ThenWaitFor(ctx_cu_stream); auto total_max_in_size = num_inputs * max_in_size; CudaLaunch(GroupCastFp16ToFp32, total_max_in_size, 0, d, stream, total_max_in_size, max_in_size, dd_in, dd_out, d_size); } template <> void GroupCast<Eigen::half, float>::operator()(const std::vector<Tensor*>& in, std::vector<Tensor*>* out, OpKernelContext* ctx, cudaStream_t* stream) { const int64 num_inputs = in.size(); auto d = ctx->eigen_device<GPUDevice>(); auto* ctx_stream = ctx->op_device_context()->stream(); CudaStream ctx_cu_stream = CudaStream(ctx_stream); CudaStream cu_stream = CudaStream(stream); AllocatorAttributes host_alloc_attrs; host_alloc_attrs.set_on_host(true); host_alloc_attrs.set_gpu_compatible(true); Tensor h_size_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &h_size_t, host_alloc_attrs)); Tensor d_size_t; OP_REQUIRES_OK( ctx, ctx->allocate_temp(DT_INT32, TensorShape({num_inputs}), &d_size_t)); int32* h_size = h_size_t.flat<int32>().data(); int32* d_size = d_size_t.flat<int32>().data(); const int32 buffer_size = static_cast<int32>((sizeof(float*) + sizeof(Eigen::half*)) * num_inputs); Tensor h_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &h_buffer_t, host_alloc_attrs)); Tensor d_buffer_t; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_INT8, TensorShape({buffer_size}), &d_buffer_t)); int8* h_buffer = h_buffer_t.flat<int8>().data(); int8* d_buffer = d_buffer_t.flat<int8>().data(); const __half** hd_in = reinterpret_cast<const __half**>(h_buffer); const __half** dd_in = reinterpret_cast<const __half**>(d_buffer); float** hd_out = reinterpret_cast<float**>(h_buffer + sizeof(Eigen::half*) * num_inputs); float** dd_out = reinterpret_cast<float**>(d_buffer + sizeof(Eigen::half*) * num_inputs); size_t max_in_size = 0; for (size_t i = 0; i < num_inputs; ++i) { const size_t size = in[i]->NumElements(); h_size[i] = size; hd_in[i] = reinterpret_cast<const __half*>(in[i]->flat<Eigen::half>().data()); hd_out[i] = out->at(i)->flat<float>().data(); if (size > max_in_size) { max_in_size = size; } } ctx_cu_stream.ThenCopyToDevice(d_size, h_size, sizeof(int32) * num_inputs); ctx_cu_stream.ThenCopyToDevice(d_buffer, h_buffer, buffer_size); cu_stream.ThenWaitFor(ctx_cu_stream); auto total_max_in_size = num_inputs * max_in_size; CudaLaunch(GroupCastFp16ToFp32, total_max_in_size, 0, d, stream, total_max_in_size, max_in_size, dd_in, dd_out, d_size); } template struct GroupCast<Eigen::half, float>; } // namespace functor } // namespace hybridbackend } // namespace tensorflow #endif // GOOGLE_CUDA #endif // HYBRIDBACKEND_TENSORFLOW
39.947896
80
0.637855
[ "vector" ]
00ee6120789022dbdea437494fd6051a9e8c8191
4,519
cpp
C++
lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.cpp
rjordans/avr-llvm
1802f85a455fbbe5fd1b55183bf588e2e4731dc5
[ "FSFAP" ]
1
2021-01-07T11:56:45.000Z
2021-01-07T11:56:45.000Z
lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.cpp
rjordans/avr-llvm
1802f85a455fbbe5fd1b55183bf588e2e4731dc5
[ "FSFAP" ]
null
null
null
lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.cpp
rjordans/avr-llvm
1802f85a455fbbe5fd1b55183bf588e2e4731dc5
[ "FSFAP" ]
null
null
null
//===-- AVRMCTargetDesc.cpp - AVR Target Descriptions ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides AVR specific target descriptions. // //===----------------------------------------------------------------------===// #include "AVRMCTargetDesc.h" #include "llvm/MC/MCCodeGenInfo.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCELFStreamer.h" #include "llvm/Support/TargetRegistry.h" #include "AVRMCAsmInfo.h" #include "AVRTargetStreamer.h" #include "InstPrinter/AVRInstPrinter.h" #define GET_INSTRINFO_MC_DESC #include "AVRGenInstrInfo.inc" #define GET_SUBTARGETINFO_MC_DESC #include "AVRGenSubtargetInfo.inc" #define GET_REGINFO_MC_DESC #include "AVRGenRegisterInfo.inc" namespace llvm { static MCInstrInfo *createAVRMCInstrInfo() { MCInstrInfo *X = new MCInstrInfo(); InitAVRMCInstrInfo(X); return X; } static MCRegisterInfo *createAVRMCRegisterInfo(const Triple &TT) { MCRegisterInfo *X = new MCRegisterInfo(); InitAVRMCRegisterInfo(X, 0); return X; } static MCSubtargetInfo *createAVRMCSubtargetInfo(const Triple &TT, StringRef CPU, StringRef FS) { return createAVRMCSubtargetInfoImpl(TT, CPU, FS); } static MCCodeGenInfo *createAVRMCCodeGenInfo(const Triple &TT, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) { MCCodeGenInfo *X = new MCCodeGenInfo(); X->initMCCodeGenInfo(RM, CM, OL); return X; } static MCInstPrinter *createAVRMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) { if (SyntaxVariant == 0) { return new AVRInstPrinter(MAI, MII, MRI); } return 0; } static MCStreamer *createMCStreamer(const Triple &T, MCContext &Context, MCAsmBackend &MAB, raw_pwrite_stream &OS, MCCodeEmitter *Emitter, bool RelaxAll) { return createELFStreamer(Context, MAB, OS, Emitter, RelaxAll); } static MCTargetStreamer * createAVRObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo &STI) { return new AVRTargetELFStreamer(S, STI); } static MCTargetStreamer *createMCAsmTargetStreamer(MCStreamer &S, formatted_raw_ostream &OS, MCInstPrinter *InstPrint, bool isVerboseAsm) { return new AVRTargetAsmStreamer(S); } extern "C" void LLVMInitializeAVRTargetMC() { // Register the MC asm info. RegisterMCAsmInfo<AVRMCAsmInfo> X(TheAVRTarget); // Register the MC codegen info. TargetRegistry::RegisterMCCodeGenInfo(TheAVRTarget, createAVRMCCodeGenInfo); // Register the MC instruction info. TargetRegistry::RegisterMCInstrInfo(TheAVRTarget, createAVRMCInstrInfo); // Register the MC register info. TargetRegistry::RegisterMCRegInfo(TheAVRTarget, createAVRMCRegisterInfo); // Register the MC subtarget info. TargetRegistry::RegisterMCSubtargetInfo(TheAVRTarget, createAVRMCSubtargetInfo); // Register the MCInstPrinter. TargetRegistry::RegisterMCInstPrinter(TheAVRTarget, createAVRMCInstPrinter); // Register the MC Code Emitter TargetRegistry::RegisterMCCodeEmitter(TheAVRTarget, createAVRMCCodeEmitter); // Register the ELF streamer TargetRegistry::RegisterELFStreamer(TheAVRTarget, createMCStreamer); // Register the obj target streamer. TargetRegistry::RegisterObjectTargetStreamer(TheAVRTarget, createAVRObjectTargetStreamer); // Register the asm target streamer. TargetRegistry::RegisterAsmTargetStreamer(TheAVRTarget, createMCAsmTargetStreamer); // Register the asm backend (as little endian). TargetRegistry::RegisterMCAsmBackend(TheAVRTarget, createAVRAsmBackend); } } // end of namespace llvm
33.474074
80
0.629564
[ "model" ]
00ef4f9f49a3dc36d74b38ee51250defb4804672
12,971
cpp
C++
benchmark_apps/elmerfem/ElmerGUI/netgen/libsrc/interface/writejcm.cpp
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
2
2020-11-25T13:10:11.000Z
2021-03-15T20:26:35.000Z
elmerfem/ElmerGUI/netgen/libsrc/interface/writejcm.cpp
jcmcmurry/pipelining
8fface1a501b5050f58e7b902aacdcdde68e9648
[ "MIT" ]
null
null
null
elmerfem/ElmerGUI/netgen/libsrc/interface/writejcm.cpp
jcmcmurry/pipelining
8fface1a501b5050f58e7b902aacdcdde68e9648
[ "MIT" ]
2
2021-08-02T23:23:40.000Z
2022-02-26T12:39:30.000Z
// // Write JCMwave file // 07.07.2005, Sven Burger, ZIB Berlin // #include <mystdlib.h> #include <myadt.hpp> #include <linalg.hpp> #include <csg.hpp> #include <meshing.hpp> #include <sys/stat.h> namespace netgen { #include "writeuser.hpp" void WriteJCMFormat (const Mesh & mesh, const CSGeometry & geom, const string & filename) { if (mesh.GetDimension() != 3) { cout <<"\n Error: Dimension 3 only supported by this output format!"<<endl; return; } int bc_at_infinity = 0; int i, j, jj, ct(0), counter; double dx1, dx2, dx3, dy1, dy2, dy3, dz1, dz2, dz3, vol; // number of points int np = mesh.GetNP(); // Identic points ARRAY<int,1> identmap1, identmap2, identmap3; mesh.GetIdentifications().GetMap(1, identmap1); mesh.GetIdentifications().GetMap(2, identmap2); mesh.GetIdentifications().GetMap(3, identmap3); // number of volume elements int ne = mesh.GetNE(); int ntets = 0; int nprisms = 0; for (i = 1; i <= ne; i++) { Element el = mesh.VolumeElement(i); if (el.GetNP() == 4) { ntets++; // Check that no two points on a tetrahedron are identified with each other for (j = 1; j <= 4; j++) for (jj = 1; jj <=4; jj++) { if (identmap1.Elem(el.PNum(j)) == el.PNum(jj)) { cout << "\n Error: two points on a tetrahedron identified (1) with each other" << "\n REFINE MESH !" << endl; return; } if (identmap2.Elem(el.PNum(j)) == el.PNum(jj)) { cout << "\n Error: two points on a tetrahedron identified (2) with each other" << "\n REFINE MESH !" << endl; return; } if (identmap3.Elem(el.PNum(j)) == el.PNum(jj)) { cout << "\n Error: two points on a tetrahedron identified (3) with each other" << "\n REFINE MESH !" << endl; return; } } } else if (el.GetNP() == 6) nprisms++; } if ( ne != (ntets+nprisms)) { cout<< "\n Error in determining number of volume elements!\n" << "\n Prisms and tetrahedra only implemented in the JCMwave format!\n"<<endl; return; } if (nprisms > 0) cout << " Please note: Boundaries at infinity have to carry the bc-attribute '-bc=" << bc_at_infinity <<"'."<<endl; // number of surface elements int nse = mesh.GetNSE(); // number of boundary triangles int nbtri = 0; // number of boundary quadrilaterals int nbquad = 0; // array with 1 if point on any tetra, 0 else // this is needed in order to arrange the prism points in the right order ARRAY<int,1> pointsOnTetras; pointsOnTetras.SetSize (mesh.GetNP()); pointsOnTetras = 0; for (i = 1; i <= ne; i++) { Element el = mesh.VolumeElement(i); if (el.GetNP() == 4) { for (j = 1; j <= 4; j++) pointsOnTetras.Set(el.PNum(j).GetInt(),1); } } // number of boundary triangles and boundary quadrilaterals for (i = 1; i <= nse; i++) { Element2d el = mesh.SurfaceElement(i); if (el.GetNP() == 3 && ( mesh.GetFaceDescriptor (el.GetIndex()).DomainIn()==0 || mesh.GetFaceDescriptor (el.GetIndex()).DomainOut()==0 ) ) nbtri++; else if (el.GetNP() == 4 && ( mesh.GetFaceDescriptor (el.GetIndex()).DomainIn()==0 || mesh.GetFaceDescriptor (el.GetIndex()).DomainOut()==0 ) ) nbquad++; } ofstream outfile (filename.c_str()); outfile.precision(6); outfile.setf (ios::fixed, ios::floatfield); outfile.setf (ios::showpoint); outfile << "/* <BLOBHead>\n"; outfile << "__BLOBTYPE__=Grid\n"; outfile << "__OWNER__=JCMwave\n"; outfile << "<I>SpaceDim=3\n"; outfile << "<I>ManifoldDim=3\n"; outfile << "<I>NRefinementSteps=0\n"; outfile << "<I>NPoints="<<np<<"\n"; outfile << "<I>NTetrahedra="<<ntets<<"\n"; outfile << "<I>NPrisms="<<nprisms<<"\n"; outfile << "<I>NBoundaryTriangles="<<nbtri<<"\n"; outfile << "<I>NBoundaryQuadrilaterals="<<nbquad<<"\n"; outfile << "*/\n"; outfile << "\n"; outfile << "# output from Netgen\n\n"; int nDomains=mesh.GetNDomains(); for (i=1; i<=nDomains; i++) { if (mesh.GetMaterial(i)) outfile << "#" << mesh.GetMaterial(i) << ": Material ID = " << i << "\n"; } outfile << "# Points\n"; cout << " Please note: The unit of length in the .geo file is assumed to be 'microns'."<<endl; for (i = 1; i <= np; i++) { const Point<3> & p = mesh.Point(i); outfile << i << "\n"; outfile << p(0) << "e-6\n"; outfile << p(1) << "e-6\n"; outfile << p(2) << "e-6\n\n"; } outfile << "\n"; outfile << "# Tetrahedra\n"; counter = 0; for (i = 1; i <= ne; i++) { Element el = mesh.VolumeElement(i); if (el.GetNP() == 4) { counter++; dx1 = mesh.Point(el.PNum(2))(0) - mesh.Point(el.PNum(1))(0); dx2 = mesh.Point(el.PNum(3))(0) - mesh.Point(el.PNum(1))(0); dx3 = mesh.Point(el.PNum(4))(0) - mesh.Point(el.PNum(1))(0); dy1 = mesh.Point(el.PNum(2))(1) - mesh.Point(el.PNum(1))(1); dy2 = mesh.Point(el.PNum(3))(1) - mesh.Point(el.PNum(1))(1); dy3 = mesh.Point(el.PNum(4))(1) - mesh.Point(el.PNum(1))(1); dz1 = mesh.Point(el.PNum(2))(2) - mesh.Point(el.PNum(1))(2); dz2 = mesh.Point(el.PNum(3))(2) - mesh.Point(el.PNum(1))(2); dz3 = mesh.Point(el.PNum(4))(2) - mesh.Point(el.PNum(1))(2); vol = (dy1*dz2-dz1*dy2)*dx3 + (dz1*dx2-dx1*dz2)*dy3 + (dx1*dy2-dy1*dx2)*dz3; if ( vol > 0 ) for (j = 1; j <= 4; j++) outfile << el.PNum(j)<<"\n"; else { for (j = 2; j >= 1; j--) outfile << el.PNum(j)<<"\n"; for (j = 3; j <= 4; j++) outfile << el.PNum(j)<<"\n"; } outfile << el.GetIndex() << "\n\n"; } } if ( counter != ntets) { cout<< "\n Error in determining number of tetras!\n"<<endl; return; } outfile << "\n"; outfile << "# Prisms\n"; counter = 0; for (i = 1; i <= ne; i++) { Element el = mesh.VolumeElement(i); if (el.GetNP() == 6) { counter++; dx1 = mesh.Point(el.PNum(2))(0) - mesh.Point(el.PNum(1))(0); dx2 = mesh.Point(el.PNum(3))(0) - mesh.Point(el.PNum(1))(0); dx3 = mesh.Point(el.PNum(4))(0) - mesh.Point(el.PNum(1))(0); dy1 = mesh.Point(el.PNum(2))(1) - mesh.Point(el.PNum(1))(1); dy2 = mesh.Point(el.PNum(3))(1) - mesh.Point(el.PNum(1))(1); dy3 = mesh.Point(el.PNum(4))(1) - mesh.Point(el.PNum(1))(1); dz1 = mesh.Point(el.PNum(2))(2) - mesh.Point(el.PNum(1))(2); dz2 = mesh.Point(el.PNum(3))(2) - mesh.Point(el.PNum(1))(2); dz3 = mesh.Point(el.PNum(4))(2) - mesh.Point(el.PNum(1))(2); vol = (dy1*dz2-dz1*dy2)*dx3 + (dz1*dx2-dx1*dz2)*dy3 + (dx1*dy2-dy1*dx2)*dz3; if (pointsOnTetras.Get(el.PNum(1)) && pointsOnTetras.Get(el.PNum(2)) && pointsOnTetras.Get(el.PNum(3))) { if (vol > 0) for (j = 1; j <= 6; j++) outfile << el.PNum(j)<<"\n"; else { for (j = 3; j >= 1; j--) outfile << el.PNum(j)<<"\n"; for (j = 6; j >= 4; j--) outfile << el.PNum(j)<<"\n"; } } else if ( pointsOnTetras.Get(el.PNum(4)) && pointsOnTetras.Get(el.PNum(5)) && pointsOnTetras.Get(el.PNum(6)) ) { if ( vol < 0 ) { for (j = 4; j <= 6; j++) outfile << el.PNum(j)<<"\n"; for (j = 1; j <= 3; j++) outfile << el.PNum(j)<<"\n"; } else { for (j = 6; j >= 4; j--) outfile << el.PNum(j)<<"\n"; for (j = 3; j >= 1; j--) outfile << el.PNum(j)<<"\n"; } } else { cout << "\n Error in determining prism point numbering!\n"<<endl; return; } outfile << el.GetIndex() << "\n\n"; } } if ( counter != nprisms) { cout<< "\n Error in determining number of prisms!\n"<<endl; return; } int npid1 = 0; int npid2 = 0; int npid3 = 0; for (i=1; i<=np; i++) { if (identmap1.Elem(i)) npid1++; if (identmap2.Elem(i)) npid2++; if (identmap3.Elem(i)) npid3++; } outfile << "\n"; outfile << "# Boundary triangles\n"; outfile << "# Number of identified points in 1-direction: " << npid1 << "\n"; outfile << "# Number of identified points in 2-direction: " << npid2 << "\n"; outfile << "# Number of identified points in 3-direction: " << npid3 << "\n"; for (i = 1; i <= nse; i++) { Element2d el = mesh.SurfaceElement(i); if (el.GetNP() == 3 && (mesh.GetFaceDescriptor (el.GetIndex()).DomainIn()==0 || mesh.GetFaceDescriptor (el.GetIndex()).DomainOut()==0)) { outfile <<"# T\n"; for (j = 1; j <= 3; j++) outfile << el.PNum(j)<<"\n"; if (mesh.GetFaceDescriptor (el.GetIndex()).BCProperty()==bc_at_infinity) outfile << 1000 << "\n"; else outfile << mesh.GetFaceDescriptor (el.GetIndex()).BCProperty() << "\n"; if (mesh.GetFaceDescriptor (el.GetIndex()).BCProperty() == bc_at_infinity) outfile << "-2\n\n"; else if (identmap1.Elem(el.PNum(1)) &&identmap1.Elem(el.PNum(2)) &&identmap1.Elem(el.PNum(3))) { outfile << "-1\n"; for (j = 1; j <= 3; j++) outfile << identmap1.Elem(el.PNum(j))<<"\n"; outfile << "\n"; } else if (identmap2.Elem(el.PNum(1)) &&identmap2.Elem(el.PNum(2)) &&identmap2.Elem(el.PNum(3))) { outfile << "-1\n"; for (j = 1; j <= 3; j++) outfile << identmap2.Elem(el.PNum(j))<<"\n"; outfile << "\n"; } else if (identmap3.Elem(el.PNum(1)) &&identmap3.Elem(el.PNum(2)) &&identmap3.Elem(el.PNum(3))) { outfile << "-1\n"; for (j = 1; j <= 3; j++) outfile << identmap3.Elem(el.PNum(j))<<"\n"; outfile << "\n"; } else outfile << "1\n\n"; } } outfile << "\n"; outfile << "# Boundary quadrilaterals\n"; for (i = 1; i <= nse; i++) { Element2d el = mesh.SurfaceElement(i); if (el.GetNP() == 4 && (mesh.GetFaceDescriptor (el.GetIndex()).DomainIn()==0 || mesh.GetFaceDescriptor (el.GetIndex()).DomainOut()==0)) { if (pointsOnTetras.Get(el.PNum(1)) && pointsOnTetras.Get(el.PNum(2))) ct = 0; else if (pointsOnTetras.Get(el.PNum(2)) && pointsOnTetras.Get(el.PNum(3))) ct = 1; else if (pointsOnTetras.Get(el.PNum(3)) && pointsOnTetras.Get(el.PNum(4))) ct = 2; else if (pointsOnTetras.Get(el.PNum(4)) && pointsOnTetras.Get(el.PNum(1))) ct = 3; else cout << "\nWarning: Quadrilateral with inconsistent points found!"<<endl; for (j = 1; j <= 4; j++) { jj = j + ct; if ( jj >= 5 ) jj = jj - 4; outfile << el.PNum(jj)<<"\n"; } outfile << mesh.GetFaceDescriptor (el.GetIndex()).BCProperty() << "\n"; if (mesh.GetFaceDescriptor (el.GetIndex()).BCProperty() == bc_at_infinity) { outfile << "-2\n\n"; cout << "\nWarning: Quadrilateral at infinity found (this should not occur)!"<<endl; } else if ( identmap1.Elem(el.PNum(1)) && identmap1.Elem(el.PNum(2)) && identmap1.Elem(el.PNum(3)) && identmap1.Elem(el.PNum(4)) ) { outfile << "-1\n"; for (j = 1; j <= 4; j++) { jj = j + ct; if ( jj >= 5 ) jj = jj - 4; outfile << identmap1.Elem(el.PNum(jj))<<"\n"; } outfile << "\n"; } else if ( identmap2.Elem(el.PNum(1)) && identmap2.Elem(el.PNum(2)) && identmap2.Elem(el.PNum(3)) && identmap2.Elem(el.PNum(4)) ) { outfile << "-1\n"; for (j = 1; j <= 4; j++) { jj = j + ct; if ( jj >= 5 ) jj = jj - 4; outfile << identmap2.Elem(el.PNum(jj))<<"\n"; } outfile << "\n"; } else if ( identmap3.Elem(el.PNum(1)) && identmap3.Elem(el.PNum(2)) && identmap3.Elem(el.PNum(3)) && identmap3.Elem(el.PNum(4)) ) { outfile << "-1\n"; for (j = 1; j <= 4; j++) { jj = j + ct; if ( jj >= 5 ) jj = jj - 4; outfile << identmap3.Elem(el.PNum(jj))<<"\n"; } outfile << "\n"; } else outfile << "1\n\n"; } } cout << " JCMwave grid file written." << endl; } }
30.095128
97
0.491096
[ "mesh" ]
00f1bc9afeaa95f2f481a2c71a9f26b3ac8d8c98
16,348
hpp
C++
lib/include/libvideostitch/quaternion.hpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
lib/include/libvideostitch/quaternion.hpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
lib/include/libvideostitch/quaternion.hpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #ifndef QUATERNION_HPP_ #define QUATERNION_HPP_ #include "matrix.hpp" #include "config.hpp" #include "assert.h" #include <cmath> #include <iosfwd> namespace VideoStitch { /** * @brief A quaternion class. */ template <typename T> class VS_EXPORT Quaternion { public: /** * Creates a unit quaternion (1). */ Quaternion() { // yaw = pitch = roll = 0 q0 = 1; q1 = q2 = q3 = 0; } /** * Creates a quaternion with given components. * @param q0 Real component * @param q1 i component * @param q2 j component * @param q3 k component */ Quaternion(const T q0, const T q1, const T q2, const T q3) : q0(q0), q1(q1), q2(q2), q3(q3) {} /** * @brief Gives vector-like access to quaternion elements * @param i * 0: returns q0 (usually you should be using the method this->getQ0() instead) * 1: returns q1 (usually you should be using the method this->getQ1() instead) * 2: returns q2 (usually you should be using the method this->getQ2() instead) * 3: returns q3 (usually you should be using the method this->getQ3() instead) * * Any other value for @param i is invalid and will return a NaN */ T getQ(int i) const { if (i == 0) { return q0; } if (i == 1) { return q1; } if (i == 2) { return q2; } if (i == 3) { return q3; } assert(false); return std::numeric_limits<T>::quiet_NaN(); } /** * Scalar multiplication. * @param s scale factor */ Quaternion operator*(const T s) const { return Quaternion(q0 * s, q1 * s, q2 * s, q3 * s); } /** * Scalar multiply/assign. * @param s scale factor */ void operator*=(const T s) { q0 *= s; q1 *= s; q2 *= s; q3 *= s; } /** * Scalar division. * @param s inverse scale factor */ Quaternion operator/(const T s) const { return Quaternion(q0 / s, q1 / s, q2 / s, q3 / s); } /** * Scalar division. * @param s inverse scale factor */ void operator/=(const T s) { q0 /= s; q1 /= s; q2 /= s; q3 /= s; } /** * Equality operator. * WARNING: exact equality. * @param rhs right hand side */ bool operator==(const Quaternion& rhs) const { return ((q0 - rhs.q0 == 0.0 && q1 - rhs.q1 == 0.0 && q2 - rhs.q2 == 0.0 && q3 - rhs.q3 == 0.0) || (q0 + rhs.q0 == 0.0 && q1 + rhs.q1 == 0.0 && q2 + rhs.q2 == 0.0 && q3 + rhs.q3 == 0.0)); } /** * Addition. Commutative. * @param rhs right hand side */ Quaternion operator+(const Quaternion& rhs) const { return Quaternion(q0 + rhs.q0, q1 + rhs.q1, q2 + rhs.q2, q3 + rhs.q3); } /** * Add/assign. * @param rhs right hand side */ void operator+=(const Quaternion& rhs) { q0 += rhs.q0; q1 += rhs.q1; q2 += rhs.q2; q3 += rhs.q3; } /** * Subtraction. Commutative. * @param rhs right hand side */ Quaternion operator-(const Quaternion& rhs) const { return Quaternion(q0 - rhs.q0, q1 - rhs.q1, q2 - rhs.q2, q3 - rhs.q3); } /** * Subtract/assign. * @param rhs right hand side */ void operator-=(const Quaternion& rhs) { q0 -= rhs.q0; q1 -= rhs.q1; q2 -= rhs.q2; q3 -= rhs.q3; } /** * Returns the opposite quaternion; */ Quaternion operator-() const { return Quaternion(-q0, -q1, -q2, -q3); ; } /** * @brief negate * * if q is a rotation quaternion, then q.negate() represents the same rotation */ void negate() { q0 = -q0; q1 = -q1; q2 = -q2; q3 = -q3; } /** * Dot product. Commutative. * @param rhs right hand side */ T dot(const Quaternion& rhs) const { return q0 * rhs.q0 + q1 * rhs.q1 + q2 * rhs.q2 + q3 * rhs.q3; } /** * Cross product. * WARNING: Multiply semantics are q * r * @param rhs right hand side */ Quaternion operator*(const Quaternion& rhs) const { return Quaternion(this->q0 * rhs.q0 - this->q1 * rhs.q1 - this->q2 * rhs.q2 - this->q3 * rhs.q3, this->q0 * rhs.q1 + this->q1 * rhs.q0 + this->q2 * rhs.q3 - this->q3 * rhs.q2, this->q0 * rhs.q2 - this->q1 * rhs.q3 + this->q2 * rhs.q0 + this->q3 * rhs.q1, this->q0 * rhs.q3 + this->q1 * rhs.q2 - this->q2 * rhs.q1 + this->q3 * rhs.q0); } /** * Cross product / assign. * WARNING: Multiply semantics are q * r * @param rhs right hand side */ void operator*=(const Quaternion& rhs) { const T mq0 = this->q0 * rhs.q0 - this->q1 * rhs.q1 - this->q2 * rhs.q2 - this->q3 * rhs.q3; const T mq1 = this->q0 * rhs.q1 + this->q1 * rhs.q0 + this->q2 * rhs.q3 - this->q3 * rhs.q2; const T mq2 = this->q0 * rhs.q2 - this->q1 * rhs.q3 + this->q2 * rhs.q0 + this->q3 * rhs.q1; const T mq3 = this->q0 * rhs.q3 + this->q1 * rhs.q2 - this->q2 * rhs.q1 + this->q3 * rhs.q0; q0 = mq0; q1 = mq1; q2 = mq2; q3 = mq3; } /** * Conjugation. Note that this is NOT in place. */ Quaternion conjugate() const { return Quaternion(this->q0, -this->q1, -this->q2, -this->q3); } /** * Norm. */ T norm() const { return std::sqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3); } /** * Normalize. Note that this is NOT in place. */ Quaternion normalize() { return *this / norm(); } /** * Normalize. Note that this is NOT in place. * Note: if the quaternion is known to be an unit quaternion, * use the conjugate directly */ Quaternion inverse() const { return conjugate() / norm(); } /** * Exponential. Note that typical formulas (e.g. exp(a+b) = exp(a)exp(b)) don't hold because of non-commutativity. */ Quaternion exp() const { T angle = std::sqrt(q1 * q1 + q2 * q2 + q3 * q3); T sin = std::sin(angle); if (sin != 0.0) { T coeff = sin / angle; return Quaternion(std::cos(angle), coeff * q1, coeff * q2, coeff * q3); } return Quaternion(); } /** * Log. Note that typical formulas (e.g. log(a * b) = log(a)+ log(b)) don't hold because of non-commutativity. */ Quaternion log() const { if (q1 == 0.0 && q2 == 0.0 && q3 == 0.0) { if (q0 > 0.0) { return Quaternion(::log(q0), 0.0, 0.0, 0.0); } else if (q0 < 0.0) { return Quaternion(::log(-q0), M_PI, 0.0, 0.0); } else { return Quaternion(std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity()); } } else { T imag = std::sqrt(q1 * q1 + q2 * q2 + q3 * q3); T norm = std::sqrt(imag * imag + q0 * q0); T t = std::atan2(imag, T(q0)) / imag; return Quaternion(::log(norm), t * q1, t * q2, t * q3); } } /** * @brief Initialize a rotation quaternion from an axis-angle representation * ||v|| is the angle * v / ||v|| is the axis */ static Quaternion fromAxisAngle(const Vector3<T>& v) { T angle = v.norm(); if (angle < 1e-6) { Quaternion<T> q; return q; } Quaternion q(std::cos(angle / 2), std::sin(angle / 2) * v(0) / angle, std::sin(angle / 2) * v(1) / angle, std::sin(angle / 2) * v(2) / angle); if (q.q0 < 0) { q.negate(); } return q; } /** * @brief toAxisAngle * @return axis angle representation * * The norm of the returned vector is the angle. The direction is the rotation axis. * This quaternion must be a rotation quaternion (norm 1). Otherwise, the null vector (0, 0 ,0) is returned */ Vector3<T> toAxisAngle() const { T x, y, z; if (std::abs(this->norm() - 1) > 1e-3) { return Vector3<T>(0, 0, 0); } T angle = std::acos(q0); if (angle > M_PI / 2) { angle = 2 * angle - 2 * M_PI; } else { angle = 2 * angle; } T normV = std::sqrt(1 - q0 * q0); x = q1 / normV; y = q2 / normV; z = q3 / normV; return Vector3<T>(x * angle, y * angle, z * angle); } /** * @brief rotate rhs using this as the rotation * @param rhs quaternion to be rotated around this * @return rotated quaternion * * this must be a rotation quaternion (norm 1). Otherwise (1, 0, 0, 0) is returned * rhs.q0 must be 0 (pure imaginary quaternion). Otherwise (1, 0, 0, 0) is returned */ Quaternion<T> rotate(const Quaternion<T>& rhs) const { if (std::abs(norm() - 1) > 1e-6) { return Quaternion<T>(); } if (std::abs(rhs.q0) > 1e-6) { return Quaternion<T>(); } return ((*this) * (rhs * conjugate())); } // ------------------- Conversions to Euler angles ------------ // ftp://sbai2009.ene.unb.br/Projects/GPS-IMU/George/arquivos/Bibliografia/79.pdf // // We're using the Body 3-1-2 euler angle sequence in VideoStitch // In addition, we use the convention that rotation rotates the axes, not // the object, so the above formulae actually give the inverse rotation. /** * Creates from euler angles. * @param yaw yaw * @param pitch pitch * @param roll roll */ static Quaternion fromEulerZXY(const T yaw, const T pitch, const T roll) { const T cy = std::cos(yaw * 0.5); const T cp = std::cos(pitch * 0.5); const T cr = std::cos(roll * 0.5); const T sy = std::sin(yaw * 0.5); const T sp = std::sin(pitch * 0.5); const T sr = std::sin(roll * 0.5); Quaternion<T> q = Quaternion(-cr * cp * cy - sr * sp * sy, cr * cy * sp + sr * cp * sy, cr * cp * sy - sr * cy * sp, -cr * sp * sy + cp * cy * sr); if (q.q0 < 0) { q.negate(); } return q; } /** * @brief Creates a rotation quaternion from a 3x3 rotation matrix * @param R: rotation matrix * @return unit quaternion which represents the same rotation */ static Quaternion fromRotationMatrix(const Matrix33<double>& R) { T yaw = 0, pitch = 0, roll = 0; R.toEuler(yaw, pitch, roll); return fromEulerZXY(yaw, pitch, roll); } /** * Converts to (canonical) Euler angles. * @param yaw output yaw * @param pitch output pitch * @param roll output roll */ void toEuler(T& yaw, T& pitch, T& roll) const { // Body 3-1-2 yaw = std::atan2(2.0 * (q1 * q3 - q0 * q2), q3 * q3 - q2 * q2 - q1 * q1 + q0 * q0); pitch = -std::asin(2.0 * (q2 * q3 + q0 * q1)); roll = std::atan2(2.0 * (q1 * q2 - q0 * q3), q2 * q2 - q3 * q3 + q0 * q0 - q1 * q1); } /** * Converts to a (euler) rotation matrix. */ Matrix33<double> toRotationMatrix() const { const T q0q0 = q0 * q0; const T q0q1 = q0 * q1; const T q0q2 = q0 * q2; const T q0q3 = q0 * q3; const T q1q1 = q1 * q1; const T q1q2 = q1 * q2; const T q1q3 = q1 * q3; const T q2q2 = q2 * q2; const T q2q3 = q2 * q3; const T q3q3 = q3 * q3; return Matrix33<double>(q0q0 + q1q1 - q2q2 - q3q3, 2 * q1q2 - 2 * q0q3, 2 * q1q3 + 2 * q0q2, 2 * q1q2 + 2 * q0q3, q0q0 - q1q1 + q2q2 - q3q3, 2 * q2q3 - 2 * q0q1, 2 * q1q3 - 2 * q0q2, 2 * q2q3 + 2 * q0q1, q0q0 - q1q1 - q2q2 + q3q3); } /** * Find a quaternion representing the rotation between two 3D vectors */ static Quaternion fromTwoVectors(const Vector3<T>& v0, const Vector3<T>& v1) { Vector3<T> v0_normalized = v0; v0_normalized.normalize(); Vector3<T> v1_normalized = v1; v1_normalized.normalize(); const Vector3<T> w = crossVector(v0_normalized, v1_normalized); const T d01 = dotVector(v0_normalized, v1_normalized); Quaternion q = Quaternion(1.f + d01, w(0), w(1), w(2)); return q.normalize(); } // ------------------- Interpolations -------------------------- // Ken Shoemake. Animating rotation with quaternion curves, SIGGRAPH '85 /** * Spherical linear interpolation * @param q0 quaternion at t=0 * @param q1 quaternion at t=1 * @param t interpolation time in [0;1] */ static Quaternion slerp(const Quaternion& q0, Quaternion q1, const T t) { T dot = q0.dot(q1); if (dot < 0.0) { // because the covering is double (q and -q map to the same rotation), the rotation path may turn either the // "short way" (less than 180°) or the "long way" (more than 180°). long paths can be prevented by negating one // end if the dot product, cos Ω, is negative, thus ensuring that −90° ≤ Ω ≤ 90°. dot = -dot; q1 = -q1; // TODO: q1.negate() instead would be faster } const double omega = std::acos(dot); if (VS_ISNAN(omega) || std::abs(omega) < 1e-10) { // if the orientations are too close // fallback to linear interpolation const Quaternion<double> linint = q0 + t * (q1 - q0); return linint / linint.norm(); } const double som = std::sin(omega); const double st0 = std::sin((1 - t) * omega) / som; const double st1 = std::sin(t * omega) / som; return q0 * st0 + st1 * q1; } /** * Spherical centripetal catmull-rom interpolation (deprecated) * * This function is deprecated. Use catmullRom() instead. * * @param q00 quaternion at previous time * @param q01 quaternion at time t=time1 * @param time1 time for q01 * @param q02 quaternion at time t=time2 * @param time2 time for q02 * @param q03 quaternion at next time * @param time query time, in [time1;time2] */ static Quaternion catmullRom_deprecated(const Quaternion& q00, Quaternion q01, const T time1, Quaternion q02, const T time2, Quaternion q03, const T time) { const T t0 = 0; T dot = q00.dot(q01); if (dot < 0.0) { dot = -dot; q01 = -q01; } if (dot > 1.0) { dot = 1.0; } const T t1 = t0 + std::sqrt(std::acos(dot)); dot = q01.dot(q02); if (dot < 0.0) { dot = -dot; q02 = -q02; } if (dot > 1.0) { dot = 1.0; } const T t2 = t1 + std::sqrt(std::acos(dot)); dot = q02.dot(q03); if (dot < 0.0) { dot = -dot; q03 = -q03; } if (dot > 1.0) { dot = 1.0; } const T t3 = t2 + std::sqrt(std::acos(dot)); const T t = (time - time1) / (time2 - time1) * (t2 - t1) + t1; Quaternion q10 = slerp(q00, q01, t1 > t0 ? (t - t0) / (t1 - t0) : 0); Quaternion q11 = slerp(q01, q02, t2 > t1 ? (t - t1) / (t2 - t1) : 0); Quaternion q12 = slerp(q02, q03, t3 > t2 ? (t - t2) / (t3 - t2) : 0); Quaternion q20 = slerp(q10, q11, t2 > t0 ? (t - t0) / (t2 - t0) : 0); Quaternion q21 = slerp(q11, q12, t3 > t1 ? (t - t1) / (t3 - t1) : 0); return slerp(q20, q21, t2 > t1 ? (t - t1) / (t2 - t1) : 0); } /** * Spherical centripetal catmull-rom interpolation * SCHLAG, J. * Using geometric constructions to interpolate orientation with quaternions. * Graphics GEMS II, Academic Press, 1992, pp. 377-380. * * @param q00 quaternion at previous time * @param q01 quaternion at time t=0 * @param q02 quaternion at time t=1 * @param q03 quaternion at next time * @param t query time, in [0;1] */ static Quaternion catmullRom(const Quaternion& q00, const Quaternion& q01, const Quaternion& q02, const Quaternion& q03, const T t) { Quaternion q10 = slerp(q00, q01, t + 1); Quaternion q11 = slerp(q01, q02, t); Quaternion q12 = slerp(q02, q03, t - 1); Quaternion q20 = slerp(q10, q11, (t + 1) / 2); Quaternion q21 = slerp(q11, q12, t / 2); return slerp(q20, q21, t); } /** * Returns the real component. */ const T& getQ0() const { return q0; } /** * Returns the i component. */ const T& getQ1() const { return q1; } /** * Returns the j component. */ const T& getQ2() const { return q2; } /** * Returns the k component. */ const T& getQ3() const { return q3; } private: T q0, q1, q2, q3; }; /** * Scalar multiplication. * @param s scale factor * @param q quaternion */ template <typename T> Quaternion<T> operator*(T s, const Quaternion<T>& q) { return q * s; } /** * Output for debug. * @param os output stream * @param q quaternion. */ template <typename T> std::ostream& operator<<(std::ostream& os, const Quaternion<T>& q) { os << q.getQ0() << ',' << q.getQ1() << ',' << q.getQ2() << ',' << q.getQ3(); return os; } } // namespace VideoStitch #endif // QUATERNION_HPP_
28.883392
120
0.558723
[ "object", "vector", "3d" ]
00f587e3f5f724a7105825c75086dfc871f7e8c2
5,723
cpp
C++
src/cluster/cluster_utils.cpp
themisvr/Vector-Clustering-Algorithms
c27906f15dd90e57db98506d5a443304a908c5dd
[ "MIT" ]
1
2021-03-04T19:09:06.000Z
2021-03-04T19:09:06.000Z
src/cluster/cluster_utils.cpp
themisvr/Vector-Clustering-Algorithms
c27906f15dd90e57db98506d5a443304a908c5dd
[ "MIT" ]
null
null
null
src/cluster/cluster_utils.cpp
themisvr/Vector-Clustering-Algorithms
c27906f15dd90e57db98506d5a443304a908c5dd
[ "MIT" ]
3
2021-03-19T14:18:38.000Z
2021-11-17T18:03:53.000Z
#include <iostream> #include <string> #include <utility> #include <unistd.h> #include <getopt.h> #include <fstream> #include "../../include/io_utils/io_utils.h" #include "../../include/cluster/cluster_utils.h" void cluster_usage(const char *exec) { fprintf(stderr, "\nUsage: %s \n\n" "[+] -i [input_file]\n" "[+] -c [configuration_file]\n" "[+] -o [output_file]\n" "[+] --complete [optional]\n" "[+] -m [assignment method]\n" "\nProvide all the above arguments\n", exec); exit(EXIT_FAILURE); } void parse_cluster_args(int argc, char * const argv[], cluster_args *args) { int opt; std::string input, output, config; int option_index = 0; const struct option longopts[] = { {"complete", no_argument, 0, 'f'}, {0, 0, 0, 0} }; args->complete = false; while ((opt = getopt_long(argc, argv, "i:c:o:m:f", longopts, &option_index)) != -1) { switch(opt) { case 'i': if ( !file_exists(optarg) ) { std::cerr << "\n[+]Error: Input file does not exist!\n" << std::endl; exit(EXIT_FAILURE); } args->input_file = optarg; break; case 'c': if ( !file_exists(optarg) ) { std::cerr << "\n[+]Error: Configuration file does not exist!\n" << std::endl; exit(EXIT_FAILURE); } args->config_file = optarg; break; case 'o': // convention: if the output file does not exist, create one on the working directory if( file_exists(optarg) ) args->output_file = optarg; else { std::ofstream out("./output"); args->output_file = "output"; } break; case 'm': args->method = optarg; break; case 'f': args->complete = true; break; default: // one or more of the "-x" options did not appear cluster_usage(argv[0]); break; } } } static void evaluate_configuration_values(cluster_configs *configs) { if (configs->number_of_hash_tables == 0) configs->number_of_hash_tables = 3; if (configs->number_of_hash_functions == 0) configs->number_of_hash_functions = 4; if (configs->max_number_M_hypercube == 0) configs->max_number_M_hypercube = 10; if (configs->hypercube_dimensions == 0) configs->hypercube_dimensions = 3; if (configs->number_of_probes == 0) configs->number_of_probes = 2; } void parse_cluster_configurations(std::string config_file, cluster_configs *configs) { std::string delimiter = ": "; std::string token; size_t pos = 0; std::ifstream file(config_file); std::string line; while (std::getline(file, line)) { while ((pos = line.find(delimiter)) != std::string::npos) { token = line.substr(0, pos); line.erase(0, pos + delimiter.length()); } if (token == "number_of_clusters") { configs->number_of_clusters = stoi(line); } else if (token == "number_of_vector_hash_tables") { configs->number_of_hash_tables = stoi(line); } else if (token == "number_of_vector_hash_functions") { configs->number_of_hash_functions = stoi(line); } else if (token == "max_number_M_hypercube") { configs->max_number_M_hypercube = stoi(line); } else if (token == "number_of_hypercube_dimensions") { configs->hypercube_dimensions = stoi(line); } else if (token == "number_of_probes") { configs->number_of_probes = stoi(line); } } evaluate_configuration_values(configs); } size_t binary_search(const std::vector<std::pair<float, size_t>> &partial_sums, float val) { size_t middle = 0, begin = 0, end = partial_sums.size(); const std::pair<float, size_t> *less_than = &partial_sums[0]; //const std::pair<float, size_t> *greater_than = &partial_sums[0]; while (begin <= end) { middle = begin + (end - begin) / 2; if (val == partial_sums[middle].first) { return partial_sums[middle].second; } if(val < partial_sums[middle].first) { less_than = &partial_sums[middle]; end = middle - 1; } else { //greater_than = &partial_sums[middle]; begin = middle + 1; } } //std::cout << "P(r-1) = " << greater_than->first << " < " << val << " <= P(r) = " << less_than->first << std::endl; return less_than->second; } float find_max(const std::vector<float> &min_distances) { float max_dist = std::numeric_limits<float>::min(); for (float dist : min_distances) { if (dist > max_dist) max_dist = dist; } return max_dist; } void normalize_distances(std::vector<float> &min_distances) { float dmax = find_max(min_distances); for (float &d : min_distances) d /= dmax; } bool in(const std::vector<size_t> &centroid_indexes, size_t index) { for (size_t j = 0; j != centroid_indexes.size(); ++j) { if (centroid_indexes[j] == index) return true; } return false; } bool compare(const std::pair<float, size_t> &p1, const std::pair<float, size_t> &p2) { return p1.first < p2.first; }
29.19898
120
0.539402
[ "vector" ]
2e00da840a31a0d9ad5cd2d6e2e6176c7077a6a2
306
cpp
C++
cpp/abc049_b/main.cpp
kokosabu/atcoder
8d512587d234eb45941a2f6341c4dd003e6c9ad3
[ "Apache-2.0" ]
null
null
null
cpp/abc049_b/main.cpp
kokosabu/atcoder
8d512587d234eb45941a2f6341c4dd003e6c9ad3
[ "Apache-2.0" ]
null
null
null
cpp/abc049_b/main.cpp
kokosabu/atcoder
8d512587d234eb45941a2f6341c4dd003e6c9ad3
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { int H, W; cin >> H >> W; vector<string> C(H); for(int i = 0; i < H; i++) { cin >> C[i]; } for(int i = 0; i < H; i++) { cout << C[i] << endl; cout << C[i] << endl; } return 0; }
16.105263
32
0.424837
[ "vector" ]
2e02978671ee5e80441100d0598e8118342a6efd
7,829
cpp
C++
src/t8_package/src/cup_segmentation.cpp
jmdbo/TRSA
69c05e877ce1330faf4a1720137b0fbc50d044d8
[ "MIT" ]
1
2017-08-05T08:08:44.000Z
2017-08-05T08:08:44.000Z
src/t8_package/src/cup_segmentation.cpp
jmdbo/TRSA
69c05e877ce1330faf4a1720137b0fbc50d044d8
[ "MIT" ]
null
null
null
src/t8_package/src/cup_segmentation.cpp
jmdbo/TRSA
69c05e877ce1330faf4a1720137b0fbc50d044d8
[ "MIT" ]
null
null
null
#include "t8_package/cup_segmentation.h" Cup_Segmentation::Cup_Segmentation(ros::NodeHandle n) : n_(n) { cloud_sub_ = n_.subscribe("/octomap_cloud", 1000, &Cup_Segmentation::cloudCallback, this); treated_cloud_pub_ = n_.advertise<sensor_msgs::PointCloud2>("/cup_cloud",1); } void Cup_Segmentation::cloudCallback (const sensor_msgs::PointCloud2::ConstPtr& cloud_in) { ROS_INFO("Processing!"); /************************ CENTER AND LEFT BOXES ***************************************/ //Creating point cloud and convert ROS Message pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_cloud (new pcl::PointCloud<pcl::PointXYZ> ()); pcl::PointCloud<pcl::PointXYZ>::Ptr seg_cloud (new pcl::PointCloud<pcl::PointXYZ>); pcl::fromROSMsg(*cloud_in, *pcl_cloud); //Create and define filter parameters pcl::PassThrough<pcl::PointXYZ> pass3; pass3.setFilterFieldName("x"); pass3.setFilterLimits(0, 1.2); //-0.5 0.5 pass3.setInputCloud(pcl_cloud); pass3.filter(*pcl_cloud); pcl::PassThrough<pcl::PointXYZ> pass; pass.setFilterFieldName("y"); pass.setFilterLimits(-0.7, 0.1); //-0.5 0.5 pass.setInputCloud(pcl_cloud); pass.filter(*pcl_cloud); pcl::PassThrough<pcl::PointXYZ> pass2; pass2.setFilterFieldName("z"); pass2.setFilterLimits(0.0, 1.0); //-0.5 0.5 pass2.setInputCloud(pcl_cloud); pass2.filter(*pcl_cloud); //Model fitting process ->RANSAC pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); pcl::PointIndices::Ptr inliers (new pcl::PointIndices); pcl::SACSegmentation<pcl::PointXYZ> seg; seg.setOptimizeCoefficients (true); seg.setModelType (pcl::SACMODEL_PARALLEL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setDistanceThreshold (0.03); //0.03 seg.setAxis (Eigen::Vector3f(1, 0, 0)); seg.setEpsAngle (0.1); //0.02 seg.setInputCloud (pcl_cloud); seg.segment (*inliers, *coefficients); //Verify if inliers is not empty if (inliers->indices.size () == 0) return; pcl::PointCloud<pcl::PointXYZ>::Ptr treated_cloud (new pcl::PointCloud<pcl::PointXYZ> ()); for (std::vector<int>::const_iterator it = inliers->indices.begin(); it != inliers->indices.end (); ++it) treated_cloud->push_back(pcl_cloud->points[*it]); pcl::ExtractIndices<pcl::PointXYZ> extract; extract.setInputCloud(pcl_cloud); extract.setIndices(inliers); extract.setNegative(true); extract.filter(*seg_cloud); //Create and define radial filter parameters //pcl::RadiusOutlierRemoval<pcl::PointXYZ> radialFilter; //radialFilter.setInputCloud(treated_cloud); //radialFilter.setRadiusSearch(0.03); //radialFilter.setMinNeighborsInRadius (20); //radialFilter.filter (*treated_cloud); //Apply clustering algorithm pcl::search::KdTree<pcl::PointXYZ>::Ptr kdtree (new pcl::search::KdTree<pcl::PointXYZ>); kdtree->setInputCloud (seg_cloud); std::vector<pcl::PointIndices> cluster_indices; pcl::EuclideanClusterExtraction<pcl::PointXYZ> ec; ec.setClusterTolerance (0.06); ec.setMinClusterSize (6); ec.setMaxClusterSize (150); ec.setSearchMethod (kdtree); ec.setInputCloud (seg_cloud); ec.extract (cluster_indices); pcl::PointCloud<pcl::PointXYZI>::Ptr cluster_cloud (new pcl::PointCloud<pcl::PointXYZI> ()); pcl::PointXYZI cluster_point; double cluster_final_average; int cluster_id=0; float x1 = 0.0, y1 = 0.0, z1 = 0.0; float x2 = 0.0, y2 = 0.0, z2 = 0.0; float x3 = 0.0, y3 = 0.0, z3 = 0.0; int total1 = 0, total2 = 0, total3 = 0; bool hasCup1, hasCup2, hasCup3; for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it, cluster_id+=1) { for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); pit++) { cluster_point.x = seg_cloud->points[*pit].x; cluster_point.y = seg_cloud->points[*pit].y; cluster_point.z = seg_cloud->points[*pit].z; cluster_point.intensity = cluster_id; cluster_cloud->push_back(cluster_point); if(cluster_id == 0){ x1 += seg_cloud->points[*pit].x; y1 += seg_cloud->points[*pit].y; z1 += seg_cloud->points[*pit].z; total1++; } else if (cluster_id == 1){ x2 += seg_cloud->points[*pit].x; y2 += seg_cloud->points[*pit].y; z2 += seg_cloud->points[*pit].z; total2++; } else if (cluster_id == 2){ x3 += seg_cloud->points[*pit].x; y3 += seg_cloud->points[*pit].y; z3 += seg_cloud->points[*pit].z; total3++; } } } if(total1 != 0 ){ x1 = x1/total1; y1 = y1/total1; z1 = z1/total1; hasCup1=true; }else{ hasCup1 = false; } if(total2 != 0 ){ x2 = x2/total2; y2 = y2/total2; z2 = z2/total2; hasCup2 = true; } else { hasCup2 = false; } if(total3 != 0){ x3 = x3/total2; y3 = y3/total2; z3 = z3/total2; hasCup3 = true; } else{ hasCup3 = false; } //Publish message sensor_msgs::PointCloud2 cloud; pcl::toROSMsg(*cluster_cloud, cloud); cloud.header.stamp = ros::Time::now(); cloud.header.frame_id = cloud_in->header.frame_id; treated_cloud_pub_.publish(cloud); //Geometry geometry_msgs::PointStamped cupPoint1; geometry_msgs::PointStamped cupPoint2; geometry_msgs::PointStamped cupPoint3; tf::Quaternion q; geometry_msgs::PointStamped cupSensorPoint1; geometry_msgs::PointStamped cupSensorPoint2; geometry_msgs::PointStamped cupSensorPoint3; static tf::TransformBroadcaster tfBc1; static tf::TransformBroadcaster tfBc2; static tf::TransformBroadcaster tfBc3; tf::Transform tfCup1; tf::Transform tfCup2; tf::Transform tfCup3; cupPoint1.header.frame_id = "base_footprint"; cupPoint2.header.frame_id = "base_footprint"; cupPoint3.header.frame_id = "base_footprint"; cupPoint1.header.stamp = cloud_in->header.stamp; cupPoint2.header.stamp = cloud_in->header.stamp; cupPoint3.header.stamp = cloud_in->header.stamp; cupPoint1.point.x = x1; cupPoint2.point.x = x2; cupPoint3.point.x = x3; cupPoint1.point.y = y1; cupPoint2.point.y = y2; cupPoint3.point.y = y3; cupPoint1.point.z = z1; cupPoint2.point.z = z2; cupPoint3.point.z = z3; ROS_INFO("Cup 1: X=%f Y=%f Z=%f", cupPoint1.point.x, cupPoint1.point.y, cupPoint1.point.z); ROS_INFO("Cup 2: X=%f Y=%f Z=%f", cupPoint2.point.x, cupPoint2.point.y, cupPoint2.point.z); ROS_INFO("Cup 3: X=%f Y=%f Z=%f", cupPoint3.point.x, cupPoint3.point.y, cupPoint3.point.z); tf_listener.transformPoint("sensors_frame", cupPoint1, cupSensorPoint1); tf_listener.transformPoint("sensors_frame", cupPoint2, cupSensorPoint2); tf_listener.transformPoint("sensors_frame", cupPoint3, cupSensorPoint3); tfCup1.setOrigin( tf::Vector3(cupSensorPoint1.point.x, cupSensorPoint1.point.y, cupSensorPoint1.point.z) ); tfCup2.setOrigin( tf::Vector3(cupSensorPoint2.point.x, cupSensorPoint2.point.y, cupSensorPoint2.point.z) ); tfCup3.setOrigin( tf::Vector3(cupSensorPoint3.point.x, cupSensorPoint3.point.y, cupSensorPoint3.point.z) ); ROS_INFO("Sensor Frame Cup 1: X=%f Y=%f Z=%f", cupSensorPoint1.point.x, cupSensorPoint1.point.y, cupSensorPoint1.point.z); ROS_INFO("Sensor Frame Cup 2: X=%f Y=%f Z=%f", cupSensorPoint2.point.x, cupSensorPoint2.point.y, cupSensorPoint2.point.z); ROS_INFO("Sensor Frame Cup 3: X=%f Y=%f Z=%f", cupSensorPoint3.point.x, cupSensorPoint3.point.y, cupSensorPoint3.point.z); q.setRPY(0, 0, 0); tfCup1.setRotation(q); tfCup2.setRotation(q); tfCup3.setRotation(q); tfBc1.sendTransform(tf::StampedTransform(tfCup1, cloud_in->header.stamp, "sensors_frame", "cup1")); tfBc2.sendTransform(tf::StampedTransform(tfCup2, cloud_in->header.stamp, "sensors_frame", "cup2")); tfBc3.sendTransform(tf::StampedTransform(tfCup3, cloud_in->header.stamp, "sensors_frame", "cup3")); ROS_INFO("All Sent!"); }
34.795556
124
0.691276
[ "geometry", "vector", "model", "transform" ]
2e03c176b75003f56a97610276811657c6540683
3,911
cpp
C++
src/serialbox/core/StorageView.cpp
elsagermann/serialbox
c590561d0876f3ce9a07878e4862a46003a37879
[ "BSD-2-Clause" ]
10
2017-04-18T14:28:07.000Z
2019-10-23T03:22:16.000Z
src/serialbox/core/StorageView.cpp
elsagermann/serialbox
c590561d0876f3ce9a07878e4862a46003a37879
[ "BSD-2-Clause" ]
172
2017-02-16T14:24:33.000Z
2019-11-06T08:46:34.000Z
src/serialbox/core/StorageView.cpp
elsagermann/serialbox
c590561d0876f3ce9a07878e4862a46003a37879
[ "BSD-2-Clause" ]
21
2016-12-15T15:22:02.000Z
2019-10-02T09:40:10.000Z
//===-- serialbox/core/StorageView.cpp ----------------------------------------------*- C++ -*-===// // // S E R I A L B O X // // This file is distributed under terms of BSD license. // See LICENSE.txt for more information // //===------------------------------------------------------------------------------------------===// // /// \file /// This file contains the StorageView which represent a mutable view to a multi-dimensional /// storage. /// //===------------------------------------------------------------------------------------------===// #include "serialbox/core/StorageView.h" #include "serialbox/core/Exception.h" #include "serialbox/core/Logging.h" #include "serialbox/core/StorageViewIterator.h" #include <algorithm> #include <cassert> namespace serialbox { StorageView::StorageView(void* originPtr, TypeID type, const std::vector<int>& dims, const std::vector<int>& strides) : originPtr_(reinterpret_cast<Byte*>(originPtr)), type_(type), dims_(dims), strides_(strides), slice_((Slice::Empty())) { assert(!dims_.empty() && "empty dimension"); assert(dims_.size() == strides_.size() && "dimension mismatch"); assert(slice_.empty()); } StorageView::StorageView(void* originPtr, TypeID type, std::vector<int>&& dims, std::vector<int>&& strides) : originPtr_(reinterpret_cast<Byte*>(originPtr)), type_(type), dims_(dims), strides_(strides), slice_((Slice::Empty())) { assert(!dims_.empty() && "empty dimension"); assert(dims_.size() == strides_.size() && "dimension mismatch"); assert(slice_.empty()); } void StorageView::swap(StorageView& other) noexcept { std::swap(originPtr_, other.originPtr_); std::swap(type_, other.type_); dims_.swap(other.dims_); strides_.swap(other.strides_); } bool StorageView::operator==(const StorageView& right) const noexcept { return (originPtr_ == right.originPtr_ && type_ == right.type_ && dims_ == right.dims_); } std::ostream& operator<<(std::ostream& stream, const StorageView& s) { stream << "StorageView = {\n"; stream << " originPtr: " << static_cast<void*>(s.originPtr_) << "\n"; stream << " type: " << s.type_ << "\n"; stream << " dims: ["; for(auto i : s.dims_) stream << " " << i; stream << " ]\n strides: ["; for(auto i : s.strides_) stream << " " << i; stream << " ]\n}\n"; return stream; } void StorageView::setSlice(Slice slice) { if(slice.sliceTriples().size() > dims_.size()) throw Exception("number of slices (%i) exceeds number of dimensions (%i)", slice.sliceTriples().size(), dims_.size()); // Append un-sliced dimensions while(slice.sliceTriples().size() != dims_.size()) slice(); // Expand negative Slice.stop for(std::size_t i = 0; i < slice.sliceTriples().size(); ++i) { slice.sliceTriples()[i].stop = (slice.sliceTriples()[i].stop < 0 ? dims_[i] + 1 + slice.sliceTriples()[i].stop : slice.sliceTriples()[i].stop); } assert(slice.sliceTriples().size() == dims_.size()); slice_ = std::move(slice); } bool StorageView::isMemCopyable() const noexcept { // Check if data is sliced if(!slice_.empty()) return false; // Check if data is col-major int stride = 1; if(strides_[0] != 1) return false; // Check that there is no padding for(std::size_t i = 1; i < dims_.size(); ++i) { stride *= dims_[i - 1]; if(strides_[i] != stride) return false; } return true; } std::size_t StorageView::size() const noexcept { std::size_t size = 1; for(std::size_t i = 0; i < dims_.size(); ++i) size *= (dims_[i] == 0 ? 1 : dims_[i]); return size; } std::size_t StorageView::sizeInBytes() const noexcept { return size() * bytesPerElement(); } void swap(StorageView& a, StorageView& b) noexcept { a.swap(b); } } // namespace serialbox
32.057377
100
0.582715
[ "vector" ]
2e0429d2c28bc3a09379db538991d47b05498b65
6,597
cxx
C++
Qt/Core/pqServerResources.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
1
2016-05-09T00:36:44.000Z
2016-05-09T00:36:44.000Z
Qt/Core/pqServerResources.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
null
null
null
Qt/Core/pqServerResources.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
3
2015-05-14T21:18:53.000Z
2022-03-07T02:53:45.000Z
/*========================================================================= Program: ParaView Module: $RCSfile: pqServerResources.cxx,v $ Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.1. See License_v1.1.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS 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 "pqApplicationCore.h" #include "pqObjectBuilder.h" #include "pqReaderFactory.h" #include "pqServer.h" #include "pqServerResources.h" #include "pqServerStartups.h" #include "pqSettings.h" #include "pqUndoStack.h" #include <QStringList> #include <QtDebug> #include <QPointer> #include <vtkPVXMLParser.h> #include <vtkstd/algorithm> #include <vtkstd/vector> class pqServerResources::pqImplementation { public: typedef vtkstd::vector<pqServerResource> ResourcesT; ResourcesT Resources; }; class pqServerResources::pqMatchHostPath { public: pqMatchHostPath(const pqServerResource& resource) : Resource(resource) { } bool operator()(const pqServerResource& rhs) const { return this->Resource.hostPath() == rhs.hostPath(); } private: const pqServerResource& Resource; }; //----------------------------------------------------------------------------- pqServerResources::pqServerResources(QObject* p) : QObject(p), Implementation(new pqImplementation()) { } //----------------------------------------------------------------------------- pqServerResources::~pqServerResources() { delete this->Implementation; } //----------------------------------------------------------------------------- void pqServerResources::add(const pqServerResource& resource) { // Remove any existing resources that match the resource we're about to add ... // Note: we consider a resource a "match" if it has the same host(s) and path; // we ignore scheme and port(s) this->Implementation->Resources.erase( vtkstd::remove_if( this->Implementation->Resources.begin(), this->Implementation->Resources.end(), pqMatchHostPath(resource)), this->Implementation->Resources.end()); this->Implementation->Resources.insert(this->Implementation->Resources.begin(), resource); const unsigned long max_length = 10; if(this->Implementation->Resources.size() > max_length) { this->Implementation->Resources.resize(max_length); } emit this->changed(); } //----------------------------------------------------------------------------- const pqServerResources::ListT pqServerResources::list() const { ListT results; vtkstd::copy( this->Implementation->Resources.begin(), this->Implementation->Resources.end(), vtkstd::back_inserter(results)); return results; } //----------------------------------------------------------------------------- void pqServerResources::load(pqSettings& settings) { const QStringList resources = settings.value("ServerResources").toStringList(); for(int i = resources.size() - 1; i >= 0; --i) { this->add(pqServerResource(resources[i])); } } //----------------------------------------------------------------------------- void pqServerResources::save(pqSettings& settings) { QStringList resources; for( pqImplementation::ResourcesT::const_iterator resource = this->Implementation->Resources.begin(); resource != this->Implementation->Resources.end(); ++resource) { resources.push_back(resource->serializeString()); } settings.setValue("ServerResources", resources); } //----------------------------------------------------------------------------- void pqServerResources::open(pqServer* server, const pqServerResource& resource) { if(!server) { qCritical() << "Cannot open a resource with NULL server"; return; } if(resource.scheme() == "session") { if(!resource.path().isEmpty()) { // Read in the xml file to restore. vtkSmartPointer<vtkPVXMLParser> xmlParser = vtkSmartPointer<vtkPVXMLParser>::New(); xmlParser->SetFileName(resource.path().toAscii().data()); xmlParser->Parse(); // Get the root element from the parser. if(vtkPVXMLElement* const root = xmlParser->GetRootElement()) { pqApplicationCore::instance()->loadState(root, server, 0/*this->getActiveRenderModule()*/); } else { qCritical() << "Root does not exist. Either state file could not be opened " "or it does not contain valid xml"; } } } else { if (!resource.path().isEmpty()) { QString readerGroup = resource.data("readergroup"); QString readerName = resource.data("reader"); pqPipelineSource* reader = 0; if (!readerName.isEmpty() && !readerGroup.isEmpty()) { pqApplicationCore* core = pqApplicationCore::instance(); pqObjectBuilder* builder = core->getObjectBuilder(); pqUndoStack* ustack = core->getUndoStack(); if (ustack) { ustack->beginUndoSet("Create Reader"); } QStringList files; files.push_back(resource.path()); reader = builder->createReader( readerGroup, readerName, files, server); if (ustack) { ustack->endUndoSet(); } } else { qDebug() << "Recent changes to the settings code have " << "made these old entries unusable."; } if (!reader) { qCritical() << "Error opening file " << resource.path() << "\n"; return; } } } }
30.261468
102
0.604214
[ "vector" ]
2e1685af368ec69f125ff5e346dc6bf53a974bd4
24,222
cpp
C++
thirdparty/physx/PhysXSDK/Source/GeomUtils/src/pcm/GuPCMContactGenBoxConvex.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
thirdparty/physx/PhysXSDK/Source/GeomUtils/src/pcm/GuPCMContactGenBoxConvex.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
thirdparty/physx/PhysXSDK/Source/GeomUtils/src/pcm/GuPCMContactGenBoxConvex.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
/* * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. */ // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuGeometryUnion.h" #include "GuPCMContactGen.h" #include "GuPCMShapeConvex.h" #include "CmRenderOutput.h" #include "GuPCMContactGenUtil.h" #include "PsVecMath.h" #include "GuVecCapsule.h" #include "GuVecBox.h" #ifdef PCM_LOW_LEVEL_DEBUG #include "CmRenderOutput.h" physx::Cm::RenderOutput* gRenderOutPut = NULL; #endif #ifdef PX_WIIU #pragma ghs nowarning 1656 //within a function using alloca or VLAs, alignment of local variables #endif #define PCM_USE_INTERNAL_OBJECT 1 using namespace physx; using namespace Gu; //Precompute the convex data // 7+------+6 0 = --- // /| /| 1 = +-- // / | / | 2 = ++- // / 4+---/--+5 3 = -+- // 3+------+2 / y z 4 = --+ // | / | / | / 5 = +-+ // |/ |/ |/ 6 = +++ // 0+------+1 *---x 7 = -++ namespace physx { namespace Gu { static bool testFaceNormal(const Gu::PolygonalData& polyData0, const Gu::PolygonalData& polyData1, SupportLocal* map0, SupportLocal* map1, const Ps::aos::PsMatTransformV& transform0To1, const Ps::aos::PsMatTransformV& transform1To0, const Ps::aos::FloatVArg contactDist, Ps::aos::FloatV& minOverlap, PxU32& feature, Ps::aos::Vec3V& faceNormal, const FeatureStatus faceStatus, FeatureStatus& status) { PX_UNUSED(polyData1); using namespace Ps::aos; FloatV _minOverlap = FMax();//minOverlap; PxU32 _feature = 0; Vec3V _faceNormal = faceNormal; FloatV min0, max0; FloatV min1, max1; const BoolV bTrue = BTTTT(); const Vec3V center1To0 = transform1To0.p; #if PCM_USE_INTERNAL_OBJECT const Vec3V zeroV = V3Zero(); const Vec3V shapeSpaceCenter1 = V3LoadU(polyData1.mCenter); const Vec3V internalCenter1In0 = transform1To0.transform(shapeSpaceCenter1); const FloatV internalRadius1 = FLoad(polyData1.mInternal.mRadius); const Vec3V internalExtents1 = V3LoadU(polyData1.mInternal.mExtents); const Vec3V negInternalExtents1 = V3Neg(internalExtents1); #endif //in the local space of polyData0 for(PxU32 i=0; i<polyData0.mNbPolygons; ++i) { const Gu::HullPolygonData& polygon = polyData0.mPolygons[i]; const Vec3V minVert = V3LoadU(polyData0.mVerts[polygon.mMinIndex]); const FloatV planeDist = FLoad(polygon.mPlane.d); const Vec3V vertexSpacePlaneNormal = V3LoadU(polygon.mPlane.n); //transform plane n to shape space const Vec3V shapeSpacePlaneNormal = M33TrnspsMulV3(map0->shape2Vertex, vertexSpacePlaneNormal); const FloatV magnitude = FRecip(V3Length(shapeSpacePlaneNormal)); //ML::use this to avoid LHS min0 = FMul(V3Dot(vertexSpacePlaneNormal, minVert), magnitude); max0 = FMul(FNeg(planeDist), magnitude); //normalize shape space normal const Vec3V n0 = V3Scale(shapeSpacePlaneNormal, magnitude); //calculate polyData1 projection //rotate polygon's normal into the local space of polyData1 const Vec3V n1 = transform0To1.rotate(n0); #if PCM_USE_INTERNAL_OBJECT //test internal object //ML: we don't need to transform the normal into the vertex space. If polyData1 don't have scale, //the vertex2Shape matrix will be identity, shape space normal will be the same as vertex space's normal. //If polyData0 have scale, internalExtens1 will be 0. const Vec3V proj = V3Sel(V3IsGrtr(n1, zeroV), internalExtents1, negInternalExtents1); const FloatV radius = FMax(V3Dot(n1, proj), internalRadius1); const FloatV internalTrans = V3Dot(internalCenter1In0, n0); const FloatV _min1 = FSub(internalTrans, radius); const FloatV _max1 = FAdd(internalTrans, radius); const FloatV _min = FMax(min0, _min1); const FloatV _max = FMin(max0, _max1); const FloatV _tempOverlap = FSub(_max, _min); //const FloatV _tempOverlap = FSub(max0, _min1); //Internal object overlaps more than current min, so can skip it //because (a) it isn't a separating axis and (b) it isn't the smallest axis if(FAllGrtr(_tempOverlap, _minOverlap)) { continue; } #endif const FloatV translate = V3Dot(center1To0, n0); map1->doSupport(n1, min1, max1); min1 = FAdd(translate, min1); max1 = FAdd(translate, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEq(con, bTrue)) return false; const FloatV tempOverlap = FSub(max0, min1); if(FAllGrtr(_minOverlap, tempOverlap)) { _minOverlap = tempOverlap; _feature = i; _faceNormal = n0; } } if(FAllGrtr(minOverlap, _minOverlap)) { faceNormal = _faceNormal; minOverlap = _minOverlap; status = faceStatus; } feature = _feature; return true; } //plane is in the shape space of polyData void buildPartialHull(const Gu::PolygonalData& polyData, SupportLocal* map, Gu::SeparatingAxes& validAxes, const Ps::aos::Vec3VArg planeP, const Ps::aos::Vec3VArg planeDir) { using namespace Ps::aos; const FloatV zero = FZero(); const BoolV bTrue = BTTTT(); const Vec3V dir = V3Normalize(planeDir); for(PxU32 i=0; i<polyData.mNbPolygons; ++i) { const Gu::HullPolygonData& polygon = polyData.mPolygons[i]; const PxU8* inds = polyData.mPolygonVertexRefs + polygon.mVRef8; Vec3V v0 = M33MulV3(map->vertex2Shape, V3LoadU(polyData.mVerts[inds[polygon.mNbVerts - 1]])); FloatV dist0 = V3Dot(dir, V3Sub(v0, planeP)); for (PxU32 iStart = 0; iStart < polygon.mNbVerts; iStart++) { const Vec3V v1 = M33MulV3(map->vertex2Shape, V3LoadU(polyData.mVerts[inds[iStart]])); const FloatV dist1 = V3Dot(dir, V3Sub(v1, planeP)); const BoolV con = BOr(FIsGrtr(dist0, zero), FIsGrtr(dist1, zero)); //cull edge if either of the vertex will on the positive size of the plane if(BAllEq(con, bTrue)) { const Vec3V tempV = V3Sub(v0, v1); PxVec3 temp; V3StoreU(tempV, temp); validAxes.addAxis(temp.getNormalized()); } v0 = v1; dist0 = dist1; } } } static bool testEdgeNormal(const Gu::PolygonalData& polyData0, const Gu::PolygonalData& polyData1, SupportLocal* map0, SupportLocal* map1, const Ps::aos::PsMatTransformV& transform0To1, const Ps::aos::PsMatTransformV& transform1To0, const Ps::aos::FloatVArg contactDist, Ps::aos::FloatV& minOverlap, Ps::aos::Vec3V& edgeNormalIn0, const FeatureStatus edgeStatus, FeatureStatus& status) { using namespace Ps::aos; FloatV overlap = minOverlap; FloatV min0, max0; FloatV min1, max1; const BoolV bTrue = BTTTT(); const FloatV eps = FEps(); const Vec3V shapeSpaceCenter0 = V3LoadU(polyData0.mCenter); const Vec3V shapeSpaceCenter1 = V3LoadU(polyData1.mCenter); #if PCM_USE_INTERNAL_OBJECT const Vec3V zeroV = V3Zero(); const Vec3V internalCenter1In0 = V3Sub(transform1To0.transform(shapeSpaceCenter1), shapeSpaceCenter0); const FloatV internalRadius1 = FLoad(polyData1.mInternal.mRadius); const Vec3V internalExtents1 = V3LoadU(polyData1.mInternal.mExtents); const Vec3V negInternalExtents1 = V3Neg(internalExtents1); const FloatV internalRadius0 = FLoad(polyData0.mInternal.mRadius); const Vec3V internalExtents0 = V3LoadU(polyData0.mInternal.mExtents); const Vec3V negInternalExtents0 = V3Neg(internalExtents0); #endif const Vec3V center1To0 = transform1To0.p; //in polyData0 shape space const Vec3V dir0 = V3Sub(transform1To0.transform(shapeSpaceCenter1), shapeSpaceCenter0); const Vec3V support0 = map0->doSupport(dir0); //in polyData1 shape space const Vec3V dir1 = transform0To1.rotate(V3Neg(dir0)); const Vec3V support1 = map1->doSupport(dir1); const Vec3V support0In1 = transform0To1.transform(support0); const Vec3V support1In0 = transform1To0.transform(support1); SeparatingAxes mSA0; SeparatingAxes mSA1; mSA0.reset(); mSA1.reset(); buildPartialHull(polyData0, map0, mSA0, support1In0, dir0); buildPartialHull(polyData1, map1, mSA1, support0In1, dir1); const PxVec3* axe0 = mSA0.getAxes(); const PxVec3* axe1 = mSA1.getAxes(); const PxU32 numAxe0 = mSA0.getNumAxes(); const PxU32 numAxe1 = mSA1.getNumAxes(); for(PxU32 i=0; i < numAxe0; ++i) { //axe0[i] is in the shape space of polyData0 const Vec3V v0 = V3LoadU(axe0[i]); for(PxU32 j=0; j< numAxe1; ++j) { //axe1[j] is in the shape space of polyData1 const Vec3V v1 = V3LoadU(axe1[j]); const Vec3V dir = V3Cross(v0, transform1To0.rotate(v1)); const FloatV lenSq = V3Dot(dir, dir); if(FAllGrtr(eps, lenSq)) continue; //n0 is in polyData0's local space const Vec3V n0 = V3Scale(dir, FRsqrt(lenSq)); //n1 is in polyData1's local space const Vec3V n1 = transform0To1.rotate(n0); #if PCM_USE_INTERNAL_OBJECT //ML: we don't need to transform the normal into the vertex space. If polyData1 don't have scale, //the vertex2Shape matrix will be identity, shape space normal will be the same as vertex space's normal. //If polyData0 have scale, internalExtens1 will be 0. //vertex space n1 const Vec3V proj = V3Sel(V3IsGrtr(n1, zeroV), internalExtents1, negInternalExtents1); const FloatV radius = FMax(V3Dot(n1, proj), internalRadius1); const FloatV internalTrans = V3Dot(internalCenter1In0, n0); const FloatV _min1 = FSub(internalTrans, radius); const FloatV _max1 = FAdd(internalTrans, radius); const Vec3V proj0 = V3Sel(V3IsGrtr(n0, zeroV), internalExtents0, negInternalExtents0); const FloatV radius0 = FMax(V3Dot(n0, proj0), internalRadius0); const FloatV _max0 = radius0; const FloatV _min0 = FNeg(radius0); PX_ASSERT(FAllGrtrOrEq(_max0, _min0)); PX_ASSERT(FAllGrtrOrEq(_max1, _min1)); const FloatV _min = FMax(_min0, _min1); const FloatV _max = FMin(_max0, _max1); const FloatV _tempOverlap = FSub(_max, _min); //Internal object overlaps more than current min, so can skip it //because (a) it isn't a separating axis and (b) it isn't the smallest axis if(FAllGrtr(_tempOverlap, overlap)) { continue; } #endif //get polyData0's projection map0->doSupport(n0, min0, max0); const FloatV translate = V3Dot(center1To0, n0); //get polyData1's projection map1->doSupport(n1, min1, max1); min1 = FAdd(translate, min1); max1 = FAdd(translate, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEq(con, bTrue)) return false; const FloatV tempOverlap = FSub(max0, min1); #if PCM_USE_INTERNAL_OBJECT PX_ASSERT(FAllGrtrOrEq(tempOverlap, _tempOverlap)); #endif if(FAllGrtr(overlap, tempOverlap)) { overlap = tempOverlap; edgeNormalIn0 = n0; status = edgeStatus; } } } minOverlap = overlap; return true; } //contactNormal is in the space of polyData0 void generatedContacts(Gu::PolygonalData& polyData0, Gu::PolygonalData& polyData1,const Gu::HullPolygonData& referencePolygon, const Gu::HullPolygonData& incidentPolygon, Gu::SupportLocal* map0, Gu::SupportLocal* map1, const Ps::aos::PsMatTransformV& transform0To1, Gu::PersistentContact* manifoldContacts, PxU32& numContacts, const Ps::aos::FloatVArg contactDist) { using namespace Ps::aos; const FloatV zero = FZero(); const BoolV bTrue = BTTTT(); const PxU8* inds0 = polyData0.mPolygonVertexRefs + referencePolygon.mVRef8; //transform the plane normal to shape space const Vec3V contactNormal = V3Normalize(M33TrnspsMulV3(map0->shape2Vertex, V3LoadU(referencePolygon.mPlane.n))); //this is the matrix transform all points to the 2d plane const Mat33V rot = findRotationMatrixFromZAxis(contactNormal); const PxU8* inds1 = polyData1.mPolygonVertexRefs + incidentPolygon.mVRef8; Vec3V* points0In0 = (Vec3V*)PxAllocaAligned(sizeof(Vec3V)*referencePolygon.mNbVerts, 16); Vec3V* points1In0 = (Vec3V*)PxAllocaAligned(sizeof(Vec3V)*incidentPolygon.mNbVerts, 16); bool* points1In0Penetration = (bool*)PxAlloca(sizeof(bool)*incidentPolygon.mNbVerts); FloatV* points1In0TValue = (FloatV*)PxAllocaAligned(sizeof(FloatV)*incidentPolygon.mNbVerts, 16); //Transform all the verts from vertex space to shape space map0->populateVerts(inds0, referencePolygon.mNbVerts, polyData0.mVerts, points0In0); map1->populateVerts(inds1, incidentPolygon.mNbVerts, polyData1.mVerts, points1In0); //This is used to calculate the project point when the 2D reference face points is inside the 2D incident face point const Vec3V sPoint = points1In0[0]; PX_ASSERT(incidentPolygon.mNbVerts <= 64); Vec3V eps = Vec3V_From_FloatV(FEps()); Vec3V max = Vec3V_From_FloatV(FMax()); Vec3V nmax = V3Neg(max); //transform reference polygon to 2d, calculate min and max Vec3V rPolygonMin= max; Vec3V rPolygonMax = nmax; for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i) { points0In0[i] = M33MulV3(rot, points0In0[i]); rPolygonMin = V3Min(rPolygonMin, points0In0[i]); rPolygonMax = V3Max(rPolygonMax, points0In0[i]); } rPolygonMin = V3Sub(rPolygonMin, eps); rPolygonMax = V3Add(rPolygonMax, eps); const FloatV d = V3GetZ(points0In0[0]); const FloatV rd = FAdd(d, contactDist); Vec3V iPolygonMin= max; Vec3V iPolygonMax = nmax; PxU32 inside = 0; for(PxU32 i=0; i<incidentPolygon.mNbVerts; ++i) { const Vec3V vert1 =points1In0[i]; //this still in polyData1's local space const Vec3V a = transform0To1.transformInv(vert1); points1In0[i] = M33MulV3(rot, a); const FloatV z = V3GetZ(points1In0[i]); points1In0TValue[i] = FSub(z, d); points1In0[i] = V3SetZ(points1In0[i], d); iPolygonMin = V3Min(iPolygonMin, points1In0[i]); iPolygonMax = V3Max(iPolygonMax, points1In0[i]); if(FAllGrtr(rd, z)) { points1In0Penetration[i] = true; if(contains(points0In0, referencePolygon.mNbVerts, points1In0[i], rPolygonMin, rPolygonMax)) { inside++; const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), points1In0TValue[i]); manifoldContacts[numContacts].mLocalPointA = vert1; manifoldContacts[numContacts].mLocalPointB = M33TrnspsMulV3(rot, points1In0[i]); manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen; } } else { points1In0Penetration[i] = false; } } if(inside == incidentPolygon.mNbVerts) { return; } inside = 0; iPolygonMin = V3Sub(iPolygonMin, eps); iPolygonMax = V3Add(iPolygonMax, eps); const Vec3V incidentNormal = V3Normalize(M33TrnspsMulV3(map1->shape2Vertex, V3LoadU(incidentPolygon.mPlane.n))); const Vec3V contactNormalIn1 = transform0To1.rotate(contactNormal); for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i) { if(contains(points1In0, incidentPolygon.mNbVerts, points0In0[i], iPolygonMin, iPolygonMax)) { //const Vec3V vert0=Vec3V_From_PxVec3(polyData0.mVerts[inds0[i]]); const Vec3V vert0 = M33TrnspsMulV3(rot, points0In0[i]); const Vec3V a = transform0To1.transform(vert0); const FloatV nom = V3Dot(incidentNormal, V3Sub(sPoint, a)); const FloatV denom = V3Dot(incidentNormal, contactNormalIn1); PX_ASSERT(FAllEq(denom, zero)==0); const FloatV t = FDiv(nom, denom); if(FAllGrtr(t, contactDist)) continue; const Vec3V projPoint = V3ScaleAdd(contactNormalIn1, t, a); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), t); manifoldContacts[numContacts].mLocalPointA = projPoint; manifoldContacts[numContacts].mLocalPointB = vert0; manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen; } } if(inside == referencePolygon.mNbVerts) return; //(2) segment intesection for (PxU32 iStart = 0, iEnd = PxU32(incidentPolygon.mNbVerts - 1); iStart < incidentPolygon.mNbVerts; iEnd = iStart++) { if((!points1In0Penetration[iStart] && !points1In0Penetration[iEnd] ) )//|| (points1In0[i].status == POINT_OUTSIDE && points1In0[incidentIndex].status == POINT_OUTSIDE)) continue; const Vec3V ipA = points1In0[iStart]; const Vec3V ipB = points1In0[iEnd]; Vec3V ipAOri = V3SetZ(points1In0[iStart], FAdd(points1In0TValue[iStart], d)); Vec3V ipBOri = V3SetZ(points1In0[iEnd], FAdd(points1In0TValue[iEnd], d)); const Vec3V iMin = V3Min(ipA, ipB); const Vec3V iMax = V3Max(ipA, ipB); for (PxU32 rStart = 0, rEnd = PxU32(referencePolygon.mNbVerts - 1); rStart < referencePolygon.mNbVerts; rEnd = rStart++) { const Vec3V rpA = points0In0[rStart]; const Vec3V rpB = points0In0[rEnd]; const Vec3V rMin = V3Min(rpA, rpB); const Vec3V rMax = V3Max(rpA, rpB); const BoolV tempCon =BOr(V3IsGrtr(iMin, rMax), V3IsGrtr(rMin, iMax)); const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon)); if(BAllEq(con, bTrue)) continue; FloatV a1 = signed2DTriArea(rpA, rpB, ipA); FloatV a2 = signed2DTriArea(rpA, rpB, ipB); if(FAllGrtr(zero, FMul(a1, a2))) { FloatV a3 = signed2DTriArea(ipA, ipB, rpA); FloatV a4 = signed2DTriArea(ipA, ipB, rpB); if(FAllGrtr(zero, FMul(a3, a4))) { //these two segment intersect const FloatV t = FDiv(a1, FSub(a2, a1)); const Vec3V pBB = V3NegScaleSub(V3Sub(ipBOri, ipAOri), t, ipAOri); const Vec3V pAA = V3SetZ(pBB, d); const Vec3V pA = M33TrnspsMulV3(rot, pAA); const Vec3V pB = transform0To1.transform(M33TrnspsMulV3(rot, pBB)); const FloatV pen = FSub(V3GetZ(pBB), V3GetZ(pAA)); if(FAllGrtr(pen, contactDist)) continue; const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), pen); manifoldContacts[numContacts].mLocalPointA = pB; manifoldContacts[numContacts].mLocalPointB = pA; manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen; } } } } } bool generateFullContactManifold(Gu::PolygonalData& polyData0, Gu::PolygonalData& polyData1, SupportLocal* map0, SupportLocal* map1,/* Gu::PersistentContactManifold& manifold,*/ Gu::PersistentContact* manifoldContacts, PxU32& numContacts, const Ps::aos::FloatVArg contactDist, const Ps::aos::Vec3VArg normal, const bool doOverlapTest) { using namespace Ps::aos; const PsMatTransformV transform1To0V = map0->transform.transformInv(map1->transform); const PsMatTransformV transform0To1V = map1->transform.transformInv(map0->transform); PxU32 origContactCount = numContacts; if(doOverlapTest) { //if gjk fail, SAT based yes/no test FeatureStatus status = POLYDATA0; FloatV minOverlap = FMax(); Vec3V minNormal = V3Zero(); PxU32 feature0; //in the local space of polyData0, minNormal is in polyData0 space if(!testFaceNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, feature0, minNormal, POLYDATA0, status)) return false; PxU32 feature1; //in the local space of polyData1, if minOverlap is overwrite inside this function, minNormal will be in polyData1 space if(!testFaceNormal(polyData1, polyData0, map1, map0, transform1To0V, transform0To1V, contactDist, minOverlap, feature1, minNormal, POLYDATA1, status)) return false; bool doEdgeTest = false; EdgeTest: if(doEdgeTest) { if(!testEdgeNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, minNormal, EDGE0, status)) return false; if(status != EDGE0) return true; } if(status == POLYDATA0) { //minNormal is in the local space of polydata0 const Gu::HullPolygonData& referencePolygon = polyData0.mPolygons[feature0]; const Vec3V n = transform0To1V.rotate(minNormal); const Gu::HullPolygonData& incidentPolygon = polyData1.mPolygons[getPolygonIndex(polyData1, map1, n)]; generatedContacts(polyData0, polyData1, referencePolygon, incidentPolygon, map0, map1, transform0To1V, manifoldContacts, numContacts, contactDist); if(numContacts != origContactCount) { const Vec3V nn = V3Neg(n); //flip the contacts for(PxU32 i=origContactCount; i<numContacts; ++i) { const Vec3V localPointB = manifoldContacts[i].mLocalPointB; manifoldContacts[i].mLocalPointB = manifoldContacts[i].mLocalPointA; manifoldContacts[i].mLocalPointA = localPointB; manifoldContacts[i].mLocalNormalPen = V4SetW(nn, V4GetW(manifoldContacts[i].mLocalNormalPen)); } } } else if(status == POLYDATA1) { //minNormal is in the local space of polydata1 const Gu::HullPolygonData& referencePolygon = polyData1.mPolygons[feature1]; const Gu::HullPolygonData& incidentPolygon = polyData0.mPolygons[getPolygonIndex(polyData0, map0, transform1To0V.rotate(minNormal))]; //reference face is polyData1 generatedContacts(polyData1, polyData0, referencePolygon, incidentPolygon, map1, map0, transform1To0V, manifoldContacts, numContacts, contactDist); } else //if(status == EDGE0) { //minNormal is in the local space of polydata0 const Gu::HullPolygonData& incidentPolygon = polyData0.mPolygons[getPolygonIndex(polyData0, map0, V3Neg(minNormal))]; const Gu::HullPolygonData& referencePolygon = polyData1.mPolygons[getPolygonIndex(polyData1, map1, transform0To1V.rotate(minNormal))]; generatedContacts(polyData1, polyData0, referencePolygon, incidentPolygon, map1, map0, transform1To0V, manifoldContacts, numContacts, contactDist); } if(numContacts == origContactCount && !doEdgeTest) { doEdgeTest = true; goto EdgeTest; } } else { //use gjk normal to get the faceIndex(status == GJK_CONTACT) const PxI32 faceIndex1 = getPolygonIndex(polyData1, map1, V3Neg(normal)); const PxI32 faceIndex0 = getPolygonIndex(polyData0, map0, transform0To1V.rotateInv(normal)); const Gu::HullPolygonData& referencePolygon = polyData1.mPolygons[faceIndex1]; const Gu::HullPolygonData& incidentPolygon = polyData0.mPolygons[faceIndex0]; generatedContacts(polyData1, polyData0, referencePolygon, incidentPolygon, map1, map0, transform1To0V, manifoldContacts, numContacts, contactDist); } return true; } bool computeMTD(Gu::PolygonalData& polyData0, Gu::PolygonalData& polyData1, SupportLocal* map0, SupportLocal* map1, Ps::aos::FloatV& penDepth, Ps::aos::Vec3V& normal) { using namespace Ps::aos; const PsMatTransformV transform1To0V = map0->transform.transformInv(map1->transform); const PsMatTransformV transform0To1V = map1->transform.transformInv(map0->transform); FeatureStatus status = POLYDATA0; FloatV minOverlap = FMax(); Vec3V minNormal = V3Zero(); const FloatV contactDist = FZero(); PxU32 feature0; //in the local space of polyData0, minNormal is in polyData0 space if(!testFaceNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, feature0, minNormal, POLYDATA0, status)) return false; PxU32 feature1; //in the local space of polyData1, if minOverlap is overwrite inside this function, minNormal will be in polyData1 space if(!testFaceNormal(polyData1, polyData0, map1, map0, transform1To0V, transform0To1V, contactDist, minOverlap, feature1, minNormal, POLYDATA1, status)) return false; if(!testEdgeNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, minNormal, EDGE0, status)) return false; penDepth = minOverlap; if(status == POLYDATA1) { //minNormal is in the local space of polydata1 normal = map1->transform.rotate(minNormal); } else { PX_ASSERT(status == POLYDATA0 || status == EDGE0); //ML: status == POLYDATA0 or status == EDGE, minNormal is in the local space of polydata0 normal = V3Neg(map0->transform.rotate(minNormal)); } return true; } }//Gu }//physx
33.641667
272
0.7153
[ "object", "shape", "transform" ]
2e2cd42ca02de4355310b7faf5ca9776f401bacb
1,222
cpp
C++
snippets/pose-estimation-2d2d.cpp
district10/snippet-manager
bebe45a601368947168e3ee6e6ab8c1fc2ee2055
[ "MIT" ]
7
2018-08-04T09:28:19.000Z
2020-10-19T17:46:34.000Z
snippets/pose-estimation-2d2d.cpp
district10/snippet-manager
bebe45a601368947168e3ee6e6ab8c1fc2ee2055
[ "MIT" ]
null
null
null
snippets/pose-estimation-2d2d.cpp
district10/snippet-manager
bebe45a601368947168e3ee6e6ab8c1fc2ee2055
[ "MIT" ]
2
2018-07-31T04:14:55.000Z
2020-04-02T01:22:39.000Z
Mat pose_estimation_2d2d ( std::vector<KeyPoint> keypoints_1, std::vector<KeyPoint> keypoints_2, std::vector< DMatch > matches, Mat& R, Mat& t ) { Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 ); vector<Point2f> points1, points2; for ( int i = 0; i < ( int ) matches.size(); i++ ) { points1.push_back ( keypoints_1[matches[i].queryIdx].pt ); points2.push_back ( keypoints_2[matches[i].trainIdx].pt ); } Mat fundamental_matrix; fundamental_matrix = findFundamentalMat ( points1, points2, CV_FM_8POINT ); Point2d principal_point ( 325.1, 249.7 ); // focal point, cx, cy double focal_length = 521; // fx, fy Mat essential_matrix; essential_matrix = findEssentialMat ( points1, points2, focal_length, principal_point ); Mat homography_matrix; // ransacReprojThreshold homography_matrix = findHomography ( points1, points2, RANSAC, 3 ); // E -> R|t (E = t^*R) recoverPose ( essential_matrix, points1, points2, R, t, focal_length, principal_point ); return essential_matrix; }
40.733333
92
0.590835
[ "vector" ]