text
stringlengths
54
60.6k
<commit_before>#include <DuiApplicationWindow> #include <DuiApplication> #include <QDBusInterface> #include <QDebug> #include "lockscreenui.h" #include "lockscreenbusinesslogic.h" LockScreenBusinessLogic::LockScreenBusinessLogic(QObject* parent) : QObject(parent), display(NULL), lockUI(NULL) { qDebug() << Q_FUNC_INFO; display = new QmDisplayState(this); lockUI = new LockScreenUI(); connect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)), this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState))); connect(lockUI, SIGNAL(unlocked()), this, SLOT(unlockScreen())); /* dbusIf = new QDBusInterface("org.maemo.dui.NotificationManager", "/systemui", "org.maemo.dui.NotificationManager.MissedEvents", QDBusConnection::sessionBus(), this); connect(dbusIf, SIGNAL(missedEventAmountsChanged(int, int, int, int)), this, SLOT(updateMissedEventAmounts(int, int, int, int))); dbusIf->call(QDBus::NoBlock, QString("missedEventAmountsRequired")); */ shortPowerKeyPressOccured(); } LockScreenBusinessLogic::~LockScreenBusinessLogic() { //delete eventEater; //eventEater = NULL; delete lockUI; } void LockScreenBusinessLogic::shortPowerKeyPressOccured() { qDebug() << Q_FUNC_INFO; switch (display->get()) { case Maemo::QmDisplayState::Off: toggleScreenLockUI(true); //make sure the UI is on toggleKeyPadLock(false); display->set(Maemo::QmDisplayState::On); break; case Maemo::QmDisplayState::On: case Maemo::QmDisplayState::Dimmed: toggleKeyPadLock(true); display->set(Maemo::QmDisplayState::Off); toggleScreenLockUI(true); break; } } void LockScreenBusinessLogic::displayStateChanged(Maemo::QmDisplayState::DisplayState state) { qDebug() << Q_FUNC_INFO << state; switch (state) { case Maemo::QmDisplayState::Off: toggleKeyPadLock(true); //lock the keypad toggleScreenLockUI(true); //show UI break; case Maemo::QmDisplayState::On: toggleKeyPadLock(false); //unlock the keypad break; default: break; } } void LockScreenBusinessLogic::unlockScreen() { qDebug() << Q_FUNC_INFO; toggleScreenLockUI(false); //turn off the UI toggleKeyPadLock(false); //unlock the keypad } void LockScreenBusinessLogic::updateMissedEventAmounts(int a, int b, int c, int d) { qDebug() << "LockScreenBusinessLogic::updateMissedEventAmounts(" << a << ", " << b << ", " << c << ", " << d << ")"; lockUI->updateMissedEventAmounts(a, b, c, d); } void LockScreenBusinessLogic::toggleKeyPadLock(bool toggle) { qDebug() << Q_FUNC_INFO << toggle; QmLocks::State newState = (toggle ? QmLocks::Locked : QmLocks::Unlocked); QmLocks touchPadLocker; touchPadLocker.setState(QmLocks::TouchAndKeyboard, newState); } void LockScreenBusinessLogic::toggleScreenLockUI(bool toggle) { qDebug() << Q_FUNC_INFO << toggle; if (toggle) { DuiApplication::activeApplicationWindow()->show(); lockUI->appear(); } else { DuiApplication::activeApplicationWindow()->hide(); } } <commit_msg>Removing test code, once again<commit_after>#include <DuiApplicationWindow> #include <DuiApplication> #include <QDBusInterface> #include <QDebug> #include "lockscreenui.h" #include "lockscreenbusinesslogic.h" LockScreenBusinessLogic::LockScreenBusinessLogic(QObject* parent) : QObject(parent), display(NULL), lockUI(NULL) { qDebug() << Q_FUNC_INFO; display = new QmDisplayState(this); lockUI = new LockScreenUI(); connect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)), this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState))); connect(lockUI, SIGNAL(unlocked()), this, SLOT(unlockScreen())); /* dbusIf = new QDBusInterface("org.maemo.dui.NotificationManager", "/systemui", "org.maemo.dui.NotificationManager.MissedEvents", QDBusConnection::sessionBus(), this); connect(dbusIf, SIGNAL(missedEventAmountsChanged(int, int, int, int)), this, SLOT(updateMissedEventAmounts(int, int, int, int))); dbusIf->call(QDBus::NoBlock, QString("missedEventAmountsRequired")); */ } LockScreenBusinessLogic::~LockScreenBusinessLogic() { //delete eventEater; //eventEater = NULL; delete lockUI; } void LockScreenBusinessLogic::shortPowerKeyPressOccured() { qDebug() << Q_FUNC_INFO; switch (display->get()) { case Maemo::QmDisplayState::Off: toggleScreenLockUI(true); //make sure the UI is on toggleKeyPadLock(false); display->set(Maemo::QmDisplayState::On); break; case Maemo::QmDisplayState::On: case Maemo::QmDisplayState::Dimmed: toggleKeyPadLock(true); display->set(Maemo::QmDisplayState::Off); toggleScreenLockUI(true); break; } } void LockScreenBusinessLogic::displayStateChanged(Maemo::QmDisplayState::DisplayState state) { qDebug() << Q_FUNC_INFO << state; switch (state) { case Maemo::QmDisplayState::Off: toggleKeyPadLock(true); //lock the keypad toggleScreenLockUI(true); //show UI break; case Maemo::QmDisplayState::On: toggleKeyPadLock(false); //unlock the keypad break; default: break; } } void LockScreenBusinessLogic::unlockScreen() { qDebug() << Q_FUNC_INFO; toggleScreenLockUI(false); //turn off the UI toggleKeyPadLock(false); //unlock the keypad } void LockScreenBusinessLogic::updateMissedEventAmounts(int a, int b, int c, int d) { qDebug() << "LockScreenBusinessLogic::updateMissedEventAmounts(" << a << ", " << b << ", " << c << ", " << d << ")"; lockUI->updateMissedEventAmounts(a, b, c, d); } void LockScreenBusinessLogic::toggleKeyPadLock(bool toggle) { qDebug() << Q_FUNC_INFO << toggle; QmLocks::State newState = (toggle ? QmLocks::Locked : QmLocks::Unlocked); QmLocks touchPadLocker; touchPadLocker.setState(QmLocks::TouchAndKeyboard, newState); } void LockScreenBusinessLogic::toggleScreenLockUI(bool toggle) { qDebug() << Q_FUNC_INFO << toggle; if (toggle) { DuiApplication::activeApplicationWindow()->show(); lockUI->appear(); } else { DuiApplication::activeApplicationWindow()->hide(); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef INTERRUPTS_H #define INTERRUPTS_H #include "stl/types.hpp" namespace interrupt { constexpr const size_t SYSCALL_FIRST = 50; constexpr const size_t SYSCALL_MAX = 10; struct fault_regs { uint64_t error_no; uint64_t error_code; uint64_t rip; uint64_t rflags; uint64_t cs; uint64_t rsp; uint64_t ss; } __attribute__((packed)); struct syscall_regs { uint64_t data_segment; uint64_t rax; uint64_t rbx; uint64_t rcx; uint64_t rdx; uint64_t rsi; uint64_t rdi; uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t code; } __attribute__((packed)); void setup_interrupts(); void register_irq_handler(size_t irq, void (*handler)()); void register_syscall_handler(size_t irq, void (*handler)(const syscall_regs&)); } //end of interrupt namespace #endif <commit_msg>Get reference to the values that are pushed on the stack by int<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef INTERRUPTS_H #define INTERRUPTS_H #include "stl/types.hpp" namespace interrupt { constexpr const size_t SYSCALL_FIRST = 50; constexpr const size_t SYSCALL_MAX = 10; struct fault_regs { uint64_t error_no; uint64_t error_code; uint64_t rip; uint64_t rflags; uint64_t cs; uint64_t rsp; uint64_t ss; } __attribute__((packed)); struct syscall_regs { uint64_t data_segment; uint64_t rax; uint64_t rbx; uint64_t rcx; uint64_t rdx; uint64_t rsi; uint64_t rdi; uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t rbp; uint64_t rsp; uint64_t code; uint64_t rip; uint64_t cs; uint64_t rflags; uint64_t rsp; } __attribute__((packed)); void setup_interrupts(); void register_irq_handler(size_t irq, void (*handler)()); void register_syscall_handler(size_t irq, void (*handler)(const syscall_regs&)); } //end of interrupt namespace #endif <|endoftext|>
<commit_before>#if !defined( __CINT__) || defined(__MAKECINT__) #include <AliRun.h> #include <AliStack.h> #include <AliLoader.h> #include <AliRunLoader.h> #include "AliRICH.h" #include "AliRICHDisplFast.h" #endif //globals for easy manual manipulations AliRun *a; AliStack *s; AliRunLoader *al; AliRICH *r; AliLoader *rl,*vl; //__________________________________________________________________________________________________ void pp(int tid) { if(!al) return; al->LoadHeader(); al->LoadKinematics(); if(tid<0||tid>=al->Stack()->GetNtrack()) cout<<"Valid tid number is 0-"<<al->Stack()->GetNtrack()-1<<" for this event.\n"; else PrintParticleInfo(tid); al->UnloadKinematics(); al->UnloadHeader(); } //__________________________________________________________________________________________________ void PrintParticleInfo(int tid) { // Prints particle info for a given TID TParticle *p=al->Stack()->Particle(tid); cout<<p->GetName()<<"("<<tid<<")"; if(!p->IsPrimary()){cout<<" from "; PrintParticleInfo(p->GetFirstMother());} else {cout<<endl;} } //__________________________________________________________________________________________________ Int_t mother(Int_t tid) { // Who is the mother of given track TID? al->LoadHeader(); al->LoadKinematics(); if(tid<0||tid>=al->Stack()->GetNtrack()) cout<<"Valid tid number is 0-"<<al->Stack()->GetNtrack()-1<<" for this event.\n"; else while(1){ TParticle *p=al->Stack()->Particle(tid); if(p->IsPrimary()) break; tid=p->GetFirstMother(); } al->UnloadKinematics(); al->UnloadHeader(); return tid; } //__________________________________________________________________________________________________ Bool_t AliceRead() { Info("ReadAlice","Tring to read ALICE from SIMULATED FILE..."); if(gAlice){ delete gAlice->GetRunLoader(); delete gAlice; } if(gSystem->Exec("ls galice.root>/dev/null")==256){//there is no galice.root in current directory AliceNew(); RichGet(); return kFALSE; //new session }else{ if(!(al=AliRunLoader::Open())){//if not possible to read from galice.root, then remove grabage and reinvoke AliceRead() gSystem->Exec("rm -rf *.root *.dat"); AliceRead(); } al->LoadgAlice();//before this gAlice is 0; if(!gAlice) Fatal("menu.C::ReadAlice","No gAlice in file"); a=al->GetAliRun();//provides pointer to AliRun object Info("AliceRead","Run contains %i event(s)",a->GetEventsPerRun()); RichGet(); return kTRUE; //old session opened from file } }//AliceRead() //__________________________________________________________________________________________________ void AliceNew() { Info("AliceNew","Init new session"); new AliRun("gAlice","Alice experiment system"); gAlice->Init(); a=gAlice; al=gAlice->GetRunLoader(); }//AliceNew() //__________________________________________________________________________________________________ void RichGet() { if(!(r=r())) Warning("RICH/menu.C::ReadAlice","No RICH in file"); if(!(rl=rl())) Warning("RICH/menu.C::ReadAlice","No RICH loader in file"); } //__________________________________________________________________________________________________ void MenuRich() { TControlBar *pMenu = new TControlBar("vertical","RICH"); pMenu->AddButton("Display single chambers" ,"r->Display();" , "Display Fast"); pMenu->AddButton("Display ALL chambers" ,"r->DisplayEvent(0,0);" , "Display Fast"); pMenu->AddButton("Print hits" ,"r->HitsPrint();" ,"????"); pMenu->AddButton("Print sdigits" ,"r->SDigitsPrint();" ,"????"); pMenu->AddButton("Print digits" ,"r->DigitsPrint();" ,"????"); pMenu->AddButton("Print clusters" ,"r->ClustersPrint();" ,"????"); pMenu->AddButton("Print occupancy" ,"r->OccupancyPrint();" ,"????"); pMenu->AddButton("Event Summary " ,"r->SummaryOfEvent();" ,"????"); pMenu->AddButton("Hits plots" ,"r->ControlPlots()" ,"????"); pMenu->AddButton("Recon with stack" ,"r->CheckPR()" , "Create RSR.root with ntuple hn"); pMenu->Show(); }//TestMenu() //__________________________________________________________________________________________________ void RichMenu() { TControlBar *pMenu = new TControlBar("vertical","MAIN"); if(AliceRead()){//it's from file, show some info if(r) pMenu->AddButton("RICH submenu" , "MenuRich()" , "Show RICH submenu" ); }else{//it's aliroot, simulate pMenu->AddButton("Debug ON", "DebugON();", "Switch debug on-off"); pMenu->AddButton("Debug OFF", "DebugOFF();", "Switch debug on-off"); pMenu->AddButton("Run", "a()->Run(1)", "Process!"); } pMenu->AddButton("Test segmentation" ,"rp->TestSeg()" ,"Test AliRICHParam segmentation methods" ); pMenu->AddButton("Test response" ,"rp->TestResp()" ,"Test AliRICHParam response methods" ); pMenu->AddButton("Test transformation","rp->TestTrans()","Test AliRICHParam transformation methods" ); pMenu->AddButton("Test opticals" ,".x Opticals.h" ,"Test optical properties" ); pMenu->AddButton("Geo GUI" ,"GeomGui()" ,"Shows geometry" ); pMenu->AddButton("Browser" ,"new TBrowser;" ,"Start ROOT TBrowser" ); pMenu->AddButton("Quit" ,".q" ,"Close session" ); pMenu->Show(); }//menu() //__________________________________________________________________________________________________ void DebugOFF(){ Info("DebugOFF",""); AliLog::SetGlobalDebugLevel(0);} void DebugON() { Info("DebugON",""); AliLog::SetGlobalDebugLevel(AliLog::kDebug);} //__________________________________________________________________________________________________ void GeomGui() { if(gGeoManager){ gGeoManager->GetTopVolume()->Draw(); AliRICHParam::DrawAxis(); }else new G3GeometryGUI; } AliRun *a() {return al->GetAliRun();} //provides pointer to main AliRun object (aka gAlice) AliRICH *r() {return (AliRICH*) a()->GetDetector("RICH");} //provides pointer to RICH detector AliLoader *rl(){return al->GetLoader("RICHLoader");} void rt(Int_t event=0) {r->PrintTracks (event);} //utility print tracks Int_t nem(Int_t event=0) {AliRICH::Nparticles(kElectron ,event,al);} //utility number of electrons Int_t nep(Int_t event=0) {AliRICH::Nparticles(kPositron ,event,al);} //utility number of positrons Int_t nmup(Int_t event=0) {AliRICH::Nparticles(kMuonPlus ,event,al);} //utility number of positive muons Int_t nmum(Int_t event=0) {AliRICH::Nparticles(kMuonMinus ,event,al);} //utility number of negative muons Int_t npi0(Int_t event=0) {AliRICH::Nparticles(kPi0 ,event,al);} //utility number of neutral pions Int_t npip(Int_t event=0) {AliRICH::Nparticles(kPiPlus ,event,al);} //utility number of positive pions Int_t npim(Int_t event=0) {AliRICH::Nparticles(kPiMinus ,event,al);} //utility number of negative pions Int_t nk0(Int_t event=0) {AliRICH::Nparticles(kK0 ,event,al);} //utility number of neutral kaons Int_t nkp(Int_t event=0) {AliRICH::Nparticles(kKPlus ,event,al);} //utility number of positive kaons Int_t nkm(Int_t event=0) {AliRICH::Nparticles(kKMinus ,event,al);} //utility number of negative kaons Int_t npp(Int_t event=0) {AliRICH::Nparticles(kProton ,event,al);} //utility number of protons Int_t npm(Int_t event=0) {AliRICH::Nparticles(kProtonBar ,event,al);} //utility number of antiprotons <commit_msg>Minor change<commit_after>#if !defined( __CINT__) || defined(__MAKECINT__) #include <AliRun.h> #include <AliStack.h> #include <AliLoader.h> #include <AliRunLoader.h> #include "AliRICH.h" #include "AliRICHDisplFast.h" #endif //globals for easy manual manipulations AliRun *a; AliStack *s; AliRunLoader *al; AliRICH *r; AliLoader *rl,*vl; //__________________________________________________________________________________________________ void pp(int tid) { if(!al) return; al->LoadHeader(); al->LoadKinematics(); if(tid<0||tid>=al->Stack()->GetNtrack()) cout<<"Valid tid number is 0-"<<al->Stack()->GetNtrack()-1<<" for this event.\n"; else PrintParticleInfo(tid); al->UnloadKinematics(); al->UnloadHeader(); } //__________________________________________________________________________________________________ void PrintParticleInfo(int tid) { // Prints particle info for a given TID TParticle *p=al->Stack()->Particle(tid); cout<<p->GetName()<<"("<<tid<<")"; if(!p->IsPrimary()){cout<<" from "; PrintParticleInfo(p->GetFirstMother());} else {cout<<endl;} } //__________________________________________________________________________________________________ Int_t mother(Int_t tid) { // Who is the mother of given track TID? al->LoadHeader(); al->LoadKinematics(); if(tid<0||tid>=al->Stack()->GetNtrack()) cout<<"Valid tid number is 0-"<<al->Stack()->GetNtrack()-1<<" for this event.\n"; else while(1){ TParticle *p=al->Stack()->Particle(tid); if(p->IsPrimary()) break; tid=p->GetFirstMother(); } al->UnloadKinematics(); al->UnloadHeader(); return tid; } //__________________________________________________________________________________________________ Bool_t AliceRead() { Info("ReadAlice","Tring to read ALICE from SIMULATED FILE..."); if(gAlice){ delete gAlice->GetRunLoader(); delete gAlice; } if(gSystem->Exec("ls galice.root>/dev/null")==256){//there is no galice.root in current directory AliceNew(); RichGet(); return kFALSE; //new session }else{ if(!(al=AliRunLoader::Open())){//if not possible to read from galice.root, then remove grabage and reinvoke AliceRead() gSystem->Exec("rm -rf *.root *.dat"); AliceRead(); } al->LoadgAlice();//before this gAlice is 0; if(!gAlice) Fatal("menu.C::ReadAlice","No gAlice in file"); a=al->GetAliRun();//provides pointer to AliRun object Info("AliceRead","Run contains %i event(s)",a->GetEventsPerRun()); RichGet(); return kTRUE; //old session opened from file } }//AliceRead() //__________________________________________________________________________________________________ void AliceNew() { Info("AliceNew","Init new session"); new AliRun("gAlice","Alice experiment system"); gAlice->Init(); a=gAlice; al=gAlice->GetRunLoader(); }//AliceNew() //__________________________________________________________________________________________________ void RichGet() { if(!(r=r())) Warning("RICH/menu.C::ReadAlice","No RICH in file"); if(!(rl=rl())) Warning("RICH/menu.C::ReadAlice","No RICH loader in file"); } //__________________________________________________________________________________________________ void MenuRich() { TControlBar *pMenu = new TControlBar("vertical","RICH"); pMenu->AddButton("Display single chambers" ,"r->Display();" , "Display Fast"); pMenu->AddButton("Display ALL chambers" ,"r->DisplayEvent(0,0);" , "Display Fast"); pMenu->AddButton("Print hits" ,"r->HitsPrint();" ,"????"); pMenu->AddButton("Print sdigits" ,"r->SDigitsPrint();" ,"????"); pMenu->AddButton("Print digits" ,"r->DigitsPrint();" ,"????"); pMenu->AddButton("Print clusters" ,"r->ClustersPrint();" ,"????"); pMenu->AddButton("Print occupancy" ,"r->OccupancyPrint(-1);" ,"????"); pMenu->AddButton("Event Summary " ,"r->SummaryOfEvent();" ,"????"); pMenu->AddButton("Hits plots" ,"r->ControlPlots()" ,"????"); pMenu->AddButton("Recon with stack" ,"r->CheckPR()" , "Create RSR.root with ntuple hn"); pMenu->Show(); }//TestMenu() //__________________________________________________________________________________________________ void RichMenu() { TControlBar *pMenu = new TControlBar("vertical","MAIN"); if(AliceRead()){//it's from file, show some info if(r) pMenu->AddButton("RICH submenu" , "MenuRich()" , "Show RICH submenu" ); }else{//it's aliroot, simulate pMenu->AddButton("Debug ON", "DebugON();", "Switch debug on-off"); pMenu->AddButton("Debug OFF", "DebugOFF();", "Switch debug on-off"); pMenu->AddButton("Run", "a()->Run(1)", "Process!"); } pMenu->AddButton("Test segmentation" ,"rp->TestSeg()" ,"Test AliRICHParam segmentation methods" ); pMenu->AddButton("Test response" ,"rp->TestResp()" ,"Test AliRICHParam response methods" ); pMenu->AddButton("Test transformation","rp->TestTrans()","Test AliRICHParam transformation methods" ); pMenu->AddButton("Test opticals" ,".x Opticals.h" ,"Test optical properties" ); pMenu->AddButton("Geo GUI" ,"GeomGui()" ,"Shows geometry" ); pMenu->AddButton("Browser" ,"new TBrowser;" ,"Start ROOT TBrowser" ); pMenu->AddButton("Quit" ,".q" ,"Close session" ); pMenu->Show(); }//menu() //__________________________________________________________________________________________________ void DebugOFF(){ Info("DebugOFF",""); AliLog::SetGlobalDebugLevel(0);} void DebugON() { Info("DebugON",""); AliLog::SetGlobalDebugLevel(AliLog::kDebug);} //__________________________________________________________________________________________________ void GeomGui() { if(gGeoManager){ gGeoManager->GetTopVolume()->Draw(); AliRICHParam::DrawAxis(); }else new G3GeometryGUI; } AliRun *a() {return al->GetAliRun();} //provides pointer to main AliRun object (aka gAlice) AliRICH *r() {return (AliRICH*) a()->GetDetector("RICH");} //provides pointer to RICH detector AliLoader *rl(){return al->GetLoader("RICHLoader");} void rt(Int_t event=0) {r->PrintTracks (event);} //utility print tracks Int_t nem(Int_t event=0) {AliRICH::Nparticles(kElectron ,event,al);} //utility number of electrons Int_t nep(Int_t event=0) {AliRICH::Nparticles(kPositron ,event,al);} //utility number of positrons Int_t nmup(Int_t event=0) {AliRICH::Nparticles(kMuonPlus ,event,al);} //utility number of positive muons Int_t nmum(Int_t event=0) {AliRICH::Nparticles(kMuonMinus ,event,al);} //utility number of negative muons Int_t npi0(Int_t event=0) {AliRICH::Nparticles(kPi0 ,event,al);} //utility number of neutral pions Int_t npip(Int_t event=0) {AliRICH::Nparticles(kPiPlus ,event,al);} //utility number of positive pions Int_t npim(Int_t event=0) {AliRICH::Nparticles(kPiMinus ,event,al);} //utility number of negative pions Int_t nk0(Int_t event=0) {AliRICH::Nparticles(kK0 ,event,al);} //utility number of neutral kaons Int_t nkp(Int_t event=0) {AliRICH::Nparticles(kKPlus ,event,al);} //utility number of positive kaons Int_t nkm(Int_t event=0) {AliRICH::Nparticles(kKMinus ,event,al);} //utility number of negative kaons Int_t npp(Int_t event=0) {AliRICH::Nparticles(kProton ,event,al);} //utility number of protons Int_t npm(Int_t event=0) {AliRICH::Nparticles(kProtonBar ,event,al);} //utility number of antiprotons <|endoftext|>
<commit_before>/* * Asynchronous local file access. * * author: Max Kellermann <[email protected]> */ #include "istream_file.hxx" #include "istream_buffer.hxx" #include "buffered_io.hxx" #include "system/fd_util.h" #include "gerrno.h" #include "pool.hxx" #include "fb_pool.hxx" #include "SliceFifoBuffer.hxx" #include "util/Cast.hxx" #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <limits.h> #include <event.h> /** * If EAGAIN occurs (on NFS), we try again after 100ms. We can't * check EV_READ, because the kernel always indicates VFS files as * "readable without blocking". */ static const struct timeval file_retry_timeout = { .tv_sec = 0, .tv_usec = 100000, }; struct FileIstream { struct istream stream; int fd; FdType fd_type; /** * A timer to retry reading after EAGAIN. */ struct event event; off_t rest; SliceFifoBuffer buffer; const char *path; }; static void file_close(FileIstream *file) { if (file->fd >= 0) { evtimer_del(&file->event); close(file->fd); file->fd = -1; } } static void file_destroy(FileIstream *file) { file_close(file); file->buffer.FreeIfDefined(fb_pool_get()); } static void file_abort(FileIstream *file, GError *error) { file_destroy(file); istream_deinit_abort(&file->stream, error); } /** * @return the number of bytes still in the buffer */ static size_t istream_file_invoke_data(FileIstream *file) { return istream_buffer_consume(&file->stream, file->buffer); } static void istream_file_eof_detected(FileIstream *file) { assert(file->fd >= 0); file_destroy(file); istream_deinit_eof(&file->stream); } static inline size_t istream_file_max_read(const FileIstream *file) { if (file->rest != (off_t)-1 && file->rest < (off_t)INT_MAX) return (size_t)file->rest; else return INT_MAX; } static void istream_file_try_data(FileIstream *file) { size_t rest = 0; if (file->buffer.IsNull()) { if (file->rest != 0) file->buffer.Allocate(fb_pool_get()); } else { const size_t available = file->buffer.GetAvailable(); if (available > 0) { rest = istream_file_invoke_data(file); if (rest == available) /* not a single byte was consumed: we may have been closed, and we must bail out now */ return; } } if (file->rest == 0) { if (rest == 0) istream_file_eof_detected(file); return; } ForeignFifoBuffer<uint8_t> &buffer = file->buffer; ssize_t nbytes = read_to_buffer(file->fd, buffer, istream_file_max_read(file)); if (nbytes == 0) { if (file->rest == (off_t)-1) { file->rest = 0; if (rest == 0) istream_file_eof_detected(file); } else { GError *error = g_error_new(g_file_error_quark(), 0, "premature end of file in '%s'", file->path); file_abort(file, error); } return; } else if (nbytes == -1) { GError *error = g_error_new(errno_quark(), errno, "failed to read from '%s': %s", file->path, strerror(errno)); file_abort(file, error); return; } else if (nbytes > 0 && file->rest != (off_t)-1) { file->rest -= (off_t)nbytes; assert(file->rest >= 0); } assert(!file->buffer.IsEmpty()); rest = istream_file_invoke_data(file); if (rest == 0 && file->rest == 0) istream_file_eof_detected(file); } static void istream_file_try_direct(FileIstream *file) { assert(file->stream.handler->direct != nullptr); /* first consume the rest of the buffer */ if (istream_file_invoke_data(file) > 0) return; if (file->rest == 0) { istream_file_eof_detected(file); return; } ssize_t nbytes = istream_invoke_direct(&file->stream, file->fd_type, file->fd, istream_file_max_read(file)); if (nbytes == ISTREAM_RESULT_CLOSED) /* this stream was closed during the direct() callback */ return; if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) { /* -2 means the callback wasn't able to consume any data right now */ if (nbytes > 0 && file->rest != (off_t)-1) { file->rest -= (off_t)nbytes; assert(file->rest >= 0); if (file->rest == 0) istream_file_eof_detected(file); } } else if (nbytes == ISTREAM_RESULT_EOF) { if (file->rest == (off_t)-1) { istream_file_eof_detected(file); } else { GError *error = g_error_new(g_file_error_quark(), 0, "premature end of file in '%s'", file->path); file_abort(file, error); } } else if (errno == EAGAIN) { /* this should only happen for splice(SPLICE_F_NONBLOCK) from NFS files - unfortunately we cannot use EV_READ here, so we just install a timer which retries after 100ms */ evtimer_add(&file->event, &file_retry_timeout); } else { /* XXX */ GError *error = g_error_new(errno_quark(), errno, "failed to read from '%s': %s", file->path, strerror(errno)); file_abort(file, error); } } static void file_try_read(FileIstream *file) { if (istream_check_direct(&file->stream, file->fd_type)) istream_file_try_direct(file); else istream_file_try_data(file); } static void file_event_callback(gcc_unused int fd, gcc_unused short event, void *ctx) { FileIstream *file = (FileIstream *)ctx; file_try_read(file); } /* * istream implementation * */ static inline FileIstream * istream_to_file(struct istream *istream) { return &ContainerCast2(*istream, &FileIstream::stream); } static off_t istream_file_available(struct istream *istream, bool partial) { FileIstream *file = istream_to_file(istream); off_t available = 0; if (file->rest != (off_t)-1) available = file->rest; else if (!partial) return (off_t)-1; else available = 0; available += file->buffer.GetAvailable(); return available; } static off_t istream_file_skip(struct istream *istream, off_t length) { FileIstream *file = istream_to_file(istream); evtimer_del(&file->event); if (file->rest == (off_t)-1) return (off_t)-1; if (length == 0) return 0; /* clear the buffer; later we could optimize this function by flushing only the skipped number of bytes */ file->buffer.Clear(); if (length >= file->rest) { /* skip beyond EOF */ length = file->rest; file->rest = 0; } else { /* seek the file descriptor */ off_t ret = lseek(file->fd, length, SEEK_CUR); if (ret < 0) return -1; file->rest -= length; } return length; } static void istream_file_read(struct istream *istream) { FileIstream *file = istream_to_file(istream); assert(file->stream.handler != nullptr); evtimer_del(&file->event); file_try_read(file); } static int istream_file_as_fd(struct istream *istream) { FileIstream *file = istream_to_file(istream); int fd = file->fd; evtimer_del(&file->event); istream_deinit(&file->stream); return fd; } static void istream_file_close(struct istream *istream) { FileIstream *file = istream_to_file(istream); file_destroy(file); istream_deinit(&file->stream); } static const struct istream_class istream_file = { .available = istream_file_available, .skip = istream_file_skip, .read = istream_file_read, .as_fd = istream_file_as_fd, .close = istream_file_close, }; /* * constructor and public methods * */ struct istream * istream_file_fd_new(struct pool *pool, const char *path, int fd, FdType fd_type, off_t length) { assert(fd >= 0); assert(length >= -1); auto file = NewFromPool<FileIstream>(*pool); istream_init(&file->stream, &istream_file, pool); file->fd = fd; file->fd_type = fd_type; file->rest = length; file->buffer.SetNull(); file->path = path; evtimer_set(&file->event, file_event_callback, file); return &file->stream; } struct istream * istream_file_stat_new(struct pool *pool, const char *path, struct stat *st, GError **error_r) { assert(path != nullptr); assert(st != nullptr); int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0); if (fd < 0) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to open %s: ", path); return nullptr; } if (fstat(fd, st) < 0) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to stat %s: ", path); close(fd); return nullptr; } FdType fd_type = FdType::FD_FILE; off_t size = st->st_size; if (S_ISCHR(st->st_mode)) { fd_type = FdType::FD_CHARDEV; size = -1; } return istream_file_fd_new(pool, path, fd, fd_type, size); } struct istream * istream_file_new(struct pool *pool, const char *path, off_t length, GError **error_r) { assert(length >= -1); int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0); if (fd < 0) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to open %s: ", path); return nullptr; } return istream_file_fd_new(pool, path, fd, FdType::FD_FILE, length); } int istream_file_fd(struct istream *istream) { assert(istream != nullptr); assert(istream->cls == &istream_file); FileIstream *file = istream_to_file(istream); assert(file->fd >= 0); return file->fd; } bool istream_file_set_range(struct istream *istream, off_t start, off_t end) { assert(istream != nullptr); assert(istream->cls == &istream_file); assert(start >= 0); assert(end >= start); FileIstream *file = istream_to_file(istream); assert(file->fd >= 0); assert(file->rest >= 0); assert(file->buffer.IsNull()); assert(end <= file->rest); if (start > 0 && lseek(file->fd, start, SEEK_CUR) < 0) return false; file->rest = end - start; return true; } <commit_msg>istream_file: rename "rest" to "buffer_rest"<commit_after>/* * Asynchronous local file access. * * author: Max Kellermann <[email protected]> */ #include "istream_file.hxx" #include "istream_buffer.hxx" #include "buffered_io.hxx" #include "system/fd_util.h" #include "gerrno.h" #include "pool.hxx" #include "fb_pool.hxx" #include "SliceFifoBuffer.hxx" #include "util/Cast.hxx" #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <limits.h> #include <event.h> /** * If EAGAIN occurs (on NFS), we try again after 100ms. We can't * check EV_READ, because the kernel always indicates VFS files as * "readable without blocking". */ static const struct timeval file_retry_timeout = { .tv_sec = 0, .tv_usec = 100000, }; struct FileIstream { struct istream stream; int fd; FdType fd_type; /** * A timer to retry reading after EAGAIN. */ struct event event; off_t rest; SliceFifoBuffer buffer; const char *path; }; static void file_close(FileIstream *file) { if (file->fd >= 0) { evtimer_del(&file->event); close(file->fd); file->fd = -1; } } static void file_destroy(FileIstream *file) { file_close(file); file->buffer.FreeIfDefined(fb_pool_get()); } static void file_abort(FileIstream *file, GError *error) { file_destroy(file); istream_deinit_abort(&file->stream, error); } /** * @return the number of bytes still in the buffer */ static size_t istream_file_invoke_data(FileIstream *file) { return istream_buffer_consume(&file->stream, file->buffer); } static void istream_file_eof_detected(FileIstream *file) { assert(file->fd >= 0); file_destroy(file); istream_deinit_eof(&file->stream); } static inline size_t istream_file_max_read(const FileIstream *file) { if (file->rest != (off_t)-1 && file->rest < (off_t)INT_MAX) return (size_t)file->rest; else return INT_MAX; } static void istream_file_try_data(FileIstream *file) { size_t buffer_rest = 0; if (file->buffer.IsNull()) { if (file->rest != 0) file->buffer.Allocate(fb_pool_get()); } else { const size_t available = file->buffer.GetAvailable(); if (available > 0) { buffer_rest = istream_file_invoke_data(file); if (buffer_rest == available) /* not a single byte was consumed: we may have been closed, and we must bail out now */ return; } } if (file->rest == 0) { if (buffer_rest == 0) istream_file_eof_detected(file); return; } ForeignFifoBuffer<uint8_t> &buffer = file->buffer; ssize_t nbytes = read_to_buffer(file->fd, buffer, istream_file_max_read(file)); if (nbytes == 0) { if (file->rest == (off_t)-1) { file->rest = 0; if (buffer_rest == 0) istream_file_eof_detected(file); } else { GError *error = g_error_new(g_file_error_quark(), 0, "premature end of file in '%s'", file->path); file_abort(file, error); } return; } else if (nbytes == -1) { GError *error = g_error_new(errno_quark(), errno, "failed to read from '%s': %s", file->path, strerror(errno)); file_abort(file, error); return; } else if (nbytes > 0 && file->rest != (off_t)-1) { file->rest -= (off_t)nbytes; assert(file->rest >= 0); } assert(!file->buffer.IsEmpty()); buffer_rest = istream_file_invoke_data(file); if (buffer_rest == 0 && file->rest == 0) istream_file_eof_detected(file); } static void istream_file_try_direct(FileIstream *file) { assert(file->stream.handler->direct != nullptr); /* first consume the rest of the buffer */ if (istream_file_invoke_data(file) > 0) return; if (file->rest == 0) { istream_file_eof_detected(file); return; } ssize_t nbytes = istream_invoke_direct(&file->stream, file->fd_type, file->fd, istream_file_max_read(file)); if (nbytes == ISTREAM_RESULT_CLOSED) /* this stream was closed during the direct() callback */ return; if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) { /* -2 means the callback wasn't able to consume any data right now */ if (nbytes > 0 && file->rest != (off_t)-1) { file->rest -= (off_t)nbytes; assert(file->rest >= 0); if (file->rest == 0) istream_file_eof_detected(file); } } else if (nbytes == ISTREAM_RESULT_EOF) { if (file->rest == (off_t)-1) { istream_file_eof_detected(file); } else { GError *error = g_error_new(g_file_error_quark(), 0, "premature end of file in '%s'", file->path); file_abort(file, error); } } else if (errno == EAGAIN) { /* this should only happen for splice(SPLICE_F_NONBLOCK) from NFS files - unfortunately we cannot use EV_READ here, so we just install a timer which retries after 100ms */ evtimer_add(&file->event, &file_retry_timeout); } else { /* XXX */ GError *error = g_error_new(errno_quark(), errno, "failed to read from '%s': %s", file->path, strerror(errno)); file_abort(file, error); } } static void file_try_read(FileIstream *file) { if (istream_check_direct(&file->stream, file->fd_type)) istream_file_try_direct(file); else istream_file_try_data(file); } static void file_event_callback(gcc_unused int fd, gcc_unused short event, void *ctx) { FileIstream *file = (FileIstream *)ctx; file_try_read(file); } /* * istream implementation * */ static inline FileIstream * istream_to_file(struct istream *istream) { return &ContainerCast2(*istream, &FileIstream::stream); } static off_t istream_file_available(struct istream *istream, bool partial) { FileIstream *file = istream_to_file(istream); off_t available = 0; if (file->rest != (off_t)-1) available = file->rest; else if (!partial) return (off_t)-1; else available = 0; available += file->buffer.GetAvailable(); return available; } static off_t istream_file_skip(struct istream *istream, off_t length) { FileIstream *file = istream_to_file(istream); evtimer_del(&file->event); if (file->rest == (off_t)-1) return (off_t)-1; if (length == 0) return 0; /* clear the buffer; later we could optimize this function by flushing only the skipped number of bytes */ file->buffer.Clear(); if (length >= file->rest) { /* skip beyond EOF */ length = file->rest; file->rest = 0; } else { /* seek the file descriptor */ off_t ret = lseek(file->fd, length, SEEK_CUR); if (ret < 0) return -1; file->rest -= length; } return length; } static void istream_file_read(struct istream *istream) { FileIstream *file = istream_to_file(istream); assert(file->stream.handler != nullptr); evtimer_del(&file->event); file_try_read(file); } static int istream_file_as_fd(struct istream *istream) { FileIstream *file = istream_to_file(istream); int fd = file->fd; evtimer_del(&file->event); istream_deinit(&file->stream); return fd; } static void istream_file_close(struct istream *istream) { FileIstream *file = istream_to_file(istream); file_destroy(file); istream_deinit(&file->stream); } static const struct istream_class istream_file = { .available = istream_file_available, .skip = istream_file_skip, .read = istream_file_read, .as_fd = istream_file_as_fd, .close = istream_file_close, }; /* * constructor and public methods * */ struct istream * istream_file_fd_new(struct pool *pool, const char *path, int fd, FdType fd_type, off_t length) { assert(fd >= 0); assert(length >= -1); auto file = NewFromPool<FileIstream>(*pool); istream_init(&file->stream, &istream_file, pool); file->fd = fd; file->fd_type = fd_type; file->rest = length; file->buffer.SetNull(); file->path = path; evtimer_set(&file->event, file_event_callback, file); return &file->stream; } struct istream * istream_file_stat_new(struct pool *pool, const char *path, struct stat *st, GError **error_r) { assert(path != nullptr); assert(st != nullptr); int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0); if (fd < 0) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to open %s: ", path); return nullptr; } if (fstat(fd, st) < 0) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to stat %s: ", path); close(fd); return nullptr; } FdType fd_type = FdType::FD_FILE; off_t size = st->st_size; if (S_ISCHR(st->st_mode)) { fd_type = FdType::FD_CHARDEV; size = -1; } return istream_file_fd_new(pool, path, fd, fd_type, size); } struct istream * istream_file_new(struct pool *pool, const char *path, off_t length, GError **error_r) { assert(length >= -1); int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0); if (fd < 0) { set_error_errno(error_r); g_prefix_error(error_r, "Failed to open %s: ", path); return nullptr; } return istream_file_fd_new(pool, path, fd, FdType::FD_FILE, length); } int istream_file_fd(struct istream *istream) { assert(istream != nullptr); assert(istream->cls == &istream_file); FileIstream *file = istream_to_file(istream); assert(file->fd >= 0); return file->fd; } bool istream_file_set_range(struct istream *istream, off_t start, off_t end) { assert(istream != nullptr); assert(istream->cls == &istream_file); assert(start >= 0); assert(end >= start); FileIstream *file = istream_to_file(istream); assert(file->fd >= 0); assert(file->rest >= 0); assert(file->buffer.IsNull()); assert(end <= file->rest); if (start > 0 && lseek(file->fd, start, SEEK_CUR) < 0) return false; file->rest = end - start; return true; } <|endoftext|>
<commit_before>#include "memory.hpp" #include "memory/immix_collector.hpp" #include "memory/immix_marker.hpp" #include "capi/handles.hpp" #include "capi/tag.hpp" #include "object_watch.hpp" #include "configuration.hpp" #include "instruments/timing.hpp" #include "util/logger.hpp" #ifdef ENABLE_LLVM #include "llvm/state.hpp" #endif namespace rubinius { namespace memory { void ImmixGC::Diagnostics::log() { if(!modified_p()) return; diagnostics::Diagnostics::log(); utilities::logger::write("immix: diagnostics: " \ "collections: %ld, " \ "objects: %ld, " \ "bytes: %ld, " \ "total_bytes: %ld, " \ "chunks: %ld, " \ "holes: %ld, " \ "percentage: %f", collections_, objects_, bytes_, total_bytes_, chunks_, holes_, percentage_); } void ImmixGC::ObjectDescriber::added_chunk(int count) { if(object_memory_) { object_memory_->vm()->metrics().memory.immix_chunks++; if(gc_->dec_chunks_left() <= 0) { gc_->reset_chunks_left(); } } } /** * This means we're getting low on memory! Time to schedule a garbage * collection. */ void ImmixGC::ObjectDescriber::last_block() { if(object_memory_) { object_memory_->schedule_full_collection(); } } void ImmixGC::ObjectDescriber::set_forwarding_pointer(memory::Address from, memory::Address to) { from.as<Object>()->set_forward(to.as<Object>()); } ImmixGC::ImmixGC(Memory* om) : GarbageCollector(om) , allocator_(gc_.block_allocator()) , memory_(om) , marker_(NULL) , chunks_left_(0) , chunks_before_collection_(10) , diagnostics_(Diagnostics()) { gc_.describer().set_object_memory(om, this); reset_chunks_left(); } ImmixGC::~ImmixGC() { if(marker_) { delete marker_; } } memory::Address ImmixGC::ObjectDescriber::copy(memory::Address original, ImmixAllocator& alloc) { Object* orig = original.as<Object>(); bool collect_flag = false; memory::Address copy_addr = alloc.allocate( orig->size_in_bytes(object_memory_->vm()), collect_flag); if(collect_flag) { object_memory_->schedule_full_collection(); } Object* copy = copy_addr.as<Object>(); copy->initialize_full_state(object_memory_->vm(), orig, 0); copy->set_zone(MatureObjectZone); copy->set_in_immix(); return copy_addr; } int ImmixGC::ObjectDescriber::size(memory::Address addr) { return addr.as<Object>()->size_in_bytes(object_memory_->vm()); } Address ImmixGC::ObjectDescriber::update_pointer(Address addr) { Object* obj = addr.as<Object>(); if(!obj) return Address::null(); if(obj->young_object_p()) { if(obj->forwarded_p()) return obj->forward(); return Address::null(); } else { // we must remember this because it might // contain references to young gen objects object_memory_->remember_object(obj); } return addr; } bool ImmixGC::ObjectDescriber::mark_address(Address addr, MarkStack& ms, bool push) { Object* obj = addr.as<Object>(); if(obj->marked_p(object_memory_->mark())) return false; obj->mark(object_memory_, object_memory_->mark()); if(push) ms.push_back(addr); // If this is a young object, let the GC know not to try and mark // the block it's in. return obj->in_immix_p(); } Object* ImmixGC::allocate(uint32_t bytes, bool& collect_now) { if(bytes > cMaxObjectSize) return 0; Object* obj = allocator_.allocate(bytes, collect_now).as<Object>(); obj->init_header(MatureObjectZone, InvalidType); obj->set_in_immix(); return obj; } Object* ImmixGC::move_object(Object* orig, uint32_t bytes, bool& collect_now) { if(bytes > cMaxObjectSize) return 0; Object* obj = allocator_.allocate(bytes, collect_now).as<Object>(); memcpy(obj, orig, bytes); obj->set_zone(MatureObjectZone); obj->set_in_immix(); orig->set_forward(obj); return obj; } Object* ImmixGC::saw_object(Object* obj) { #ifdef ENABLE_OBJECT_WATCH if(watched_p(obj)) { std::cout << "detected " << obj << " during immix scanning.\n"; } #endif if(!obj->reference_p()) return NULL; memory::Address fwd = gc_.mark_address(memory::Address(obj), allocator_); Object* copy = fwd.as<Object>(); // Check and update an inflated header if(copy && copy != obj) { obj->set_forward(copy); return copy; } // Always return NULL for non moved objects return NULL; } void ImmixGC::scanned_object(Object* obj) { obj->scanned(); } bool ImmixGC::mature_gc_in_progress() { return object_memory_->mature_gc_in_progress(); } ObjectPosition ImmixGC::validate_object(Object* obj) { if(gc_.allocated_address(memory::Address(obj))) { if(obj->in_immix_p()) { return cInImmix; } else { return cInImmixCorruptHeader; } } return cUnknown; } /** * Performs a garbage collection of the immix space. */ void ImmixGC::collect(GCData* data) { gc_.clear_marks(); } void ImmixGC::collect_start(GCData* data) { gc_.clear_marks(); collect_scan(data); marker_->concurrent_mark(data); } void ImmixGC::collect_scan(GCData* data) { for(Roots::Iterator i(data->roots()); i.more(); i.advance()) { if(Object* fwd = saw_object(i->get())) { i->set(fwd); } } { utilities::thread::SpinLock::LockGuard guard(data->thread_nexus()->threads_lock()); for(ThreadList::iterator i = data->thread_nexus()->threads()->begin(); i != data->thread_nexus()->threads()->end(); ++i) { scan(*i, false); } } for(Allocator<capi::Handle>::Iterator i(data->handles()->allocator()); i.more(); i.advance()) { if(i->in_use_p() && !i->weak_p()) { if(Object* fwd = saw_object(i->object())) { i->set_object(fwd); } } } std::list<capi::GlobalHandle*>* gh = data->global_handle_locations(); if(gh) { for(std::list<capi::GlobalHandle*>::iterator i = gh->begin(); i != gh->end(); ++i) { capi::Handle** loc = (*i)->handle(); if(capi::Handle* hdl = *loc) { if(!REFERENCE_P(hdl)) continue; if(hdl->valid_p()) { Object* obj = hdl->object(); if(obj && obj->reference_p()) { if(Object* fwd = saw_object(obj)) { hdl->set_object(fwd); } } } else { std::cerr << "Detected bad handle checking global capi handles\n"; } } } } #ifdef ENABLE_LLVM if(LLVMState* ls = data->llvm_state()) ls->gc_scan(this); #endif } void ImmixGC::collect_finish(GCData* data) { collect_scan(data); process_mark_stack(); ObjectArray* marked_set = object_memory_->swap_marked_set(); for(ObjectArray::iterator oi = marked_set->begin(); oi != marked_set->end(); ++oi) { Object* obj = *oi; if(obj) { if(Object* fwd = saw_object(obj)) { *oi = fwd; } } } delete marked_set; // Users manipulate values accessible from the data* within an // RData without running a write barrier. Thusly if we see any rdata // we must always scan it again here because it could contain new pointers. // // We do this in a loop because the scanning might generate new entries // on the mark stack. do { for(Allocator<capi::Handle>::Iterator i(data->handles()->allocator()); i.more(); i.advance()) { capi::Handle* hdl = i.current(); if(!hdl->in_use_p()) continue; if(hdl->is_rdata()) { Object* obj = hdl->object(); if(obj->marked_p(object_memory_->mark())) { scan_object(obj); } } } } while(process_mark_stack()); // We've now finished marking the entire object graph. // Clean weakrefs before keeping additional objects alive // for finalization, so people don't get a hold of finalized // objects through weakrefs. clean_weakrefs(); // Marking objects to be Finalized can cause more things to continue to // live, so we must check the mark_stack again. do { walk_finalizers(); scan_fibers(data, true); } while(process_mark_stack()); // Remove unreachable locked objects still in the list { utilities::thread::SpinLock::LockGuard guard(data->thread_nexus()->threads_lock()); for(ThreadList::iterator i = data->thread_nexus()->threads()->begin(); i != data->thread_nexus()->threads()->end(); ++i) { clean_locked_objects(*i, false); } } // Clear unreachable objects from the various remember sets unsigned int mark = object_memory_->mark(); object_memory_->unremember_objects(mark); } void ImmixGC::sweep() { // Copy marks for use in new allocations gc_.copy_marks(); // Sweep up the garbage gc_.sweep_blocks(); // This resets the allocator state to sync it up with the BlockAllocator // properly. allocator_.get_new_block(); { timer::StopWatch<timer::microseconds> timer( vm()->metrics().gc.immix_diagnostics_us); diagnostics_ = Diagnostics(diagnostics_.collections_); // Now, calculate how much space we're still using. Chunks& chunks = gc_.block_allocator().chunks(); AllBlockIterator iter(chunks); diagnostics_.chunks_ = chunks.size(); while(Block* block = iter.next()) { diagnostics_.holes_ += block->holes(); diagnostics_.objects_ += block->objects(); diagnostics_.bytes_ += block->object_bytes(); diagnostics_.total_bytes_ += cBlockSize; } diagnostics_.percentage_ = (double)diagnostics_.bytes_ / (double)diagnostics_.total_bytes_; diagnostics_.collections_++; diagnostics_.modify(); } if(diagnostics_.percentage_ >= 0.90) { gc_.block_allocator().add_chunk(); } } void ImmixGC::start_marker(STATE) { if(!marker_) { marker_ = new ImmixMarker(state, this); } } bool ImmixGC::process_mark_stack() { bool exit = false; return gc_.process_mark_stack(allocator_, exit); } bool ImmixGC::process_mark_stack(bool& exit) { return gc_.process_mark_stack(allocator_, exit); } MarkStack& ImmixGC::mark_stack() { return gc_.mark_stack(); } void ImmixGC::walk_finalizers() { FinalizerThread* fh = object_memory_->finalizer_handler(); if(!fh) return; for(FinalizerThread::iterator i = fh->begin(); !i.end(); /* advance is handled in the loop */) { FinalizeObject& fi = i.current(); bool live = fi.object->marked_p(object_memory_->mark()); if(fi.ruby_finalizer) { if(Object* fwd = saw_object(fi.ruby_finalizer)) { fi.ruby_finalizer = fwd; } } if(Object* fwd = saw_object(fi.object)) { fi.object = fwd; } i.next(live); } } } } <commit_msg>Fixed namespaced references to Address.<commit_after>#include "memory.hpp" #include "memory/immix_collector.hpp" #include "memory/immix_marker.hpp" #include "capi/handles.hpp" #include "capi/tag.hpp" #include "object_watch.hpp" #include "configuration.hpp" #include "instruments/timing.hpp" #include "util/logger.hpp" #ifdef ENABLE_LLVM #include "llvm/state.hpp" #endif namespace rubinius { namespace memory { void ImmixGC::Diagnostics::log() { if(!modified_p()) return; diagnostics::Diagnostics::log(); utilities::logger::write("immix: diagnostics: " \ "collections: %ld, " \ "objects: %ld, " \ "bytes: %ld, " \ "total_bytes: %ld, " \ "chunks: %ld, " \ "holes: %ld, " \ "percentage: %f", collections_, objects_, bytes_, total_bytes_, chunks_, holes_, percentage_); } void ImmixGC::ObjectDescriber::added_chunk(int count) { if(object_memory_) { object_memory_->vm()->metrics().memory.immix_chunks++; if(gc_->dec_chunks_left() <= 0) { gc_->reset_chunks_left(); } } } /** * This means we're getting low on memory! Time to schedule a garbage * collection. */ void ImmixGC::ObjectDescriber::last_block() { if(object_memory_) { object_memory_->schedule_full_collection(); } } void ImmixGC::ObjectDescriber::set_forwarding_pointer(Address from, Address to) { from.as<Object>()->set_forward(to.as<Object>()); } ImmixGC::ImmixGC(Memory* om) : GarbageCollector(om) , allocator_(gc_.block_allocator()) , memory_(om) , marker_(NULL) , chunks_left_(0) , chunks_before_collection_(10) , diagnostics_(Diagnostics()) { gc_.describer().set_object_memory(om, this); reset_chunks_left(); } ImmixGC::~ImmixGC() { if(marker_) { delete marker_; } } Address ImmixGC::ObjectDescriber::copy(Address original, ImmixAllocator& alloc) { Object* orig = original.as<Object>(); bool collect_flag = false; Address copy_addr = alloc.allocate( orig->size_in_bytes(object_memory_->vm()), collect_flag); if(collect_flag) { object_memory_->schedule_full_collection(); } Object* copy = copy_addr.as<Object>(); copy->initialize_full_state(object_memory_->vm(), orig, 0); copy->set_zone(MatureObjectZone); copy->set_in_immix(); return copy_addr; } int ImmixGC::ObjectDescriber::size(Address addr) { return addr.as<Object>()->size_in_bytes(object_memory_->vm()); } Address ImmixGC::ObjectDescriber::update_pointer(Address addr) { Object* obj = addr.as<Object>(); if(!obj) return Address::null(); if(obj->young_object_p()) { if(obj->forwarded_p()) return obj->forward(); return Address::null(); } else { // we must remember this because it might // contain references to young gen objects object_memory_->remember_object(obj); } return addr; } bool ImmixGC::ObjectDescriber::mark_address(Address addr, MarkStack& ms, bool push) { Object* obj = addr.as<Object>(); if(obj->marked_p(object_memory_->mark())) return false; obj->mark(object_memory_, object_memory_->mark()); if(push) ms.push_back(addr); // If this is a young object, let the GC know not to try and mark // the block it's in. return obj->in_immix_p(); } Object* ImmixGC::allocate(uint32_t bytes, bool& collect_now) { if(bytes > cMaxObjectSize) return 0; Object* obj = allocator_.allocate(bytes, collect_now).as<Object>(); obj->init_header(MatureObjectZone, InvalidType); obj->set_in_immix(); return obj; } Object* ImmixGC::move_object(Object* orig, uint32_t bytes, bool& collect_now) { if(bytes > cMaxObjectSize) return 0; Object* obj = allocator_.allocate(bytes, collect_now).as<Object>(); memcpy(obj, orig, bytes); obj->set_zone(MatureObjectZone); obj->set_in_immix(); orig->set_forward(obj); return obj; } Object* ImmixGC::saw_object(Object* obj) { #ifdef ENABLE_OBJECT_WATCH if(watched_p(obj)) { std::cout << "detected " << obj << " during immix scanning.\n"; } #endif if(!obj->reference_p()) return NULL; Address fwd = gc_.mark_address(Address(obj), allocator_); Object* copy = fwd.as<Object>(); // Check and update an inflated header if(copy && copy != obj) { obj->set_forward(copy); return copy; } // Always return NULL for non moved objects return NULL; } void ImmixGC::scanned_object(Object* obj) { obj->scanned(); } bool ImmixGC::mature_gc_in_progress() { return object_memory_->mature_gc_in_progress(); } ObjectPosition ImmixGC::validate_object(Object* obj) { if(gc_.allocated_address(Address(obj))) { if(obj->in_immix_p()) { return cInImmix; } else { return cInImmixCorruptHeader; } } return cUnknown; } /** * Performs a garbage collection of the immix space. */ void ImmixGC::collect(GCData* data) { gc_.clear_marks(); } void ImmixGC::collect_start(GCData* data) { gc_.clear_marks(); collect_scan(data); marker_->concurrent_mark(data); } void ImmixGC::collect_scan(GCData* data) { for(Roots::Iterator i(data->roots()); i.more(); i.advance()) { if(Object* fwd = saw_object(i->get())) { i->set(fwd); } } { utilities::thread::SpinLock::LockGuard guard(data->thread_nexus()->threads_lock()); for(ThreadList::iterator i = data->thread_nexus()->threads()->begin(); i != data->thread_nexus()->threads()->end(); ++i) { scan(*i, false); } } for(Allocator<capi::Handle>::Iterator i(data->handles()->allocator()); i.more(); i.advance()) { if(i->in_use_p() && !i->weak_p()) { if(Object* fwd = saw_object(i->object())) { i->set_object(fwd); } } } std::list<capi::GlobalHandle*>* gh = data->global_handle_locations(); if(gh) { for(std::list<capi::GlobalHandle*>::iterator i = gh->begin(); i != gh->end(); ++i) { capi::Handle** loc = (*i)->handle(); if(capi::Handle* hdl = *loc) { if(!REFERENCE_P(hdl)) continue; if(hdl->valid_p()) { Object* obj = hdl->object(); if(obj && obj->reference_p()) { if(Object* fwd = saw_object(obj)) { hdl->set_object(fwd); } } } else { std::cerr << "Detected bad handle checking global capi handles\n"; } } } } #ifdef ENABLE_LLVM if(LLVMState* ls = data->llvm_state()) ls->gc_scan(this); #endif } void ImmixGC::collect_finish(GCData* data) { collect_scan(data); process_mark_stack(); ObjectArray* marked_set = object_memory_->swap_marked_set(); for(ObjectArray::iterator oi = marked_set->begin(); oi != marked_set->end(); ++oi) { Object* obj = *oi; if(obj) { if(Object* fwd = saw_object(obj)) { *oi = fwd; } } } delete marked_set; // Users manipulate values accessible from the data* within an // RData without running a write barrier. Thusly if we see any rdata // we must always scan it again here because it could contain new pointers. // // We do this in a loop because the scanning might generate new entries // on the mark stack. do { for(Allocator<capi::Handle>::Iterator i(data->handles()->allocator()); i.more(); i.advance()) { capi::Handle* hdl = i.current(); if(!hdl->in_use_p()) continue; if(hdl->is_rdata()) { Object* obj = hdl->object(); if(obj->marked_p(object_memory_->mark())) { scan_object(obj); } } } } while(process_mark_stack()); // We've now finished marking the entire object graph. // Clean weakrefs before keeping additional objects alive // for finalization, so people don't get a hold of finalized // objects through weakrefs. clean_weakrefs(); // Marking objects to be Finalized can cause more things to continue to // live, so we must check the mark_stack again. do { walk_finalizers(); scan_fibers(data, true); } while(process_mark_stack()); // Remove unreachable locked objects still in the list { utilities::thread::SpinLock::LockGuard guard(data->thread_nexus()->threads_lock()); for(ThreadList::iterator i = data->thread_nexus()->threads()->begin(); i != data->thread_nexus()->threads()->end(); ++i) { clean_locked_objects(*i, false); } } // Clear unreachable objects from the various remember sets unsigned int mark = object_memory_->mark(); object_memory_->unremember_objects(mark); } void ImmixGC::sweep() { // Copy marks for use in new allocations gc_.copy_marks(); // Sweep up the garbage gc_.sweep_blocks(); // This resets the allocator state to sync it up with the BlockAllocator // properly. allocator_.get_new_block(); { timer::StopWatch<timer::microseconds> timer( vm()->metrics().gc.immix_diagnostics_us); diagnostics_ = Diagnostics(diagnostics_.collections_); // Now, calculate how much space we're still using. Chunks& chunks = gc_.block_allocator().chunks(); AllBlockIterator iter(chunks); diagnostics_.chunks_ = chunks.size(); while(Block* block = iter.next()) { diagnostics_.holes_ += block->holes(); diagnostics_.objects_ += block->objects(); diagnostics_.bytes_ += block->object_bytes(); diagnostics_.total_bytes_ += cBlockSize; } diagnostics_.percentage_ = (double)diagnostics_.bytes_ / (double)diagnostics_.total_bytes_; diagnostics_.collections_++; diagnostics_.modify(); } if(diagnostics_.percentage_ >= 0.90) { gc_.block_allocator().add_chunk(); } } void ImmixGC::start_marker(STATE) { if(!marker_) { marker_ = new ImmixMarker(state, this); } } bool ImmixGC::process_mark_stack() { bool exit = false; return gc_.process_mark_stack(allocator_, exit); } bool ImmixGC::process_mark_stack(bool& exit) { return gc_.process_mark_stack(allocator_, exit); } MarkStack& ImmixGC::mark_stack() { return gc_.mark_stack(); } void ImmixGC::walk_finalizers() { FinalizerThread* fh = object_memory_->finalizer_handler(); if(!fh) return; for(FinalizerThread::iterator i = fh->begin(); !i.end(); /* advance is handled in the loop */) { FinalizeObject& fi = i.current(); bool live = fi.object->marked_p(object_memory_->mark()); if(fi.ruby_finalizer) { if(Object* fwd = saw_object(fi.ruby_finalizer)) { fi.ruby_finalizer = fwd; } } if(Object* fwd = saw_object(fi.object)) { fi.object = fwd; } i.next(live); } } } } <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <[email protected]>" // Copyright 2007 Inge Wallin <[email protected]>" // #include "PlacemarkManager.h" #include <QtCore/QBuffer> #include <QtCore/QByteArray> #include <QtCore/QDataStream> #include <QtCore/QDateTime> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtXml/QXmlInputSource> #include <QtXml/QXmlSimpleReader> #include "KmlFileViewItem.h" #include "FileViewModel.h" #include "MarbleDirs.h" #include "MarblePlacemarkModel.h" #include "MarbleGeometryModel.h" #include "PlacemarkContainer.h" #include "PlacemarkLoader.h" #include "GeoDataDocument.h" #include "GeoDataParser.h" #include "GeoDataPlacemark.h" using namespace Marble; namespace Marble { class PlacemarkManagerPrivate { public: PlacemarkManagerPrivate( QObject* parent ) : m_model( 0 ) , m_geomodel( new MarbleGeometryModel() ) , m_target( QString() ) , m_finalized( true ) , m_fileViewModel( new FileViewModel(parent ) ) { }; MarblePlacemarkModel* m_model; MarbleGeometryModel* m_geomodel; QList<PlacemarkLoader*> m_loaderList; FileViewModel* m_fileViewModel; bool m_finalized; QString m_target; }; } PlacemarkManager::PlacemarkManager( QObject *parent ) : QObject( parent ) , d( new PlacemarkManagerPrivate( parent ) ) { } PlacemarkManager::~PlacemarkManager() { foreach( PlacemarkLoader *loader, d->m_loaderList ) { if ( loader ) { loader->wait(); } } delete d->m_model; delete d->m_fileViewModel; delete d; /* do not delete the d->m_geomodel here * it is not this models property */ } MarblePlacemarkModel* PlacemarkManager::model() const { return d->m_model; } FileViewModel* PlacemarkManager::fileViewModel() const { return d->m_fileViewModel; } MarbleGeometryModel* PlacemarkManager::geomodel() const { return d->m_geomodel; } void PlacemarkManager::setGeoModel( MarbleGeometryModel * model ) { d->m_geomodel = model; } void PlacemarkManager::setPlacemarkModel( MarblePlacemarkModel *model ) { d->m_model = model; } void PlacemarkManager::clearPlacemarks() { d->m_model->clearPlacemarks(); } void PlacemarkManager::addPlacemarkFile( const QString& filepath, bool finalized ) { if( !(d->m_model->containers().contains( filepath ) ) ) { qDebug() << "adding container:" << filepath << finalized; PlacemarkLoader* loader = new PlacemarkLoader( this, filepath, finalized ); connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) ); connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), this, SLOT( cleanupLoader( PlacemarkLoader* ) ) ); connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), this, SIGNAL( geoDataDocumentAdded( GeoDataDocument* ) ) ); connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) ); d->m_loaderList.append( loader ); loader->start(); } } void PlacemarkManager::addGeoDataDocument( GeoDataDocument* document ) { AbstractFileViewItem* item = new KmlFileViewItem( *this, *document ); d->m_fileViewModel->append( item ); } void PlacemarkManager::addPlacemarkData( const QString& data, const QString& key ) { loadKmlFromData( data, key, false ); } void PlacemarkManager::removePlacemarkKey( const QString& key ) { QString nkey = key; qDebug() << "trying to remove file:" << key; for( int i = 0; i < d->m_fileViewModel->rowCount(); ++i ) { if(nkey.remove(".kml").remove(".cache") == d->m_fileViewModel->data(d->m_fileViewModel->index(i, 0)).toString().remove(".kml").remove(".cache")) { d->m_fileViewModel->remove(d->m_fileViewModel->index(i, 0)); } }; } void PlacemarkManager::cleanupLoader( PlacemarkLoader* loader ) { d->m_loaderList.removeAll( loader ); if ( loader->isFinished() ) { delete loader; } } void PlacemarkManager::loadPlacemarkContainer( PlacemarkLoader* loader, PlacemarkContainer * container ) { qDebug() << "Containername:" << container->name() << "to be finalized:" << loader->finalize() << d->m_loaderList.size(); d->m_loaderList.removeAll( loader ); if ( container ) { d->m_model->addPlacemarks( *container, false, d->m_finalized && d->m_loaderList.isEmpty() ); } if( 0 == d->m_loaderList.size() ) emit finalize(); if ( loader->isFinished() ) { delete loader; } } void PlacemarkManager::loadKml( const QString& filename, bool clearPrevious ) { addPlacemarkFile( filename, true ); } void PlacemarkManager::loadKmlFromData( const QString& data, const QString& key, bool finalize ) { Q_ASSERT( d->m_model != 0 && "You have called loadKmlFromData before creating a model!" ); PlacemarkContainer container; d->m_finalized = true; qDebug() << "adding container:" << key; PlacemarkLoader* loader = new PlacemarkLoader( this, data, key ); connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) ); connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), this, SLOT( cleanupLoader( PlacemarkLoader* ) ) ); connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), this, SIGNAL( geoDataDocumentAdded( GeoDataDocument* ) ) ); connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) ); d->m_loaderList.append( loader ); loader->start(); } #include "PlacemarkManager.moc" <commit_msg>use isEmpty() instead of compairing sizes<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <[email protected]>" // Copyright 2007 Inge Wallin <[email protected]>" // #include "PlacemarkManager.h" #include <QtCore/QBuffer> #include <QtCore/QByteArray> #include <QtCore/QDataStream> #include <QtCore/QDateTime> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtXml/QXmlInputSource> #include <QtXml/QXmlSimpleReader> #include "KmlFileViewItem.h" #include "FileViewModel.h" #include "MarbleDirs.h" #include "MarblePlacemarkModel.h" #include "MarbleGeometryModel.h" #include "PlacemarkContainer.h" #include "PlacemarkLoader.h" #include "GeoDataDocument.h" #include "GeoDataParser.h" #include "GeoDataPlacemark.h" using namespace Marble; namespace Marble { class PlacemarkManagerPrivate { public: PlacemarkManagerPrivate( QObject* parent ) : m_model( 0 ) , m_geomodel( new MarbleGeometryModel() ) , m_target( QString() ) , m_finalized( true ) , m_fileViewModel( new FileViewModel(parent ) ) { }; MarblePlacemarkModel* m_model; MarbleGeometryModel* m_geomodel; QList<PlacemarkLoader*> m_loaderList; FileViewModel* m_fileViewModel; bool m_finalized; QString m_target; }; } PlacemarkManager::PlacemarkManager( QObject *parent ) : QObject( parent ) , d( new PlacemarkManagerPrivate( parent ) ) { } PlacemarkManager::~PlacemarkManager() { foreach( PlacemarkLoader *loader, d->m_loaderList ) { if ( loader ) { loader->wait(); } } delete d->m_model; delete d->m_fileViewModel; delete d; /* do not delete the d->m_geomodel here * it is not this models property */ } MarblePlacemarkModel* PlacemarkManager::model() const { return d->m_model; } FileViewModel* PlacemarkManager::fileViewModel() const { return d->m_fileViewModel; } MarbleGeometryModel* PlacemarkManager::geomodel() const { return d->m_geomodel; } void PlacemarkManager::setGeoModel( MarbleGeometryModel * model ) { d->m_geomodel = model; } void PlacemarkManager::setPlacemarkModel( MarblePlacemarkModel *model ) { d->m_model = model; } void PlacemarkManager::clearPlacemarks() { d->m_model->clearPlacemarks(); } void PlacemarkManager::addPlacemarkFile( const QString& filepath, bool finalized ) { if( !(d->m_model->containers().contains( filepath ) ) ) { qDebug() << "adding container:" << filepath << finalized; PlacemarkLoader* loader = new PlacemarkLoader( this, filepath, finalized ); connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) ); connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), this, SLOT( cleanupLoader( PlacemarkLoader* ) ) ); connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), this, SIGNAL( geoDataDocumentAdded( GeoDataDocument* ) ) ); connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) ); d->m_loaderList.append( loader ); loader->start(); } } void PlacemarkManager::addGeoDataDocument( GeoDataDocument* document ) { AbstractFileViewItem* item = new KmlFileViewItem( *this, *document ); d->m_fileViewModel->append( item ); } void PlacemarkManager::addPlacemarkData( const QString& data, const QString& key ) { loadKmlFromData( data, key, false ); } void PlacemarkManager::removePlacemarkKey( const QString& key ) { QString nkey = key; qDebug() << "trying to remove file:" << key; for( int i = 0; i < d->m_fileViewModel->rowCount(); ++i ) { if(nkey.remove(".kml").remove(".cache") == d->m_fileViewModel->data(d->m_fileViewModel->index(i, 0)).toString().remove(".kml").remove(".cache")) { d->m_fileViewModel->remove(d->m_fileViewModel->index(i, 0)); } }; } void PlacemarkManager::cleanupLoader( PlacemarkLoader* loader ) { d->m_loaderList.removeAll( loader ); if ( loader->isFinished() ) { delete loader; } } void PlacemarkManager::loadPlacemarkContainer( PlacemarkLoader* loader, PlacemarkContainer * container ) { qDebug() << "Containername:" << container->name() << "to be finalized:" << (d->m_loaderList.size() == 1) << d->m_loaderList.size(); d->m_loaderList.removeAll( loader ); if ( container ) { d->m_model->addPlacemarks( *container, false, d->m_finalized && d->m_loaderList.isEmpty() ); } if( d->m_loaderList.isEmpty() ) { emit finalize(); } if ( loader->isFinished() ) { delete loader; } } void PlacemarkManager::loadKml( const QString& filename, bool clearPrevious ) { addPlacemarkFile( filename, true ); } void PlacemarkManager::loadKmlFromData( const QString& data, const QString& key, bool finalize ) { Q_ASSERT( d->m_model != 0 && "You have called loadKmlFromData before creating a model!" ); PlacemarkContainer container; d->m_finalized = true; qDebug() << "adding container:" << key; PlacemarkLoader* loader = new PlacemarkLoader( this, data, key ); connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) ); connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), this, SLOT( cleanupLoader( PlacemarkLoader* ) ) ); connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), this, SIGNAL( geoDataDocumentAdded( GeoDataDocument* ) ) ); connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) ); d->m_loaderList.append( loader ); loader->start(); } #include "PlacemarkManager.moc" <|endoftext|>
<commit_before>#include "shape/sphere.h" namespace AT_NAME { static AT_DEVICE_API void getUV(real& u, real& v, const aten::vec3& p) { auto phi = aten::asin(p.y); auto theta = aten::atan(p.x / p.z); u = (theta + AT_MATH_PI_HALF) / AT_MATH_PI; v = (phi + AT_MATH_PI_HALF) / AT_MATH_PI; } sphere::sphere(const aten::vec3& center, real radius, material* mtrl) : m_param(center, radius, mtrl) { auto _min = center - radius; auto _max = center + radius; m_aabb.init(_min, _max); } bool sphere::hit( const aten::ray& r, real t_min, real t_max, aten::Intersection& isect) const { bool isHit = hit(&m_param, r, t_min, t_max, &isect); if (isHit) { isect.objid = id(); isect.mtrlid = ((material*)m_param.mtrl.ptr)->id(); } return isHit; } bool AT_DEVICE_API sphere::hit( const aten::ShapeParameter* param, const aten::ray& r, real t_min, real t_max, aten::Intersection* isect) { // NOTE // https://www.slideshare.net/h013/edupt-kaisetsu-22852235 // p52 - p58 const aten::vec3 p_o = param->center - r.org; const real b = dot(p_o, r.dir); // ʎ. const real D4 = b * b - dot(p_o, p_o) + param->radius * param->radius; if (D4 < real(0)) { return false; } const real sqrt_D4 = aten::sqrt(D4); const real t1 = b - sqrt_D4; const real t2 = b + sqrt_D4; #if 0 if (t1 > AT_MATH_EPSILON) { isect->t = t1; } else if (t2 > AT_MATH_EPSILON) { isect->t = t2; } else { return false; } #elif 1 bool close = aten::isClose(aten::abs(b), sqrt_D4, 25000); if (t1 > AT_MATH_EPSILON && !close) { isect->t = t1; } else if (t2 > AT_MATH_EPSILON && !close) { isect->t = t2; } else { return false; } #else if (t1 < 0 && t2 < 0) { return false; } else if (t1 > 0 && t2 > 0) { isect->t = aten::cmpMin(t1, t2); } else { isect->t = aten::cmpMax(t1, t2); } #endif return true; } void sphere::evalHitResult( const aten::ray& r, aten::hitrecord& rec, const aten::Intersection& isect) const { evalHitResult(&m_param, r, aten::mat4(), &rec, &isect); } void sphere::evalHitResult( const aten::ray& r, const aten::mat4& mtxL2W, aten::hitrecord& rec, const aten::Intersection& isect) const { evalHitResult(&m_param, r, mtxL2W, &rec, &isect); } void sphere::evalHitResult( const aten::ShapeParameter* param, const aten::ray& r, aten::hitrecord* rec, const aten::Intersection* isect) { evalHitResult(param, r, aten::mat4(), rec, isect); } void sphere::evalHitResult( const aten::ShapeParameter* param, const aten::ray& r, const aten::mat4& mtxL2W, aten::hitrecord* rec, const aten::Intersection* isect) { rec->p = r.org + isect->t * r.dir; rec->normal = (rec->p - param->center) / param->radius; // KĖ@𓾂 rec->objid = isect->objid; rec->mtrlid = isect->mtrlid; { auto tmp = param->center + aten::vec3(param->radius, 0, 0); auto center = mtxL2W.apply(param->center); tmp = mtxL2W.apply(tmp); auto radius = length(tmp - center); rec->area = 4 * AT_MATH_PI * radius * radius; } getUV(rec->u, rec->v, rec->normal); } void sphere::getSamplePosNormalArea( aten::hitable::SamplePosNormalPdfResult* result, aten::sampler* sampler) const { return getSamplePosNormalArea(result, aten::mat4::Identity, sampler); } AT_DEVICE_API void sphere::getSamplePosNormalArea( aten::hitable::SamplePosNormalPdfResult* result, const aten::ShapeParameter* param, aten::sampler* sampler) { getSamplePosNormalArea(result, param, aten::mat4(), sampler); } void sphere::getSamplePosNormalArea( aten::hitable::SamplePosNormalPdfResult* result, const aten::mat4& mtxL2W, aten::sampler* sampler) const { getSamplePosNormalArea(result, &m_param, mtxL2W, sampler); } void sphere::getSamplePosNormalArea( aten::hitable::SamplePosNormalPdfResult* result, const aten::ShapeParameter* param, const aten::mat4& mtxL2W, aten::sampler* sampler) { auto r1 = sampler->nextSample(); auto r2 = sampler->nextSample(); auto r = param->radius; auto z = real(2) * r1 - real(1); // [0,1] -> [-1, 1] auto sin_theta = aten::sqrt(1 - z * z); auto phi = 2 * AT_MATH_PI * r2; auto x = aten::cos(phi) * sin_theta; auto y = aten::sin(phi) * sin_theta; aten::vec3 dir = aten::vec3(x, y, z); dir = normalize(dir); auto p = dir * (r + AT_MATH_EPSILON); result->pos = param->center + p; result->nml = normalize(result->pos - param->center); result->area = real(1); { auto tmp = param->center + aten::vec3(param->radius, 0, 0); auto center = mtxL2W.apply(param->center); tmp = mtxL2W.apply(tmp); auto radius = length(tmp - center); result->area = 4 * AT_MATH_PI * radius * radius; } } } <commit_msg>Modify threshold to hit test for sphere.<commit_after>#include "shape/sphere.h" namespace AT_NAME { static AT_DEVICE_API void getUV(real& u, real& v, const aten::vec3& p) { auto phi = aten::asin(p.y); auto theta = aten::atan(p.x / p.z); u = (theta + AT_MATH_PI_HALF) / AT_MATH_PI; v = (phi + AT_MATH_PI_HALF) / AT_MATH_PI; } sphere::sphere(const aten::vec3& center, real radius, material* mtrl) : m_param(center, radius, mtrl) { auto _min = center - radius; auto _max = center + radius; m_aabb.init(_min, _max); } bool sphere::hit( const aten::ray& r, real t_min, real t_max, aten::Intersection& isect) const { bool isHit = hit(&m_param, r, t_min, t_max, &isect); if (isHit) { isect.objid = id(); isect.mtrlid = ((material*)m_param.mtrl.ptr)->id(); } return isHit; } bool AT_DEVICE_API sphere::hit( const aten::ShapeParameter* param, const aten::ray& r, real t_min, real t_max, aten::Intersection* isect) { // NOTE // https://www.slideshare.net/h013/edupt-kaisetsu-22852235 // p52 - p58 const aten::vec3 p_o = param->center - r.org; const real b = dot(p_o, r.dir); // ʎ. const real D4 = b * b - dot(p_o, p_o) + param->radius * param->radius; if (D4 < real(0)) { return false; } const real sqrt_D4 = aten::sqrt(D4); const real t1 = b - sqrt_D4; const real t2 = b + sqrt_D4; #if 0 if (t1 > AT_MATH_EPSILON) { isect->t = t1; } else if (t2 > AT_MATH_EPSILON) { isect->t = t2; } else { return false; } #elif 1 bool close = aten::isClose(aten::abs(b), sqrt_D4, 2500); if (t1 > AT_MATH_EPSILON && !close) { isect->t = t1; } else if (t2 > AT_MATH_EPSILON && !close) { isect->t = t2; } else { return false; } #else if (t1 < 0 && t2 < 0) { return false; } else if (t1 > 0 && t2 > 0) { isect->t = aten::cmpMin(t1, t2); } else { isect->t = aten::cmpMax(t1, t2); } #endif return true; } void sphere::evalHitResult( const aten::ray& r, aten::hitrecord& rec, const aten::Intersection& isect) const { evalHitResult(&m_param, r, aten::mat4(), &rec, &isect); } void sphere::evalHitResult( const aten::ray& r, const aten::mat4& mtxL2W, aten::hitrecord& rec, const aten::Intersection& isect) const { evalHitResult(&m_param, r, mtxL2W, &rec, &isect); } void sphere::evalHitResult( const aten::ShapeParameter* param, const aten::ray& r, aten::hitrecord* rec, const aten::Intersection* isect) { evalHitResult(param, r, aten::mat4(), rec, isect); } void sphere::evalHitResult( const aten::ShapeParameter* param, const aten::ray& r, const aten::mat4& mtxL2W, aten::hitrecord* rec, const aten::Intersection* isect) { rec->p = r.org + isect->t * r.dir; rec->normal = (rec->p - param->center) / param->radius; // KĖ@𓾂 rec->objid = isect->objid; rec->mtrlid = isect->mtrlid; { auto tmp = param->center + aten::vec3(param->radius, 0, 0); auto center = mtxL2W.apply(param->center); tmp = mtxL2W.apply(tmp); auto radius = length(tmp - center); rec->area = 4 * AT_MATH_PI * radius * radius; } getUV(rec->u, rec->v, rec->normal); } void sphere::getSamplePosNormalArea( aten::hitable::SamplePosNormalPdfResult* result, aten::sampler* sampler) const { return getSamplePosNormalArea(result, aten::mat4::Identity, sampler); } AT_DEVICE_API void sphere::getSamplePosNormalArea( aten::hitable::SamplePosNormalPdfResult* result, const aten::ShapeParameter* param, aten::sampler* sampler) { getSamplePosNormalArea(result, param, aten::mat4(), sampler); } void sphere::getSamplePosNormalArea( aten::hitable::SamplePosNormalPdfResult* result, const aten::mat4& mtxL2W, aten::sampler* sampler) const { getSamplePosNormalArea(result, &m_param, mtxL2W, sampler); } void sphere::getSamplePosNormalArea( aten::hitable::SamplePosNormalPdfResult* result, const aten::ShapeParameter* param, const aten::mat4& mtxL2W, aten::sampler* sampler) { auto r1 = sampler->nextSample(); auto r2 = sampler->nextSample(); auto r = param->radius; auto z = real(2) * r1 - real(1); // [0,1] -> [-1, 1] auto sin_theta = aten::sqrt(1 - z * z); auto phi = 2 * AT_MATH_PI * r2; auto x = aten::cos(phi) * sin_theta; auto y = aten::sin(phi) * sin_theta; aten::vec3 dir = aten::vec3(x, y, z); dir = normalize(dir); auto p = dir * (r + AT_MATH_EPSILON); result->pos = param->center + p; result->nml = normalize(result->pos - param->center); result->area = real(1); { auto tmp = param->center + aten::vec3(param->radius, 0, 0); auto center = mtxL2W.apply(param->center); tmp = mtxL2W.apply(tmp); auto radius = length(tmp - center); result->area = 4 * AT_MATH_PI * radius * radius; } } } <|endoftext|>
<commit_before>#include <iostream> #include "SDL.h" #include "fxgl_controllerinput.h" SDL_GameController* controllers[10]; int num_controllers = 0; /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: getBackendVersion * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_getBackendVersion (JNIEnv* env, jclass clazz) { SDL_version linked; SDL_GetVersion(&linked); return (int)linked.patch; } /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: connectControllers * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_connectControllers (JNIEnv* env, jclass clazz) { SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER); for (int i = 0; i < SDL_NumJoysticks(); ++i) { if (SDL_IsGameController(i)) { controller = SDL_GameControllerOpen(i); if (controller) { controllers[num_controllers++] = controller; } else { // TODO: add a callback with SDL_GetError() to say failed to access game controller } } } } /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: updateState * Signature: (I)V */ JNIEXPORT void JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_updateState (JNIEnv* env, jclass clazz, jint controller_id) { SDL_GameControllerUpdate(); } /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: isButtonPressed * Signature: (II)Z */ JNIEXPORT jboolean JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_isButtonPressed (JNIEnv* env, jclass clazz, jint controller_id, jint button_id) { if (controller_id >= num_controllers) { return JNI_FALSE; } SDL_GameControllerButton btn = static_cast<SDL_GameControllerButton>(button_id); if (SDL_GameControllerGetButton(controllers[controller_id], btn)) { return JNI_TRUE; } return JNI_FALSE; } /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: getAxis * Signature: (II)D */ JNIEXPORT jdouble JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_getAxis (JNIEnv* env, jclass clazz, jint controller_id, jint axis_id) { if (controller_id >= num_controllers) { return 0.0; } SDL_GameControllerAxis axis = static_cast<SDL_GameControllerAxis>(axis_id); return (jdouble)SDL_GameControllerGetAxis(controllers[controller_id], axis); } /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: disconnectControllers * Signature: ()V */ JNIEXPORT void JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_disconnectControllers (JNIEnv* env, jclass clazz) { for (int i = 0; i < num_controllers; i++) { SDL_GameControllerClose(controllers[i]); } SDL_Quit(); }<commit_msg>fixed not declared<commit_after>#include <iostream> #include "SDL.h" #include "fxgl_controllerinput.h" SDL_GameController* controllers[10]; int num_controllers = 0; /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: getBackendVersion * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_getBackendVersion (JNIEnv* env, jclass clazz) { SDL_version linked; SDL_GetVersion(&linked); return (int)linked.patch; } /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: connectControllers * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_connectControllers (JNIEnv* env, jclass clazz) { SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER); for (int i = 0; i < SDL_NumJoysticks(); ++i) { if (SDL_IsGameController(i)) { SDL_GameController* controller = SDL_GameControllerOpen(i); if (controller) { controllers[num_controllers++] = controller; } else { // TODO: add a callback with SDL_GetError() to say failed to access game controller } } } } /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: updateState * Signature: (I)V */ JNIEXPORT void JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_updateState (JNIEnv* env, jclass clazz, jint controller_id) { SDL_GameControllerUpdate(); } /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: isButtonPressed * Signature: (II)Z */ JNIEXPORT jboolean JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_isButtonPressed (JNIEnv* env, jclass clazz, jint controller_id, jint button_id) { if (controller_id >= num_controllers) { return JNI_FALSE; } SDL_GameControllerButton btn = static_cast<SDL_GameControllerButton>(button_id); if (SDL_GameControllerGetButton(controllers[controller_id], btn)) { return JNI_TRUE; } return JNI_FALSE; } /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: getAxis * Signature: (II)D */ JNIEXPORT jdouble JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_getAxis (JNIEnv* env, jclass clazz, jint controller_id, jint axis_id) { if (controller_id >= num_controllers) { return 0.0; } SDL_GameControllerAxis axis = static_cast<SDL_GameControllerAxis>(axis_id); return (jdouble)SDL_GameControllerGetAxis(controllers[controller_id], axis); } /* * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl * Method: disconnectControllers * Signature: ()V */ JNIEXPORT void JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_disconnectControllers (JNIEnv* env, jclass clazz) { for (int i = 0; i < num_controllers; i++) { SDL_GameControllerClose(controllers[i]); } SDL_Quit(); }<|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 "config.h" #include "webkit/glue/image_decoder.h" #include "base/compiler_specific.h" #include "third_party/skia/include/core/SkBitmap.h" MSVC_PUSH_WARNING_LEVEL(0); #if defined(OS_WIN) || defined(OS_LINUX) #include "ImageSourceSkia.h" #elif defined(OS_MACOSX) #include "ImageSource.h" #include "RetainPtr.h" #endif #include "IntSize.h" #include "RefPtr.h" #include "SharedBuffer.h" MSVC_POP_WARNING(); namespace webkit_glue { ImageDecoder::ImageDecoder() : desired_icon_size_(0, 0) { } ImageDecoder::ImageDecoder(const gfx::Size& desired_icon_size) : desired_icon_size_(desired_icon_size) { } ImageDecoder::~ImageDecoder() { } SkBitmap ImageDecoder::Decode(const unsigned char* data, size_t size) const { // What's going on here? ImageDecoder is only used by ImageResourceFetcher, // which is only used (but extensively) by WebViewImpl. On the Mac we're using // CoreGraphics, but right now WebViewImpl uses SkBitmaps everywhere. For now, // this is a convenient bottleneck to convert from CGImageRefs to SkBitmaps, // but in the future we will need to replumb to get CGImageRefs (or whatever // the native type is) everywhere, directly. #if defined(OS_WIN) || defined(OS_LINUX) WebCore::ImageSourceSkia source; #elif defined(OS_MACOSX) WebCore::ImageSource source; #endif WTF::RefPtr<WebCore::SharedBuffer> buffer(WebCore::SharedBuffer::create( data, static_cast<int>(size))); #if defined(OS_WIN) || defined(OS_LINUX) source.setData(buffer.get(), true, WebCore::IntSize(desired_icon_size_.width(), desired_icon_size_.height())); #elif defined(OS_MACOSX) source.setData(buffer.get(), true); #endif if (!source.isSizeAvailable()) return SkBitmap(); WebCore::NativeImagePtr frame0 = source.createFrameAtIndex(0); if (!frame0) return SkBitmap(); #if defined(OS_WIN) || defined(OS_LINUX) return *reinterpret_cast<SkBitmap*>(frame0); #elif defined(OS_MACOSX) // BitmapImage releases automatically, but we're bypassing it so we'll need // to do the releasing. RetainPtr<CGImageRef> image(AdoptCF, frame0); SkBitmap result; result.setConfig(SkBitmap::kARGB_8888_Config, CGImageGetWidth(image.get()), CGImageGetHeight(image.get())); // TODO(port): // This line is a waste, but is needed when the renderer sends a // ViewHostMsg_DidDownloadImage and tries to pickle the SkBitmap. // Presumably this will be removed when we (ImageDecoder::Decode()) // are changed to not return a fake SkBitmap. result.allocPixels(); RetainPtr<CGColorSpace> cg_color(AdoptCF, CGColorSpaceCreateDeviceRGB()); // The last parameter is a total guess. Feel free to adjust it if images draw // incorrectly. TODO(avi): Verify byte ordering; it should be possible to // swizzle bytes with various combinations of the byte order and alpha // constants. RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate( result.getPixels(), result.width(), result.height(), result.bytesPerPixel() * 8 / 4, result.rowBytes(), cg_color.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); CGRect rect = CGRectMake(0, 0, CGImageGetWidth(image.get()), CGImageGetHeight(image.get())); CGContextDrawImage(context.get(), rect, image.get()); return result; #endif } } // namespace webkit_glue <commit_msg>Fix a leak in ImageDecoder::Decode.<commit_after>// Copyright (c) 2006-2008 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 "config.h" #include "webkit/glue/image_decoder.h" #include "base/compiler_specific.h" #include "third_party/skia/include/core/SkBitmap.h" MSVC_PUSH_WARNING_LEVEL(0); #if defined(OS_WIN) || defined(OS_LINUX) #include "ImageSourceSkia.h" #include "NativeImageSkia.h" #elif defined(OS_MACOSX) #include "ImageSource.h" #include "RetainPtr.h" #endif #include "IntSize.h" #include "RefPtr.h" #include "SharedBuffer.h" MSVC_POP_WARNING(); namespace webkit_glue { ImageDecoder::ImageDecoder() : desired_icon_size_(0, 0) { } ImageDecoder::ImageDecoder(const gfx::Size& desired_icon_size) : desired_icon_size_(desired_icon_size) { } ImageDecoder::~ImageDecoder() { } SkBitmap ImageDecoder::Decode(const unsigned char* data, size_t size) const { // What's going on here? ImageDecoder is only used by ImageResourceFetcher, // which is only used (but extensively) by WebViewImpl. On the Mac we're using // CoreGraphics, but right now WebViewImpl uses SkBitmaps everywhere. For now, // this is a convenient bottleneck to convert from CGImageRefs to SkBitmaps, // but in the future we will need to replumb to get CGImageRefs (or whatever // the native type is) everywhere, directly. #if defined(OS_WIN) || defined(OS_LINUX) WebCore::ImageSourceSkia source; #elif defined(OS_MACOSX) WebCore::ImageSource source; #endif WTF::RefPtr<WebCore::SharedBuffer> buffer(WebCore::SharedBuffer::create( data, static_cast<int>(size))); #if defined(OS_WIN) || defined(OS_LINUX) source.setData(buffer.get(), true, WebCore::IntSize(desired_icon_size_.width(), desired_icon_size_.height())); #elif defined(OS_MACOSX) source.setData(buffer.get(), true); #endif if (!source.isSizeAvailable()) return SkBitmap(); WebCore::NativeImagePtr frame0 = source.createFrameAtIndex(0); if (!frame0) return SkBitmap(); #if defined(OS_WIN) || defined(OS_LINUX) SkBitmap retval = *reinterpret_cast<SkBitmap*>(frame0); delete frame0; return retval; #elif defined(OS_MACOSX) // TODO(port): should we delete frame0 like Linux/Windows do above? // BitmapImage releases automatically, but we're bypassing it so we'll need // to do the releasing. RetainPtr<CGImageRef> image(AdoptCF, frame0); SkBitmap result; result.setConfig(SkBitmap::kARGB_8888_Config, CGImageGetWidth(image.get()), CGImageGetHeight(image.get())); // TODO(port): // This line is a waste, but is needed when the renderer sends a // ViewHostMsg_DidDownloadImage and tries to pickle the SkBitmap. // Presumably this will be removed when we (ImageDecoder::Decode()) // are changed to not return a fake SkBitmap. result.allocPixels(); RetainPtr<CGColorSpace> cg_color(AdoptCF, CGColorSpaceCreateDeviceRGB()); // The last parameter is a total guess. Feel free to adjust it if images draw // incorrectly. TODO(avi): Verify byte ordering; it should be possible to // swizzle bytes with various combinations of the byte order and alpha // constants. RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate( result.getPixels(), result.width(), result.height(), result.bytesPerPixel() * 8 / 4, result.rowBytes(), cg_color.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); CGRect rect = CGRectMake(0, 0, CGImageGetWidth(image.get()), CGImageGetHeight(image.get())); CGContextDrawImage(context.get(), rect, image.get()); return result; #endif } } // namespace webkit_glue <|endoftext|>
<commit_before>#ifndef VIENNAFVM_QUANTITY_HPP #define VIENNAFVM_QUANTITY_HPP /* ======================================================================= Copyright (c) 2011, Institute for Microelectronics, TU Wien http://www.iue.tuwien.ac.at ----------------- ViennaFVM - The Vienna Finite Volume Method Library ----------------- authors: Karl Rupp [email protected] (add your name here) license: To be discussed, see file LICENSE in the ViennaFVM base directory ======================================================================= */ #include "viennafvm/forwards.h" #include "viennamath/forwards.h" #include "viennamath/manipulation/substitute.hpp" #include "viennamath/expression.hpp" #include "viennagrid/forwards.hpp" #include "viennagrid/mesh/segmentation.hpp" /** @file quantity.hpp @brief Defines the basic quantity which may be entirely known or unknown (with suitable boundary conditions) over a mesh */ namespace viennafvm { namespace traits { template<typename EleT> inline std::size_t id(EleT const& elem) { return elem.id().get(); } } // traits template<typename AssociatedT, typename ValueT = double> class quantity { public: typedef ValueT value_type; typedef AssociatedT associated_type; quantity() {} // to fulfill default constructible concept! quantity(std::size_t id, std::string const & quan_name, std::size_t num_values, value_type default_value = value_type()) : id_(id), name_(quan_name), values_ (num_values, default_value), boundary_types_ (num_values, BOUNDARY_NONE), boundary_values_ (num_values, default_value), unknown_mask_ (num_values, false), unknowns_indices_(num_values, -1) {} std::string get_name() const { return name_; } ValueT get_value(associated_type const & elem) const { return values_.at(viennafvm::traits::id(elem)); } void set_value(associated_type const & elem, ValueT value) { values_.at(viennafvm::traits::id(elem)) = value; } // Dirichlet and Neumann ValueT get_boundary_value(associated_type const & elem) const { return boundary_values_.at(viennafvm::traits::id(elem)); } void set_boundary_value(associated_type const & elem, ValueT value) { boundary_values_.at(viennafvm::traits::id(elem)) = value; } boundary_type_id get_boundary_type(associated_type const & elem) const { return boundary_types_.at(viennafvm::traits::id(elem)); } void set_boundary_type(associated_type const & elem, boundary_type_id value) { boundary_types_.at(viennafvm::traits::id(elem)) = value; } bool get_unknown_mask(associated_type const & elem) const { return unknown_mask_.at(viennafvm::traits::id(elem)); } void set_unknown_mask(associated_type const & elem, bool value) { unknown_mask_.at(viennafvm::traits::id(elem)) = value; } long get_unknown_index(associated_type const & elem) const { return unknowns_indices_.at(viennafvm::traits::id(elem)); } void set_unknown_index(associated_type const & elem, long value) { unknowns_indices_.at(viennafvm::traits::id(elem)) = value; } std::size_t get_unknown_num() const { std::size_t num = 0; for (std::size_t i=0; i<unknowns_indices_.size(); ++i) { if (unknowns_indices_[i] >= 0) ++num; } return num; } // possible design flaws: std::vector<ValueT> const & values() const { return values_; } std::size_t const& id () const { return id_; } void set_id(std::size_t id) { id_ = id; } private: // std::size_t id(associated_type const elem) const { return elem.id().get(); } std::size_t id_; std::string name_; std::vector<ValueT> values_; std::vector<boundary_type_id> boundary_types_; std::vector<ValueT> boundary_values_; std::vector<bool> unknown_mask_; std::vector<long> unknowns_indices_; }; } #endif <commit_msg>@Quantity class: added 'are_entries_zero()' and 'get_sum()' methods<commit_after>#ifndef VIENNAFVM_QUANTITY_HPP #define VIENNAFVM_QUANTITY_HPP /* ======================================================================= Copyright (c) 2011, Institute for Microelectronics, TU Wien http://www.iue.tuwien.ac.at ----------------- ViennaFVM - The Vienna Finite Volume Method Library ----------------- authors: Karl Rupp [email protected] (add your name here) license: To be discussed, see file LICENSE in the ViennaFVM base directory ======================================================================= */ #include <numeric> #include "viennafvm/forwards.h" #include "viennamath/forwards.h" #include "viennamath/manipulation/substitute.hpp" #include "viennamath/expression.hpp" #include "viennagrid/forwards.hpp" #include "viennagrid/mesh/segmentation.hpp" /** @file quantity.hpp @brief Defines the basic quantity which may be entirely known or unknown (with suitable boundary conditions) over a mesh */ namespace viennafvm { namespace traits { template<typename EleT> inline std::size_t id(EleT const& elem) { return elem.id().get(); } } // traits template<typename AssociatedT, typename ValueT = double> class quantity { public: typedef ValueT value_type; typedef AssociatedT associated_type; quantity() {} // to fulfill default constructible concept! quantity(std::size_t id, std::string const & quan_name, std::size_t num_values, value_type default_value = value_type()) : id_(id), name_(quan_name), values_ (num_values, default_value), boundary_types_ (num_values, BOUNDARY_NONE), boundary_values_ (num_values, default_value), unknown_mask_ (num_values, false), unknowns_indices_(num_values, -1) {} std::string get_name() const { return name_; } ValueT get_value(associated_type const & elem) const { return values_.at(viennafvm::traits::id(elem)); } void set_value(associated_type const & elem, ValueT value) { values_.at(viennafvm::traits::id(elem)) = value; } // Dirichlet and Neumann ValueT get_boundary_value(associated_type const & elem) const { return boundary_values_.at(viennafvm::traits::id(elem)); } void set_boundary_value(associated_type const & elem, ValueT value) { boundary_values_.at(viennafvm::traits::id(elem)) = value; } boundary_type_id get_boundary_type(associated_type const & elem) const { return boundary_types_.at(viennafvm::traits::id(elem)); } void set_boundary_type(associated_type const & elem, boundary_type_id value) { boundary_types_.at(viennafvm::traits::id(elem)) = value; } bool get_unknown_mask(associated_type const & elem) const { return unknown_mask_.at(viennafvm::traits::id(elem)); } void set_unknown_mask(associated_type const & elem, bool value) { unknown_mask_.at(viennafvm::traits::id(elem)) = value; } long get_unknown_index(associated_type const & elem) const { return unknowns_indices_.at(viennafvm::traits::id(elem)); } void set_unknown_index(associated_type const & elem, long value) { unknowns_indices_.at(viennafvm::traits::id(elem)) = value; } std::size_t get_unknown_num() const { std::size_t num = 0; for (std::size_t i=0; i<unknowns_indices_.size(); ++i) { if (unknowns_indices_[i] >= 0) ++num; } return num; } bool are_entries_zero() { if( std::fabs(this->get_sum()) < 1.0E-20 ) return true; else return false; } value_type get_sum() { return std::accumulate(values_.begin(), values_.end(), 0.0); } // possible design flaws: std::vector<ValueT> const & values() const { return values_; } std::size_t const& id () const { return id_; } void set_id(std::size_t id) { id_ = id; } private: // std::size_t id(associated_type const elem) const { return elem.id().get(); } std::size_t id_; std::string name_; std::vector<ValueT> values_; std::vector<boundary_type_id> boundary_types_; std::vector<ValueT> boundary_values_; std::vector<bool> unknown_mask_; std::vector<long> unknowns_indices_; }; } #endif <|endoftext|>
<commit_before>#include "qmljslink.h" #include "parser/qmljsast_p.h" #include "qmljsdocument.h" #include "qmljsbind.h" #include <QtCore/QFileInfo> #include <QtCore/QDir> #include <QtCore/QDebug> using namespace QmlJS; using namespace QmlJS::Interpreter; using namespace QmlJS::AST; Link::Link(Context *context, Document::Ptr currentDoc, const Snapshot &snapshot) : _snapshot(snapshot) , _context(context) { _docs = reachableDocuments(currentDoc, snapshot); linkImports(); } Link::~Link() { } Interpreter::Engine *Link::engine() { return _context->engine(); } void Link::scopeChainAt(Document::Ptr doc, Node *currentObject) { // ### TODO: This object ought to contain the global namespace additions by QML. _context->pushScope(engine()->globalObject()); if (! doc) return; Bind *bind = doc->bind(); QStringList linkedDocs; // to prevent cycles if (doc->qmlProgram()) { _context->setLookupMode(Context::QmlLookup); ObjectValue *scopeObject = 0; if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(currentObject)) scopeObject = bind->findQmlObject(definition); else if (UiObjectBinding *binding = cast<UiObjectBinding *>(currentObject)) scopeObject = bind->findQmlObject(binding); pushScopeChainForComponent(doc, &linkedDocs, scopeObject); if (const ObjectValue *typeEnvironment = _context->typeEnvironment(doc.data())) _context->pushScope(typeEnvironment); } else { // add scope chains for all components that source this document foreach (Document::Ptr otherDoc, _docs) { if (otherDoc->bind()->includedScripts().contains(doc->fileName())) pushScopeChainForComponent(otherDoc, &linkedDocs); } // ### TODO: Which type environment do scripts see? _context->pushScope(bind->rootObjectValue()); } if (FunctionDeclaration *fun = cast<FunctionDeclaration *>(currentObject)) { ObjectValue *activation = engine()->newObject(/*prototype = */ 0); for (FormalParameterList *it = fun->formals; it; it = it->next) { if (it->name) activation->setProperty(it->name->asString(), engine()->undefinedValue()); } _context->pushScope(activation); } } void Link::pushScopeChainForComponent(Document::Ptr doc, QStringList *linkedDocs, ObjectValue *scopeObject) { if (!doc->qmlProgram()) return; linkedDocs->append(doc->fileName()); Bind *bind = doc->bind(); // add scopes for all components instantiating this one foreach (Document::Ptr otherDoc, _docs) { if (linkedDocs->contains(otherDoc->fileName())) continue; if (otherDoc->bind()->usesQmlPrototype(bind->rootObjectValue(), _context)) { // ### TODO: Depth-first insertion doesn't give us correct name shadowing. pushScopeChainForComponent(otherDoc, linkedDocs); } } if (bind->rootObjectValue()) _context->pushScope(bind->rootObjectValue()); if (scopeObject && scopeObject != bind->rootObjectValue()) _context->pushScope(scopeObject); const QStringList &includedScripts = bind->includedScripts(); for (int index = includedScripts.size() - 1; index != -1; --index) { const QString &scriptFile = includedScripts.at(index); if (Document::Ptr scriptDoc = _snapshot.document(scriptFile)) { if (scriptDoc->jsProgram()) { _context->pushScope(scriptDoc->bind()->rootObjectValue()); } } } _context->pushScope(bind->functionEnvironment()); _context->pushScope(bind->idEnvironment()); } void Link::linkImports() { foreach (Document::Ptr doc, _docs) { ObjectValue *typeEnv = engine()->newObject(/*prototype =*/0); // ### FIXME // Populate the _typeEnvironment with imports. populateImportedTypes(typeEnv, doc); _context->setTypeEnvironment(doc.data(), typeEnv); } } static QString componentName(const QString &fileName) { QString componentName = fileName; int dotIndex = componentName.indexOf(QLatin1Char('.')); if (dotIndex != -1) componentName.truncate(dotIndex); componentName[0] = componentName[0].toUpper(); return componentName; } void Link::populateImportedTypes(Interpreter::ObjectValue *typeEnv, Document::Ptr doc) { if (! (doc->qmlProgram() && doc->qmlProgram()->imports)) return; QFileInfo fileInfo(doc->fileName()); const QString absolutePath = fileInfo.absolutePath(); // implicit imports: // qml files in the same directory are available without explicit imports foreach (Document::Ptr otherDoc, _docs) { if (otherDoc == doc) continue; QFileInfo otherFileInfo(otherDoc->fileName()); const QString otherAbsolutePath = otherFileInfo.absolutePath(); if (otherAbsolutePath != absolutePath) continue; typeEnv->setProperty(componentName(otherFileInfo.fileName()), otherDoc->bind()->rootObjectValue()); } // explicit imports, whether directories or files for (UiImportList *it = doc->qmlProgram()->imports; it; it = it->next) { if (! it->import) continue; if (it->import->fileName) { importFile(typeEnv, doc, it->import, absolutePath); } else if (it->import->importUri) { importNonFile(typeEnv, doc, it->import); } } } /* import "content" import "content" as Xxx import "content" 4.6 import "content" 4.6 as Xxx import "http://www.ovi.com/" as Ovi */ void Link::importFile(Interpreter::ObjectValue *typeEnv, Document::Ptr doc, AST::UiImport *import, const QString &startPath) { Q_UNUSED(doc) if (!import->fileName) return; QString path = startPath; path += QLatin1Char('/'); path += import->fileName->asString(); path = QDir::cleanPath(path); ObjectValue *importNamespace = 0; foreach (Document::Ptr otherDoc, _docs) { QFileInfo otherFileInfo(otherDoc->fileName()); const QString otherAbsolutePath = otherFileInfo.absolutePath(); bool directoryImport = (path == otherAbsolutePath); bool fileImport = (path == otherDoc->fileName()); if (!directoryImport && !fileImport) continue; if (directoryImport && import->importId && !importNamespace) { importNamespace = engine()->newObject(/*prototype =*/0); typeEnv->setProperty(import->importId->asString(), importNamespace); } QString targetName; if (fileImport && import->importId) { targetName = import->importId->asString(); } else { targetName = componentName(otherFileInfo.fileName()); } ObjectValue *importInto = typeEnv; if (importNamespace) importInto = importNamespace; importInto->setProperty(targetName, otherDoc->bind()->rootObjectValue()); } } /* import Qt 4.6 import Qt 4.6 as Xxx (import com.nokia.qt is the same as the ones above) */ void Link::importNonFile(Interpreter::ObjectValue *typeEnv, Document::Ptr doc, AST::UiImport *import) { ObjectValue *namespaceObject = 0; if (import->importId) { // with namespace we insert an object in the type env. to hold the imported types namespaceObject = engine()->newObject(/*prototype */ 0); typeEnv->setProperty(import->importId->asString(), namespaceObject); } else { // without namespace we insert all types directly into the type env. namespaceObject = typeEnv; } // try the metaobject system if (import->importUri) { const QString package = Bind::toString(import->importUri, '/'); int majorVersion = -1; // ### TODO: Check these magic version numbers int minorVersion = -1; // ### TODO: Check these magic version numbers if (import->versionToken.isValid()) { const QString versionString = doc->source().mid(import->versionToken.offset, import->versionToken.length); const int dotIdx = versionString.indexOf(QLatin1Char('.')); if (dotIdx == -1) { // only major (which is probably invalid, but let's handle it anyway) majorVersion = versionString.toInt(); minorVersion = 0; // ### TODO: Check with magic version numbers above } else { majorVersion = versionString.left(dotIdx).toInt(); minorVersion = versionString.mid(dotIdx + 1).toInt(); } } #ifndef NO_DECLARATIVE_BACKEND foreach (QmlObjectValue *object, engine()->metaTypeSystem().staticTypesForImport(package, majorVersion, minorVersion)) { namespaceObject->setProperty(object->qmlTypeName(), object); } #endif // NO_DECLARATIVE_BACKEND } } UiQualifiedId *Link::qualifiedTypeNameId(Node *node) { if (UiObjectBinding *binding = AST::cast<UiObjectBinding *>(node)) return binding->qualifiedTypeNameId; else if (UiObjectDefinition *binding = AST::cast<UiObjectDefinition *>(node)) return binding->qualifiedTypeNameId; else return 0; } static uint qHash(Document::Ptr doc) { return qHash(doc.data()); } QList<Document::Ptr> Link::reachableDocuments(Document::Ptr startDoc, const Snapshot &snapshot) { QSet<Document::Ptr> docs; if (! startDoc) return docs.values(); QMultiHash<QString, Document::Ptr> documentByPath; foreach (Document::Ptr doc, snapshot) documentByPath.insert(doc->path(), doc); // ### TODO: This doesn't scale well. Maybe just use the whole snapshot? // Find all documents that (indirectly) include startDoc { QList<Document::Ptr> todo; todo += startDoc; while (! todo.isEmpty()) { Document::Ptr doc = todo.takeFirst(); docs += doc; Snapshot::const_iterator it, end = snapshot.end(); for (it = snapshot.begin(); it != end; ++it) { Document::Ptr otherDoc = *it; if (docs.contains(otherDoc)) continue; QStringList localImports = otherDoc->bind()->localImports(); if (localImports.contains(doc->fileName()) || localImports.contains(doc->path()) || otherDoc->bind()->includedScripts().contains(doc->fileName()) ) { todo += otherDoc; } } } } // Find all documents that are included by these (even if indirectly). { QSet<QString> processed; QStringList todo; foreach (Document::Ptr doc, docs) todo.append(doc->fileName()); while (! todo.isEmpty()) { QString path = todo.takeFirst(); if (processed.contains(path)) continue; processed.insert(path); if (Document::Ptr doc = snapshot.document(path)) { docs += doc; if (doc->qmlProgram()) path = doc->path(); else continue; } QStringList localImports; foreach (Document::Ptr doc, documentByPath.values(path)) { if (doc->qmlProgram()) { docs += doc; localImports += doc->bind()->localImports(); localImports += doc->bind()->includedScripts(); } } localImports.removeDuplicates(); todo += localImports; } } return docs.values(); } <commit_msg>Remove the lookup into including Qml files in the root scope of a JS file.<commit_after>#include "qmljslink.h" #include "parser/qmljsast_p.h" #include "qmljsdocument.h" #include "qmljsbind.h" #include <QtCore/QFileInfo> #include <QtCore/QDir> #include <QtCore/QDebug> using namespace QmlJS; using namespace QmlJS::Interpreter; using namespace QmlJS::AST; Link::Link(Context *context, Document::Ptr currentDoc, const Snapshot &snapshot) : _snapshot(snapshot) , _context(context) { _docs = reachableDocuments(currentDoc, snapshot); linkImports(); } Link::~Link() { } Interpreter::Engine *Link::engine() { return _context->engine(); } void Link::scopeChainAt(Document::Ptr doc, Node *currentObject) { // ### TODO: This object ought to contain the global namespace additions by QML. _context->pushScope(engine()->globalObject()); if (! doc) return; Bind *bind = doc->bind(); QStringList linkedDocs; // to prevent cycles if (doc->qmlProgram()) { _context->setLookupMode(Context::QmlLookup); ObjectValue *scopeObject = 0; if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(currentObject)) scopeObject = bind->findQmlObject(definition); else if (UiObjectBinding *binding = cast<UiObjectBinding *>(currentObject)) scopeObject = bind->findQmlObject(binding); pushScopeChainForComponent(doc, &linkedDocs, scopeObject); if (const ObjectValue *typeEnvironment = _context->typeEnvironment(doc.data())) _context->pushScope(typeEnvironment); } else { // the global scope of a js file does not see the instantiating component if (currentObject != 0) { // add scope chains for all components that source this document foreach (Document::Ptr otherDoc, _docs) { if (otherDoc->bind()->includedScripts().contains(doc->fileName())) pushScopeChainForComponent(otherDoc, &linkedDocs); } // ### TODO: Which type environment do scripts see? } _context->pushScope(bind->rootObjectValue()); } if (FunctionDeclaration *fun = cast<FunctionDeclaration *>(currentObject)) { ObjectValue *activation = engine()->newObject(/*prototype = */ 0); for (FormalParameterList *it = fun->formals; it; it = it->next) { if (it->name) activation->setProperty(it->name->asString(), engine()->undefinedValue()); } _context->pushScope(activation); } } void Link::pushScopeChainForComponent(Document::Ptr doc, QStringList *linkedDocs, ObjectValue *scopeObject) { if (!doc->qmlProgram()) return; linkedDocs->append(doc->fileName()); Bind *bind = doc->bind(); // add scopes for all components instantiating this one foreach (Document::Ptr otherDoc, _docs) { if (linkedDocs->contains(otherDoc->fileName())) continue; if (otherDoc->bind()->usesQmlPrototype(bind->rootObjectValue(), _context)) { // ### TODO: Depth-first insertion doesn't give us correct name shadowing. pushScopeChainForComponent(otherDoc, linkedDocs); } } if (bind->rootObjectValue()) _context->pushScope(bind->rootObjectValue()); if (scopeObject && scopeObject != bind->rootObjectValue()) _context->pushScope(scopeObject); const QStringList &includedScripts = bind->includedScripts(); for (int index = includedScripts.size() - 1; index != -1; --index) { const QString &scriptFile = includedScripts.at(index); if (Document::Ptr scriptDoc = _snapshot.document(scriptFile)) { if (scriptDoc->jsProgram()) { _context->pushScope(scriptDoc->bind()->rootObjectValue()); } } } _context->pushScope(bind->functionEnvironment()); _context->pushScope(bind->idEnvironment()); } void Link::linkImports() { foreach (Document::Ptr doc, _docs) { ObjectValue *typeEnv = engine()->newObject(/*prototype =*/0); // ### FIXME // Populate the _typeEnvironment with imports. populateImportedTypes(typeEnv, doc); _context->setTypeEnvironment(doc.data(), typeEnv); } } static QString componentName(const QString &fileName) { QString componentName = fileName; int dotIndex = componentName.indexOf(QLatin1Char('.')); if (dotIndex != -1) componentName.truncate(dotIndex); componentName[0] = componentName[0].toUpper(); return componentName; } void Link::populateImportedTypes(Interpreter::ObjectValue *typeEnv, Document::Ptr doc) { if (! (doc->qmlProgram() && doc->qmlProgram()->imports)) return; QFileInfo fileInfo(doc->fileName()); const QString absolutePath = fileInfo.absolutePath(); // implicit imports: // qml files in the same directory are available without explicit imports foreach (Document::Ptr otherDoc, _docs) { if (otherDoc == doc) continue; QFileInfo otherFileInfo(otherDoc->fileName()); const QString otherAbsolutePath = otherFileInfo.absolutePath(); if (otherAbsolutePath != absolutePath) continue; typeEnv->setProperty(componentName(otherFileInfo.fileName()), otherDoc->bind()->rootObjectValue()); } // explicit imports, whether directories or files for (UiImportList *it = doc->qmlProgram()->imports; it; it = it->next) { if (! it->import) continue; if (it->import->fileName) { importFile(typeEnv, doc, it->import, absolutePath); } else if (it->import->importUri) { importNonFile(typeEnv, doc, it->import); } } } /* import "content" import "content" as Xxx import "content" 4.6 import "content" 4.6 as Xxx import "http://www.ovi.com/" as Ovi */ void Link::importFile(Interpreter::ObjectValue *typeEnv, Document::Ptr doc, AST::UiImport *import, const QString &startPath) { Q_UNUSED(doc) if (!import->fileName) return; QString path = startPath; path += QLatin1Char('/'); path += import->fileName->asString(); path = QDir::cleanPath(path); ObjectValue *importNamespace = 0; foreach (Document::Ptr otherDoc, _docs) { QFileInfo otherFileInfo(otherDoc->fileName()); const QString otherAbsolutePath = otherFileInfo.absolutePath(); bool directoryImport = (path == otherAbsolutePath); bool fileImport = (path == otherDoc->fileName()); if (!directoryImport && !fileImport) continue; if (directoryImport && import->importId && !importNamespace) { importNamespace = engine()->newObject(/*prototype =*/0); typeEnv->setProperty(import->importId->asString(), importNamespace); } QString targetName; if (fileImport && import->importId) { targetName = import->importId->asString(); } else { targetName = componentName(otherFileInfo.fileName()); } ObjectValue *importInto = typeEnv; if (importNamespace) importInto = importNamespace; importInto->setProperty(targetName, otherDoc->bind()->rootObjectValue()); } } /* import Qt 4.6 import Qt 4.6 as Xxx (import com.nokia.qt is the same as the ones above) */ void Link::importNonFile(Interpreter::ObjectValue *typeEnv, Document::Ptr doc, AST::UiImport *import) { ObjectValue *namespaceObject = 0; if (import->importId) { // with namespace we insert an object in the type env. to hold the imported types namespaceObject = engine()->newObject(/*prototype */ 0); typeEnv->setProperty(import->importId->asString(), namespaceObject); } else { // without namespace we insert all types directly into the type env. namespaceObject = typeEnv; } // try the metaobject system if (import->importUri) { const QString package = Bind::toString(import->importUri, '/'); int majorVersion = -1; // ### TODO: Check these magic version numbers int minorVersion = -1; // ### TODO: Check these magic version numbers if (import->versionToken.isValid()) { const QString versionString = doc->source().mid(import->versionToken.offset, import->versionToken.length); const int dotIdx = versionString.indexOf(QLatin1Char('.')); if (dotIdx == -1) { // only major (which is probably invalid, but let's handle it anyway) majorVersion = versionString.toInt(); minorVersion = 0; // ### TODO: Check with magic version numbers above } else { majorVersion = versionString.left(dotIdx).toInt(); minorVersion = versionString.mid(dotIdx + 1).toInt(); } } #ifndef NO_DECLARATIVE_BACKEND foreach (QmlObjectValue *object, engine()->metaTypeSystem().staticTypesForImport(package, majorVersion, minorVersion)) { namespaceObject->setProperty(object->qmlTypeName(), object); } #endif // NO_DECLARATIVE_BACKEND } } UiQualifiedId *Link::qualifiedTypeNameId(Node *node) { if (UiObjectBinding *binding = AST::cast<UiObjectBinding *>(node)) return binding->qualifiedTypeNameId; else if (UiObjectDefinition *binding = AST::cast<UiObjectDefinition *>(node)) return binding->qualifiedTypeNameId; else return 0; } static uint qHash(Document::Ptr doc) { return qHash(doc.data()); } QList<Document::Ptr> Link::reachableDocuments(Document::Ptr startDoc, const Snapshot &snapshot) { QSet<Document::Ptr> docs; if (! startDoc) return docs.values(); QMultiHash<QString, Document::Ptr> documentByPath; foreach (Document::Ptr doc, snapshot) documentByPath.insert(doc->path(), doc); // ### TODO: This doesn't scale well. Maybe just use the whole snapshot? // Find all documents that (indirectly) include startDoc { QList<Document::Ptr> todo; todo += startDoc; while (! todo.isEmpty()) { Document::Ptr doc = todo.takeFirst(); docs += doc; Snapshot::const_iterator it, end = snapshot.end(); for (it = snapshot.begin(); it != end; ++it) { Document::Ptr otherDoc = *it; if (docs.contains(otherDoc)) continue; QStringList localImports = otherDoc->bind()->localImports(); if (localImports.contains(doc->fileName()) || localImports.contains(doc->path()) || otherDoc->bind()->includedScripts().contains(doc->fileName()) ) { todo += otherDoc; } } } } // Find all documents that are included by these (even if indirectly). { QSet<QString> processed; QStringList todo; foreach (Document::Ptr doc, docs) todo.append(doc->fileName()); while (! todo.isEmpty()) { QString path = todo.takeFirst(); if (processed.contains(path)) continue; processed.insert(path); if (Document::Ptr doc = snapshot.document(path)) { docs += doc; if (doc->qmlProgram()) path = doc->path(); else continue; } QStringList localImports; foreach (Document::Ptr doc, documentByPath.values(path)) { if (doc->qmlProgram()) { docs += doc; localImports += doc->bind()->localImports(); localImports += doc->bind()->includedScripts(); } } localImports.removeDuplicates(); todo += localImports; } } return docs.values(); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 <fstream> #include "itkConnectedThresholdImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkFilterWatcher.h" int itkConnectedThresholdImageFilterTest(int ac, char* av[] ) { if(ac < 7) { std::cerr << "Usage: " << av[0] << " InputImage OutputImage " << "seed_x seed_y " << "LowerConnectedThreshold UpperConnectedThreshold " << "Connectivity[1=Full,0=Face]" << std::endl; return -1; } typedef unsigned char PixelType; typedef itk::Image<PixelType, 2> myImage; itk::ImageFileReader<myImage>::Pointer input = itk::ImageFileReader<myImage>::New(); input->SetFileName(av[1]); // Create a filter typedef itk::ConnectedThresholdImageFilter<myImage,myImage> FilterType; FilterType::Pointer filter = FilterType::New(); FilterWatcher watcher(filter); filter->SetInput(input->GetOutput()); FilterType::IndexType seed; seed[0] = atoi(av[3]); seed[1] = atoi(av[4]); filter->AddSeed(seed); filter->SetLower(atoi(av[5])); filter->SetUpper(atoi(av[6])); filter->SetReplaceValue(255); // Test the use of full (8 connectivity in 2D) on this image. if (ac > 7) { filter->SetConnectivity( atoi(av[7]) ? FilterType::FullConnectivity : FilterType::FaceConnectivity ); } try { input->Update(); filter->Update(); } catch (itk::ExceptionObject& e) { std::cerr << "Exception detected: " << e.GetDescription(); return -1; } // Generate test image itk::ImageFileWriter<myImage>::Pointer writer; writer = itk::ImageFileWriter<myImage>::New(); writer->SetInput( filter->GetOutput() ); writer->SetFileName( av[2] ); writer->Update(); return EXIT_SUCCESS; } <commit_msg>ENH: Improve itkConnectedThresholdImageFilter coverage.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 <fstream> #include "itkConnectedThresholdImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkFilterWatcher.h" #include "itkTestingMacros.h" int itkConnectedThresholdImageFilterTest( int argc, char* argv[] ) { if( argc < 7 ) { std::cerr << "Usage: " << argv[0] << " InputImage OutputImage " << "seed_x seed_y " << "LowerConnectedThreshold UpperConnectedThreshold " << "Connectivity[1=Full,0=Face]" << std::endl; return -1; } // Define the dimension of the images const unsigned int Dimension = 2; // Define the pixel types of the images typedef unsigned char PixelType; // Define the types of the images typedef itk::Image< PixelType, Dimension > ImageType; itk::ImageFileReader< ImageType >::Pointer imageReader = itk::ImageFileReader< ImageType >::New(); std::string inputImageFilename = argv[1]; imageReader->SetFileName( inputImageFilename ); TRY_EXPECT_NO_EXCEPTION( imageReader->Update(); ); // Create the filter typedef itk::ConnectedThresholdImageFilter< ImageType, ImageType > ConnectedThresholdImageFilterType; ConnectedThresholdImageFilterType::Pointer connectedThresholdFilter = ConnectedThresholdImageFilterType::New(); FilterWatcher watcher( connectedThresholdFilter ); EXERCISE_BASIC_OBJECT_METHODS( connectedThresholdFilter, ConnectedThresholdImageFilter, ImageToImageFilter ); ConnectedThresholdImageFilterType::IndexType seed; seed[0] = atoi( argv[3] ); seed[1] = atoi( argv[4] ); connectedThresholdFilter->AddSeed( seed ); ConnectedThresholdImageFilterType::SeedContainerType seedContainer = connectedThresholdFilter->GetSeeds(); connectedThresholdFilter->ClearSeeds(); seedContainer = connectedThresholdFilter->GetSeeds(); if( seedContainer.size() != 0 ) { std::cerr << "Test FAILED !" << std::endl; std::cerr << "Seed container not empty after clearing filter seed container !" << std::endl; return EXIT_FAILURE; } connectedThresholdFilter->SetSeed( seed ); ConnectedThresholdImageFilterType::InputPixelObjectType * lowerInputPixelObject = connectedThresholdFilter->GetLowerInput(); connectedThresholdFilter->SetLower( lowerInputPixelObject->Get() ); TEST_SET_GET_VALUE( lowerInputPixelObject->Get(), connectedThresholdFilter->GetLower() ); ConnectedThresholdImageFilterType::InputPixelObjectType * upperInputPixelObject = connectedThresholdFilter->GetUpperInput(); connectedThresholdFilter->SetUpper( upperInputPixelObject->Get() ); TEST_SET_GET_VALUE( upperInputPixelObject->Get(), connectedThresholdFilter->GetUpper() ); ConnectedThresholdImageFilterType::InputImagePixelType lowerThreshold = atoi( argv[5] ); connectedThresholdFilter->SetLower( lowerThreshold ); TEST_SET_GET_VALUE( lowerThreshold, connectedThresholdFilter->GetLower() ); ConnectedThresholdImageFilterType::InputImagePixelType upperThreshold = atoi( argv[6] ); connectedThresholdFilter->SetUpper( upperThreshold ); TEST_SET_GET_VALUE( upperThreshold, connectedThresholdFilter->GetUpper() ); ConnectedThresholdImageFilterType::OutputImagePixelType replaceValue = 255; connectedThresholdFilter->SetReplaceValue( replaceValue ); TEST_SET_GET_VALUE( replaceValue, connectedThresholdFilter->GetReplaceValue() ); // Test the use of full (8 connectivity in 2D) on this image if( argc > 7 ) { ConnectedThresholdImageFilterType::ConnectivityEnumType conenctivity = atoi( argv[7] ) ? ConnectedThresholdImageFilterType::FullConnectivity : ConnectedThresholdImageFilterType::FaceConnectivity; connectedThresholdFilter->SetConnectivity( conenctivity ); TEST_SET_GET_VALUE( conenctivity, connectedThresholdFilter->GetConnectivity() ); } connectedThresholdFilter->SetInput( imageReader->GetOutput() ); TRY_EXPECT_NO_EXCEPTION( connectedThresholdFilter->Update(); ); // Write the output image itk::ImageFileWriter< ImageType >::Pointer writer = itk::ImageFileWriter< ImageType >::New(); std::string ouputImageFilename = argv[2]; writer->SetFileName( ouputImageFilename ); writer->SetInput( connectedThresholdFilter->GetOutput() ); TRY_EXPECT_NO_EXCEPTION( writer->Update() ); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * File: multi_unbounded_queue.hpp * Author: Barath Kannan * Vector of unbounded queues. Enqueue operations are assigned a subqueue, * which is used for all enqueue operations occuring from that thread. The dequeue * operation maintains a list of subqueues on which a "hit" has occured - pertaining * to the subqueues from which a successful dequeue operation has occured. On a * successful dequeue operation, the queue that is used is pushed to the front of the * list. The "hit lists" allow the queue to adapt fairly well to different usage contexts. * Created on 25 September 2016, 12:04 AM */ #ifndef BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP #define BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP #include <thread> #include <vector> #include <mutex> #include <bk_conq/unbounded_queue.hpp> namespace bk_conq { template<typename TT> class multi_unbounded_queue; template <template <typename> class Q, typename T> class multi_unbounded_queue<Q<T>> : public unbounded_queue<T, multi_unbounded_queue<Q<T>>>{ friend unbounded_queue<T, multi_unbounded_queue<Q<T>>>; public: multi_unbounded_queue(size_t subqueues) : _q(subqueues), _hitlist([&]() {return hitlist_sequence(); }), _enqueue_identifier([&]() { return get_enqueue_index(); }, [&](size_t indx) {return return_enqueue_index(indx); }) { static_assert(std::is_base_of<bk_conq::unbounded_queue_typed_tag<T>, Q<T>>::value, "Q<T> must be an unbounded queue"); } multi_unbounded_queue(const multi_unbounded_queue&) = delete; void operator=(const multi_unbounded_queue&) = delete; protected: template <typename R> void sp_enqueue_impl(R&& input) { size_t indx = _enqueue_identifier.get_tlcl(); _q[indx].sp_enqueue(std::forward<R>(input)); } template <typename R> void mp_enqueue_impl(R&& input) { size_t indx = _enqueue_identifier.get_tlcl(); _q[indx].mp_enqueue(std::forward<R>(input)); } bool sc_dequeue_impl(T& output) { auto& hitlist = _hitlist.get_tlcl(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].sc_dequeue(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } bool mc_dequeue_impl(T& output) { auto& hitlist = _hitlist.get_tlcl(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue_uncontended(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } bool mc_dequeue_uncontended_impl(T& output) { auto& hitlist = _hitlist.get_tlcl(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue_uncontended(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } private: template <typename U> class tlcl { public: tlcl(std::function<U()> defaultvalfunc = nullptr, std::function<void(U)> defaultdeletefunc = nullptr) : _defaultvalfunc(defaultvalfunc), _defaultdeletefunc(defaultdeletefunc) { std::lock_guard<std::mutex> lock(_m); if (!_available.empty()) { _mycounter = _available.back(); _available.pop_back(); } else { _mycounter = _counter++; } } virtual ~tlcl() { std::lock_guard<std::mutex> lock(_m); _available.push_back(_mycounter); } U& get_tlcl() { thread_local std::vector<std::pair<tlcl<U>*, U>> vec; if (vec.size() <= _mycounter) vec.resize(_mycounter+1); auto& ret = vec[_mycounter]; if (ret.first != this) { //reset to default if (_defaultdeletefunc && ret.first != nullptr) _defaultdeletefunc(ret.second); if (_defaultvalfunc) ret.second = _defaultvalfunc(); ret.first = this; } return ret.second; } private: std::function<U()> _defaultvalfunc; std::function<void(U)> _defaultdeletefunc; size_t _mycounter; static size_t _counter; static std::vector<size_t> _available; static std::mutex _m; }; std::vector<size_t> hitlist_sequence() { std::vector<size_t> hitlist(_q.size()); std::iota(hitlist.begin(), hitlist.end(), 0); return hitlist; } size_t get_enqueue_index() { std::lock_guard<std::mutex> lock(_m); if (_unused_enqueue_indexes.empty()) { return _enqueue_index++; } size_t ret = _unused_enqueue_indexes.back(); _unused_enqueue_indexes.pop_back(); return ret; } void return_enqueue_index(size_t index) { std::lock_guard<std::mutex> lock(_m); _unused_enqueue_indexes.push_back(index); } class padded_unbounded_queue : public Q<T>{ char padding[64]; }; std::vector<padded_unbounded_queue> _q; std::vector<size_t> _unused_enqueue_indexes; size_t _enqueue_index{ 0 }; std::mutex _m; tlcl<std::vector<size_t>> _hitlist; tlcl<size_t> _enqueue_identifier; }; template <template <typename> class Q, typename T> template <typename U> size_t multi_unbounded_queue<Q<T>>::tlcl<U>::_counter = 0; template <template <typename> class Q, typename T> template <typename U> std::vector<size_t> multi_unbounded_queue<Q<T>>::tlcl<U>::_available; template <template <typename> class Q, typename T> template <typename U> std::mutex multi_unbounded_queue<Q<T>>::tlcl<U>::_m; }//namespace bk_conq #endif /* BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP */ <commit_msg>forgot to add modulo operation when acquiring an enqueue index<commit_after>/* * File: multi_unbounded_queue.hpp * Author: Barath Kannan * Vector of unbounded queues. Enqueue operations are assigned a subqueue, * which is used for all enqueue operations occuring from that thread. The dequeue * operation maintains a list of subqueues on which a "hit" has occured - pertaining * to the subqueues from which a successful dequeue operation has occured. On a * successful dequeue operation, the queue that is used is pushed to the front of the * list. The "hit lists" allow the queue to adapt fairly well to different usage contexts. * Created on 25 September 2016, 12:04 AM */ #ifndef BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP #define BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP #include <thread> #include <vector> #include <mutex> #include <bk_conq/unbounded_queue.hpp> namespace bk_conq { template<typename TT> class multi_unbounded_queue; template <template <typename> class Q, typename T> class multi_unbounded_queue<Q<T>> : public unbounded_queue<T, multi_unbounded_queue<Q<T>>>{ friend unbounded_queue<T, multi_unbounded_queue<Q<T>>>; public: multi_unbounded_queue(size_t subqueues) : _q(subqueues), _hitlist([&]() {return hitlist_sequence(); }), _enqueue_identifier([&]() { return get_enqueue_index(); }, [&](size_t indx) {return return_enqueue_index(indx); }) { static_assert(std::is_base_of<bk_conq::unbounded_queue_typed_tag<T>, Q<T>>::value, "Q<T> must be an unbounded queue"); } multi_unbounded_queue(const multi_unbounded_queue&) = delete; void operator=(const multi_unbounded_queue&) = delete; protected: template <typename R> void sp_enqueue_impl(R&& input) { size_t indx = _enqueue_identifier.get_tlcl(); _q[indx].sp_enqueue(std::forward<R>(input)); } template <typename R> void mp_enqueue_impl(R&& input) { size_t indx = _enqueue_identifier.get_tlcl(); _q[indx].mp_enqueue(std::forward<R>(input)); } bool sc_dequeue_impl(T& output) { auto& hitlist = _hitlist.get_tlcl(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].sc_dequeue(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } bool mc_dequeue_impl(T& output) { auto& hitlist = _hitlist.get_tlcl(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue_uncontended(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } bool mc_dequeue_uncontended_impl(T& output) { auto& hitlist = _hitlist.get_tlcl(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue_uncontended(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } private: template <typename U> class tlcl { public: tlcl(std::function<U()> defaultvalfunc = nullptr, std::function<void(U)> defaultdeletefunc = nullptr) : _defaultvalfunc(defaultvalfunc), _defaultdeletefunc(defaultdeletefunc) { std::lock_guard<std::mutex> lock(_m); if (!_available.empty()) { _mycounter = _available.back(); _available.pop_back(); } else { _mycounter = _counter++; } } virtual ~tlcl() { std::lock_guard<std::mutex> lock(_m); _available.push_back(_mycounter); } U& get_tlcl() { thread_local std::vector<std::pair<tlcl<U>*, U>> vec; if (vec.size() <= _mycounter) vec.resize(_mycounter+1); auto& ret = vec[_mycounter]; if (ret.first != this) { //reset to default if (_defaultdeletefunc && ret.first != nullptr) _defaultdeletefunc(ret.second); if (_defaultvalfunc) ret.second = _defaultvalfunc(); ret.first = this; } return ret.second; } private: std::function<U()> _defaultvalfunc; std::function<void(U)> _defaultdeletefunc; size_t _mycounter; static size_t _counter; static std::vector<size_t> _available; static std::mutex _m; }; std::vector<size_t> hitlist_sequence() { std::vector<size_t> hitlist(_q.size()); std::iota(hitlist.begin(), hitlist.end(), 0); return hitlist; } size_t get_enqueue_index() { std::lock_guard<std::mutex> lock(_m); if (_unused_enqueue_indexes.empty()) { return (_enqueue_index++)%_q.size(); } size_t ret = _unused_enqueue_indexes.back(); _unused_enqueue_indexes.pop_back(); return ret; } void return_enqueue_index(size_t index) { std::lock_guard<std::mutex> lock(_m); _unused_enqueue_indexes.push_back(index); } class padded_unbounded_queue : public Q<T>{ char padding[64]; }; std::vector<padded_unbounded_queue> _q; std::vector<size_t> _unused_enqueue_indexes; size_t _enqueue_index{ 0 }; std::mutex _m; tlcl<std::vector<size_t>> _hitlist; tlcl<size_t> _enqueue_identifier; }; template <template <typename> class Q, typename T> template <typename U> size_t multi_unbounded_queue<Q<T>>::tlcl<U>::_counter = 0; template <template <typename> class Q, typename T> template <typename U> std::vector<size_t> multi_unbounded_queue<Q<T>>::tlcl<U>::_available; template <template <typename> class Q, typename T> template <typename U> std::mutex multi_unbounded_queue<Q<T>>::tlcl<U>::_m; }//namespace bk_conq #endif /* BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP */ <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkStandaloneDataStorage.h" #include "mitkDataNode.h" #include "mitkProperties.h" #include "mitkNodePredicateBase.h" #include "mitkNodePredicateProperty.h" #include "mitkGroupTagProperty.h" #include "itkSimpleFastMutexLock.h" #include "itkMutexLockHolder.h" mitk::StandaloneDataStorage::StandaloneDataStorage() : mitk::DataStorage() { } mitk::StandaloneDataStorage::~StandaloneDataStorage() { for(AdjacencyList::iterator it = m_SourceNodes.begin(); it != m_SourceNodes.end(); it++) { this->RemoveListeners(it->first); } } bool mitk::StandaloneDataStorage::IsInitialized() const { return true; } void mitk::StandaloneDataStorage::Add(mitk::DataNode* node, const mitk::DataStorage::SetOfObjects* parents) { { itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex); if (!IsInitialized()) throw std::logic_error("DataStorage not initialized"); /* check if node is in its own list of sources */ if ((parents != NULL) && (std::find(parents->begin(), parents->end(), node) != parents->end())) throw std::invalid_argument("Node is it's own parent"); /* check if node already exists in StandaloneDataStorage */ if (m_SourceNodes.find(node) != m_SourceNodes.end()) throw std::invalid_argument("Node is already in DataStorage"); /* create parent list if it does not exist */ mitk::DataStorage::SetOfObjects::ConstPointer sp; if (parents != NULL) sp = parents; else sp = mitk::DataStorage::SetOfObjects::New(); /* Store node and parent list in sources adjacency list */ m_SourceNodes.insert(std::make_pair(node, sp)); /* Store node and an empty children list in derivations adjacency list */ mitk::DataStorage::SetOfObjects::Pointer childrenPointer = mitk::DataStorage::SetOfObjects::New(); mitk::DataStorage::SetOfObjects::ConstPointer children = children.GetPointer(); m_DerivedNodes.insert(std::make_pair(node, children)); /* create entry in derivations adjacency list for each parent of the new node */ for (SetOfObjects::ConstIterator it = sp->Begin(); it != sp->End(); it++) { mitk::DataNode::ConstPointer parent = it.Value().GetPointer(); mitk::DataStorage::SetOfObjects::ConstPointer derivedObjects = m_DerivedNodes[parent]; // get or create pointer to list of derived objects for that parent node if (derivedObjects.IsNull()) m_DerivedNodes[parent] = mitk::DataStorage::SetOfObjects::New(); // Create a set of Objects, if it does not already exist mitk::DataStorage::SetOfObjects* deob = const_cast<mitk::DataStorage::SetOfObjects*>(m_DerivedNodes[parent].GetPointer()); // temporarily get rid of const pointer to insert new element deob->InsertElement(deob->Size(), node); // node is derived from parent. Insert it into the parents list of derived objects } // register for ITK changed events this->AddListeners(node); } /* Notify observers */ EmitAddNodeEvent(node); } void mitk::StandaloneDataStorage::Remove(const mitk::DataNode* node) { if (!IsInitialized()) throw std::logic_error("DataStorage not initialized"); if (node == NULL) return; // remove ITK modified event listener this->RemoveListeners(node); // muellerm, 22.9.10: add additional reference count to ensure // that the node is not deleted when removed from the relation map // while m_Mutex is locked. This would cause the an itk::DeleteEvent // is thrown and a deadlock will occur when event receivers // access the DataStorage again in their event processing function // mitk::DataNode::ConstPointer nodeGuard(node); /* Notify observers of imminent node removal */ EmitRemoveNodeEvent(node); { itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex); /* remove node from both relation adjacency lists */ this->RemoveFromRelation(node, m_SourceNodes); this->RemoveFromRelation(node, m_DerivedNodes); } } bool mitk::StandaloneDataStorage::Exists(const mitk::DataNode* node) const { itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex); return (m_SourceNodes.find(node) != m_SourceNodes.end()); } void mitk::StandaloneDataStorage::RemoveFromRelation(const mitk::DataNode* node, AdjacencyList& relation) { for (AdjacencyList::const_iterator mapIter = relation.begin(); mapIter != relation.end(); ++mapIter) // for each node in the relation if (mapIter->second.IsNotNull()) // if node has a relation list { SetOfObjects::Pointer s = const_cast<SetOfObjects*>(mapIter->second.GetPointer()); // search for node to be deleted in the relation list SetOfObjects::STLContainerType::iterator relationListIter = std::find(s->begin(), s->end(), node); // this assumes, that the relation list does not contain duplicates (which should be safe to assume) if (relationListIter != s->end()) // if node to be deleted is in relation list s->erase(relationListIter); // remove it from parentlist } /* now remove node from the relation */ AdjacencyList::iterator adIt; adIt = relation.find(node); if (adIt != relation.end()) relation.erase(adIt); } mitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetAll() const { itk::MutexLockHolder<itk::SimpleFastMutexLock > locked(m_Mutex); if (!IsInitialized()) throw std::logic_error("DataStorage not initialized"); mitk::DataStorage::SetOfObjects::Pointer resultset = mitk::DataStorage::SetOfObjects::New(); /* Fill resultset with all objects that are managed by the StandaloneDataStorage object */ unsigned int index = 0; for (AdjacencyList::const_iterator it = m_SourceNodes.begin(); it != m_SourceNodes.end(); ++it) if (it->first.IsNull()) continue; else resultset->InsertElement(index++, const_cast<mitk::DataNode*>(it->first.GetPointer())); return SetOfObjects::ConstPointer(resultset); } mitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetRelations(const mitk::DataNode* node, const AdjacencyList& relation, const NodePredicateBase* condition, bool onlyDirectlyRelated) const { if (node == NULL) throw std::invalid_argument("invalid node"); /* Either read direct relations directly from adjacency list */ if (onlyDirectlyRelated) { AdjacencyList::const_iterator it = relation.find(node); // get parents of current node if ((it == relation.end()) || (it->second.IsNull())) // node not found in list or no set of parents return SetOfObjects::ConstPointer(mitk::DataStorage::SetOfObjects::New()); // return an empty set else return this->FilterSetOfObjects(it->second, condition); } /* Or traverse adjacency list to collect all related nodes */ std::vector<mitk::DataNode::ConstPointer> resultset; std::vector<mitk::DataNode::ConstPointer> openlist; /* Initialize openlist with node. this will add node to resultset, but that is necessary to detect circular relations that would lead to endless recursion */ openlist.push_back(node); while (openlist.size() > 0) { mitk::DataNode::ConstPointer current = openlist.back(); // get element that needs to be processed openlist.pop_back(); // remove last element, because it gets processed now resultset.push_back(current); // add current element to resultset AdjacencyList::const_iterator it = relation.find(current); // get parents of current node if ( (it == relation.end()) // if node not found in list || (it->second.IsNull()) // or no set of parents available || (it->second->Size() == 0)) // or empty set of parents continue; // then continue with next node in open list else for (SetOfObjects::ConstIterator parentIt = it->second->Begin(); parentIt != it->second->End(); ++parentIt) // for each parent of current node { mitk::DataNode::ConstPointer p = parentIt.Value().GetPointer(); if ( !(std::find(resultset.begin(), resultset.end(), p) != resultset.end()) // if it is not already in resultset && !(std::find(openlist.begin(), openlist.end(), p) != openlist.end())) // and not already in openlist openlist.push_back(p); // then add it to openlist, so that it can be processed } } /* now finally copy the results to a proper SetOfObjects variable exluding the initial node and checking the condition if any is given */ mitk::DataStorage::SetOfObjects::Pointer realResultset = mitk::DataStorage::SetOfObjects::New(); if (condition != NULL) { for (std::vector<mitk::DataNode::ConstPointer>::iterator resultIt = resultset.begin(); resultIt != resultset.end(); resultIt++) if ((*resultIt != node) && (condition->CheckNode(*resultIt) == true)) realResultset->InsertElement(realResultset->Size(), mitk::DataNode::Pointer(const_cast<mitk::DataNode*>((*resultIt).GetPointer()))); } else { for (std::vector<mitk::DataNode::ConstPointer>::iterator resultIt = resultset.begin(); resultIt != resultset.end(); resultIt++) if (*resultIt != node) realResultset->InsertElement(realResultset->Size(), mitk::DataNode::Pointer(const_cast<mitk::DataNode*>((*resultIt).GetPointer()))); } return SetOfObjects::ConstPointer(realResultset); } mitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetSources(const mitk::DataNode* node, const NodePredicateBase* condition, bool onlyDirectSources) const { itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex); return this->GetRelations(node, m_SourceNodes, condition, onlyDirectSources); } mitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetDerivations(const mitk::DataNode* node, const NodePredicateBase* condition, bool onlyDirectDerivations) const { itk::MutexLockHolder<itk::SimpleFastMutexLock>locked(m_Mutex); return this->GetRelations(node, m_DerivedNodes, condition, onlyDirectDerivations); } void mitk::StandaloneDataStorage::PrintSelf(std::ostream& os, itk::Indent indent) const { os << indent << "StandaloneDataStorage:\n"; Superclass::PrintSelf(os, indent); } <commit_msg>Workaround for small bug<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkStandaloneDataStorage.h" #include "mitkDataNode.h" #include "mitkProperties.h" #include "mitkNodePredicateBase.h" #include "mitkNodePredicateProperty.h" #include "mitkGroupTagProperty.h" #include "itkSimpleFastMutexLock.h" #include "itkMutexLockHolder.h" mitk::StandaloneDataStorage::StandaloneDataStorage() : mitk::DataStorage() { } mitk::StandaloneDataStorage::~StandaloneDataStorage() { for(AdjacencyList::iterator it = m_SourceNodes.begin(); it != m_SourceNodes.end(); it++) { this->RemoveListeners(it->first); } } bool mitk::StandaloneDataStorage::IsInitialized() const { return true; } void mitk::StandaloneDataStorage::Add(mitk::DataNode* node, const mitk::DataStorage::SetOfObjects* parents) { { itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex); if (!IsInitialized()) throw std::logic_error("DataStorage not initialized"); /* check if node is in its own list of sources */ if ((parents != NULL) && (std::find(parents->begin(), parents->end(), node) != parents->end())) throw std::invalid_argument("Node is it's own parent"); /* check if node already exists in StandaloneDataStorage */ if (m_SourceNodes.find(node) != m_SourceNodes.end()) throw std::invalid_argument("Node is already in DataStorage"); /* create parent list if it does not exist */ mitk::DataStorage::SetOfObjects::ConstPointer sp; if (parents != NULL) sp = parents; else sp = mitk::DataStorage::SetOfObjects::New(); /* Store node and parent list in sources adjacency list */ m_SourceNodes.insert(std::make_pair(node, sp)); /* Store node and an empty children list in derivations adjacency list */ mitk::DataStorage::SetOfObjects::Pointer childrenPointer = mitk::DataStorage::SetOfObjects::New(); mitk::DataStorage::SetOfObjects::ConstPointer children = childrenPointer.GetPointer(); m_DerivedNodes.insert(std::make_pair(node, children)); /* create entry in derivations adjacency list for each parent of the new node */ for (SetOfObjects::ConstIterator it = sp->Begin(); it != sp->End(); it++) { mitk::DataNode::ConstPointer parent = it.Value().GetPointer(); mitk::DataStorage::SetOfObjects::ConstPointer derivedObjects = m_DerivedNodes[parent]; // get or create pointer to list of derived objects for that parent node if (derivedObjects.IsNull()) m_DerivedNodes[parent] = mitk::DataStorage::SetOfObjects::New(); // Create a set of Objects, if it does not already exist mitk::DataStorage::SetOfObjects* deob = const_cast<mitk::DataStorage::SetOfObjects*>(m_DerivedNodes[parent].GetPointer()); // temporarily get rid of const pointer to insert new element deob->InsertElement(deob->Size(), node); // node is derived from parent. Insert it into the parents list of derived objects } // register for ITK changed events this->AddListeners(node); } /* Notify observers */ EmitAddNodeEvent(node); } void mitk::StandaloneDataStorage::Remove(const mitk::DataNode* node) { if (!IsInitialized()) throw std::logic_error("DataStorage not initialized"); if (node == NULL) return; // remove ITK modified event listener this->RemoveListeners(node); // muellerm, 22.9.10: add additional reference count to ensure // that the node is not deleted when removed from the relation map // while m_Mutex is locked. This would cause the an itk::DeleteEvent // is thrown and a deadlock will occur when event receivers // access the DataStorage again in their event processing function // mitk::DataNode::ConstPointer nodeGuard(node); /* Notify observers of imminent node removal */ EmitRemoveNodeEvent(node); { itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex); /* remove node from both relation adjacency lists */ this->RemoveFromRelation(node, m_SourceNodes); this->RemoveFromRelation(node, m_DerivedNodes); } } bool mitk::StandaloneDataStorage::Exists(const mitk::DataNode* node) const { itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex); return (m_SourceNodes.find(node) != m_SourceNodes.end()); } void mitk::StandaloneDataStorage::RemoveFromRelation(const mitk::DataNode* node, AdjacencyList& relation) { for (AdjacencyList::const_iterator mapIter = relation.begin(); mapIter != relation.end(); ++mapIter) // for each node in the relation if (mapIter->second.IsNotNull()) // if node has a relation list { SetOfObjects::Pointer s = const_cast<SetOfObjects*>(mapIter->second.GetPointer()); // search for node to be deleted in the relation list SetOfObjects::STLContainerType::iterator relationListIter = std::find(s->begin(), s->end(), node); // this assumes, that the relation list does not contain duplicates (which should be safe to assume) if (relationListIter != s->end()) // if node to be deleted is in relation list s->erase(relationListIter); // remove it from parentlist } /* now remove node from the relation */ AdjacencyList::iterator adIt; adIt = relation.find(node); if (adIt != relation.end()) relation.erase(adIt); } mitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetAll() const { itk::MutexLockHolder<itk::SimpleFastMutexLock > locked(m_Mutex); if (!IsInitialized()) throw std::logic_error("DataStorage not initialized"); mitk::DataStorage::SetOfObjects::Pointer resultset = mitk::DataStorage::SetOfObjects::New(); /* Fill resultset with all objects that are managed by the StandaloneDataStorage object */ unsigned int index = 0; for (AdjacencyList::const_iterator it = m_SourceNodes.begin(); it != m_SourceNodes.end(); ++it) if (it->first.IsNull()) continue; else resultset->InsertElement(index++, const_cast<mitk::DataNode*>(it->first.GetPointer())); return SetOfObjects::ConstPointer(resultset); } mitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetRelations(const mitk::DataNode* node, const AdjacencyList& relation, const NodePredicateBase* condition, bool onlyDirectlyRelated) const { if (node == NULL) throw std::invalid_argument("invalid node"); /* Either read direct relations directly from adjacency list */ if (onlyDirectlyRelated) { AdjacencyList::const_iterator it = relation.find(node); // get parents of current node if ((it == relation.end()) || (it->second.IsNull())) // node not found in list or no set of parents return SetOfObjects::ConstPointer(mitk::DataStorage::SetOfObjects::New()); // return an empty set else return this->FilterSetOfObjects(it->second, condition); } /* Or traverse adjacency list to collect all related nodes */ std::vector<mitk::DataNode::ConstPointer> resultset; std::vector<mitk::DataNode::ConstPointer> openlist; /* Initialize openlist with node. this will add node to resultset, but that is necessary to detect circular relations that would lead to endless recursion */ openlist.push_back(node); while (openlist.size() > 0) { mitk::DataNode::ConstPointer current = openlist.back(); // get element that needs to be processed openlist.pop_back(); // remove last element, because it gets processed now resultset.push_back(current); // add current element to resultset AdjacencyList::const_iterator it = relation.find(current); // get parents of current node if ( (it == relation.end()) // if node not found in list || (it->second.IsNull()) // or no set of parents available || (it->second->Size() == 0)) // or empty set of parents continue; // then continue with next node in open list else for (SetOfObjects::ConstIterator parentIt = it->second->Begin(); parentIt != it->second->End(); ++parentIt) // for each parent of current node { mitk::DataNode::ConstPointer p = parentIt.Value().GetPointer(); if ( !(std::find(resultset.begin(), resultset.end(), p) != resultset.end()) // if it is not already in resultset && !(std::find(openlist.begin(), openlist.end(), p) != openlist.end())) // and not already in openlist openlist.push_back(p); // then add it to openlist, so that it can be processed } } /* now finally copy the results to a proper SetOfObjects variable exluding the initial node and checking the condition if any is given */ mitk::DataStorage::SetOfObjects::Pointer realResultset = mitk::DataStorage::SetOfObjects::New(); if (condition != NULL) { for (std::vector<mitk::DataNode::ConstPointer>::iterator resultIt = resultset.begin(); resultIt != resultset.end(); resultIt++) if ((*resultIt != node) && (condition->CheckNode(*resultIt) == true)) realResultset->InsertElement(realResultset->Size(), mitk::DataNode::Pointer(const_cast<mitk::DataNode*>((*resultIt).GetPointer()))); } else { for (std::vector<mitk::DataNode::ConstPointer>::iterator resultIt = resultset.begin(); resultIt != resultset.end(); resultIt++) if (*resultIt != node) realResultset->InsertElement(realResultset->Size(), mitk::DataNode::Pointer(const_cast<mitk::DataNode*>((*resultIt).GetPointer()))); } return SetOfObjects::ConstPointer(realResultset); } mitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetSources(const mitk::DataNode* node, const NodePredicateBase* condition, bool onlyDirectSources) const { itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex); return this->GetRelations(node, m_SourceNodes, condition, onlyDirectSources); } mitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetDerivations(const mitk::DataNode* node, const NodePredicateBase* condition, bool onlyDirectDerivations) const { itk::MutexLockHolder<itk::SimpleFastMutexLock>locked(m_Mutex); return this->GetRelations(node, m_DerivedNodes, condition, onlyDirectDerivations); } void mitk::StandaloneDataStorage::PrintSelf(std::ostream& os, itk::Indent indent) const { os << indent << "StandaloneDataStorage:\n"; Superclass::PrintSelf(os, indent); } <|endoftext|>
<commit_before>#include "RTSPluginPCH.h" #include "RTSProductionComponent.h" #include "GameFramework/Actor.h" #include "GameFramework/Controller.h" #include "Engine/BlueprintGeneratedClass.h" #include "Engine/SCS_Node.h" #include "Kismet/GameplayStatics.h" #include "RTSGameMode.h" #include "RTSProductionCostComponent.h" #include "RTSPlayerController.h" #include "RTSPlayerAdvantageComponent.h" #include "RTSPlayerResourcesComponent.h" #include "RTSUtilities.h" URTSProductionComponent::URTSProductionComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryComponentTick.bCanEverTick = true; SetIsReplicated(true); } void URTSProductionComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(URTSProductionComponent, ProductionQueues); } void URTSProductionComponent::BeginPlay() { UActorComponent::BeginPlay(); // Setup queues. for (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex) { FRTSProductionQueue NewQueue; ProductionQueues.Add(NewQueue); } } void URTSProductionComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { UActorComponent::TickComponent(DeltaTime, TickType, ThisTickFunction); // Check for speed boosts. float SpeedBoostFactor = 1.0f; AActor* OwningActor = GetOwner(); if (OwningActor) { AActor* OwningPlayer = OwningActor->GetOwner(); if (OwningPlayer) { URTSPlayerAdvantageComponent* PlayerAdvantageComponent = OwningPlayer->FindComponentByClass<URTSPlayerAdvantageComponent>(); if (PlayerAdvantageComponent) { SpeedBoostFactor = PlayerAdvantageComponent->SpeedBoostFactor; } } } // Process all queues. for (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex) { if (ProductionQueues[QueueIndex].Num() <= 0) { continue; } // Check production costs. auto ProductClass = GetCurrentProduction(QueueIndex); auto ProductionCostComponent = URTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass); bool bProductionCostPaid = false; if (ProductionCostComponent && ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayOverTime) { auto Owner = GetOwner()->GetOwner(); if (!Owner) { UE_LOG(LogRTS, Error, TEXT("%s needs to pay for production, but has no owner."), *GetOwner()->GetName()); continue; } auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>(); if (!PlayerResourcesComponent) { UE_LOG(LogRTS, Error, TEXT("%s needs to pay for production, but has no PlayerResourcesComponent."), *Owner->GetName()); continue; } bool bCanPayAllProductionCosts = true; for (auto& Resource : ProductionCostComponent->Resources) { float ResourceAmount = Resource.Value * SpeedBoostFactor * DeltaTime / ProductionCostComponent->ProductionTime; if (!PlayerResourcesComponent->CanPayResources(Resource.Key, ResourceAmount)) { // Production stopped until resources become available again. bCanPayAllProductionCosts = false; break; } } if (bCanPayAllProductionCosts) { // Pay production costs. for (auto& Resource : ProductionCostComponent->Resources) { float ResourceAmount = Resource.Value * SpeedBoostFactor * DeltaTime / ProductionCostComponent->ProductionTime; PlayerResourcesComponent->PayResources(Resource.Key, ResourceAmount); } bProductionCostPaid = true; } } else { bProductionCostPaid = true; } if (!bProductionCostPaid) { continue; } // Update production progress. ProductionQueues[QueueIndex].RemainingProductionTime -= SpeedBoostFactor * DeltaTime; // Check if finished. if (ProductionQueues[QueueIndex].RemainingProductionTime <= 0) { FinishProduction(QueueIndex); } } } bool URTSProductionComponent::CanAssignProduction(TSubclassOf<AActor> ProductClass) const { return URTSUtilities::IsReadyToUse(GetOwner()) && FindQueueForProduct(ProductClass) >= 0; } int32 URTSProductionComponent::FindQueueForProduct(TSubclassOf<AActor> ProductClass) const { // Find queue with least products that is not at capacity limit. int32 QueueWithLeastProducts = -1; int32 ProductsInShortestQueue = CapacityPerQueue; for (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex) { const FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; if (Queue.Num() < ProductsInShortestQueue) { QueueWithLeastProducts = QueueIndex; ProductsInShortestQueue = Queue.Num(); } } return QueueWithLeastProducts; } TSubclassOf<AActor> URTSProductionComponent::GetCurrentProduction(int32 QueueIndex /*= 0*/) const { if (QueueIndex < 0 || QueueIndex >= QueueCount) { return nullptr; } const FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; return Queue.Num() > 0 ? Queue[0] : nullptr; } float URTSProductionComponent::GetProductionTime(int32 QueueIndex /*= 0*/) const { TSubclassOf<AActor> CurrentProduction = GetCurrentProduction(QueueIndex); if (!CurrentProduction) { return 0.0f; } return GetProductionTimeForProduct(CurrentProduction); } float URTSProductionComponent::GetProductionTimeForProduct(TSubclassOf<AActor> ProductClass) const { URTSProductionCostComponent* ProductionCostComponent = URTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass); return ProductionCostComponent ? ProductionCostComponent->ProductionTime : 0.0f; } float URTSProductionComponent::GetProgressPercentage(int32 QueueIndex /*= 0*/) const { float TotalProductionTime = GetProductionTime(QueueIndex); if (TotalProductionTime <= 0.0f) { return 1.0f; } float RemainingProductionTime = GetRemainingProductionTime(QueueIndex); if (RemainingProductionTime <= 0.0f) { return 1.0f; } return 1 - (RemainingProductionTime / TotalProductionTime); } float URTSProductionComponent::GetRemainingProductionTime(int32 QueueIndex /*= 0*/) const { if (QueueIndex < 0 || QueueIndex >= QueueCount) { return 0.0f; } return ProductionQueues[QueueIndex].RemainingProductionTime; } bool URTSProductionComponent::IsProducing() const { for (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex) { const FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; if (Queue.Num() > 0) { return true; } } return false; } void URTSProductionComponent::StartProduction(TSubclassOf<AActor> ProductClass) { // Check production state. if (!CanAssignProduction(ProductClass)) { return; } int32 QueueIndex = FindQueueForProduct(ProductClass); if (QueueIndex < 0) { return; } // Check requirements. TSubclassOf<AActor> MissingRequirement; if (URTSUtilities::GetMissingRequirementFor(this, GetOwner(), ProductClass, MissingRequirement)) { UE_LOG(LogRTS, Error, TEXT("%s wants to produce %s, but is missing requirement %s."), *GetOwner()->GetName(), *ProductClass->GetName(), *MissingRequirement->GetName()); return; } // Check production cost. URTSProductionCostComponent* ProductionCostComponent = URTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass); if (ProductionCostComponent && ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayImmediately) { auto Owner = GetOwner()->GetOwner(); if (!Owner) { UE_LOG(LogRTS, Error, TEXT("%s needs to pay for production, but has no owner."), *GetOwner()->GetName()); return; } auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>(); if (!PlayerResourcesComponent) { UE_LOG(LogRTS, Error, TEXT("%s needs to pay for production, but has no PlayerResourcesComponent."), *Owner->GetName()); return; } if (!PlayerResourcesComponent->CanPayAllResources(ProductionCostComponent->Resources)) { UE_LOG(LogRTS, Error, TEXT("%s needs to pay for producing %s, but does not have enough resources."), *Owner->GetName(), *ProductClass->GetName()); return; } // Pay production costs. PlayerResourcesComponent->PayAllResources(ProductionCostComponent->Resources); } // Insert into queue. FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; Queue.Add(ProductClass); UE_LOG(LogRTS, Log, TEXT("%s queued %s for production in queue %i."), *GetOwner()->GetName(), *ProductClass->GetName(), QueueIndex); // Notify listeners. OnProductQueued.Broadcast(ProductClass, QueueIndex); if (Queue.Num() == 1) { // Start production. StartProductionInQueue(QueueIndex); } } void URTSProductionComponent::FinishProduction(int32 QueueIndex /*= 0*/) { if (QueueIndex < 0 || QueueIndex >= QueueCount) { return; } FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; Queue.RemainingProductionTime = 0.0f; // Get game. ARTSGameMode* GameMode = Cast<ARTSGameMode>(UGameplayStatics::GetGameMode(this)); if (!GameMode) { return; } TSubclassOf<AActor> ProductClass = Queue[0]; // Determine spawn location: Start at producing actor location. FVector SpawnLocation = GetOwner()->GetActorLocation(); // Spawn next to production actor. float SpawnOffset = 0.0f; SpawnOffset += URTSUtilities::GetActorCollisionSize(GetOwner()) / 2; SpawnOffset += URTSUtilities::GetCollisionSize(ProductClass) / 2; SpawnOffset *= 1.05f; SpawnLocation.X -= SpawnOffset; // Calculate location on the ground. SpawnLocation = URTSUtilities::GetGroundLocation(this, SpawnLocation); // Prevent spawn collision or spawning at wrong side of the world. SpawnLocation.Z += URTSUtilities::GetCollisionHeight(ProductClass) + 1.0f; // Spawn product. AActor* Product = GameMode->SpawnActorForPlayer( ProductClass, Cast<AController>(GetOwner()->GetOwner()), FTransform(FRotator::ZeroRotator, SpawnLocation)); if (!Product) { return; } UE_LOG(LogRTS, Log, TEXT("%s finished producing %s in queue %i."), *GetOwner()->GetName(), *Product->GetName(), QueueIndex); // Notify listeners. OnProductionFinished.Broadcast(Product, QueueIndex); // Remove product from queue. DequeueProduct(QueueIndex); } void URTSProductionComponent::CancelProduction(int32 QueueIndex /*= 0*/, int32 ProductIndex /*= 0*/) { // Get queue. if (QueueIndex < 0 || QueueIndex >= QueueCount) { return; } FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; // Get product. if (ProductIndex < 0 || ProductIndex >= Queue.Num()) { return; } TSubclassOf<AActor> ProductClass = Queue[ProductIndex]; // Get elapsed production time. float TotalProductionTime = GetProductionTimeForProduct(ProductClass); float RemainingProductionTime = ProductIndex == 0 ? ProductionQueues[QueueIndex].RemainingProductionTime : TotalProductionTime; float ElapsedProductionTime = TotalProductionTime - RemainingProductionTime; UE_LOG(LogRTS, Log, TEXT("%s canceled producing product %i of class %s in queue %i after %f seconds."), *GetOwner()->GetName(), ProductIndex, *ProductClass->GetName(), QueueIndex, ElapsedProductionTime); // Notify listeners. OnProductionCanceled.Broadcast(ProductClass, QueueIndex, ElapsedProductionTime); // Remove product from queue. DequeueProduct(QueueIndex, ProductIndex); // Refund resources. URTSProductionCostComponent* ProductionCostComponent = URTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass); if (ProductionCostComponent) { auto Owner = GetOwner()->GetOwner(); if (!Owner) { return; } auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>(); if (!PlayerResourcesComponent) { return; } float TimeRefundFactor = 0.0f; if (ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayImmediately) { TimeRefundFactor = 1.0f; } else if (ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayOverTime) { TimeRefundFactor = ElapsedProductionTime / TotalProductionTime; } float ActualRefundFactor = ProductionCostComponent->RefundFactor * TimeRefundFactor; // Refund production costs. for (auto& Resource : ProductionCostComponent->Resources) { TSubclassOf<URTSResourceType> ResourceType = Resource.Key; float ResourceAmount = Resource.Value * ActualRefundFactor; PlayerResourcesComponent->AddResources(ResourceType, ResourceAmount); UE_LOG(LogRTS, Log, TEXT("%f %s of production costs refunded."), ResourceAmount, *ResourceType->GetName()); // Notify listeners. OnProductionCostRefunded.Broadcast(ResourceType, ResourceAmount); } } } void URTSProductionComponent::DequeueProduct(int32 QueueIndex /*= 0*/, int32 ProductIndex /*= 0*/) { // Get queue. if (QueueIndex < 0 || QueueIndex >= QueueCount) { return; } FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; if (ProductIndex < 0 || ProductIndex >= Queue.Num()) { return; } Queue.RemoveAt(ProductIndex); // Check if need to start next production. if (ProductIndex == 0 && Queue.Num() > 0) { StartProductionInQueue(QueueIndex); } } void URTSProductionComponent::StartProductionInQueue(int32 QueueIndex /*= 0*/) { // Get queue. if (QueueIndex < 0 || QueueIndex >= QueueCount) { return; } FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; // Get product. if (Queue.Num() <= 0) { return; } TSubclassOf<AActor> ProductClass = Queue[0]; // Start production. float ProductionTime = GetProductionTimeForProduct(ProductClass); Queue.RemainingProductionTime = ProductionTime; UE_LOG(LogRTS, Log, TEXT("%s started producing %s in queue %i."), *GetOwner()->GetName(), *ProductClass->GetName(), QueueIndex); // Notify listeners. OnProductionStarted.Broadcast(ProductClass, QueueIndex, ProductionTime); } <commit_msg>Prevent spawn collision or spawning at wrong side of the world for produced actors.<commit_after>#include "RTSPluginPCH.h" #include "RTSProductionComponent.h" #include "GameFramework/Actor.h" #include "GameFramework/Controller.h" #include "Engine/BlueprintGeneratedClass.h" #include "Engine/SCS_Node.h" #include "Kismet/GameplayStatics.h" #include "RTSGameMode.h" #include "RTSProductionCostComponent.h" #include "RTSPlayerController.h" #include "RTSPlayerAdvantageComponent.h" #include "RTSPlayerResourcesComponent.h" #include "RTSUtilities.h" URTSProductionComponent::URTSProductionComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryComponentTick.bCanEverTick = true; SetIsReplicated(true); } void URTSProductionComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(URTSProductionComponent, ProductionQueues); } void URTSProductionComponent::BeginPlay() { UActorComponent::BeginPlay(); // Setup queues. for (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex) { FRTSProductionQueue NewQueue; ProductionQueues.Add(NewQueue); } } void URTSProductionComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { UActorComponent::TickComponent(DeltaTime, TickType, ThisTickFunction); // Check for speed boosts. float SpeedBoostFactor = 1.0f; AActor* OwningActor = GetOwner(); if (OwningActor) { AActor* OwningPlayer = OwningActor->GetOwner(); if (OwningPlayer) { URTSPlayerAdvantageComponent* PlayerAdvantageComponent = OwningPlayer->FindComponentByClass<URTSPlayerAdvantageComponent>(); if (PlayerAdvantageComponent) { SpeedBoostFactor = PlayerAdvantageComponent->SpeedBoostFactor; } } } // Process all queues. for (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex) { if (ProductionQueues[QueueIndex].Num() <= 0) { continue; } // Check production costs. auto ProductClass = GetCurrentProduction(QueueIndex); auto ProductionCostComponent = URTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass); bool bProductionCostPaid = false; if (ProductionCostComponent && ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayOverTime) { auto Owner = GetOwner()->GetOwner(); if (!Owner) { UE_LOG(LogRTS, Error, TEXT("%s needs to pay for production, but has no owner."), *GetOwner()->GetName()); continue; } auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>(); if (!PlayerResourcesComponent) { UE_LOG(LogRTS, Error, TEXT("%s needs to pay for production, but has no PlayerResourcesComponent."), *Owner->GetName()); continue; } bool bCanPayAllProductionCosts = true; for (auto& Resource : ProductionCostComponent->Resources) { float ResourceAmount = Resource.Value * SpeedBoostFactor * DeltaTime / ProductionCostComponent->ProductionTime; if (!PlayerResourcesComponent->CanPayResources(Resource.Key, ResourceAmount)) { // Production stopped until resources become available again. bCanPayAllProductionCosts = false; break; } } if (bCanPayAllProductionCosts) { // Pay production costs. for (auto& Resource : ProductionCostComponent->Resources) { float ResourceAmount = Resource.Value * SpeedBoostFactor * DeltaTime / ProductionCostComponent->ProductionTime; PlayerResourcesComponent->PayResources(Resource.Key, ResourceAmount); } bProductionCostPaid = true; } } else { bProductionCostPaid = true; } if (!bProductionCostPaid) { continue; } // Update production progress. ProductionQueues[QueueIndex].RemainingProductionTime -= SpeedBoostFactor * DeltaTime; // Check if finished. if (ProductionQueues[QueueIndex].RemainingProductionTime <= 0) { FinishProduction(QueueIndex); } } } bool URTSProductionComponent::CanAssignProduction(TSubclassOf<AActor> ProductClass) const { return URTSUtilities::IsReadyToUse(GetOwner()) && FindQueueForProduct(ProductClass) >= 0; } int32 URTSProductionComponent::FindQueueForProduct(TSubclassOf<AActor> ProductClass) const { // Find queue with least products that is not at capacity limit. int32 QueueWithLeastProducts = -1; int32 ProductsInShortestQueue = CapacityPerQueue; for (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex) { const FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; if (Queue.Num() < ProductsInShortestQueue) { QueueWithLeastProducts = QueueIndex; ProductsInShortestQueue = Queue.Num(); } } return QueueWithLeastProducts; } TSubclassOf<AActor> URTSProductionComponent::GetCurrentProduction(int32 QueueIndex /*= 0*/) const { if (QueueIndex < 0 || QueueIndex >= QueueCount) { return nullptr; } const FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; return Queue.Num() > 0 ? Queue[0] : nullptr; } float URTSProductionComponent::GetProductionTime(int32 QueueIndex /*= 0*/) const { TSubclassOf<AActor> CurrentProduction = GetCurrentProduction(QueueIndex); if (!CurrentProduction) { return 0.0f; } return GetProductionTimeForProduct(CurrentProduction); } float URTSProductionComponent::GetProductionTimeForProduct(TSubclassOf<AActor> ProductClass) const { URTSProductionCostComponent* ProductionCostComponent = URTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass); return ProductionCostComponent ? ProductionCostComponent->ProductionTime : 0.0f; } float URTSProductionComponent::GetProgressPercentage(int32 QueueIndex /*= 0*/) const { float TotalProductionTime = GetProductionTime(QueueIndex); if (TotalProductionTime <= 0.0f) { return 1.0f; } float RemainingProductionTime = GetRemainingProductionTime(QueueIndex); if (RemainingProductionTime <= 0.0f) { return 1.0f; } return 1 - (RemainingProductionTime / TotalProductionTime); } float URTSProductionComponent::GetRemainingProductionTime(int32 QueueIndex /*= 0*/) const { if (QueueIndex < 0 || QueueIndex >= QueueCount) { return 0.0f; } return ProductionQueues[QueueIndex].RemainingProductionTime; } bool URTSProductionComponent::IsProducing() const { for (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex) { const FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; if (Queue.Num() > 0) { return true; } } return false; } void URTSProductionComponent::StartProduction(TSubclassOf<AActor> ProductClass) { // Check production state. if (!CanAssignProduction(ProductClass)) { return; } int32 QueueIndex = FindQueueForProduct(ProductClass); if (QueueIndex < 0) { return; } // Check requirements. TSubclassOf<AActor> MissingRequirement; if (URTSUtilities::GetMissingRequirementFor(this, GetOwner(), ProductClass, MissingRequirement)) { UE_LOG(LogRTS, Error, TEXT("%s wants to produce %s, but is missing requirement %s."), *GetOwner()->GetName(), *ProductClass->GetName(), *MissingRequirement->GetName()); return; } // Check production cost. URTSProductionCostComponent* ProductionCostComponent = URTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass); if (ProductionCostComponent && ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayImmediately) { auto Owner = GetOwner()->GetOwner(); if (!Owner) { UE_LOG(LogRTS, Error, TEXT("%s needs to pay for production, but has no owner."), *GetOwner()->GetName()); return; } auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>(); if (!PlayerResourcesComponent) { UE_LOG(LogRTS, Error, TEXT("%s needs to pay for production, but has no PlayerResourcesComponent."), *Owner->GetName()); return; } if (!PlayerResourcesComponent->CanPayAllResources(ProductionCostComponent->Resources)) { UE_LOG(LogRTS, Error, TEXT("%s needs to pay for producing %s, but does not have enough resources."), *Owner->GetName(), *ProductClass->GetName()); return; } // Pay production costs. PlayerResourcesComponent->PayAllResources(ProductionCostComponent->Resources); } // Insert into queue. FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; Queue.Add(ProductClass); UE_LOG(LogRTS, Log, TEXT("%s queued %s for production in queue %i."), *GetOwner()->GetName(), *ProductClass->GetName(), QueueIndex); // Notify listeners. OnProductQueued.Broadcast(ProductClass, QueueIndex); if (Queue.Num() == 1) { // Start production. StartProductionInQueue(QueueIndex); } } void URTSProductionComponent::FinishProduction(int32 QueueIndex /*= 0*/) { if (QueueIndex < 0 || QueueIndex >= QueueCount) { return; } FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; Queue.RemainingProductionTime = 0.0f; // Get game. ARTSGameMode* GameMode = Cast<ARTSGameMode>(UGameplayStatics::GetGameMode(this)); if (!GameMode) { return; } TSubclassOf<AActor> ProductClass = Queue[0]; // Determine spawn location: Start at producing actor location. FVector SpawnLocation = GetOwner()->GetActorLocation(); // Spawn next to production actor. float SpawnOffset = 0.0f; SpawnOffset += URTSUtilities::GetActorCollisionSize(GetOwner()) / 2; SpawnOffset += URTSUtilities::GetCollisionSize(ProductClass) / 2; SpawnOffset *= 1.05f; SpawnLocation.X -= SpawnOffset; // Calculate location on the ground. SpawnLocation = URTSUtilities::GetGroundLocation(this, SpawnLocation); // Prevent spawn collision or spawning at wrong side of the world. SpawnLocation.Z += URTSUtilities::GetCollisionHeight(ProductClass) * 1.1f; // Spawn product. AActor* Product = GameMode->SpawnActorForPlayer( ProductClass, Cast<AController>(GetOwner()->GetOwner()), FTransform(FRotator::ZeroRotator, SpawnLocation)); if (!Product) { return; } UE_LOG(LogRTS, Log, TEXT("%s finished producing %s in queue %i."), *GetOwner()->GetName(), *Product->GetName(), QueueIndex); // Notify listeners. OnProductionFinished.Broadcast(Product, QueueIndex); // Remove product from queue. DequeueProduct(QueueIndex); } void URTSProductionComponent::CancelProduction(int32 QueueIndex /*= 0*/, int32 ProductIndex /*= 0*/) { // Get queue. if (QueueIndex < 0 || QueueIndex >= QueueCount) { return; } FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; // Get product. if (ProductIndex < 0 || ProductIndex >= Queue.Num()) { return; } TSubclassOf<AActor> ProductClass = Queue[ProductIndex]; // Get elapsed production time. float TotalProductionTime = GetProductionTimeForProduct(ProductClass); float RemainingProductionTime = ProductIndex == 0 ? ProductionQueues[QueueIndex].RemainingProductionTime : TotalProductionTime; float ElapsedProductionTime = TotalProductionTime - RemainingProductionTime; UE_LOG(LogRTS, Log, TEXT("%s canceled producing product %i of class %s in queue %i after %f seconds."), *GetOwner()->GetName(), ProductIndex, *ProductClass->GetName(), QueueIndex, ElapsedProductionTime); // Notify listeners. OnProductionCanceled.Broadcast(ProductClass, QueueIndex, ElapsedProductionTime); // Remove product from queue. DequeueProduct(QueueIndex, ProductIndex); // Refund resources. URTSProductionCostComponent* ProductionCostComponent = URTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass); if (ProductionCostComponent) { auto Owner = GetOwner()->GetOwner(); if (!Owner) { return; } auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>(); if (!PlayerResourcesComponent) { return; } float TimeRefundFactor = 0.0f; if (ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayImmediately) { TimeRefundFactor = 1.0f; } else if (ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayOverTime) { TimeRefundFactor = ElapsedProductionTime / TotalProductionTime; } float ActualRefundFactor = ProductionCostComponent->RefundFactor * TimeRefundFactor; // Refund production costs. for (auto& Resource : ProductionCostComponent->Resources) { TSubclassOf<URTSResourceType> ResourceType = Resource.Key; float ResourceAmount = Resource.Value * ActualRefundFactor; PlayerResourcesComponent->AddResources(ResourceType, ResourceAmount); UE_LOG(LogRTS, Log, TEXT("%f %s of production costs refunded."), ResourceAmount, *ResourceType->GetName()); // Notify listeners. OnProductionCostRefunded.Broadcast(ResourceType, ResourceAmount); } } } void URTSProductionComponent::DequeueProduct(int32 QueueIndex /*= 0*/, int32 ProductIndex /*= 0*/) { // Get queue. if (QueueIndex < 0 || QueueIndex >= QueueCount) { return; } FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; if (ProductIndex < 0 || ProductIndex >= Queue.Num()) { return; } Queue.RemoveAt(ProductIndex); // Check if need to start next production. if (ProductIndex == 0 && Queue.Num() > 0) { StartProductionInQueue(QueueIndex); } } void URTSProductionComponent::StartProductionInQueue(int32 QueueIndex /*= 0*/) { // Get queue. if (QueueIndex < 0 || QueueIndex >= QueueCount) { return; } FRTSProductionQueue& Queue = ProductionQueues[QueueIndex]; // Get product. if (Queue.Num() <= 0) { return; } TSubclassOf<AActor> ProductClass = Queue[0]; // Start production. float ProductionTime = GetProductionTimeForProduct(ProductClass); Queue.RemainingProductionTime = ProductionTime; UE_LOG(LogRTS, Log, TEXT("%s started producing %s in queue %i."), *GetOwner()->GetName(), *ProductClass->GetName(), QueueIndex); // Notify listeners. OnProductionStarted.Broadcast(ProductClass, QueueIndex, ProductionTime); } <|endoftext|>
<commit_before>// // AudioListener.cpp // Created by Matt Kaufmann on 04/10/14. // #include "Vajra/Common/Messages/Message.h" #include "Vajra/Common/Objects/Object.h" #include "Vajra/Engine/AudioManager/AudioManager.h" #include "Vajra/Engine/Components/ComponentTypes/ComponentTypeIds.h" #include "Vajra/Engine/Components/DerivedComponents/Audio/AudioListener.h" #include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h" #include "Vajra/Engine/Core/Engine.h" unsigned int AudioListener::componentTypeId = COMPONENT_TYPE_ID_AUDIO_LISTENER; ObjectIdType AudioListener::activeListener = OBJECT_ID_INVALID; // Constructors AudioListener::AudioListener() : Component() { this->init(); } AudioListener::AudioListener(Object* object_) : Component(object_) { this->init(); } // Destructor AudioListener::~AudioListener() { this->destroy(); } bool AudioListener::Is3DSoundEnabled() { return this->is3D; } void AudioListener::Enable3DSound() { this->is3D = true; if (AudioListener::activeListener == this->GetObject()->GetId()) { ENGINE->GetAudioManager()->Enable3DSound(); } } void AudioListener::Disable3DSound() { this->is3D = false; if (AudioListener::activeListener == this->GetObject()->GetId()) { ENGINE->GetAudioManager()->Disable3DSound(); } } void AudioListener::SetVelocity(glm::vec3 vel) { this->velocity = vel; if (AudioListener::activeListener == this->GetObject()->GetId()) { ENGINE->GetAudioManager()->SetListenerVelocity(vel); } } void AudioListener::SetVelocity(float x, float y, float z) { this->velocity = glm::vec3(x, y, z); if (AudioListener::activeListener == this->GetObject()->GetId()) { ENGINE->GetAudioManager()->SetListenerVelocity(x, y, z); } } void AudioListener::SetVolume(float vol) { this->volume = vol; if (AudioListener::activeListener == this->GetObject()->GetId()) { ENGINE->GetAudioManager()->SetListenerVolume(vol); } } void AudioListener::HandleMessage(MessageChunk messageChunk) { Component::HandleMessage(messageChunk); switch (messageChunk->GetMessageType()) { case MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT: onTransformChanged(); break; } } void AudioListener::SetAsActiveListener() { if (AudioListener::activeListener != this->GetObject()->GetId()) { if (this->is3D) { ENGINE->GetAudioManager()->Enable3DSound(); } else { ENGINE->GetAudioManager()->Disable3DSound(); } Transform* trans = this->GetObject()->GetComponent<Transform>(); ENGINE->GetAudioManager()->SetListenerPosition(trans->GetPositionWorld()); ENGINE->GetAudioManager()->SetListenerOrientation(trans->GetOrientationWorld()); ENGINE->GetAudioManager()->SetListenerVelocity(this->velocity); ENGINE->GetAudioManager()->SetListenerVolume(this->volume); AudioListener::activeListener = this->GetObject()->GetId(); } } void AudioListener::init() { this->is3D = false; this->velocity = ZERO_VEC3; this->volume = 0.0f; this->addSubscriptionToMessageType(MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT, this->GetTypeId(), true); } void AudioListener::destroy() { } void AudioListener::onTransformChanged() { if (AudioListener::activeListener == this->GetObject()->GetId()) { Transform* trans = this->GetObject()->GetComponent<Transform>(); ENGINE->GetAudioManager()->SetListenerPosition(trans->GetPositionWorld()); ENGINE->GetAudioManager()->SetListenerOrientation(trans->GetOrientationWorld()); } } <commit_msg>unmuted audio listener<commit_after>// // AudioListener.cpp // Created by Matt Kaufmann on 04/10/14. // #include "Vajra/Common/Messages/Message.h" #include "Vajra/Common/Objects/Object.h" #include "Vajra/Engine/AudioManager/AudioManager.h" #include "Vajra/Engine/Components/ComponentTypes/ComponentTypeIds.h" #include "Vajra/Engine/Components/DerivedComponents/Audio/AudioListener.h" #include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h" #include "Vajra/Engine/Core/Engine.h" unsigned int AudioListener::componentTypeId = COMPONENT_TYPE_ID_AUDIO_LISTENER; ObjectIdType AudioListener::activeListener = OBJECT_ID_INVALID; // Constructors AudioListener::AudioListener() : Component() { this->init(); } AudioListener::AudioListener(Object* object_) : Component(object_) { this->init(); } // Destructor AudioListener::~AudioListener() { this->destroy(); } bool AudioListener::Is3DSoundEnabled() { return this->is3D; } void AudioListener::Enable3DSound() { this->is3D = true; if (AudioListener::activeListener == this->GetObject()->GetId()) { ENGINE->GetAudioManager()->Enable3DSound(); } } void AudioListener::Disable3DSound() { this->is3D = false; if (AudioListener::activeListener == this->GetObject()->GetId()) { ENGINE->GetAudioManager()->Disable3DSound(); } } void AudioListener::SetVelocity(glm::vec3 vel) { this->velocity = vel; if (AudioListener::activeListener == this->GetObject()->GetId()) { ENGINE->GetAudioManager()->SetListenerVelocity(vel); } } void AudioListener::SetVelocity(float x, float y, float z) { this->velocity = glm::vec3(x, y, z); if (AudioListener::activeListener == this->GetObject()->GetId()) { ENGINE->GetAudioManager()->SetListenerVelocity(x, y, z); } } void AudioListener::SetVolume(float vol) { this->volume = vol; if (AudioListener::activeListener == this->GetObject()->GetId()) { ENGINE->GetAudioManager()->SetListenerVolume(vol); } } void AudioListener::HandleMessage(MessageChunk messageChunk) { Component::HandleMessage(messageChunk); switch (messageChunk->GetMessageType()) { case MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT: onTransformChanged(); break; } } void AudioListener::SetAsActiveListener() { if (AudioListener::activeListener != this->GetObject()->GetId()) { if (this->is3D) { ENGINE->GetAudioManager()->Enable3DSound(); } else { ENGINE->GetAudioManager()->Disable3DSound(); } Transform* trans = this->GetObject()->GetComponent<Transform>(); ENGINE->GetAudioManager()->SetListenerPosition(trans->GetPositionWorld()); ENGINE->GetAudioManager()->SetListenerOrientation(trans->GetOrientationWorld()); ENGINE->GetAudioManager()->SetListenerVelocity(this->velocity); ENGINE->GetAudioManager()->SetListenerVolume(this->volume); AudioListener::activeListener = this->GetObject()->GetId(); } } void AudioListener::init() { this->is3D = false; this->velocity = ZERO_VEC3; this->volume = 1.0f; this->addSubscriptionToMessageType(MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT, this->GetTypeId(), true); } void AudioListener::destroy() { } void AudioListener::onTransformChanged() { if (AudioListener::activeListener == this->GetObject()->GetId()) { Transform* trans = this->GetObject()->GetComponent<Transform>(); ENGINE->GetAudioManager()->SetListenerPosition(trans->GetPositionWorld()); ENGINE->GetAudioManager()->SetListenerOrientation(trans->GetOrientationWorld()); } } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2012-2013 Danny Y., Rapptz // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef GEARS_PROGRAM_OPTIONS_ARG_HPP #define GEARS_PROGRAM_OPTIONS_ARG_HPP #include <string> #ifndef GEARS_NO_IOSTREAM #include <iosfwd> #endif // GEARS_NO_IOSTREAM namespace gears { struct arg { private: friend class program_options; std::string name; std::string description; std::string parameter; std::string value; bool active = false; char short_name = '\0'; public: arg(std::string name, std::string desc = "", char shorter = '\0', std::string p = "") noexcept: name(std::move(name)), description(std::move(desc)), parameter(std::move(p)), short_name(shorter) {} template<typename Elem, typename Traits> friend auto operator<<(std::basic_ostream<Elem, Traits>& out, const arg& a) -> decltype(out) { int spaces = 30; out << " "; if(!a.name.empty()) { if(a.short_name != '\0') { out << '-' << a.short_name << ", "; spaces -= 4; } out << "--" << a.name; spaces -= 2 + a.name.size(); if(!a.parameter.empty()) { out << "[=<" << a.parameter << ">]"; spaces -= 5 + a.parameter.size(); } for(int i = 0; i < spaces; ++i) { out << ' '; } out << a.description << '\n'; } return out; } bool is_value() const noexcept { return !parameter.empty(); } arg& shorter(char c) noexcept { short_name = c; return *this; } arg& help(std::string str) noexcept { description = std::move(str); return *this; } arg& param(std::string str) noexcept { parameter = std::move(str); return *this; } }; } // gears #endif // GEARS_PROGRAM_OPTIONS_ARG_HPP<commit_msg>Fix issue with GEARS_NO_IOSTREAM missing<commit_after>// The MIT License (MIT) // Copyright (c) 2012-2013 Danny Y., Rapptz // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef GEARS_PROGRAM_OPTIONS_ARG_HPP #define GEARS_PROGRAM_OPTIONS_ARG_HPP #include <string> #ifndef GEARS_NO_IOSTREAM #include <iosfwd> #endif // GEARS_NO_IOSTREAM namespace gears { struct arg { private: friend class program_options; std::string name; std::string description; std::string parameter; std::string value; bool active = false; char short_name = '\0'; public: arg(std::string name, std::string desc = "", char shorter = '\0', std::string p = "") noexcept: name(std::move(name)), description(std::move(desc)), parameter(std::move(p)), short_name(shorter) {} bool is_value() const noexcept { return !parameter.empty(); } arg& shorter(char c) noexcept { short_name = c; return *this; } arg& help(std::string str) noexcept { description = std::move(str); return *this; } arg& param(std::string str) noexcept { parameter = std::move(str); return *this; } #ifndef GEARS_NO_IOSTREAM template<typename Elem, typename Traits> friend auto operator<<(std::basic_ostream<Elem, Traits>& out, const arg& a) -> decltype(out) { int spaces = 30; out << " "; if(!a.name.empty()) { if(a.short_name != '\0') { out << '-' << a.short_name << ", "; spaces -= 4; } out << "--" << a.name; spaces -= 2 + a.name.size(); if(!a.parameter.empty()) { out << "[=<" << a.parameter << ">]"; spaces -= 5 + a.parameter.size(); } for(int i = 0; i < spaces; ++i) { out << ' '; } out << a.description << '\n'; } return out; } #endif // GEARS_NO_IOSTREAM }; } // gears #endif // GEARS_PROGRAM_OPTIONS_ARG_HPP<|endoftext|>
<commit_before>#include <iostream> #include <External/gl_core_3_3.hpp> #include <SDL2/SDL.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <Base/Filesystem/File.h> #include "messagebox.h" using namespace gl; int keyPressed[SDL_NUM_SCANCODES] = {0}; int WINDOW_WIDTH = 1280, WINDOW_HEIGHT = 720; class String { private: const char* stringData; public: String(const char* cstr) : stringData(cstr) {} const char* str() const { return stringData; } }; class Shader { private: GLuint vertID, fragID, progID; GLuint newShader(GLenum shaderType, const char* source) { // Tutorial code from http://www.arcsynthesis.org/gltut // Copyright © 2012 Jason L. McKesson // Variable names changed take custom parameters and work with glLoadGen func_cpp functions GLuint shader = CreateShader(shaderType); ShaderSource(shader, 1, &source, NULL); CompileShader(shader); GLint status; GetShaderiv(shader, COMPILE_STATUS, &status); if (status == FALSE_) { GLint infoLogLength; GetShaderiv(shader, INFO_LOG_LENGTH, &infoLogLength); GLchar *strInfoLog = new GLchar[infoLogLength + 1]; GetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog); const char *strShaderType = NULL; switch(shaderType) { case VERTEX_SHADER: strShaderType = "vertex"; break; case GEOMETRY_SHADER: strShaderType = "geometry"; break; case FRAGMENT_SHADER: strShaderType = "fragment"; break; } fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog); delete[] strInfoLog; } return shader; } public: Shader(const File& vert, const File& frag) { // Create both shaders vertID = newShader(VERTEX_SHADER, vert.string().c_str()); fragID = newShader(FRAGMENT_SHADER, frag.string().c_str()); // Create and link a program progID = CreateProgram(); AttachShader(progID, vertID); AttachShader(progID, fragID); LinkProgram(progID); DetachShader(progID, vertID); DetachShader(progID, fragID); } const int getProgram() {return progID;} }; const float triangle[] = { // Positions -1, -1, 0, 1, 1, -1, 0, 1, 0, 1, 0, 1, // Colors 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1 }; #include "cube.cpp" class TestScene { private: Shader shader; GLuint VBO_id; GLuint VAO_id; GLuint mvpLocation, offsetLocation; unsigned deltaTime; unsigned currentFrame; unsigned lastFrame; glm::mat4 model, view, projection; glm::vec4 offset; public: TestScene() : shader("Shaders/UnlitGeneric.vert", "Shaders/UnlitGeneric.frag"), lastFrame(SDL_GetTicks()) { ClearColor(0, 0, 0, 1); ClearDepth(1); Enable(DEPTH_TEST); Enable(CULL_FACE); CullFace(BACK); FrontFace(CW); Viewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); // Set up uniforms for the shader mvpLocation = GetUniformLocation(shader.getProgram(), "MVP"); offsetLocation = GetUniformLocation(shader.getProgram(), "offset"); // Generate a VBO and VAO GenBuffers(1, &VBO_id); GenVertexArrays(1, &VAO_id); // Bind them BindBuffer(ARRAY_BUFFER, VBO_id); BindVertexArray(VAO_id); // Set the buffer data BufferData(ARRAY_BUFFER, sizeof(vertexData), vertexData, STATIC_DRAW); // Enable the first two vertex attributes EnableVertexAttribArray(0); EnableVertexAttribArray(1); // Attribute index, 4 values per position, inform they're floats, unknown, space between values, first value VertexAttribPointer(0, 4, gl::FLOAT, false, 0, 0); VertexAttribPointer(1, 4, gl::FLOAT, false, 0, (void*) (sizeof(vertexData) / 2)); // And clean up DisableVertexAttribArray(0); DisableVertexAttribArray(1); BindBuffer(ARRAY_BUFFER, 0); BindVertexArray(0); } void draw() { static unsigned totalTime = 0; currentFrame = SDL_GetTicks(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; totalTime += deltaTime; // Matrices model = glm::mat4(1); view = glm::lookAt(glm::vec3(0, 0, 2), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); int sizeX = WINDOW_WIDTH, sizeY = WINDOW_HEIGHT; projection = glm::perspective(60.0, (double)sizeX/(double)sizeY, 0.01, 10000.0); glm::mat4 modelViewProjection = projection * view * model; static float modelX = 0, modelY = 0; if (keyPressed[SDL_SCANCODE_LEFT]) { modelX -= float(deltaTime * 0.001); } if (keyPressed[SDL_SCANCODE_RIGHT]) { modelX += float(deltaTime * 0.001); } if (keyPressed[SDL_SCANCODE_UP]) { modelY += float(deltaTime * 0.001); } if (keyPressed[SDL_SCANCODE_DOWN]) { modelY -= float(deltaTime * 0.001); } // Offset offset.x = modelX; offset.y = modelY; offset.z = 0; offset.w = 1; // Set the shader program UseProgram(shader.getProgram()); UniformMatrix4fv(mvpLocation, 1, FALSE_, &modelViewProjection[0][0]); Uniform4fv(offsetLocation, 1, &offset[0]); // Bind the vertex array BindVertexArray(VAO_id); EnableVertexAttribArray(0); EnableVertexAttribArray(1); // Draw the values DrawArrays(TRIANGLES, 0, 36); // And unbind the vertex array DisableVertexAttribArray(0); DisableVertexAttribArray(1); BindVertexArray(0); } }; void cbfun_windowResized(int width, int height) { WINDOW_WIDTH = width; WINDOW_HEIGHT = height; Viewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); } int main(int argc, char** argv) { PHYSFS_init(argv[0]); setRootPath("../Data"); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("SomeGame (SDL)", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); SDL_GLContext context = SDL_GL_CreateContext(window); SDL_GL_SetSwapInterval(1); if (!window || !sys::LoadFunctions()) { MessageBoxError("Fatal Error", "Could not initialize an OpenGL context\nMake sure your computer supports OpenGL 3.3 and drivers are updated"); fprintf(stderr, "SDL_GetError(): %s", SDL_GetError()); return -1; } fprintf(stdout, "OpenGL version: %s\nDisplay device: %s\nVendor: %s\n", GetString(VERSION), GetString(RENDERER), GetString(VENDOR)); TestScene scene; bool runGame = true; while (runGame) { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN) { keyPressed[event.key.keysym.scancode] = 1; } else if (event.type == SDL_KEYUP) { keyPressed[event.key.keysym.scancode] = 0; } if (event.type == SDL_QUIT or event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) { runGame = false; } else if (event.type == SDL_WINDOWEVENT_RESIZED) { cbfun_windowResized(event.window.data1, event.window.data2); } } Clear(COLOR_BUFFER_BIT | DEPTH_BUFFER_BIT); scene.draw(); SDL_GL_SwapWindow(window); } SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 0; } <commit_msg>Fix glViewport() not being called on window resize<commit_after>#include <iostream> #include <External/gl_core_3_3.hpp> #include <SDL2/SDL.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <Base/Filesystem/File.h> #include "messagebox.h" using namespace gl; int keyPressed[SDL_NUM_SCANCODES] = {0}; int WINDOW_WIDTH = 1280, WINDOW_HEIGHT = 720; class String { private: const char* stringData; public: String(const char* cstr) : stringData(cstr) {} const char* str() const { return stringData; } }; class Shader { private: GLuint vertID, fragID, progID; GLuint newShader(GLenum shaderType, const char* source) { // Tutorial code from http://www.arcsynthesis.org/gltut // Copyright © 2012 Jason L. McKesson // Variable names changed take custom parameters and work with glLoadGen func_cpp functions GLuint shader = CreateShader(shaderType); ShaderSource(shader, 1, &source, NULL); CompileShader(shader); GLint status; GetShaderiv(shader, COMPILE_STATUS, &status); if (status == FALSE_) { GLint infoLogLength; GetShaderiv(shader, INFO_LOG_LENGTH, &infoLogLength); GLchar *strInfoLog = new GLchar[infoLogLength + 1]; GetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog); const char *strShaderType = NULL; switch(shaderType) { case VERTEX_SHADER: strShaderType = "vertex"; break; case GEOMETRY_SHADER: strShaderType = "geometry"; break; case FRAGMENT_SHADER: strShaderType = "fragment"; break; } fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog); delete[] strInfoLog; } return shader; } public: Shader(const File& vert, const File& frag) { // Create both shaders vertID = newShader(VERTEX_SHADER, vert.string().c_str()); fragID = newShader(FRAGMENT_SHADER, frag.string().c_str()); // Create and link a program progID = CreateProgram(); AttachShader(progID, vertID); AttachShader(progID, fragID); LinkProgram(progID); DetachShader(progID, vertID); DetachShader(progID, fragID); } const int getProgram() {return progID;} }; const float triangle[] = { // Positions -1, -1, 0, 1, 1, -1, 0, 1, 0, 1, 0, 1, // Colors 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1 }; #include "cube.cpp" class TestScene { private: Shader shader; GLuint VBO_id; GLuint VAO_id; GLuint mvpLocation, offsetLocation; unsigned deltaTime; unsigned currentFrame; unsigned lastFrame; glm::mat4 model, view, projection; glm::vec4 offset; public: TestScene() : shader("Shaders/UnlitGeneric.vert", "Shaders/UnlitGeneric.frag"), lastFrame(SDL_GetTicks()) { ClearColor(0, 0, 0, 1); ClearDepth(1); Enable(DEPTH_TEST); Enable(CULL_FACE); CullFace(BACK); FrontFace(CW); Viewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); // Set up uniforms for the shader mvpLocation = GetUniformLocation(shader.getProgram(), "MVP"); offsetLocation = GetUniformLocation(shader.getProgram(), "offset"); // Generate a VBO and VAO GenBuffers(1, &VBO_id); GenVertexArrays(1, &VAO_id); // Bind them BindBuffer(ARRAY_BUFFER, VBO_id); BindVertexArray(VAO_id); // Set the buffer data BufferData(ARRAY_BUFFER, sizeof(vertexData), vertexData, STATIC_DRAW); // Enable the first two vertex attributes EnableVertexAttribArray(0); EnableVertexAttribArray(1); // Attribute index, 4 values per position, inform they're floats, unknown, space between values, first value VertexAttribPointer(0, 4, gl::FLOAT, false, 0, 0); VertexAttribPointer(1, 4, gl::FLOAT, false, 0, (void*) (sizeof(vertexData) / 2)); // And clean up DisableVertexAttribArray(0); DisableVertexAttribArray(1); BindBuffer(ARRAY_BUFFER, 0); BindVertexArray(0); } void draw() { static unsigned totalTime = 0; currentFrame = SDL_GetTicks(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; totalTime += deltaTime; // Matrices model = glm::mat4(1); view = glm::lookAt(glm::vec3(0, 0, 2), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); int sizeX = WINDOW_WIDTH, sizeY = WINDOW_HEIGHT; projection = glm::perspective(60.0, (double)sizeX/(double)sizeY, 0.01, 10000.0); glm::mat4 modelViewProjection = projection * view * model; static float modelX = 0, modelY = 0; if (keyPressed[SDL_SCANCODE_LEFT]) { modelX -= float(deltaTime * 0.001); } if (keyPressed[SDL_SCANCODE_RIGHT]) { modelX += float(deltaTime * 0.001); } if (keyPressed[SDL_SCANCODE_UP]) { modelY += float(deltaTime * 0.001); } if (keyPressed[SDL_SCANCODE_DOWN]) { modelY -= float(deltaTime * 0.001); } // Offset offset.x = modelX; offset.y = modelY; offset.z = 0; offset.w = 1; // Set the shader program UseProgram(shader.getProgram()); UniformMatrix4fv(mvpLocation, 1, FALSE_, &modelViewProjection[0][0]); Uniform4fv(offsetLocation, 1, &offset[0]); // Bind the vertex array BindVertexArray(VAO_id); EnableVertexAttribArray(0); EnableVertexAttribArray(1); // Draw the values DrawArrays(TRIANGLES, 0, 36); // And unbind the vertex array DisableVertexAttribArray(0); DisableVertexAttribArray(1); BindVertexArray(0); } }; int main(int argc, char** argv) { PHYSFS_init(argv[0]); setRootPath("../Data"); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("SomeGame (SDL)", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); SDL_GLContext context = SDL_GL_CreateContext(window); SDL_GL_SetSwapInterval(1); if (!window || !sys::LoadFunctions()) { MessageBoxError("Fatal Error", "Could not initialize an OpenGL context\nMake sure your computer supports OpenGL 3.3 and drivers are updated"); fprintf(stderr, "SDL_GetError(): %s", SDL_GetError()); return -1; } fprintf(stdout, "OpenGL version: %s\nDisplay device: %s\nVendor: %s\n", GetString(VERSION), GetString(RENDERER), GetString(VENDOR)); TestScene scene; bool runGame = true; while (runGame) { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN) { keyPressed[event.key.keysym.scancode] = 1; } else if (event.type == SDL_KEYUP) { keyPressed[event.key.keysym.scancode] = 0; } if (event.type == SDL_QUIT or event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) { runGame = false; } if (event.type == SDL_WINDOWEVENT and event.window.event == SDL_WINDOWEVENT_RESIZED) { WINDOW_WIDTH = event.window.data1; WINDOW_HEIGHT = event.window.data2; Viewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); } } Clear(COLOR_BUFFER_BIT | DEPTH_BUFFER_BIT); scene.draw(); SDL_GL_SwapWindow(window); } SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegistrationHistogramPlotter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // The example shows how to use the \doxygen{HistogramToImageFilter} class. // The example registers two images using the gradient descent optimizer. // The transform used here is a simple translation transform. The metric // is a MutualInformationHistogramImageToImageMetric. // // The jointHistogramWriter is invoked after every iteration of the optimizer. // the writer here writes the joint histogram after every iteration as // JointHistogramXXX.mhd // // Note: This may not work for some VNL optimizers like Amoeba which do not throw // events. // #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImageRegistrationMethod.h" #include "itkTranslationTransform.h" #include "itkMutualInformationHistogramImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkGradientDescentOptimizer.h" #include "itkImage.h" #include "itkNormalizeImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" #include "itkHistogramToImageFilter.h" #include "itkCommand.h" const unsigned int Dimension = 2; class HistogramWriter { public: typedef float InternalPixelType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::MutualInformationHistogramImageToImageMetric< InternalImageType, InternalImageType > MetricType; typedef MetricType::Pointer MetricPointer; typedef MetricType::HistogramType HistogramType; typedef itk::HistogramToImageFilter< HistogramType > HistogramToImageFilterType; typedef HistogramToImageFilterType::Pointer HistogramToImageFilterPointer; typedef itk::ImageFileWriter< HistogramToImageFilterType::OutputImageType > HistogramWriterType; typedef HistogramWriterType::Pointer HistogramWriterPointer; HistogramWriter(): m_Metric(0) { this->m_Filter = HistogramToImageFilterType::New(); this->histogramWriter = HistogramWriterType::New(); this->histogramWriter->SetInput( this->m_Filter->GetOutput() ); std::string outputFileBase = "JointHistogram"; // Base of series filenames ( of the joint histogram ) this->outputFile = outputFileBase + "%03d."; this->outputFile += "mhd"; // histogram filename extension } ~HistogramWriter() { }; void SetMetric( MetricPointer metric ) { this->m_Metric = metric; } MetricPointer GetMetric( ) { return this->m_Metric; } void WriteHistogramFile( unsigned int iterationNumber ) { char outputFilename[1000]; sprintf (outputFilename, this->outputFile.c_str(), iterationNumber ); histogramWriter->SetFileName( outputFilename ); this->m_Filter->SetInput( m_Metric->GetHistogram() ); try { m_Filter->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ERROR: ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; } try { histogramWriter->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception thrown " << excp << std::endl; } std::cout << "Joint Histogram file: " << outputFilename << " written" << std::endl; } private: MetricPointer m_Metric; HistogramToImageFilterPointer m_Filter; HistogramWriterPointer histogramWriter; std::string outputFile; } jointHistogramWriter; class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::GradientDescentOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( typeid( event ) != typeid( itk::IterationEvent ) ) { return; } std::cout << optimizer->GetCurrentIteration() << " "; std::cout << optimizer->GetValue() << " "; std::cout << optimizer->GetCurrentPosition() << std::endl; // Write the joint histogram as a file JointHistogramXXX.mhd // where XXX is the iteration number jointHistogramWriter.WriteHistogramFile( optimizer->GetCurrentIteration() ); } }; int main( int argc, char *argv[] ) { if( argc < 4 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile "; std::cerr << "Number of histogram bins for writing the MutualInformationHistogramMetric"; std::cerr << std::endl; std::cerr << "Example: ImageRegistrationHistogramPlotter BrainT1Slice.png BrainProtonDensitySliceShifted13x17y.png Output.png 32" << std::endl; return 1; } typedef unsigned short PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef float InternalPixelType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::TranslationTransform< double, Dimension > TransformType; typedef itk::GradientDescentOptimizer OptimizerType; typedef itk::LinearInterpolateImageFunction< InternalImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< InternalImageType, InternalImageType > RegistrationType; typedef itk::MutualInformationHistogramImageToImageMetric< InternalImageType, InternalImageType > MetricType; TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); MetricType::Pointer metric = MetricType::New(); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); unsigned int numberOfHistogramBins = atoi( argv[4] ); MetricType::HistogramType::SizeType histogramSize; histogramSize[0] = numberOfHistogramBins; histogramSize[1] = numberOfHistogramBins; metric->SetHistogramSize( histogramSize ); const unsigned int numberOfParameters = transform->GetNumberOfParameters(); typedef MetricType::ScalesType ScalesType; ScalesType scales( numberOfParameters ); scales.Fill( 1.0 ); metric->SetDerivativeStepLengthScales(scales); // Set the metric for the joint histogram writer jointHistogramWriter.SetMetric( metric ); registration->SetMetric( metric ); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( argv[1] ); movingImageReader->SetFileName( argv[2] ); typedef itk::NormalizeImageFilter< FixedImageType, InternalImageType > FixedNormalizeFilterType; typedef itk::NormalizeImageFilter< MovingImageType, InternalImageType > MovingNormalizeFilterType; FixedNormalizeFilterType::Pointer fixedNormalizer = FixedNormalizeFilterType::New(); MovingNormalizeFilterType::Pointer movingNormalizer = MovingNormalizeFilterType::New(); typedef itk::DiscreteGaussianImageFilter< InternalImageType, InternalImageType > GaussianFilterType; GaussianFilterType::Pointer fixedSmoother = GaussianFilterType::New(); GaussianFilterType::Pointer movingSmoother = GaussianFilterType::New(); fixedSmoother->SetVariance( 2.0 ); movingSmoother->SetVariance( 2.0 ); fixedNormalizer->SetInput( fixedImageReader->GetOutput() ); movingNormalizer->SetInput( movingImageReader->GetOutput() ); fixedSmoother->SetInput( fixedNormalizer->GetOutput() ); movingSmoother->SetInput( movingNormalizer->GetOutput() ); registration->SetFixedImage( fixedSmoother->GetOutput() ); registration->SetMovingImage( movingSmoother->GetOutput() ); fixedNormalizer->Update(); registration->SetFixedImageRegion( fixedNormalizer->GetOutput()->GetBufferedRegion() ); typedef RegistrationType::ParametersType ParametersType; ParametersType initialParameters( transform->GetNumberOfParameters() ); initialParameters[0] = 0.0; // Initial offset in mm along X initialParameters[1] = 0.0; // Initial offset in mm along Y registration->SetInitialTransformParameters( initialParameters ); optimizer->SetLearningRate( 20.0 ); optimizer->SetNumberOfIterations( 200 ); optimizer->MaximizeOn(); CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } ParametersType finalParameters = registration->GetLastTransformParameters(); double TranslationAlongX = finalParameters[0]; double TranslationAlongY = finalParameters[1]; unsigned int numberOfIterations = optimizer->GetCurrentIteration(); double bestValue = optimizer->GetValue(); std::cout << "Result = " << std::endl; std::cout << " Translation X = " << TranslationAlongX << std::endl; std::cout << " Translation Y = " << TranslationAlongY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); ResampleFilterType::Pointer resample = ResampleFilterType::New(); resample->SetTransform( finalTransform ); resample->SetInput( movingImageReader->GetOutput() ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resample->SetOutputOrigin( fixedImage->GetOrigin() ); resample->SetOutputSpacing( fixedImage->GetSpacing() ); resample->SetDefaultPixelValue( 100 ); typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::CastImageFilter< FixedImageType, OutputImageType > CastFilterType; typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); CastFilterType::Pointer caster = CastFilterType::New(); writer->SetFileName( argv[3] ); caster->SetInput( resample->GetOutput() ); writer->SetInput( caster->GetOutput() ); writer->Update(); return EXIT_SUCCESS; } <commit_msg>ENH: Example showing the use of HistogramToEntropyImageFilter<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegistrationHistogramPlotter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // The example shows how to use the \doxygen{HistogramToEntropyImageFilter} class. // The example registers two images using the gradient descent optimizer. // The transform used here is a simple translation transform. The metric // is a MutualInformationHistogramImageToImageMetric. // // The jointHistogramWriter is invoked after every iteration of the optimizer. // the writer here writes the joint histogram after every iteration as // JointHistogramXXX.mhd. The output image contains the joint entropy histogram // given by // \begin{equation} // f(I) = -p \log_2 p // \end{equation} // // where // \begin{equation} // p = \frac{q_I}{\sum_{i \in I} q_I} // \end{equation} // and $q_I$ is the frequency of measurement vector, I. // // p is the probability of the occurance of the measurement vector, \f$q_I\f$. // // The output image is of type double. // // You may similarly instantiate \doxygen{HistogramToIntensityImageFilter} // or \doxygen{HistogramToProbabilityImageFilter} or // \doxygen{HistogramToLogProbabilityImageFilter}. // \TODO: Put SoftwareGuide comments. #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImageRegistrationMethod.h" #include "itkTranslationTransform.h" #include "itkMutualInformationHistogramImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkGradientDescentOptimizer.h" #include "itkImage.h" #include "itkNormalizeImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" #include "itkHistogramToEntropyImageFilter.h" #include "itkCommand.h" const unsigned int Dimension = 2; class HistogramWriter { public: typedef float InternalPixelType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::MutualInformationHistogramImageToImageMetric< InternalImageType, InternalImageType > MetricType; typedef MetricType::Pointer MetricPointer; typedef MetricType::HistogramType HistogramType; typedef itk::HistogramToEntropyImageFilter< HistogramType > HistogramToEntropyImageFilterType; typedef HistogramToEntropyImageFilterType::Pointer HistogramToImageFilterPointer; typedef itk::ImageFileWriter< HistogramToEntropyImageFilterType::OutputImageType > HistogramWriterType; typedef HistogramWriterType::Pointer HistogramWriterPointer; HistogramWriter(): m_Metric(0) { this->m_Filter = HistogramToEntropyImageFilterType::New(); this->histogramWriter = HistogramWriterType::New(); this->histogramWriter->SetInput( this->m_Filter->GetOutput() ); std::string outputFileBase = "JointHistogram"; // Base of series filenames ( of the joint histogram ) this->outputFile = outputFileBase + "%03d."; this->outputFile += "mhd"; // histogram filename extension } ~HistogramWriter() { }; void SetMetric( MetricPointer metric ) { this->m_Metric = metric; } MetricPointer GetMetric( ) { return this->m_Metric; } void WriteHistogramFile( unsigned int iterationNumber ) { char outputFilename[1000]; sprintf (outputFilename, this->outputFile.c_str(), iterationNumber ); histogramWriter->SetFileName( outputFilename ); this->m_Filter->SetInput( m_Metric->GetHistogram() ); try { m_Filter->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ERROR: ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; } try { histogramWriter->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception thrown " << excp << std::endl; } std::cout << "Joint Histogram file: " << outputFilename << " written" << std::endl; } private: MetricPointer m_Metric; HistogramToImageFilterPointer m_Filter; HistogramWriterPointer histogramWriter; std::string outputFile; } jointHistogramWriter; class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::GradientDescentOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( typeid( event ) != typeid( itk::IterationEvent ) ) { return; } std::cout << optimizer->GetCurrentIteration() << " "; std::cout << optimizer->GetValue() << " "; std::cout << optimizer->GetCurrentPosition() << std::endl; // Write the joint histogram as a file JointHistogramXXX.mhd // where XXX is the iteration number jointHistogramWriter.WriteHistogramFile( optimizer->GetCurrentIteration() ); } }; int main( int argc, char *argv[] ) { if( argc < 3 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile "; std::cerr << "Number of histogram bins for writing the MutualInformationHistogramMetric"; std::cerr << std::endl; return 1; } typedef unsigned short PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef float InternalPixelType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::TranslationTransform< double, Dimension > TransformType; typedef itk::GradientDescentOptimizer OptimizerType; typedef itk::LinearInterpolateImageFunction< InternalImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< InternalImageType, InternalImageType > RegistrationType; typedef itk::MutualInformationHistogramImageToImageMetric< InternalImageType, InternalImageType > MetricType; TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); MetricType::Pointer metric = MetricType::New(); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); unsigned int numberOfHistogramBins = atoi( argv[4] ); MetricType::HistogramType::SizeType histogramSize; histogramSize[0] = numberOfHistogramBins; histogramSize[1] = numberOfHistogramBins; metric->SetHistogramSize( histogramSize ); const unsigned int numberOfParameters = transform->GetNumberOfParameters(); typedef MetricType::ScalesType ScalesType; ScalesType scales( numberOfParameters ); scales.Fill( 1.0 ); metric->SetDerivativeStepLengthScales(scales); // Set the metric for the joint histogram writer jointHistogramWriter.SetMetric( metric ); registration->SetMetric( metric ); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( argv[1] ); movingImageReader->SetFileName( argv[2] ); typedef itk::NormalizeImageFilter< FixedImageType, InternalImageType > FixedNormalizeFilterType; typedef itk::NormalizeImageFilter< MovingImageType, InternalImageType > MovingNormalizeFilterType; FixedNormalizeFilterType::Pointer fixedNormalizer = FixedNormalizeFilterType::New(); MovingNormalizeFilterType::Pointer movingNormalizer = MovingNormalizeFilterType::New(); typedef itk::DiscreteGaussianImageFilter< InternalImageType, InternalImageType > GaussianFilterType; GaussianFilterType::Pointer fixedSmoother = GaussianFilterType::New(); GaussianFilterType::Pointer movingSmoother = GaussianFilterType::New(); fixedSmoother->SetVariance( 2.0 ); movingSmoother->SetVariance( 2.0 ); fixedNormalizer->SetInput( fixedImageReader->GetOutput() ); movingNormalizer->SetInput( movingImageReader->GetOutput() ); fixedSmoother->SetInput( fixedNormalizer->GetOutput() ); movingSmoother->SetInput( movingNormalizer->GetOutput() ); registration->SetFixedImage( fixedSmoother->GetOutput() ); registration->SetMovingImage( movingSmoother->GetOutput() ); fixedNormalizer->Update(); registration->SetFixedImageRegion( fixedNormalizer->GetOutput()->GetBufferedRegion() ); typedef RegistrationType::ParametersType ParametersType; ParametersType initialParameters( transform->GetNumberOfParameters() ); initialParameters[0] = 0.0; // Initial offset in mm along X initialParameters[1] = 0.0; // Initial offset in mm along Y registration->SetInitialTransformParameters( initialParameters ); optimizer->SetLearningRate( 20.0 ); optimizer->SetNumberOfIterations( 200 ); optimizer->MaximizeOn(); CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } ParametersType finalParameters = registration->GetLastTransformParameters(); double TranslationAlongX = finalParameters[0]; double TranslationAlongY = finalParameters[1]; unsigned int numberOfIterations = optimizer->GetCurrentIteration(); double bestValue = optimizer->GetValue(); std::cout << "Result = " << std::endl; std::cout << " Translation X = " << TranslationAlongX << std::endl; std::cout << " Translation Y = " << TranslationAlongY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); ResampleFilterType::Pointer resample = ResampleFilterType::New(); resample->SetTransform( finalTransform ); resample->SetInput( movingImageReader->GetOutput() ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resample->SetOutputOrigin( fixedImage->GetOrigin() ); resample->SetOutputSpacing( fixedImage->GetSpacing() ); resample->SetDefaultPixelValue( 100 ); typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::CastImageFilter< FixedImageType, OutputImageType > CastFilterType; typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); CastFilterType::Pointer caster = CastFilterType::New(); writer->SetFileName( argv[3] ); caster->SetInput( resample->GetOutput() ); writer->SetInput( caster->GetOutput() ); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <GarrysMod/Lua/Interface.h> #include <GarrysMod/Lua/LuaInterface.h> #include <SymbolFinder.hpp> #include <MologieDetours/detours.h> #include <stdexcept> #include <stdint.h> #include <stdio.h> #include <sha1.h> #if defined _WIN32 #define snprintf _snprintf #define FASTCALL __fastcall #define THISCALL __thiscall #define SERVER_BINARY "server.dll" #define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( "\x55\x8B\xEC\x83\xEC\x18\x53\x56\x8B\x75\x08\x83\xC6\x04\x83\x7E" ) #define ADDORUPDATEFILE_SYMLEN 16 #elif defined __linux || defined __APPLE__ #define CDECL __attribute__((cdecl)) #if defined __linux #define SERVER_BINARY "garrysmod/bin/server_srv.so" #define SYMBOL_PREFIX "@" #else #define SERVER_BINARY "garrysmod/bin/server.dylib" #define SYMBOL_PREFIX "@_" #endif #define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( SYMBOL_PREFIX "_ZN12GModDataPack15AddOrUpdateFileEP7LuaFileb" ) #define ADDORUPDATEFILE_SYMLEN 0 #endif GarrysMod::Lua::ILuaInterface *lua = NULL; class GModDataPack; struct LuaFile { uint32_t skip; const char *path; }; #if defined _WIN32 typedef void ( THISCALL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force ); #elif defined __linux || defined __APPLE__ typedef void ( CDECL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force ); #endif AddOrUpdateFile_t AddOrUpdateFile = NULL; MologieDetours::Detour<AddOrUpdateFile_t> *AddOrUpdateFile_d = NULL; #if defined _WIN32 void FASTCALL AddOrUpdateFile_h( GModDataPack *self, void *, LuaFile *file, bool b ) #elif defined __linux || defined __APPLE__ void CDECL AddOrUpdateFile_h( GModDataPack *self, LuaFile *file, bool b ) #endif { lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB ); if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) { lua->GetField( -1, "hook" ); if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) { lua->GetField( -1, "Run" ); if( lua->IsType( -1, GarrysMod::Lua::Type::FUNCTION ) ) { lua->PushString( "AddOrUpdateCSLuaFile" ); lua->PushString( file->path ); lua->PushBool( b ); if( lua->PCall( 3, 1, 0 ) != 0 ) { lua->Msg( "[luapack_internal] %s\n", lua->GetString( ) ); lua->Pop( 3 ); return AddOrUpdateFile( self, file, b ); } if( lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) && lua->GetBool( ) ) { lua->Pop( 3 ); return; } lua->Pop( 1 ); } else { lua->Pop( 1 ); } } lua->Pop( 1 ); } lua->Pop( 1 ); return AddOrUpdateFile( self, file, b ); } #define HASHER_METATABLE "SHA1" #define HASHER_TYPE 31 #define THROW_ERROR( error ) ( LUA->ThrowError( error ), 0 ) #define LUA_ERROR( ) THROW_ERROR( LUA->GetString( ) ) #define GET_USERDATA( index ) reinterpret_cast<GarrysMod::Lua::UserData *>( LUA->GetUserdata( index ) ) #define GET_HASHER( index ) reinterpret_cast<sha1_context *>( GET_USERDATA( index )->data ) #define VALIDATE_HASHER( hasher ) if( hasher == 0 ) return THROW_ERROR( HASHER_METATABLE " object is not valid" ) LUA_FUNCTION_STATIC( hasher__new ) { try { sha1_context *context = new sha1_context; sha1_starts( context ); void *luadata = LUA->NewUserdata( sizeof( GarrysMod::Lua::UserData ) ); GarrysMod::Lua::UserData *userdata = reinterpret_cast<GarrysMod::Lua::UserData *>( luadata ); userdata->data = context; userdata->type = HASHER_TYPE; LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE ); LUA->SetMetaTable( -2 ); return 1; } catch( std::exception &e ) { LUA->PushString( e.what( ) ); } return LUA_ERROR( ); } LUA_FUNCTION_STATIC( hasher__gc ) { LUA->CheckType( 1, HASHER_TYPE ); GarrysMod::Lua::UserData *userdata = GET_USERDATA( 1 ); sha1_context *hasher = reinterpret_cast<sha1_context *>( userdata->data ); VALIDATE_HASHER( hasher ); userdata->data = 0; delete hasher; return 0; } LUA_FUNCTION_STATIC( hasher_update ) { LUA->CheckType( 1, HASHER_TYPE ); LUA->CheckType( 2, GarrysMod::Lua::Type::STRING ); sha1_context *hasher = GET_HASHER( 1 ); VALIDATE_HASHER( hasher ); uint32_t len = 0; const uint8_t *data = reinterpret_cast<const uint8_t *>( LUA->GetString( 2, &len ) ); sha1_update( hasher, data, len ); return 0; } LUA_FUNCTION_STATIC( hasher_final ) { LUA->CheckType( 1, HASHER_TYPE ); sha1_context *hasher = GET_HASHER( 1 ); VALIDATE_HASHER( hasher ); uint8_t digest[20]; sha1_finish( hasher, digest ); LUA->PushString( reinterpret_cast<const char *>( digest ), sizeof( digest ) ); return 1; } LUA_FUNCTION_STATIC( luapack_rename ) { LUA->CheckType( 1, GarrysMod::Lua::Type::STRING ); char newto[70]; snprintf( newto, sizeof( newto ), "garrysmod/data/luapack/%s.dat", LUA->GetString( 1 ) ); LUA->PushBool( rename( "garrysmod/data/luapack/temp.dat", newto ) == 0 ); return 1; } GMOD_MODULE_OPEN( ) { lua = reinterpret_cast<GarrysMod::Lua::ILuaInterface *>( LUA ); try { lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB ); lua->GetField( -1, "luapack" ); if( !lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) throw std::runtime_error( "luapack table not found" ); lua->PushCFunction( luapack_rename ); lua->SetField( -2, "Rename" ); lua->PushCFunction( hasher__new ); lua->SetField( -2, HASHER_METATABLE ); LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE ); LUA->Push( -1 ); LUA->SetField( -2, "__index" ); LUA->PushCFunction( hasher__gc ); LUA->SetField( -2, "__gc" ); LUA->PushCFunction( hasher_update ); LUA->SetField( -2, "Update" ); LUA->PushCFunction( hasher_final ); LUA->SetField( -2, "Final" ); SymbolFinder symfinder; AddOrUpdateFile = reinterpret_cast<AddOrUpdateFile_t>( symfinder.ResolveOnBinary( SERVER_BINARY, ADDORUPDATEFILE_SYM, ADDORUPDATEFILE_SYMLEN ) ); if( AddOrUpdateFile == NULL ) throw std::runtime_error( "GModDataPack::AddOrUpdateFile detour failed" ); AddOrUpdateFile_d = new MologieDetours::Detour<AddOrUpdateFile_t>( AddOrUpdateFile, reinterpret_cast<AddOrUpdateFile_t>( AddOrUpdateFile_h ) ); AddOrUpdateFile = AddOrUpdateFile_d->GetOriginalFunction( ); lua->Msg( "[luapack_internal] GModDataPack::AddOrUpdateFile detoured.\n" ); return 0; } catch( std::exception &e ) { LUA->PushString( e.what( ) ); } return LUA_ERROR( ); } GMOD_MODULE_CLOSE( ) { delete AddOrUpdateFile_d; return 0; }<commit_msg>luapack.Rename upgraded. Now accepts 2 paths relative to garrysmod. Should still be pretty safe since all ../ are removed and the only accepted extensions are .txt, .dat and .lua<commit_after>#include <GarrysMod/Lua/Interface.h> #include <GarrysMod/Lua/LuaInterface.h> #include <SymbolFinder.hpp> #include <MologieDetours/detours.h> #include <stdexcept> #include <string> #include <stdint.h> #include <stdio.h> #include <sha1.h> #if defined _WIN32 #define snprintf _snprintf #define FASTCALL __fastcall #define THISCALL __thiscall #define SERVER_BINARY "server.dll" #define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( "\x55\x8B\xEC\x83\xEC\x18\x53\x56\x8B\x75\x08\x83\xC6\x04\x83\x7E" ) #define ADDORUPDATEFILE_SYMLEN 16 #elif defined __linux || defined __APPLE__ #define CDECL __attribute__((cdecl)) #if defined __linux #define SERVER_BINARY "garrysmod/bin/server_srv.so" #define SYMBOL_PREFIX "@" #else #define SERVER_BINARY "garrysmod/bin/server.dylib" #define SYMBOL_PREFIX "@_" #endif #define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( SYMBOL_PREFIX "_ZN12GModDataPack15AddOrUpdateFileEP7LuaFileb" ) #define ADDORUPDATEFILE_SYMLEN 0 #endif GarrysMod::Lua::ILuaInterface *lua = NULL; class GModDataPack; struct LuaFile { uint32_t skip; const char *path; }; #if defined _WIN32 typedef void ( THISCALL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force ); #elif defined __linux || defined __APPLE__ typedef void ( CDECL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force ); #endif AddOrUpdateFile_t AddOrUpdateFile = NULL; MologieDetours::Detour<AddOrUpdateFile_t> *AddOrUpdateFile_d = NULL; #if defined _WIN32 void FASTCALL AddOrUpdateFile_h( GModDataPack *self, void *, LuaFile *file, bool b ) #elif defined __linux || defined __APPLE__ void CDECL AddOrUpdateFile_h( GModDataPack *self, LuaFile *file, bool b ) #endif { lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB ); if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) { lua->GetField( -1, "hook" ); if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) { lua->GetField( -1, "Run" ); if( lua->IsType( -1, GarrysMod::Lua::Type::FUNCTION ) ) { lua->PushString( "AddOrUpdateCSLuaFile" ); lua->PushString( file->path ); lua->PushBool( b ); if( lua->PCall( 3, 1, 0 ) != 0 ) { lua->Msg( "[luapack_internal] %s\n", lua->GetString( ) ); lua->Pop( 3 ); return AddOrUpdateFile( self, file, b ); } if( lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) && lua->GetBool( ) ) { lua->Pop( 3 ); return; } lua->Pop( 1 ); } else { lua->Pop( 1 ); } } lua->Pop( 1 ); } lua->Pop( 1 ); return AddOrUpdateFile( self, file, b ); } #define HASHER_METATABLE "SHA1" #define HASHER_TYPE 31 #define THROW_ERROR( error ) ( LUA->ThrowError( error ), 0 ) #define LUA_ERROR( ) THROW_ERROR( LUA->GetString( ) ) #define GET_USERDATA( index ) reinterpret_cast<GarrysMod::Lua::UserData *>( LUA->GetUserdata( index ) ) #define GET_HASHER( index ) reinterpret_cast<sha1_context *>( GET_USERDATA( index )->data ) #define VALIDATE_HASHER( hasher ) if( hasher == 0 ) return THROW_ERROR( HASHER_METATABLE " object is not valid" ) LUA_FUNCTION_STATIC( hasher__new ) { try { sha1_context *context = new sha1_context; sha1_starts( context ); void *luadata = LUA->NewUserdata( sizeof( GarrysMod::Lua::UserData ) ); GarrysMod::Lua::UserData *userdata = reinterpret_cast<GarrysMod::Lua::UserData *>( luadata ); userdata->data = context; userdata->type = HASHER_TYPE; LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE ); LUA->SetMetaTable( -2 ); return 1; } catch( std::exception &e ) { LUA->PushString( e.what( ) ); } return LUA_ERROR( ); } LUA_FUNCTION_STATIC( hasher__gc ) { LUA->CheckType( 1, HASHER_TYPE ); GarrysMod::Lua::UserData *userdata = GET_USERDATA( 1 ); sha1_context *hasher = reinterpret_cast<sha1_context *>( userdata->data ); VALIDATE_HASHER( hasher ); userdata->data = 0; delete hasher; return 0; } LUA_FUNCTION_STATIC( hasher_update ) { LUA->CheckType( 1, HASHER_TYPE ); LUA->CheckType( 2, GarrysMod::Lua::Type::STRING ); sha1_context *hasher = GET_HASHER( 1 ); VALIDATE_HASHER( hasher ); uint32_t len = 0; const uint8_t *data = reinterpret_cast<const uint8_t *>( LUA->GetString( 2, &len ) ); sha1_update( hasher, data, len ); return 0; } LUA_FUNCTION_STATIC( hasher_final ) { LUA->CheckType( 1, HASHER_TYPE ); sha1_context *hasher = GET_HASHER( 1 ); VALIDATE_HASHER( hasher ); uint8_t digest[20]; sha1_finish( hasher, digest ); LUA->PushString( reinterpret_cast<const char *>( digest ), sizeof( digest ) ); return 1; } static void SubstituteChar( std::string &path, char part, char sub ) { size_t pos = path.find( part ); while( pos != path.npos ) { path.erase( pos, 1 ); path.insert( pos, 1, sub ); pos = path.find( part, pos + 1 ); } } static void RemovePart( std::string &path, const char *part ) { size_t len = strlen( part ), pos = path.find( part ); while( pos != path.npos ) { path.erase( pos, len ); pos = path.find( part, pos ); } } inline void FixPath( std::string &path ) { SubstituteChar( path, '\\', '/' ); RemovePart( path, "../" ); RemovePart( path, "./" ); } static bool HasWhitelistedExtension( const char *cpath ) { std::string path = cpath; size_t extstart = path.find( '.' ); if( extstart != path.npos ) { size_t lastslash = path.find( '/' ); if( lastslash != path.npos && lastslash > extstart ) return false; std::string ext = path.substr( extstart + 1 ); return ext == "txt" || ext == "dat" || ext == "lua"; } return false; } LUA_FUNCTION_STATIC( luapack_rename ) { LUA->CheckType( 1, GarrysMod::Lua::Type::STRING ); LUA->CheckType( 2, GarrysMod::Lua::Type::STRING ); const char *luafrom = LUA->GetString( 1 ); if( HasWhitelistedExtension( luafrom ) ) { LUA->PushBool( false ); return 1; } const char *luato = LUA->GetString( 2 ); if( HasWhitelistedExtension( luato ) ) { LUA->PushBool( false ); return 1; } bool success = false; // Lua (LuaJIT in x86 in particular) doesn't exactly like RAII. // Let's make a specific scope just for our logic. { std::string from = "garrysmod/"; from += luafrom; FixPath( from ); std::string to = "garrysmod/"; to += luato; FixPath( to ); success = rename( from.c_str( ), to.c_str( ) ) == 0; } LUA->PushBool( success ); return 1; } GMOD_MODULE_OPEN( ) { lua = reinterpret_cast<GarrysMod::Lua::ILuaInterface *>( LUA ); try { lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB ); lua->GetField( -1, "luapack" ); if( !lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) throw std::runtime_error( "luapack table not found" ); lua->PushCFunction( luapack_rename ); lua->SetField( -2, "Rename" ); lua->PushCFunction( hasher__new ); lua->SetField( -2, HASHER_METATABLE ); LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE ); LUA->Push( -1 ); LUA->SetField( -2, "__index" ); LUA->PushCFunction( hasher__gc ); LUA->SetField( -2, "__gc" ); LUA->PushCFunction( hasher_update ); LUA->SetField( -2, "Update" ); LUA->PushCFunction( hasher_final ); LUA->SetField( -2, "Final" ); SymbolFinder symfinder; AddOrUpdateFile = reinterpret_cast<AddOrUpdateFile_t>( symfinder.ResolveOnBinary( SERVER_BINARY, ADDORUPDATEFILE_SYM, ADDORUPDATEFILE_SYMLEN ) ); if( AddOrUpdateFile == NULL ) throw std::runtime_error( "GModDataPack::AddOrUpdateFile detour failed" ); AddOrUpdateFile_d = new MologieDetours::Detour<AddOrUpdateFile_t>( AddOrUpdateFile, reinterpret_cast<AddOrUpdateFile_t>( AddOrUpdateFile_h ) ); AddOrUpdateFile = AddOrUpdateFile_d->GetOriginalFunction( ); lua->Msg( "[luapack_internal] GModDataPack::AddOrUpdateFile detoured.\n" ); return 0; } catch( std::exception &e ) { LUA->PushString( e.what( ) ); } return LUA_ERROR( ); } GMOD_MODULE_CLOSE( ) { delete AddOrUpdateFile_d; return 0; }<|endoftext|>
<commit_before> #include <vector> #include "geometry/permutation.hpp" #include "geometry/orthogonal_map.hpp" #include "geometry/r3_element.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/si.hpp" #include "testing_utilities/almost_equals.hpp" using principia::quantities::Length; using principia::si::Metre; using principia::testing_utilities::AlmostEquals; using testing::Eq; namespace principia { namespace geometry { class PermutationTest : public testing::Test { protected: struct World; using Orth = OrthogonalMap<World, World>; using Perm = Permutation<World, World>; using R3 = R3Element<quantities::Length>; void SetUp() override { vector_ = Vector<quantities::Length, World>( R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre)); bivector_ = Bivector<quantities::Length, World>( R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre)); trivector_ = Trivector<quantities::Length, World>(4.0 * Metre); } Vector<quantities::Length, World> vector_; Bivector<quantities::Length, World> bivector_; Trivector<quantities::Length, World> trivector_; }; TEST_F(PermutationTest, Identity) { EXPECT_THAT(Perm::Identity()(vector_.coordinates()), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, XYZ) { EXPECT_THAT(Perm(Perm::XYZ)(vector_.coordinates()), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, YZX) { EXPECT_THAT(Perm(Perm::YZX)(vector_.coordinates()), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); } TEST_F(PermutationTest, ZXY) { EXPECT_THAT(Perm(Perm::ZXY)(vector_.coordinates()), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); } TEST_F(PermutationTest, XZY) { EXPECT_THAT(Perm(Perm::XZY)(vector_.coordinates()), Eq<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre})); } TEST_F(PermutationTest, ZYX) { EXPECT_THAT(Perm(Perm::ZYX)(vector_.coordinates()), Eq<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre})); } TEST_F(PermutationTest, YXZ) { EXPECT_THAT(Perm(Perm::YXZ)(vector_.coordinates()), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, Determinant) { Perm xyz(Perm::XYZ); Perm yzx(Perm::YZX); Perm zxy(Perm::ZXY); Perm xzy(Perm::XZY); Perm zyx(Perm::ZYX); Perm yxz(Perm::YXZ); EXPECT_TRUE(xyz.Determinant().Positive()); EXPECT_TRUE(yzx.Determinant().Positive()); EXPECT_TRUE(zxy.Determinant().Positive()); EXPECT_TRUE(xzy.Determinant().Negative()); EXPECT_TRUE(zyx.Determinant().Negative()); EXPECT_TRUE(yxz.Determinant().Negative()); } TEST_F(PermutationTest, AppliedToVector) { EXPECT_THAT(Perm(Perm::YZX)(vector_).coordinates(), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); EXPECT_THAT(Perm(Perm::YXZ)(vector_).coordinates(), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, AppliedToBivector) { EXPECT_THAT(Perm(Perm::ZXY)(bivector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::ZYX)(bivector_).coordinates(), Eq<R3>({-3.0 * Metre, -2.0 * Metre, -1.0 * Metre})); } TEST_F(PermutationTest, AppliedToTrivector) { EXPECT_THAT(Perm(Perm::XYZ)(trivector_).coordinates(), Eq(4.0 * Metre)); EXPECT_THAT(Perm(Perm::XZY)(trivector_).coordinates(), Eq(-4.0 * Metre)); } TEST_F(PermutationTest, Inverse) { EXPECT_THAT(Perm(Perm::YZX).Inverse()(vector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::YXZ).Inverse()(vector_).coordinates(), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); std::vector<Perm> const all = {Perm(Perm::XYZ), Perm(Perm::YZX), Perm(Perm::ZXY), Perm(Perm::XZY), Perm(Perm::ZYX), Perm(Perm::YXZ)}; for (const Perm& p : all) { Perm const identity = p * p.Inverse(); EXPECT_THAT(identity(vector_), Eq(vector_)); } } TEST_F(PermutationTest, Forget) { EXPECT_THAT(Perm(Perm::XYZ).Forget()(vector_).coordinates(), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); EXPECT_THAT(Perm(Perm::YZX).Forget()(vector_).coordinates(), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); EXPECT_THAT(Perm(Perm::ZXY).Forget()(vector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::XZY).Forget()(vector_).coordinates(), AlmostEquals<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre}, 2)); EXPECT_THAT(Perm(Perm::ZYX).Forget()(vector_).coordinates(), AlmostEquals<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre}, 4)); EXPECT_THAT(Perm(Perm::YXZ).Forget()(vector_).coordinates(), AlmostEquals<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}, 2)); } TEST_F(PermutationTest, Compose) { std::vector<Perm> const all = {Perm(Perm::XYZ), Perm(Perm::YZX), Perm(Perm::ZXY), Perm(Perm::XZY), Perm(Perm::ZYX), Perm(Perm::YXZ)}; for (Perm const& p1 : all) { Orth const o1 = p1.Forget(); for (Perm const& p2 : all) { Orth const o2 = p2.Forget(); Perm const p12 = p1 * p2; Orth const o12 = o1 * o2; for (Length l = 1 * Metre; l < 4 * Metre; l += 1 * Metre) { vector_.coordinates().x = l; EXPECT_THAT(p12(vector_), AlmostEquals(o12(vector_), 20)); } } } } } // namespace geometry } // namespace principia <commit_msg>Better testing, notably composition.<commit_after> #include <vector> #include "geometry/permutation.hpp" #include "geometry/orthogonal_map.hpp" #include "geometry/r3_element.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/si.hpp" #include "testing_utilities/almost_equals.hpp" using principia::quantities::Length; using principia::si::Metre; using principia::testing_utilities::AlmostEquals; using testing::Eq; namespace principia { namespace geometry { class PermutationTest : public testing::Test { protected: struct World1; struct World2; using Orth = OrthogonalMap<World1, World2>; using Perm = Permutation<World1, World2>; using R3 = R3Element<quantities::Length>; void SetUp() override { vector_ = Vector<quantities::Length, World1>( R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre)); bivector_ = Bivector<quantities::Length, World1>( R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre)); trivector_ = Trivector<quantities::Length, World1>(4.0 * Metre); } Vector<quantities::Length, World1> vector_; Bivector<quantities::Length, World1> bivector_; Trivector<quantities::Length, World1> trivector_; }; TEST_F(PermutationTest, Identity) { EXPECT_THAT(Perm::Identity()(vector_.coordinates()), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, XYZ) { EXPECT_THAT(Perm(Perm::XYZ)(vector_.coordinates()), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, YZX) { EXPECT_THAT(Perm(Perm::YZX)(vector_.coordinates()), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); } TEST_F(PermutationTest, ZXY) { EXPECT_THAT(Perm(Perm::ZXY)(vector_.coordinates()), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); } TEST_F(PermutationTest, XZY) { EXPECT_THAT(Perm(Perm::XZY)(vector_.coordinates()), Eq<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre})); } TEST_F(PermutationTest, ZYX) { EXPECT_THAT(Perm(Perm::ZYX)(vector_.coordinates()), Eq<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre})); } TEST_F(PermutationTest, YXZ) { EXPECT_THAT(Perm(Perm::YXZ)(vector_.coordinates()), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, Determinant) { Perm xyz(Perm::XYZ); Perm yzx(Perm::YZX); Perm zxy(Perm::ZXY); Perm xzy(Perm::XZY); Perm zyx(Perm::ZYX); Perm yxz(Perm::YXZ); EXPECT_TRUE(xyz.Determinant().Positive()); EXPECT_TRUE(yzx.Determinant().Positive()); EXPECT_TRUE(zxy.Determinant().Positive()); EXPECT_TRUE(xzy.Determinant().Negative()); EXPECT_TRUE(zyx.Determinant().Negative()); EXPECT_TRUE(yxz.Determinant().Negative()); } TEST_F(PermutationTest, AppliedToVector) { EXPECT_THAT(Perm(Perm::YZX)(vector_).coordinates(), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); EXPECT_THAT(Perm(Perm::YXZ)(vector_).coordinates(), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, AppliedToBivector) { EXPECT_THAT(Perm(Perm::ZXY)(bivector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::ZYX)(bivector_).coordinates(), Eq<R3>({-3.0 * Metre, -2.0 * Metre, -1.0 * Metre})); } TEST_F(PermutationTest, AppliedToTrivector) { EXPECT_THAT(Perm(Perm::XYZ)(trivector_).coordinates(), Eq(4.0 * Metre)); EXPECT_THAT(Perm(Perm::XZY)(trivector_).coordinates(), Eq(-4.0 * Metre)); } TEST_F(PermutationTest, Inverse) { EXPECT_THAT(Perm(Perm::YZX).Inverse()(vector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::YXZ).Inverse()(vector_).coordinates(), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); std::vector<Perm> const all = {Perm(Perm::XYZ), Perm(Perm::YZX), Perm(Perm::ZXY), Perm(Perm::XZY), Perm(Perm::ZYX), Perm(Perm::YXZ)}; for (const Perm& p : all) { Perm const identity = p * p.Inverse(); EXPECT_THAT(identity(vector_), Eq(vector_)); } } TEST_F(PermutationTest, Forget) { EXPECT_THAT(Perm(Perm::XYZ).Forget()(vector_).coordinates(), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); EXPECT_THAT(Perm(Perm::YZX).Forget()(vector_).coordinates(), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); EXPECT_THAT(Perm(Perm::ZXY).Forget()(vector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::XZY).Forget()(vector_).coordinates(), AlmostEquals<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre}, 2)); EXPECT_THAT(Perm(Perm::ZYX).Forget()(vector_).coordinates(), AlmostEquals<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre}, 4)); EXPECT_THAT(Perm(Perm::YXZ).Forget()(vector_).coordinates(), AlmostEquals<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}, 2)); } TEST_F(PermutationTest, Compose) { struct World3; using Orth12 = OrthogonalMap<World1, World2>; using Orth13 = OrthogonalMap<World1, World3>; using Orth23 = OrthogonalMap<World2, World3>; using Perm12 = Permutation<World1, World2>; using Perm13 = Permutation<World1, World3>; using Perm23 = Permutation<World2, World3>; std::vector<Perm12> const all12 = {Perm12(Perm12::XYZ), Perm12(Perm12::YZX), Perm12(Perm12::ZXY), Perm12(Perm12::XZY), Perm12(Perm12::ZYX), Perm12(Perm12::YXZ)}; std::vector<Perm23> const all23 = {Perm23(Perm23::XYZ), Perm23(Perm23::YZX), Perm23(Perm23::ZXY), Perm23(Perm23::XZY), Perm23(Perm23::ZYX), Perm23(Perm23::YXZ)}; for (Perm12 const& p12 : all12) { Orth12 const o12 = p12.Forget(); for (Perm23 const& p23 : all23) { Orth23 const o23 = p23.Forget(); Perm13 const p13 = p23 * p12; Orth13 const o13 = o23 * o12; for (Length l = 1 * Metre; l < 4 * Metre; l += 1 * Metre) { vector_.coordinates().x = l; EXPECT_THAT(p13(vector_), AlmostEquals(o13(vector_), 20)); } } } } } // namespace geometry } // namespace principia <|endoftext|>
<commit_before>/* * Copyright (c) 2018 https://www.thecoderscorner.com (Nutricherry LTD). * This product is licensed under an Apache license, see the LICENSE file in the top-level directory. */ #include <inttypes.h> #include <Arduino.h> #include "TaskManager.h" TaskManager taskManager; TimerTask::TimerTask() { next = NULL; clear(); } void TimerTask::initialise(uint16_t executionInfo, TimerFn execCallback) { this->executionInfo = executionInfo; this->callback = execCallback; this->scheduledAt = (executionInfo & TASK_MICROS) ? micros() : millis(); } bool TimerTask::isReady() { if (!isInUse() || isRunning()) return false; if ((executionInfo & TASK_MICROS) != 0) { uint16_t delay = (executionInfo & TIMER_MASK); return (micros() - scheduledAt) >= delay; } else if((executionInfo & TASK_SECONDS) != 0) { uint32_t delay = (executionInfo & TIMER_MASK) * 1000L; return (millis() - scheduledAt) >= delay; } else { uint16_t delay = (executionInfo & TIMER_MASK); return (millis() - scheduledAt) >= delay; } } unsigned long TimerTask::microsFromNow() { uint32_t microsFromNow; if ((executionInfo & TASK_MICROS) != 0) { uint16_t delay = (executionInfo & TIMER_MASK); microsFromNow = delay - (micros() - scheduledAt); } else { uint32_t startTm = (executionInfo & TIMER_MASK); if ((executionInfo & TASK_SECONDS) != 0) { startTm *= 1000; } microsFromNow = (startTm - (millis() - scheduledAt)) * 1000; } return microsFromNow; } inline void TimerTask::execute() { if (callback == NULL) return; // failsafe, always exit with null callback. // handle repeating tasks - reschedule. if (isRepeating()) { markRunning(); callback(); this->scheduledAt = (executionInfo & TASK_MICROS) ? micros() : millis(); clearRunning(); } else { TimerFn savedCallback = callback; clear(); savedCallback(); } } void TimerTask::clear() { executionInfo = 0; callback = NULL; } void TaskManager::markInterrupted(uint8_t interruptNo) { taskManager.lastInterruptTrigger = interruptNo; taskManager.interrupted = true; } TaskManager::TaskManager(uint8_t taskSlots) { this->numberOfSlots = taskSlots; this->tasks = new TimerTask[taskSlots]; interrupted = false; first = NULL; interruptCallback = NULL; } int TaskManager::findFreeTask() { for (uint8_t i = 0; i < numberOfSlots; ++i) { if (!tasks[i].isInUse()) { return i; } } return TASKMGR_INVALIDID; } inline int toTimerValue(int v, TimerUnit unit) { if (unit == TIME_MILLIS && v > TIMER_MASK) { unit = TIME_SECONDS; v = v / 1000; } v = min(v, TIMER_MASK); return v | (((uint16_t)unit) << 12); } uint8_t TaskManager::scheduleOnce(int millis, TimerFn timerFunction, TimerUnit timeUnit) { uint8_t taskId = findFreeTask(); if (taskId != TASKMGR_INVALIDID) { tasks[taskId].initialise(toTimerValue(millis, timeUnit) | TASK_IN_USE, timerFunction); putItemIntoQueue(&tasks[taskId]); } return taskId; } uint8_t TaskManager::scheduleFixedRate(int millis, TimerFn timerFunction, TimerUnit timeUnit) { uint8_t taskId = findFreeTask(); if (taskId != TASKMGR_INVALIDID) { tasks[taskId].initialise(toTimerValue(millis, timeUnit) | TASK_IN_USE | TASK_REPEATING, timerFunction); putItemIntoQueue(&tasks[taskId]); } return taskId; } void TaskManager::cancelTask(uint8_t task) { if (task < numberOfSlots) { tasks[task].clear(); removeFromQueue(&tasks[task]); } } char* TaskManager::checkAvailableSlots(char* data) { uint8_t i; for (i = 0; i < numberOfSlots; ++i) { data[i] = tasks[i].isRepeating() ? 'R' : (tasks[i].isInUse() ? 'U' : 'F'); if (tasks[i].isRunning()) data[i] = tolower(data[i]); } data[i] = 0; return data; } void TaskManager::yieldForMicros(uint16_t microsToWait) { unsigned long microsEnd = micros() + microsToWait; while(micros() < microsEnd) { runLoop(); } } void TaskManager::runLoop() { if (interrupted) { interrupted = false; interruptCallback(lastInterruptTrigger); } TimerTask* tm = first; while(tm != NULL) { if (tm->isReady()) { removeFromQueue(tm); tm->execute(); if (tm->isRepeating()) { putItemIntoQueue(tm); } } else { break; } tm = tm->getNext(); } // TODO, if not interrupted, and no task for a while sleep and set timer - go into low power. } void TaskManager::putItemIntoQueue(TimerTask* tm) { // shortcut, no first yet, so we are at the top! if (first == NULL) { first = tm; tm->setNext(NULL); return; } // if we are the new first.. if (first->microsFromNow() > tm->microsFromNow()) { tm->setNext(first); first = tm; return; } // otherwise we have to find the place in the queue for this item by time TimerTask* current = first->getNext(); TimerTask* previous = first; while (current != NULL) { if (current->microsFromNow() > tm->microsFromNow()) { previous->setNext(tm); tm->setNext(current); return; } previous = current; current = current->getNext(); } // we are at the end of the queue previous->setNext(tm); tm->setNext(NULL); } void TaskManager::removeFromQueue(TimerTask* tm) { // shortcut, if we are first, just remove us by getting the next and setting first. if (first == tm) { first = tm->getNext(); return; } // otherwise, we have a single linked list, so we need to keep previous and current and // then iterate through each item TimerTask* current = first->getNext(); TimerTask* previous = first; while (current != NULL) { // we've found the item, unlink it from the queue and nullify its next. if (current == tm) { previous->setNext(current->getNext()); current->setNext(NULL); break; } previous = current; current = current->getNext(); } } typedef void ArdunioIntFn(void); void interruptHandler1() { taskManager.markInterrupted(1); } void interruptHandler2() { taskManager.markInterrupted(2); } void interruptHandler3() { taskManager.markInterrupted(3); } void interruptHandler5() { taskManager.markInterrupted(5); } void interruptHandler18() { taskManager.markInterrupted(18); } void interruptHandlerOther() { taskManager.markInterrupted(0xff); } void TaskManager::addInterrupt(uint8_t pin, uint8_t mode) { if (interruptCallback == NULL) return; int interruptNo = digitalPinToInterrupt(pin); switch (pin) { case 1: attachInterrupt(interruptNo, interruptHandler1, mode); break; case 2: attachInterrupt(interruptNo, interruptHandler2, mode); break; case 3: attachInterrupt(interruptNo, interruptHandler3, mode); break; case 5: attachInterrupt(interruptNo, interruptHandler5, mode); break; case 18: attachInterrupt(interruptNo, interruptHandler18, mode); break; default: attachInterrupt(interruptNo, interruptHandlerOther, mode); break; } } void TaskManager::setInterruptCallback(InterruptFn handler) { interruptCallback = handler; } <commit_msg>Ensure system yield is called during waitForMicros call<commit_after>/* * Copyright (c) 2018 https://www.thecoderscorner.com (Nutricherry LTD). * This product is licensed under an Apache license, see the LICENSE file in the top-level directory. */ #include <inttypes.h> #include <Arduino.h> #include "TaskManager.h" TaskManager taskManager; TimerTask::TimerTask() { next = NULL; clear(); } void TimerTask::initialise(uint16_t executionInfo, TimerFn execCallback) { this->executionInfo = executionInfo; this->callback = execCallback; this->scheduledAt = (executionInfo & TASK_MICROS) ? micros() : millis(); } bool TimerTask::isReady() { if (!isInUse() || isRunning()) return false; if ((executionInfo & TASK_MICROS) != 0) { uint16_t delay = (executionInfo & TIMER_MASK); return (micros() - scheduledAt) >= delay; } else if((executionInfo & TASK_SECONDS) != 0) { uint32_t delay = (executionInfo & TIMER_MASK) * 1000L; return (millis() - scheduledAt) >= delay; } else { uint16_t delay = (executionInfo & TIMER_MASK); return (millis() - scheduledAt) >= delay; } } unsigned long TimerTask::microsFromNow() { uint32_t microsFromNow; if ((executionInfo & TASK_MICROS) != 0) { uint16_t delay = (executionInfo & TIMER_MASK); microsFromNow = delay - (micros() - scheduledAt); } else { uint32_t startTm = (executionInfo & TIMER_MASK); if ((executionInfo & TASK_SECONDS) != 0) { startTm *= 1000; } microsFromNow = (startTm - (millis() - scheduledAt)) * 1000; } return microsFromNow; } inline void TimerTask::execute() { if (callback == NULL) return; // failsafe, always exit with null callback. // handle repeating tasks - reschedule. if (isRepeating()) { markRunning(); callback(); this->scheduledAt = (executionInfo & TASK_MICROS) ? micros() : millis(); clearRunning(); } else { TimerFn savedCallback = callback; clear(); savedCallback(); } } void TimerTask::clear() { executionInfo = 0; callback = NULL; } void TaskManager::markInterrupted(uint8_t interruptNo) { taskManager.lastInterruptTrigger = interruptNo; taskManager.interrupted = true; } TaskManager::TaskManager(uint8_t taskSlots) { this->numberOfSlots = taskSlots; this->tasks = new TimerTask[taskSlots]; interrupted = false; first = NULL; interruptCallback = NULL; } int TaskManager::findFreeTask() { for (uint8_t i = 0; i < numberOfSlots; ++i) { if (!tasks[i].isInUse()) { return i; } } return TASKMGR_INVALIDID; } inline int toTimerValue(int v, TimerUnit unit) { if (unit == TIME_MILLIS && v > TIMER_MASK) { unit = TIME_SECONDS; v = v / 1000; } v = min(v, TIMER_MASK); return v | (((uint16_t)unit) << 12); } uint8_t TaskManager::scheduleOnce(int millis, TimerFn timerFunction, TimerUnit timeUnit) { uint8_t taskId = findFreeTask(); if (taskId != TASKMGR_INVALIDID) { tasks[taskId].initialise(toTimerValue(millis, timeUnit) | TASK_IN_USE, timerFunction); putItemIntoQueue(&tasks[taskId]); } return taskId; } uint8_t TaskManager::scheduleFixedRate(int millis, TimerFn timerFunction, TimerUnit timeUnit) { uint8_t taskId = findFreeTask(); if (taskId != TASKMGR_INVALIDID) { tasks[taskId].initialise(toTimerValue(millis, timeUnit) | TASK_IN_USE | TASK_REPEATING, timerFunction); putItemIntoQueue(&tasks[taskId]); } return taskId; } void TaskManager::cancelTask(uint8_t task) { if (task < numberOfSlots) { tasks[task].clear(); removeFromQueue(&tasks[task]); } } char* TaskManager::checkAvailableSlots(char* data) { uint8_t i; for (i = 0; i < numberOfSlots; ++i) { data[i] = tasks[i].isRepeating() ? 'R' : (tasks[i].isInUse() ? 'U' : 'F'); if (tasks[i].isRunning()) data[i] = tolower(data[i]); } data[i] = 0; return data; } void TaskManager::yieldForMicros(uint16_t microsToWait) { yield(); unsigned long microsEnd = micros() + microsToWait; while(micros() < microsEnd) { runLoop(); } } void TaskManager::runLoop() { if (interrupted) { interrupted = false; interruptCallback(lastInterruptTrigger); } TimerTask* tm = first; while(tm != NULL) { if (tm->isReady()) { removeFromQueue(tm); tm->execute(); if (tm->isRepeating()) { putItemIntoQueue(tm); } } else { break; } tm = tm->getNext(); } // TODO, if not interrupted, and no task for a while sleep and set timer - go into low power. } void TaskManager::putItemIntoQueue(TimerTask* tm) { // shortcut, no first yet, so we are at the top! if (first == NULL) { first = tm; tm->setNext(NULL); return; } // if we are the new first.. if (first->microsFromNow() > tm->microsFromNow()) { tm->setNext(first); first = tm; return; } // otherwise we have to find the place in the queue for this item by time TimerTask* current = first->getNext(); TimerTask* previous = first; while (current != NULL) { if (current->microsFromNow() > tm->microsFromNow()) { previous->setNext(tm); tm->setNext(current); return; } previous = current; current = current->getNext(); } // we are at the end of the queue previous->setNext(tm); tm->setNext(NULL); } void TaskManager::removeFromQueue(TimerTask* tm) { // shortcut, if we are first, just remove us by getting the next and setting first. if (first == tm) { first = tm->getNext(); return; } // otherwise, we have a single linked list, so we need to keep previous and current and // then iterate through each item TimerTask* current = first->getNext(); TimerTask* previous = first; while (current != NULL) { // we've found the item, unlink it from the queue and nullify its next. if (current == tm) { previous->setNext(current->getNext()); current->setNext(NULL); break; } previous = current; current = current->getNext(); } } typedef void ArdunioIntFn(void); void interruptHandler1() { taskManager.markInterrupted(1); } void interruptHandler2() { taskManager.markInterrupted(2); } void interruptHandler3() { taskManager.markInterrupted(3); } void interruptHandler5() { taskManager.markInterrupted(5); } void interruptHandler18() { taskManager.markInterrupted(18); } void interruptHandlerOther() { taskManager.markInterrupted(0xff); } void TaskManager::addInterrupt(uint8_t pin, uint8_t mode) { if (interruptCallback == NULL) return; int interruptNo = digitalPinToInterrupt(pin); switch (pin) { case 1: attachInterrupt(interruptNo, interruptHandler1, mode); break; case 2: attachInterrupt(interruptNo, interruptHandler2, mode); break; case 3: attachInterrupt(interruptNo, interruptHandler3, mode); break; case 5: attachInterrupt(interruptNo, interruptHandler5, mode); break; case 18: attachInterrupt(interruptNo, interruptHandler18, mode); break; default: attachInterrupt(interruptNo, interruptHandlerOther, mode); break; } } void TaskManager::setInterruptCallback(InterruptFn handler) { interruptCallback = handler; } <|endoftext|>
<commit_before>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "buffer_pool.hpp" #include "device.hpp" #include <utility> using namespace std; namespace Vulkan { void BufferPool::init(Device *device_, VkDeviceSize block_size_, VkDeviceSize alignment_, VkBufferUsageFlags usage_, bool need_device_local_) { device = device_; block_size = block_size_; alignment = alignment_; usage = usage_; need_device_local = need_device_local_; } void BufferPool::set_spill_region_size(VkDeviceSize spill_size_) { spill_size = spill_size_; } BufferBlock::~BufferBlock() { } void BufferPool::reset() { blocks.clear(); } BufferBlock BufferPool::allocate_block(VkDeviceSize size) { BufferDomain ideal_domain = need_device_local ? BufferDomain::Device : BufferDomain::Host; VkBufferUsageFlags extra_usage = ideal_domain == BufferDomain::Device ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0; BufferBlock block; BufferCreateInfo info; info.domain = ideal_domain; info.size = size; info.usage = usage | extra_usage; block.gpu = device->create_buffer(info, nullptr); device->set_name(*block.gpu, "chain-allocated-block-gpu"); block.gpu->set_internal_sync_object(); // Try to map it, will fail unless the memory is host visible. block.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.gpu, MEMORY_ACCESS_WRITE_BIT)); if (!block.mapped) { // Fall back to host memory, and remember to sync to gpu on submission time using DMA queue. :) BufferCreateInfo cpu_info; cpu_info.domain = BufferDomain::Host; cpu_info.size = size; cpu_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; block.cpu = device->create_buffer(cpu_info, nullptr); block.cpu->set_internal_sync_object(); device->set_name(*block.cpu, "chain-allocated-block-cpu"); block.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.cpu, MEMORY_ACCESS_WRITE_BIT)); } else block.cpu = block.gpu; block.offset = 0; block.alignment = alignment; block.size = size; block.spill_size = spill_size; return block; } BufferBlock BufferPool::request_block(VkDeviceSize minimum_size) { if ((minimum_size > block_size) || blocks.empty()) { return allocate_block(max(block_size, minimum_size)); } else { auto back = move(blocks.back()); blocks.pop_back(); back.mapped = static_cast<uint8_t *>(device->map_host_buffer(*back.cpu, MEMORY_ACCESS_WRITE_BIT)); back.offset = 0; return back; } } void BufferPool::recycle_block(BufferBlock &&block) { VK_ASSERT(block.size == block_size); blocks.push_back(move(block)); } BufferPool::~BufferPool() { VK_ASSERT(blocks.empty()); } } <commit_msg>Prefer LinkedDeviceHost domain for streamed VBO/IBO/UBO.<commit_after>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "buffer_pool.hpp" #include "device.hpp" #include <utility> using namespace std; namespace Vulkan { void BufferPool::init(Device *device_, VkDeviceSize block_size_, VkDeviceSize alignment_, VkBufferUsageFlags usage_, bool need_device_local_) { device = device_; block_size = block_size_; alignment = alignment_; usage = usage_; need_device_local = need_device_local_; } void BufferPool::set_spill_region_size(VkDeviceSize spill_size_) { spill_size = spill_size_; } BufferBlock::~BufferBlock() { } void BufferPool::reset() { blocks.clear(); } BufferBlock BufferPool::allocate_block(VkDeviceSize size) { BufferDomain ideal_domain = need_device_local ? BufferDomain::Device : ((usage & VK_BUFFER_USAGE_TRANSFER_SRC_BIT) != 0) ? BufferDomain::Host : BufferDomain::LinkedDeviceHost; VkBufferUsageFlags extra_usage = ideal_domain == BufferDomain::Device ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0; BufferBlock block; BufferCreateInfo info; info.domain = ideal_domain; info.size = size; info.usage = usage | extra_usage; block.gpu = device->create_buffer(info, nullptr); device->set_name(*block.gpu, "chain-allocated-block-gpu"); block.gpu->set_internal_sync_object(); // Try to map it, will fail unless the memory is host visible. block.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.gpu, MEMORY_ACCESS_WRITE_BIT)); if (!block.mapped) { // Fall back to host memory, and remember to sync to gpu on submission time using DMA queue. :) BufferCreateInfo cpu_info; cpu_info.domain = BufferDomain::Host; cpu_info.size = size; cpu_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; block.cpu = device->create_buffer(cpu_info, nullptr); block.cpu->set_internal_sync_object(); device->set_name(*block.cpu, "chain-allocated-block-cpu"); block.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.cpu, MEMORY_ACCESS_WRITE_BIT)); } else block.cpu = block.gpu; block.offset = 0; block.alignment = alignment; block.size = size; block.spill_size = spill_size; return block; } BufferBlock BufferPool::request_block(VkDeviceSize minimum_size) { if ((minimum_size > block_size) || blocks.empty()) { return allocate_block(max(block_size, minimum_size)); } else { auto back = move(blocks.back()); blocks.pop_back(); back.mapped = static_cast<uint8_t *>(device->map_host_buffer(*back.cpu, MEMORY_ACCESS_WRITE_BIT)); back.offset = 0; return back; } } void BufferPool::recycle_block(BufferBlock &&block) { VK_ASSERT(block.size == block_size); blocks.push_back(move(block)); } BufferPool::~BufferPool() { VK_ASSERT(blocks.empty()); } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <RakPeer.h> #include <set> #include <thread> #include <map> #include <vector> #include <random> #include <algorithm> #undef REGISTERED #include "../Core/common.cpp" using namespace gameplay; #include "../Core/Message.h" using namespace std::literals; #undef max #undef min class AI final { private: enum class Type { attack, defense, discover }; std::map<std::string, Type> mUnits; using SendFunc = std::function<void(const RakNet::BitStream&, PacketPriority, PacketReliability)>; SendFunc mSend; std::vector<Vector2> mKeyPoint; std::map<uint32_t, UnitSyncInfo> mMine; std::map<uint32_t, UnitSyncInfo> mArmies; uint32_t mGroup; float mValue; Type mStep = Type::defense; struct TeamInfo final { std::set<uint32_t> current; uint32_t size; Vector2 object; }; std::vector<TeamInfo> mTeams; std::vector<uint32_t> mFree; Vector2 mRoot; public: AI() :mValue(0.0f) { std::vector<std::string> units; listDirs("res/units", units); for (auto&& x : units) { uniqueRAII<Properties> info = Properties::create(("res/units/" + x + "/unit.info").c_str()); auto tname = info->getString("AIType", "discover"); if (tname == "attack")mUnits[x] = Type::attack; else if (tname == "defense")mUnits[x] = Type::defense; else mUnits[x] = Type::discover; } } void connect(const SendFunc& send, const std::string& map, uint8_t group) { mSend = send; uniqueRAII<Properties> info = Properties::create(("res/maps/" + map + "/map.info").c_str()); const char* id; Vector2 tmp; while ((id = info->getNextProperty()) && info->getVector2(id, &tmp)) mKeyPoint.emplace_back(tmp / 512.0f* 10000.0f - Vector2{ 5000.0f, 5000.0f }); mGroup = group; } void setRoot(const Vector2 root) { mRoot = root; } void updateUnit(const UnitSyncInfo& info) { if (info.group == mGroup) mMine[info.id] = info; else mArmies[info.id] = info; } void newUnit(const UnitSyncInfo& info) { updateUnit(info); mValue += (info.group == mGroup) ? 0.5f : -1.0f; if(info.group==mGroup) mFree.emplace_back(info.id); } void deleteUnit(uint32_t id) { if (mMine.find(id) != mMine.cend()) mMine.erase(id), --mValue; else mArmies.erase(id), mValue += 0.5f; } void send(const TeamInfo& info) { RakNet::BitStream data; data.Write(ClientMessage::setMoveTarget); data.Write(info.object); for (auto&& x : info.current) data.Write(x); mSend(data, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE_ORDERED); } void send(uint16_t id, uint16_t weight) { RakNet::BitStream data; data.Write(ClientMessage::changeWeight); data.Write(id); data.Write(weight); mSend(data, PacketPriority::MEDIUM_PRIORITY, PacketReliability::RELIABLE); } void clearTeams(){ for (auto&& x : mTeams) for (auto&& u : x.current) if (mMine.find(u) != mMine.cend()) mFree.emplace_back(u); mTeams.clear(); } void update() { auto old = mStep; //discover if (mValue > -20.0f || mArmies.empty())mStep = Type::discover; //attack if (mValue > 100.0f || (mArmies.size() && mArmies.size() * 5 < mMine.size())) mStep = Type::attack; //defense if (mValue<-10.0f || mArmies.size()>0.2*mMine.size())mStep = Type::defense; if (old != mStep) { std::cout << "Switch state : "; switch (mStep) { case Type::attack:std::cout << "attack"; break; case Type::defense:std::cout << "defense"; break; case Type::discover:std::cout << "discover"; break; default: break; } std::cout << std::endl; uint16_t id=0; for (auto&& x : mUnits) { if (x.second == mStep) send(id, 1000); ++id; } clearTeams(); switch (mStep) { case Type::attack: { } break; case Type::defense: { TeamInfo team; team.object = mRoot; team.size = std::numeric_limits<uint32_t>::max(); send(team); mTeams.emplace_back(team); uint16_t id = 0; for (auto&& x : mUnits) { if (x.second != Type::defense) send(id, 1); ++id; } } break; case Type::discover: { for (auto&& x : mKeyPoint) { TeamInfo team; team.size = 7; team.object = x; mTeams.emplace_back(team); } } break; default: break; } } if (mStep == Type::attack) { clearTeams(); std::map<Vector2, uint32_t> find; for (auto&& x : mArmies) { auto&& info = x.second; if (info.group != mGroup) { Vector2 p{ info.pos.x,info.pos.z }; bool flag = true; for (auto&& x : find) { if (x.first.distanceSquared(p) < 90000.0f) { ++x.second, flag = false; break; } } if (flag)find[p] = 1; } } for (auto&& x : find) { TeamInfo team; team.size = x.second*1.5; team.object = x.first; } } std::remove_if(mFree.begin(), mFree.end(), [this](uint32_t id) {return mMine.find(id) == mMine.cend(); }); if (mStep == Type::discover && mFree.size() > 5) { TeamInfo team; team.size = 3; team.object = { mt() % 10000 - 5000.0f,mt() % 10000 - 5000.0f }; } for (auto&& x : mTeams) { if (mFree.empty())continue; std::set<uint32_t> deferred; for (auto&& id : x.current) if (mMine.find(id) == mMine.cend()) deferred.insert(id); for (auto&& y : deferred) x.current.erase(y); uint32_t size = std::min(mFree.size(), x.size - x.current.size()); std::partial_sort(mFree.begin(), mFree.begin() + size, mFree.end(), [this,&x](uint32_t a,uint32_t b) { return x.object.distanceSquared({ mMine[a].pos.x,mMine[a].pos.z }) > x.object.distanceSquared({ mMine[b].pos.x,mMine[b].pos.z }); }); for (auto i = 0; i < size; ++i) x.current.insert(*(mFree.rbegin() + i)); mFree.resize(mFree.size() - size); send(x); } std::map<uint32_t, uint32_t> attackMap; for (auto&& x : mMine) { float md = std::numeric_limits<float>::max(); uint32_t maxwell=0; for (auto&& y : mArmies) { auto dis = y.second.pos.distanceSquared(x.second.pos); if (dis < md)md = dis, maxwell = y.first; } if (maxwell) attackMap[x.first] = maxwell; } if (attackMap.size()) { RakNet::BitStream data; data.Write(ClientMessage::setAttackTarget); for (auto&& x : attackMap){ data.Write(x.first); data.Write(x.second); } mSend(data, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE); } } } tinyAI; #define FORNET for (auto packet = peer.Receive(); packet; peer.DeallocatePacket(packet), packet = peer.Receive()) int main() { RakNet::RakPeer peer; RakNet::SocketDescriptor SD; peer.Startup(1, &SD, 1); std::cout << "Input group:" << std::endl; uint16_t group; std::cin >> group; std::cout << "Scanning servers..." << std::endl; std::string str; std::set<RakNet::SystemAddress> ban; RakNet::SystemAddress server; while (true) { peer.Ping("255.255.255.255", 23333, false); FORNET{ if (packet->data[0] == ID_UNCONNECTED_PONG && ban.find(packet->systemAddress) == ban.cend()) { std::cout << "Find server " << packet->systemAddress.ToString() << std::endl; std::cout << "Shall we connect it?(y/n)" << std::endl; char c; std::cin >> c; if (c == 'y') { server = packet->systemAddress; auto res = peer.Connect(server.ToString(false), 23333, nullptr,0); if (res == RakNet::CONNECTION_ATTEMPT_STARTED) { while (peer.NumberOfConnections() != 1) std::this_thread::sleep_for(1ms); std::cout << "OK!" << std::endl; peer.DeallocatePacket(packet); goto p1; } } else ban.insert(packet->systemAddress); } } std::this_thread::sleep_for(1ms); } p1: { RakNet::BitStream data; data.Write(ClientMessage::changeGroup); data.Write(static_cast<uint8_t>(group)); peer.Send(&data, PacketPriority::IMMEDIATE_PRIORITY, PacketReliability::RELIABLE_ORDERED, 0, server, false); } while (true) { FORNET{ CheckBegin; CheckHeader(ServerMessage::info) { RakNet::BitStream data(packet->data, packet->length,false); data.IgnoreBytes(1 + sizeof(uint64_t)); RakNet::RakString str; data.Read(str); tinyAI.connect([&](const RakNet::BitStream& data, PacketPriority pp, PacketReliability pr) { peer.Send(&data, pp, pr, 0, server, false); },str.C_String(),group); } CheckHeader(ServerMessage::go) { RakNet::BitStream data(packet->data, packet->length,false); data.IgnoreBytes(1); Vector2 p; data.Read(p); tinyAI.setRoot(p); std::cout << "Go!" << std::endl; goto p2; } } std::this_thread::sleep_for(1ms); } p2: struct UnitInfo final { uint32_t id; Vector3 pos; bool operator<(const UnitInfo& rhs) const { return id < rhs.id; } }; bool isStop = false; std::set<uint32_t> old; auto begin = std::chrono::system_clock::now(); while (true) { std::vector<unsigned char> latestData; FORNET{ if (isStop)continue; RakNet::BitStream data(packet->data, packet->length, false); data.IgnoreBytes(1); CheckBegin; CheckHeader(ServerMessage::out) { std::cout << "What a pity!" << std::endl; isStop = true; continue; } CheckHeader(ServerMessage::stop) { std::cout << "The game stopped." << std::endl; isStop = true; continue; } CheckHeader(ServerMessage::win) { std::cout << "We are winner!" << std::endl; isStop = true; continue; } CheckHeader(ServerMessage::updateUnit) { latestData = std::vector<unsigned char>(packet->data, packet->data + packet->length); } } if (isStop || peer.GetConnectionState(server) != RakNet::ConnectionState::IS_CONNECTED)break; if (latestData.empty())continue; uint32_t mine = 0, armies = 0; std::set<uint32_t> copy = old; RakNet::BitStream latest(latestData.data(), latestData.size(), false); latest.IgnoreBytes(1); uint32_t size; latest.Read(size); for (uint32_t i = 0; i < size; ++i) { UnitSyncInfo u; latest.Read(u); auto iter = copy.find(u.id); if (iter == copy.cend()) { old.insert(u.id); tinyAI.newUnit(u); } else { copy.erase(iter); tinyAI.updateUnit(u); } if (u.group == group) ++mine; else ++armies; } for (auto&& x : copy) tinyAI.deleteUnit(x); tinyAI.update(); std::cout << "mine:" << mine << " armies:" << armies << std::endl; std::this_thread::sleep_for(1s); } auto second = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - begin).count(); std::cout << "time:" << second / 60 << ":" << second % 60 << std::endl; peer.Shutdown(500, 0, IMMEDIATE_PRIORITY); std::cin.get(); std::cin.get(); return 0; } #undef FORNET <commit_msg>fix bugs<commit_after>#include <iostream> #include <fstream> #include <string> #include <RakPeer.h> #include <set> #include <thread> #include <map> #include <vector> #include <random> #include <algorithm> #undef REGISTERED #include "../Core/common.cpp" using namespace gameplay; #include "../Core/Message.h" using namespace std::literals; #undef max #undef min class AI final { private: enum class Type { attack, defense, discover }; std::map<std::string, Type> mUnits; using SendFunc = std::function<void(const RakNet::BitStream&, PacketPriority, PacketReliability)>; SendFunc mSend; std::vector<Vector2> mKeyPoint; std::map<uint32_t, UnitSyncInfo> mMine; std::map<uint32_t, UnitSyncInfo> mArmies; uint32_t mGroup; float mValue; Type mStep = Type::defense; struct TeamInfo final { std::set<uint32_t> current; uint32_t size; Vector2 object; }; std::vector<TeamInfo> mTeams; std::vector<uint32_t> mFree; Vector2 mRoot; public: AI() :mValue(0.0f) { std::vector<std::string> units; listDirs("res/units", units); for (auto&& x : units) { uniqueRAII<Properties> info = Properties::create(("res/units/" + x + "/unit.info").c_str()); auto tname = info->getString("AIType", "discover"); if (tname == "attack")mUnits[x] = Type::attack; else if (tname == "defense")mUnits[x] = Type::defense; else mUnits[x] = Type::discover; } } void connect(const SendFunc& send, const std::string& map, uint8_t group) { mSend = send; uniqueRAII<Properties> info = Properties::create(("res/maps/" + map + "/map.info").c_str()); const char* id; Vector2 tmp; while ((id = info->getNextProperty()) && info->getVector2(id, &tmp)) mKeyPoint.emplace_back(tmp / 512.0f* 10000.0f - Vector2{ 5000.0f, 5000.0f }); mGroup = group; } void setRoot(const Vector2 root) { mRoot = root; } void updateUnit(const UnitSyncInfo& info) { if (info.group == mGroup) mMine[info.id] = info; else mArmies[info.id] = info; } void newUnit(const UnitSyncInfo& info) { updateUnit(info); mValue += (info.group == mGroup) ? 0.5f : -1.0f; if(info.group==mGroup) mFree.emplace_back(info.id); } void deleteUnit(uint32_t id) { if (mMine.find(id) != mMine.cend()) mMine.erase(id), --mValue; else mArmies.erase(id), mValue += 0.5f; } void send(const TeamInfo& info) { RakNet::BitStream data; data.Write(ClientMessage::setMoveTarget); data.Write(info.object); for (auto&& x : info.current) data.Write(x); mSend(data, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE_ORDERED); } void send(uint16_t id, uint16_t weight) { RakNet::BitStream data; data.Write(ClientMessage::changeWeight); data.Write(id); data.Write(weight); mSend(data, PacketPriority::MEDIUM_PRIORITY, PacketReliability::RELIABLE); } void clearTeams(){ for (auto&& x : mTeams) for (auto&& u : x.current) if (mMine.find(u) != mMine.cend()) mFree.emplace_back(u); mTeams.clear(); } void update() { auto old = mStep; //discover if (mValue > -20.0f || mArmies.empty())mStep = Type::discover; //attack if (mValue > 100.0f || (mArmies.size() && mArmies.size() * 5 < mMine.size())) mStep = Type::attack; //defense if (mValue<-10.0f || mArmies.size()>0.2*mMine.size())mStep = Type::defense; if (old != mStep) { std::cout << "Switch state : "; switch (mStep) { case Type::attack:std::cout << "attack"; break; case Type::defense:std::cout << "defense"; break; case Type::discover:std::cout << "discover"; break; default: break; } std::cout << std::endl; uint16_t id=0; for (auto&& x : mUnits) { if (x.second == mStep) send(id, 1000); ++id; } clearTeams(); switch (mStep) { case Type::attack: { } break; case Type::defense: { TeamInfo team; team.object = mRoot; team.size = std::numeric_limits<uint32_t>::max(); send(team); mTeams.emplace_back(team); uint16_t id = 0; for (auto&& x : mUnits) { if (x.second != Type::defense) send(id, 1); ++id; } } break; case Type::discover: { for (auto&& x : mKeyPoint) { TeamInfo team; team.size = 3; team.object = x; mTeams.emplace_back(team); } } break; default: break; } } if (mStep == Type::attack) { clearTeams(); std::map<Vector2, uint32_t> find; for (auto&& x : mArmies) { auto&& info = x.second; if (info.group != mGroup) { Vector2 p{ info.pos.x,info.pos.z }; bool flag = true; for (auto&& x : find) { if (x.first.distanceSquared(p) < 90000.0f) { ++x.second, flag = false; break; } } if (flag)find[p] = 1; } } for (auto&& x : find) { TeamInfo team; team.size = x.second*1.5; team.object = x.first; mTeams.emplace_back(team); } } std::remove_if(mFree.begin(), mFree.end(), [this](uint32_t id) {return mMine.find(id) == mMine.cend(); }); if (mStep == Type::discover && mFree.size() > 5) { TeamInfo team; team.size = 3; team.object = { mt() % 10000 - 5000.0f,mt() % 10000 - 5000.0f }; mTeams.emplace_back(team); } for (auto&& x : mTeams) { if (mFree.empty())continue; std::set<uint32_t> deferred; for (auto&& id : x.current) if (mMine.find(id) == mMine.cend()) deferred.insert(id); for (auto&& y : deferred) x.current.erase(y); uint32_t size = std::min(mFree.size(), x.size - x.current.size()); std::partial_sort(mFree.begin(), mFree.begin() + size, mFree.end(), [this,&x](uint32_t a,uint32_t b) { return x.object.distanceSquared({ mMine[a].pos.x,mMine[a].pos.z }) > x.object.distanceSquared({ mMine[b].pos.x,mMine[b].pos.z }); }); for (auto i = 0; i < size; ++i) x.current.insert(*(mFree.rbegin() + i)); mFree.resize(mFree.size() - size); send(x); } std::map<uint32_t, uint32_t> attackMap; for (auto&& x : mMine) { float md = std::numeric_limits<float>::max(); uint32_t maxwell=0; for (auto&& y : mArmies) { auto dis = y.second.pos.distanceSquared(x.second.pos); if (dis < md)md = dis, maxwell = y.first; } if (maxwell) attackMap[x.first] = maxwell; } if (attackMap.size()) { RakNet::BitStream data; data.Write(ClientMessage::setAttackTarget); for (auto&& x : attackMap){ data.Write(x.first); data.Write(x.second); } mSend(data, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE); } } } tinyAI; #define FORNET for (auto packet = peer.Receive(); packet; peer.DeallocatePacket(packet), packet = peer.Receive()) int main() { RakNet::RakPeer peer; RakNet::SocketDescriptor SD; peer.Startup(1, &SD, 1); std::cout << "Input group:" << std::endl; uint16_t group; std::cin >> group; std::cout << "Scanning servers..." << std::endl; std::string str; std::set<RakNet::SystemAddress> ban; RakNet::SystemAddress server; while (true) { peer.Ping("255.255.255.255", 23333, false); FORNET{ if (packet->data[0] == ID_UNCONNECTED_PONG && ban.find(packet->systemAddress) == ban.cend()) { std::cout << "Find server " << packet->systemAddress.ToString() << std::endl; std::cout << "Shall we connect it?(y/n)" << std::endl; char c; std::cin >> c; if (c == 'y') { server = packet->systemAddress; auto res = peer.Connect(server.ToString(false), 23333, nullptr,0); if (res == RakNet::CONNECTION_ATTEMPT_STARTED) { while (peer.NumberOfConnections() != 1) std::this_thread::sleep_for(1ms); std::cout << "OK!" << std::endl; peer.DeallocatePacket(packet); goto p1; } } else ban.insert(packet->systemAddress); } } std::this_thread::sleep_for(1ms); } p1: { RakNet::BitStream data; data.Write(ClientMessage::changeGroup); data.Write(static_cast<uint8_t>(group)); peer.Send(&data, PacketPriority::IMMEDIATE_PRIORITY, PacketReliability::RELIABLE_ORDERED, 0, server, false); } while (true) { FORNET{ CheckBegin; CheckHeader(ServerMessage::info) { RakNet::BitStream data(packet->data, packet->length,false); data.IgnoreBytes(1 + sizeof(uint64_t)); RakNet::RakString str; data.Read(str); tinyAI.connect([&](const RakNet::BitStream& data, PacketPriority pp, PacketReliability pr) { peer.Send(&data, pp, pr, 0, server, false); },str.C_String(),group); } CheckHeader(ServerMessage::go) { RakNet::BitStream data(packet->data, packet->length,false); data.IgnoreBytes(1); Vector2 p; data.Read(p); tinyAI.setRoot(p); std::cout << "Go!" << std::endl; goto p2; } } std::this_thread::sleep_for(1ms); } p2: struct UnitInfo final { uint32_t id; Vector3 pos; bool operator<(const UnitInfo& rhs) const { return id < rhs.id; } }; bool isStop = false; std::set<uint32_t> old; auto begin = std::chrono::system_clock::now(); while (true) { std::vector<unsigned char> latestData; FORNET{ if (isStop)continue; RakNet::BitStream data(packet->data, packet->length, false); data.IgnoreBytes(1); CheckBegin; CheckHeader(ServerMessage::out) { std::cout << "What a pity!" << std::endl; isStop = true; continue; } CheckHeader(ServerMessage::stop) { std::cout << "The game stopped." << std::endl; isStop = true; continue; } CheckHeader(ServerMessage::win) { std::cout << "We are winner!" << std::endl; isStop = true; continue; } CheckHeader(ServerMessage::updateUnit) { latestData = std::vector<unsigned char>(packet->data, packet->data + packet->length); } } if (isStop || peer.GetConnectionState(server) != RakNet::ConnectionState::IS_CONNECTED)break; if (latestData.empty())continue; uint32_t mine = 0, armies = 0; std::set<uint32_t> copy = old; RakNet::BitStream latest(latestData.data(), latestData.size(), false); latest.IgnoreBytes(1); uint32_t size; latest.Read(size); for (uint32_t i = 0; i < size; ++i) { UnitSyncInfo u; latest.Read(u); auto iter = copy.find(u.id); if (iter == copy.cend()) { old.insert(u.id); tinyAI.newUnit(u); } else { copy.erase(iter); tinyAI.updateUnit(u); } if (u.group == group) ++mine; else ++armies; } for (auto&& x : copy) tinyAI.deleteUnit(x); tinyAI.update(); std::cout << "mine:" << mine << " armies:" << armies << std::endl; std::this_thread::sleep_for(1s); } auto second = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - begin).count(); std::cout << "time:" << second / 60 << ":" << second % 60 << std::endl; peer.Shutdown(500, 0, IMMEDIATE_PRIORITY); std::cin.get(); std::cin.get(); return 0; } #undef FORNET <|endoftext|>
<commit_before>#include "global_cached_private.h" static void __complete_req(io_request *orig, thread_safe_page *p) { int page_off = orig->get_offset() - ROUND_PAGE(orig->get_offset()); p->lock(); if (orig->get_access_method() == WRITE) { unsigned long *l = (unsigned long *) ((char *) p->get_data() + page_off); unsigned long start = orig->get_offset() / sizeof(long); if (*l != start) printf("write: start: %ld, l: %ld, offset: %ld\n", start, *l, p->get_offset() / sizeof(long)); memcpy((char *) p->get_data() + page_off, orig->get_buf(), orig->get_size()); p->set_dirty(true); } else /* I assume the data I read never crosses the page boundary */ memcpy(orig->get_buf(), (char *) p->get_data() + page_off, orig->get_size()); p->unlock(); p->dec_ref(); } class read_page_callback: public callback { public: int invoke(io_request *request) { io_request *orig = (io_request *) request->get_priv(); thread_safe_page *p = (thread_safe_page *) orig->get_priv(); std::vector<io_request> reqs; p->lock(); p->set_data_ready(true); p->set_io_pending(false); io_request *req = p->get_io_req(); assert(req); // TODO vector may allocate memory and block the thread. // I should be careful of that. while (req) { reqs.push_back(*req); req = req->get_next_req(); } p->unlock(); // At this point, data is ready, so any threads that want to add // requests to the page will fail. p->reset_reqs(); for (unsigned i = 0; i < reqs.size(); i++) { __complete_req(&reqs[i], p); io_interface *io = reqs[i].get_io(); if (io->get_callback()) io->get_callback()->invoke(&reqs[i]); } return 0; } }; global_cached_io::global_cached_io(io_interface *underlying, long cache_size, int cache_type) { cb = NULL; cache_hits = 0; this->underlying = underlying; underlying->set_callback(new read_page_callback()); num_waits = 0; this->cache_size = cache_size; if (global_cache == NULL) { global_cache = create_cache(cache_type, cache_size); } } ssize_t global_cached_io::access(io_request *requests, int num) { for (int i = 0; i < num; i++) { ssize_t ret; off_t old_off = -1; off_t offset = requests[i].get_offset(); thread_safe_page *p = (thread_safe_page *) (get_global_cache() ->search(ROUND_PAGE(offset), old_off)); /* * the page isn't in the cache, * so the cache evict a page and return it to us. */ if (old_off != ROUND_PAGE(offset) && old_off != -1) { // TODO handle dirty pages later. } p->lock(); if (!p->data_ready()) { if(!p->is_io_pending()) { p->set_io_pending(true); assert(!p->is_dirty()); p->unlock(); // If the thread can't add the request as the first IO request // of the page, it doesn't need to issue a IO request to the file. int status; io_request *orig = p->add_first_io_req(requests[i], status); if (status == ADD_REQ_SUCCESS) { io_request req((char *) p->get_data(), ROUND_PAGE(offset), PAGE_SIZE, READ, /* * it will notify the underlying IO, * which then notifies global_cached_io. */ underlying, (void *) orig); ret = underlying->access(&req, 1); if (ret < 0) { perror("read"); exit(1); } } // If data is ready, the request won't be added to the page. // so just serve the data. else if (status == ADD_REQ_DATA_READY) goto serve_data; } else { p->unlock(); // An IO request can be added only when the page is still // in IO pending state. Otherwise, it returns NULL. io_request *orig = p->add_io_req(requests[i]); // the page isn't in IO pending state any more. if (orig == NULL) goto serve_data; } } else { // If the data in the page is ready, we don't need to change any state // of the page and just read data. p->unlock(); serve_data: __complete_req(&requests[i], p); if (get_callback()) get_callback()->invoke(&requests[i]); #ifdef STATISTICS cache_hits++; #endif } } return 0; } ssize_t global_cached_io::access(char *buf, off_t offset, ssize_t size, int access_method) { ssize_t ret; off_t old_off = -1; thread_safe_page *p = (thread_safe_page *) (get_global_cache() ->search(ROUND_PAGE(offset), old_off)); /* * the page isn't in the cache, * so the cache evict a page and return it to us. */ if (old_off != ROUND_PAGE(offset) && old_off != -1) { /* * if the new page we get is dirty, * we need to write its data back to the file * before we can put data in the page. * Therefore, the data ready flag is definitely * not set yet. */ if (p->is_dirty()) { unsigned long *l = (unsigned long *) p->get_data(); unsigned long start = old_off / sizeof(long); if (*l != start) printf("start: %ld, l: %ld\n", start, *l); underlying->access((char *) p->get_data(), old_off, PAGE_SIZE, WRITE); p->set_dirty(false); } } if (!p->data_ready()) { /* if the page isn't io pending, set it io pending, and return * original result. otherwise, just return the original value. * * This is an ugly hack, but with this atomic operation, * I can avoid using locks. */ if(!p->test_and_set_io_pending()) { /* * Because of the atomic operation, it's guaranteed * that only one thread can enter here. * If other threads have reference to the page, * they must be waiting for its data to be ready. */ /* * It's possible that two threads go through here * sequentially. For example, the second thread already * sees the data isn't ready, but find io pending isn't * set when the first thread resets io pending. * * However, in any case, when the second thread comes here, * the data is already ready and the second thread should * be able to see the data is ready when it comes here. */ if (!p->data_ready()) { /* * No other threads set the page dirty at this moment, * because if a thread can set the page dirty, * it means the page isn't dirty and already has data * ready at the first place. */ if (p->is_dirty()) p->wait_cleaned(); ret = underlying->access((char *) p->get_data(), ROUND_PAGE(offset), PAGE_SIZE, READ); if (ret < 0) { perror("read"); exit(1); } } p->set_data_ready(true); p->set_io_pending(false); } else { num_waits++; // TODO this is a problem. It takes a long time to get data // from real storage devices. If we use busy waiting, // we just waste computation time. p->wait_ready(); } } else { #ifdef STATISTICS cache_hits++; #endif } int page_off = offset - ROUND_PAGE(offset); p->lock(); if (access_method == WRITE) { unsigned long *l = (unsigned long *) ((char *) p->get_data() + page_off); unsigned long start = offset / sizeof(long); if (*l != start) printf("write: start: %ld, l: %ld, offset: %ld\n", start, *l, p->get_offset() / sizeof(long)); memcpy((char *) p->get_data() + page_off, buf, size); p->set_dirty(true); } else /* I assume the data I read never crosses the page boundary */ memcpy(buf, (char *) p->get_data() + page_off, size); p->unlock(); p->dec_ref(); ret = size; return ret; } int global_cached_io::preload(off_t start, long size) { if (size > cache_size) { fprintf(stderr, "we can't preload data larger than the cache size\n"); exit(1); } /* open the file. It's a hack, but it works for now. */ underlying->init(); assert(ROUND_PAGE(start) == start); for (long offset = start; offset < start + size; offset += PAGE_SIZE) { off_t old_off = -1; thread_safe_page *p = (thread_safe_page *) (get_global_cache()->search(ROUND_PAGE(offset), old_off)); if (!p->data_ready()) { ssize_t ret = underlying->access((char *) p->get_data(), ROUND_PAGE(offset), PAGE_SIZE, READ); if (ret < 0) { perror("read"); return ret; } p->set_io_pending(false); p->set_data_ready(true); } } /* close the file as it will be opened again in the real workload. */ underlying->cleanup(); return 0; } page_cache *global_cached_io::global_cache; <commit_msg>calculate cache hit rate correctly in global cache IO.<commit_after>#include "global_cached_private.h" static void __complete_req(io_request *orig, thread_safe_page *p) { int page_off = orig->get_offset() - ROUND_PAGE(orig->get_offset()); p->lock(); if (orig->get_access_method() == WRITE) { unsigned long *l = (unsigned long *) ((char *) p->get_data() + page_off); unsigned long start = orig->get_offset() / sizeof(long); if (*l != start) printf("write: start: %ld, l: %ld, offset: %ld\n", start, *l, p->get_offset() / sizeof(long)); memcpy((char *) p->get_data() + page_off, orig->get_buf(), orig->get_size()); p->set_dirty(true); } else /* I assume the data I read never crosses the page boundary */ memcpy(orig->get_buf(), (char *) p->get_data() + page_off, orig->get_size()); p->unlock(); p->dec_ref(); } class read_page_callback: public callback { public: int invoke(io_request *request) { io_request *orig = (io_request *) request->get_priv(); thread_safe_page *p = (thread_safe_page *) orig->get_priv(); std::vector<io_request> reqs; p->lock(); p->set_data_ready(true); p->set_io_pending(false); io_request *req = p->get_io_req(); assert(req); // TODO vector may allocate memory and block the thread. // I should be careful of that. while (req) { reqs.push_back(*req); req = req->get_next_req(); } p->unlock(); // At this point, data is ready, so any threads that want to add // requests to the page will fail. p->reset_reqs(); for (unsigned i = 0; i < reqs.size(); i++) { __complete_req(&reqs[i], p); io_interface *io = reqs[i].get_io(); if (io->get_callback()) io->get_callback()->invoke(&reqs[i]); } return 0; } }; global_cached_io::global_cached_io(io_interface *underlying, long cache_size, int cache_type) { cb = NULL; cache_hits = 0; this->underlying = underlying; underlying->set_callback(new read_page_callback()); num_waits = 0; this->cache_size = cache_size; if (global_cache == NULL) { global_cache = create_cache(cache_type, cache_size); } } ssize_t global_cached_io::access(io_request *requests, int num) { for (int i = 0; i < num; i++) { ssize_t ret; off_t old_off = -1; off_t offset = requests[i].get_offset(); thread_safe_page *p = (thread_safe_page *) (get_global_cache() ->search(ROUND_PAGE(offset), old_off)); /* * the page isn't in the cache, * so the cache evict a page and return it to us. */ if (old_off != ROUND_PAGE(offset) && old_off != -1) { // TODO handle dirty pages later. } p->lock(); if (!p->data_ready()) { if(!p->is_io_pending()) { p->set_io_pending(true); assert(!p->is_dirty()); p->unlock(); // If the thread can't add the request as the first IO request // of the page, it doesn't need to issue a IO request to the file. int status; io_request *orig = p->add_first_io_req(requests[i], status); if (status == ADD_REQ_SUCCESS) { io_request req((char *) p->get_data(), ROUND_PAGE(offset), PAGE_SIZE, READ, /* * it will notify the underlying IO, * which then notifies global_cached_io. */ underlying, (void *) orig); ret = underlying->access(&req, 1); if (ret < 0) { perror("read"); exit(1); } } else { #ifdef STATISTICS cache_hits++; #endif // If data is ready, the request won't be added to the page. // so just serve the data. if (status == ADD_REQ_DATA_READY) goto serve_data; } } else { p->unlock(); #ifdef STATISTICS cache_hits++; #endif // An IO request can be added only when the page is still // in IO pending state. Otherwise, it returns NULL. io_request *orig = p->add_io_req(requests[i]); // the page isn't in IO pending state any more. if (orig == NULL) goto serve_data; } } else { // If the data in the page is ready, we don't need to change any state // of the page and just read data. p->unlock(); #ifdef STATISTICS cache_hits++; #endif serve_data: __complete_req(&requests[i], p); if (get_callback()) get_callback()->invoke(&requests[i]); } } return 0; } ssize_t global_cached_io::access(char *buf, off_t offset, ssize_t size, int access_method) { ssize_t ret; off_t old_off = -1; thread_safe_page *p = (thread_safe_page *) (get_global_cache() ->search(ROUND_PAGE(offset), old_off)); /* * the page isn't in the cache, * so the cache evict a page and return it to us. */ if (old_off != ROUND_PAGE(offset) && old_off != -1) { /* * if the new page we get is dirty, * we need to write its data back to the file * before we can put data in the page. * Therefore, the data ready flag is definitely * not set yet. */ if (p->is_dirty()) { unsigned long *l = (unsigned long *) p->get_data(); unsigned long start = old_off / sizeof(long); if (*l != start) printf("start: %ld, l: %ld\n", start, *l); underlying->access((char *) p->get_data(), old_off, PAGE_SIZE, WRITE); p->set_dirty(false); } } if (!p->data_ready()) { /* if the page isn't io pending, set it io pending, and return * original result. otherwise, just return the original value. * * This is an ugly hack, but with this atomic operation, * I can avoid using locks. */ if(!p->test_and_set_io_pending()) { /* * Because of the atomic operation, it's guaranteed * that only one thread can enter here. * If other threads have reference to the page, * they must be waiting for its data to be ready. */ /* * It's possible that two threads go through here * sequentially. For example, the second thread already * sees the data isn't ready, but find io pending isn't * set when the first thread resets io pending. * * However, in any case, when the second thread comes here, * the data is already ready and the second thread should * be able to see the data is ready when it comes here. */ if (!p->data_ready()) { /* * No other threads set the page dirty at this moment, * because if a thread can set the page dirty, * it means the page isn't dirty and already has data * ready at the first place. */ if (p->is_dirty()) p->wait_cleaned(); ret = underlying->access((char *) p->get_data(), ROUND_PAGE(offset), PAGE_SIZE, READ); if (ret < 0) { perror("read"); exit(1); } } p->set_data_ready(true); p->set_io_pending(false); } else { num_waits++; // TODO this is a problem. It takes a long time to get data // from real storage devices. If we use busy waiting, // we just waste computation time. p->wait_ready(); } } else { #ifdef STATISTICS cache_hits++; #endif } int page_off = offset - ROUND_PAGE(offset); p->lock(); if (access_method == WRITE) { unsigned long *l = (unsigned long *) ((char *) p->get_data() + page_off); unsigned long start = offset / sizeof(long); if (*l != start) printf("write: start: %ld, l: %ld, offset: %ld\n", start, *l, p->get_offset() / sizeof(long)); memcpy((char *) p->get_data() + page_off, buf, size); p->set_dirty(true); } else /* I assume the data I read never crosses the page boundary */ memcpy(buf, (char *) p->get_data() + page_off, size); p->unlock(); p->dec_ref(); ret = size; return ret; } int global_cached_io::preload(off_t start, long size) { if (size > cache_size) { fprintf(stderr, "we can't preload data larger than the cache size\n"); exit(1); } /* open the file. It's a hack, but it works for now. */ underlying->init(); assert(ROUND_PAGE(start) == start); for (long offset = start; offset < start + size; offset += PAGE_SIZE) { off_t old_off = -1; thread_safe_page *p = (thread_safe_page *) (get_global_cache()->search(ROUND_PAGE(offset), old_off)); if (!p->data_ready()) { ssize_t ret = underlying->access((char *) p->get_data(), ROUND_PAGE(offset), PAGE_SIZE, READ); if (ret < 0) { perror("read"); return ret; } p->set_io_pending(false); p->set_data_ready(true); } } /* close the file as it will be opened again in the real workload. */ underlying->cleanup(); return 0; } page_cache *global_cached_io::global_cache; <|endoftext|>
<commit_before>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkMatrix.h" #include "include/core/SkPaint.h" #include "include/core/SkPath.h" #include "include/core/SkPoint.h" #include "include/core/SkRect.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/core/SkTypes.h" #include "src/core/SkGeometry.h" static constexpr float kStrokeWidth = 40; static constexpr int kCellSize = 200; static const SkPoint kCubics[][4] = { {{122, 737}, {348, 553}, {403, 761}, {400, 760}}, {{244, 520}, {244, 518}, {1141, 634}, {394, 688}}, {{550, 194}, {138, 130}, {1035, 246}, {288, 300}}, {{226, 733}, {556, 779}, {-43, 471}, {348, 683}}, {{268, 204}, {492, 304}, {352, 23}, {433, 412}}, {{172, 480}, {396, 580}, {256, 299}, {338, 677}}, {{731, 340}, {318, 252}, {1026, -64}, {367, 265}}, {{475, 708}, {62, 620}, {770, 304}, {220, 659}}, }; static SkRect calc_tight_cubic_bounds(const SkPoint P[4], int depth=5) { if (0 == depth) { SkRect bounds; bounds.fLeft = std::min(std::min(P[0].x(), P[1].x()), std::min(P[2].x(), P[3].x())); bounds.fTop = std::min(std::min(P[0].y(), P[1].y()), std::min(P[2].y(), P[3].y())); bounds.fRight = std::max(std::max(P[0].x(), P[1].x()), std::max(P[2].x(), P[3].x())); bounds.fBottom = std::max(std::max(P[0].y(), P[1].y()), std::max(P[2].y(), P[3].y())); return bounds; } SkPoint chopped[7]; SkChopCubicAt(P, chopped, .5f); SkRect bounds = calc_tight_cubic_bounds(chopped, depth - 1); bounds.join(calc_tight_cubic_bounds(chopped+3, depth - 1)); return bounds; } // This is a compilation of cubics that have given strokers grief. Feel free to add more. class TrickyCubicStrokesGM : public skiagm::GM { public: TrickyCubicStrokesGM() {} protected: SkString onShortName() override { return SkString("trickycubicstrokes"); } SkISize onISize() override { return SkISize::Make(3*kCellSize, 3*kCellSize); } void onOnceBeforeDraw() override { fStrokePaint.setAntiAlias(true); fStrokePaint.setStrokeWidth(kStrokeWidth); fStrokePaint.setColor(SK_ColorGREEN); fStrokePaint.setStyle(SkPaint::kStroke_Style); } void onDraw(SkCanvas* canvas) override { canvas->clear(SK_ColorBLACK); for (size_t i = 0; i < SK_ARRAY_COUNT(kCubics); ++i) { this->drawStroke(canvas, kCubics[i], SkRect::MakeXYWH((i%3) * kCellSize, (i/3) * kCellSize, kCellSize, kCellSize)); } } void drawStroke(SkCanvas* canvas, const SkPoint P[4], const SkRect& location) { SkRect strokeBounds = calc_tight_cubic_bounds(P); strokeBounds.outset(kStrokeWidth, kStrokeWidth); SkMatrix matrix; matrix.setRectToRect(strokeBounds, location, SkMatrix::kCenter_ScaleToFit); SkPath path; path.moveTo(P[0]); path.cubicTo(P[1], P[2], P[3]); SkAutoCanvasRestore acr(canvas, true); canvas->concat(matrix); canvas->drawPath(path, fStrokePaint); } private: SkPaint fStrokePaint; typedef GM INHERITED; }; DEF_GM( return new TrickyCubicStrokesGM; ) <commit_msg>Add new tests to trickycubicstrokes<commit_after>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkMatrix.h" #include "include/core/SkPaint.h" #include "include/core/SkPath.h" #include "include/core/SkPoint.h" #include "include/core/SkRect.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/core/SkTypes.h" #include "src/core/SkGeometry.h" static constexpr float kStrokeWidth = 30; static constexpr int kCellSize = 200; static constexpr int kNumCols = 4; static constexpr int kNumRows = 4; enum class CellFillMode { kStretch, kCenter }; struct TrickyCubic { SkPoint fPoints[4]; CellFillMode fFillMode; float fScale = 1; }; static const TrickyCubic kTrickyCubics[] = { {{{122, 737}, {348, 553}, {403, 761}, {400, 760}}, CellFillMode::kStretch}, {{{244, 520}, {244, 518}, {1141, 634}, {394, 688}}, CellFillMode::kStretch}, {{{550, 194}, {138, 130}, {1035, 246}, {288, 300}}, CellFillMode::kStretch}, {{{226, 733}, {556, 779}, {-43, 471}, {348, 683}}, CellFillMode::kStretch}, {{{268, 204}, {492, 304}, {352, 23}, {433, 412}}, CellFillMode::kStretch}, {{{172, 480}, {396, 580}, {256, 299}, {338, 677}}, CellFillMode::kStretch}, {{{731, 340}, {318, 252}, {1026, -64}, {367, 265}}, CellFillMode::kStretch}, {{{475, 708}, {62, 620}, {770, 304}, {220, 659}}, CellFillMode::kStretch}, {{{0, 0}, {128, 128}, {128, 0}, {0, 128}}, CellFillMode::kCenter}, // Perfect cusp {{{0,.01f}, {128,127.999f}, {128,.01f}, {0,127.99f}}, CellFillMode::kCenter}, // Near-cusp {{{0,-.01f}, {128,128.001f}, {128,-.01f}, {0,128.001f}}, CellFillMode::kCenter}, // Near-cusp {{{0,0}, {0,-10}, {0,-10}, {0,10}}, CellFillMode::kCenter, 1.098283f}, // Flat line with 180 {{{10,0}, {0,0}, {20,0}, {10,0}}, CellFillMode::kStretch}, // Flat line with 2 180s {{{39,-39}, {40,-40}, {40,-40}, {0,0}}, CellFillMode::kStretch}, // Flat diagonal with 180 {{{40, 40}, {0, 0}, {200, 200}, {0, 0}}, CellFillMode::kStretch}, // Diag with an internal 180 {{{0,0}, {1e-2f,0}, {-1e-2f,0}, {0,0}}, CellFillMode::kCenter}, // Circle }; static SkRect calc_tight_cubic_bounds(const SkPoint P[4], int depth=5) { if (0 == depth) { SkRect bounds; bounds.fLeft = std::min(std::min(P[0].x(), P[1].x()), std::min(P[2].x(), P[3].x())); bounds.fTop = std::min(std::min(P[0].y(), P[1].y()), std::min(P[2].y(), P[3].y())); bounds.fRight = std::max(std::max(P[0].x(), P[1].x()), std::max(P[2].x(), P[3].x())); bounds.fBottom = std::max(std::max(P[0].y(), P[1].y()), std::max(P[2].y(), P[3].y())); return bounds; } SkPoint chopped[7]; SkChopCubicAt(P, chopped, .5f); SkRect bounds = calc_tight_cubic_bounds(chopped, depth - 1); bounds.join(calc_tight_cubic_bounds(chopped+3, depth - 1)); return bounds; } enum class FillMode { kCenter, kScale }; // This is a compilation of cubics that have given strokers grief. Feel free to add more. class TrickyCubicStrokesGM : public skiagm::GM { public: TrickyCubicStrokesGM() {} protected: SkString onShortName() override { return SkString("trickycubicstrokes"); } SkISize onISize() override { return SkISize::Make(kNumCols * kCellSize, kNumRows * kCellSize); } void onOnceBeforeDraw() override { fStrokePaint.setAntiAlias(true); fStrokePaint.setStrokeWidth(kStrokeWidth); fStrokePaint.setColor(SK_ColorGREEN); fStrokePaint.setStyle(SkPaint::kStroke_Style); } void onDraw(SkCanvas* canvas) override { canvas->clear(SK_ColorBLACK); for (size_t i = 0; i < SK_ARRAY_COUNT(kTrickyCubics); ++i) { const auto& trickyCubic = kTrickyCubics[i]; SkPoint p[7]; memcpy(p, trickyCubic.fPoints, sizeof(SkPoint) * 4); for (int j = 0; j < 4; ++j) { p[j] *= trickyCubic.fScale; } this->drawStroke(canvas, p, i, trickyCubic.fFillMode); } } void drawStroke(SkCanvas* canvas, const SkPoint p[4], int cellID, CellFillMode fillMode) { auto cellRect = SkRect::MakeXYWH((cellID % kNumCols) * kCellSize, (cellID / kNumCols) * kCellSize, kCellSize, kCellSize); SkRect strokeBounds = calc_tight_cubic_bounds(p); strokeBounds.outset(kStrokeWidth, kStrokeWidth); SkMatrix matrix; if (fillMode == CellFillMode::kStretch) { matrix.setRectToRect(strokeBounds, cellRect, SkMatrix::kCenter_ScaleToFit); } else { matrix.setTranslate(cellRect.x() + kStrokeWidth + (cellRect.width() - strokeBounds.width()) / 2, cellRect.y() + kStrokeWidth + (cellRect.height() - strokeBounds.height()) / 2); } SkAutoCanvasRestore acr(canvas, true); canvas->concat(matrix); fStrokePaint.setStrokeWidth(kStrokeWidth / matrix.getMaxScale()); canvas->drawPath(SkPath().moveTo(p[0]).cubicTo(p[1], p[2], p[3]), fStrokePaint); } private: SkPaint fStrokePaint; typedef GM INHERITED; }; DEF_GM( return new TrickyCubicStrokesGM; ) <|endoftext|>
<commit_before>// KMail startup and initialize code // Author: Stefan Taferner <[email protected]> #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <sys/types.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <kuniqueapplication.h> #include <klocale.h> #include <kglobal.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> #include <knotifyclient.h> #include <dcopclient.h> #include <kcrash.h> #include "kmkernel.h" //control center #undef Status // stupid X headers #include "kmailIface_stub.h" // to call control center of master kmail #include <kaboutdata.h> #include "kmversion.h" // OLD about text. This is horrbly outdated. /*const char* aboutText = "KMail [" KMAIL_VERSION "] by\n\n" "Stefan Taferner <[email protected]>,\n" "Markus Wbben <[email protected]>\n\n" "based on the work of:\n" "Lynx <[email protected]>,\n" "Stephan Meyer <[email protected]>,\n" "and the above authors.\n\n" "This program is covered by the GPL.\n\n" "Please send bugreports to [email protected]"; */ static KCmdLineOptions kmoptions[] = { { "s", 0 , 0 }, { "subject <subject>", I18N_NOOP("Set subject of msg."), 0 }, { "c", 0 , 0 }, { "cc <address>", I18N_NOOP("Send CC: to 'address'."), 0 }, { "b", 0 , 0 }, { "bcc <address>", I18N_NOOP("Send BCC: to 'addres'."), 0 }, { "h", 0 , 0 }, { "header <header>", I18N_NOOP("Add 'header' to msg."), 0 }, { "msg <file>", I18N_NOOP("Read msg-body from 'file'."), 0 }, { "body <text>", I18N_NOOP("Set body of msg."), 0 }, { "attach <url>", I18N_NOOP("Add an attachment to the mail, this can be repeated"), 0 }, { "check", I18N_NOOP("Check for new mail only."), 0 }, { "composer", I18N_NOOP("Open only composer window."), 0 }, { "+[address]", I18N_NOOP("Send msg to 'address'."), 0 }, // { "+[file]", I18N_NOOP("Show message from file 'file'."), 0 }, { 0, 0, 0} }; //----------------------------------------------------------------------------- extern "C" { static void setSignalHandler(void (*handler)(int)); // Crash recovery signal handler static void signalHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); ::exit(-1); // } // Crash recovery signal handler static void crashHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); // Return to DrKonqi. } //----------------------------------------------------------------------------- static void setSignalHandler(void (*handler)(int)) { signal(SIGKILL, handler); signal(SIGTERM, handler); signal(SIGHUP, handler); KCrash::setEmergencySaveFunction(crashHandler); } } //----------------------------------------------------------------------------- class KMailApplication : public KUniqueApplication { public: KMailApplication() : KUniqueApplication() { }; virtual int newInstance(); void commitData(QSessionManager& sm) { kernel->notClosedByUser(); KApplication::commitData( sm ); } }; int KMailApplication::newInstance() { QString to, cc, bcc, subj, body; KURL messageFile = QString::null; KURL::List attachURLs; bool mailto = false; bool checkMail = false; //bool viewOnly = false; // process args: KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->getOption("subject")) { mailto = true; subj = QString::fromLocal8Bit(args->getOption("subject")); } if (args->getOption("cc")) { mailto = true; cc = QString::fromLocal8Bit(args->getOption("cc")); } if (args->getOption("bcc")) { mailto = true; bcc = QString::fromLocal8Bit(args->getOption("bcc")); } if (args->getOption("msg")) { mailto = true; messageFile = QString::fromLocal8Bit(args->getOption("msg")); } if (args->getOption("body")) { mailto = true; body = QString::fromLocal8Bit(args->getOption("body")); } QCStringList attachList = args->getOptionList("attach"); if (!attachList.isEmpty()) { mailto = true; for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it ) attachURLs += KURL( QString::fromLocal8Bit( *it ) ); } if (args->isSet("composer")) mailto = true; if (args->isSet("check")) checkMail = true; for(int i= 0; i < args->count(); i++) { if (!to.isEmpty()) to += ", "; if (strncasecmp(args->arg(i),"mailto:",7)==0) to += args->arg(i); else to += args->arg(i); mailto = true; } args->clear(); if (!kapp->isRestored()) kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs); return 0; } int main(int argc, char *argv[]) { // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging // a bit harder: You should pass --nofork as commandline argument when using // a debugger. In gdb you can do this by typing "set args --nofork" before // typing "run". KAboutData about("kmail", I18N_NOOP("KMail"), KMAIL_VERSION, I18N_NOOP("The KDE Email client."), KAboutData::License_GPL, I18N_NOOP("(c) 1997-2001, The KMail developers"), 0, "http://kmail.kde.org"); about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "[email protected]" ); about.addAuthor( "Don Sanders", I18N_NOOP("Core developer and former maintainer"), "[email protected]" ); about.addAuthor( "Stefan Taferner ", I18N_NOOP("Original author"), "[email protected]" ); about.addAuthor( "Ingo Kl\303\266cker", I18N_NOOP("Encryption"), "[email protected]" ); about.addAuthor( "Marc Mutz", I18N_NOOP("Core developer"), "[email protected]" ); about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "[email protected]" ); about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "[email protected]" ); about.addAuthor( "Toyohiro Asukai", 0, "[email protected]" ); about.addAuthor( "Waldo Bastian", 0, "[email protected]" ); about.addAuthor( "Carsten Burghardt", 0, "[email protected]" ); about.addAuthor( "Steven Brown", 0, "[email protected]" ); about.addAuthor( "Cristi Dumitrescu", 0, "[email protected]" ); about.addAuthor( "Philippe Fremy", 0, "[email protected]" ); about.addAuthor( "Kurt Granroth", 0, "[email protected]" ); about.addAuthor( "Heiko Hund", 0, "[email protected]" ); about.addAuthor( "Igor Janssen", 0, "[email protected]" ); about.addAuthor( "Matt Johnston", 0, "[email protected]" ); about.addAuthor( "Christer Kaivo-oja", 0, "[email protected]" ); about.addAuthor( "Lars Knoll", 0, "[email protected]" ); about.addAuthor( "J. Nick Koston", 0, "[email protected]" ); about.addAuthor( "Stephan Kulow", 0, "[email protected]" ); about.addAuthor( "Guillaume Laurent", 0, "[email protected]" ); about.addAuthor( "Sam Magnuson", 0, "[email protected]" ); about.addAuthor( "Laurent Montel", 0, "[email protected]" ); about.addAuthor( "Matt Newell", 0, "[email protected]" ); about.addAuthor( "Denis Perchine", 0, "[email protected]" ); about.addAuthor( "Samuel Penn", 0, "[email protected]" ); about.addAuthor( "Carsten Pfeiffer", 0, "[email protected]" ); about.addAuthor( "Sven Radej", 0, "[email protected]" ); about.addAuthor( "Mark Roberts", 0, "[email protected]" ); about.addAuthor( "Wolfgang Rohdewald", 0, "[email protected]" ); about.addAuthor( "Espen Sand", 0, "[email protected]" ); about.addAuthor( "George Staikos", 0, "[email protected]" ); about.addAuthor( "Jason Stephenson", 0, "[email protected]" ); about.addAuthor( "Jacek Stolarczyk", 0, "[email protected]" ); about.addAuthor( "Roberto S. Teixeira", 0, "[email protected]" ); about.addAuthor( "Ronen Tzur", 0, "[email protected]" ); about.addAuthor( "Mario Weilguni", 0, "[email protected]" ); about.addAuthor( "Wynn Wilkes", 0, "[email protected]" ); about.addAuthor( "Robert D. Williams", 0, "[email protected]" ); about.addAuthor( "Markus Wuebben", 0, "[email protected]" ); about.addAuthor( "Thorsten Zachmann", 0, "[email protected]" ); about.addAuthor( "Karl-Heinz Zimmer", 0, "[email protected]" ); KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options if (!KMailApplication::start()) return 0; KMailApplication app; KGlobal::locale()->insertCatalogue("libkdenetwork"); KSimpleConfig config(locateLocal("appdata", "lock")); int oldPid = config.readNumEntry("pid", -1); if (oldPid != -1 && kill(oldPid, 0) != -1) { QString msg = i18n("Only one instance of KMail can be run at " "any one time. It is already running on a different display " "with PID %1.").arg(oldPid); KNotifyClient::userEvent( msg, KNotifyClient::Messagebox, KNotifyClient::Error ); fprintf(stderr, "*** KMail is already running with PID %d\n", oldPid); return 1; } config.writeEntry("pid", getpid()); config.sync(); kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet //local, do the init KMKernel kmailKernel; kmailKernel.init(); kapp->dcopClient()->setDefaultObject( kmailKernel.objId() ); // and session management kmailKernel.doSessionManagement(); // any dead letters? kmailKernel.recoverDeadLetters(); setSignalHandler(signalHandler); kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests. // Go! int ret = kapp->exec(); // clean up kmailKernel.cleanup(); config.writeEntry("pid", -1); config.sync(); return ret; } <commit_msg>Fixed "malformed URL" error message when clicking on a mailto: link.<commit_after>// KMail startup and initialize code // Author: Stefan Taferner <[email protected]> #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <sys/types.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <kuniqueapplication.h> #include <klocale.h> #include <kglobal.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> #include <knotifyclient.h> #include <dcopclient.h> #include <kcrash.h> #include "kmkernel.h" //control center #undef Status // stupid X headers #include "kmailIface_stub.h" // to call control center of master kmail #include <kaboutdata.h> #include "kmversion.h" // OLD about text. This is horrbly outdated. /*const char* aboutText = "KMail [" KMAIL_VERSION "] by\n\n" "Stefan Taferner <[email protected]>,\n" "Markus Wbben <[email protected]>\n\n" "based on the work of:\n" "Lynx <[email protected]>,\n" "Stephan Meyer <[email protected]>,\n" "and the above authors.\n\n" "This program is covered by the GPL.\n\n" "Please send bugreports to [email protected]"; */ static KCmdLineOptions kmoptions[] = { { "s", 0 , 0 }, { "subject <subject>", I18N_NOOP("Set subject of msg."), 0 }, { "c", 0 , 0 }, { "cc <address>", I18N_NOOP("Send CC: to 'address'."), 0 }, { "b", 0 , 0 }, { "bcc <address>", I18N_NOOP("Send BCC: to 'addres'."), 0 }, { "h", 0 , 0 }, { "header <header>", I18N_NOOP("Add 'header' to msg."), 0 }, { "msg <file>", I18N_NOOP("Read msg-body from 'file'."), 0 }, { "body <text>", I18N_NOOP("Set body of msg."), 0 }, { "attach <url>", I18N_NOOP("Add an attachment to the mail, this can be repeated"), 0 }, { "check", I18N_NOOP("Check for new mail only."), 0 }, { "composer", I18N_NOOP("Open only composer window."), 0 }, { "+[address]", I18N_NOOP("Send msg to 'address'."), 0 }, // { "+[file]", I18N_NOOP("Show message from file 'file'."), 0 }, { 0, 0, 0} }; //----------------------------------------------------------------------------- extern "C" { static void setSignalHandler(void (*handler)(int)); // Crash recovery signal handler static void signalHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); ::exit(-1); // } // Crash recovery signal handler static void crashHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); // Return to DrKonqi. } //----------------------------------------------------------------------------- static void setSignalHandler(void (*handler)(int)) { signal(SIGKILL, handler); signal(SIGTERM, handler); signal(SIGHUP, handler); KCrash::setEmergencySaveFunction(crashHandler); } } //----------------------------------------------------------------------------- class KMailApplication : public KUniqueApplication { public: KMailApplication() : KUniqueApplication() { }; virtual int newInstance(); void commitData(QSessionManager& sm) { kernel->notClosedByUser(); KApplication::commitData( sm ); } }; int KMailApplication::newInstance() { QString to, cc, bcc, subj, body; KURL messageFile = QString::null; KURL::List attachURLs; bool mailto = false; bool checkMail = false; //bool viewOnly = false; // process args: KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->getOption("subject")) { mailto = true; subj = QString::fromLocal8Bit(args->getOption("subject")); } if (args->getOption("cc")) { mailto = true; cc = QString::fromLocal8Bit(args->getOption("cc")); } if (args->getOption("bcc")) { mailto = true; bcc = QString::fromLocal8Bit(args->getOption("bcc")); } if (args->getOption("msg")) { mailto = true; messageFile = QString::fromLocal8Bit(args->getOption("msg")); } if (args->getOption("body")) { mailto = true; body = QString::fromLocal8Bit(args->getOption("body")); } QCStringList attachList = args->getOptionList("attach"); if (!attachList.isEmpty()) { mailto = true; for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it ) if ( !(*it).isEmpty() ) attachURLs += KURL( QString::fromLocal8Bit( *it ) ); } if (args->isSet("composer")) mailto = true; if (args->isSet("check")) checkMail = true; for(int i= 0; i < args->count(); i++) { if (!to.isEmpty()) to += ", "; if (strncasecmp(args->arg(i),"mailto:",7)==0) to += args->arg(i); else to += args->arg(i); mailto = true; } args->clear(); if (!kapp->isRestored()) kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs); return 0; } int main(int argc, char *argv[]) { // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging // a bit harder: You should pass --nofork as commandline argument when using // a debugger. In gdb you can do this by typing "set args --nofork" before // typing "run". KAboutData about("kmail", I18N_NOOP("KMail"), KMAIL_VERSION, I18N_NOOP("The KDE Email client."), KAboutData::License_GPL, I18N_NOOP("(c) 1997-2001, The KMail developers"), 0, "http://kmail.kde.org"); about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "[email protected]" ); about.addAuthor( "Don Sanders", I18N_NOOP("Core developer and former maintainer"), "[email protected]" ); about.addAuthor( "Stefan Taferner ", I18N_NOOP("Original author"), "[email protected]" ); about.addAuthor( "Ingo Kl\303\266cker", I18N_NOOP("Encryption"), "[email protected]" ); about.addAuthor( "Marc Mutz", I18N_NOOP("Core developer"), "[email protected]" ); about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "[email protected]" ); about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "[email protected]" ); about.addAuthor( "Toyohiro Asukai", 0, "[email protected]" ); about.addAuthor( "Waldo Bastian", 0, "[email protected]" ); about.addAuthor( "Carsten Burghardt", 0, "[email protected]" ); about.addAuthor( "Steven Brown", 0, "[email protected]" ); about.addAuthor( "Cristi Dumitrescu", 0, "[email protected]" ); about.addAuthor( "Philippe Fremy", 0, "[email protected]" ); about.addAuthor( "Kurt Granroth", 0, "[email protected]" ); about.addAuthor( "Heiko Hund", 0, "[email protected]" ); about.addAuthor( "Igor Janssen", 0, "[email protected]" ); about.addAuthor( "Matt Johnston", 0, "[email protected]" ); about.addAuthor( "Christer Kaivo-oja", 0, "[email protected]" ); about.addAuthor( "Lars Knoll", 0, "[email protected]" ); about.addAuthor( "J. Nick Koston", 0, "[email protected]" ); about.addAuthor( "Stephan Kulow", 0, "[email protected]" ); about.addAuthor( "Guillaume Laurent", 0, "[email protected]" ); about.addAuthor( "Sam Magnuson", 0, "[email protected]" ); about.addAuthor( "Laurent Montel", 0, "[email protected]" ); about.addAuthor( "Matt Newell", 0, "[email protected]" ); about.addAuthor( "Denis Perchine", 0, "[email protected]" ); about.addAuthor( "Samuel Penn", 0, "[email protected]" ); about.addAuthor( "Carsten Pfeiffer", 0, "[email protected]" ); about.addAuthor( "Sven Radej", 0, "[email protected]" ); about.addAuthor( "Mark Roberts", 0, "[email protected]" ); about.addAuthor( "Wolfgang Rohdewald", 0, "[email protected]" ); about.addAuthor( "Espen Sand", 0, "[email protected]" ); about.addAuthor( "George Staikos", 0, "[email protected]" ); about.addAuthor( "Jason Stephenson", 0, "[email protected]" ); about.addAuthor( "Jacek Stolarczyk", 0, "[email protected]" ); about.addAuthor( "Roberto S. Teixeira", 0, "[email protected]" ); about.addAuthor( "Ronen Tzur", 0, "[email protected]" ); about.addAuthor( "Mario Weilguni", 0, "[email protected]" ); about.addAuthor( "Wynn Wilkes", 0, "[email protected]" ); about.addAuthor( "Robert D. Williams", 0, "[email protected]" ); about.addAuthor( "Markus Wuebben", 0, "[email protected]" ); about.addAuthor( "Thorsten Zachmann", 0, "[email protected]" ); about.addAuthor( "Karl-Heinz Zimmer", 0, "[email protected]" ); KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options if (!KMailApplication::start()) return 0; KMailApplication app; KGlobal::locale()->insertCatalogue("libkdenetwork"); KSimpleConfig config(locateLocal("appdata", "lock")); int oldPid = config.readNumEntry("pid", -1); if (oldPid != -1 && kill(oldPid, 0) != -1) { QString msg = i18n("Only one instance of KMail can be run at " "any one time. It is already running on a different display " "with PID %1.").arg(oldPid); KNotifyClient::userEvent( msg, KNotifyClient::Messagebox, KNotifyClient::Error ); fprintf(stderr, "*** KMail is already running with PID %d\n", oldPid); return 1; } config.writeEntry("pid", getpid()); config.sync(); kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet //local, do the init KMKernel kmailKernel; kmailKernel.init(); kapp->dcopClient()->setDefaultObject( kmailKernel.objId() ); // and session management kmailKernel.doSessionManagement(); // any dead letters? kmailKernel.recoverDeadLetters(); setSignalHandler(signalHandler); kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests. // Go! int ret = kapp->exec(); // clean up kmailKernel.cleanup(); config.writeEntry("pid", -1); config.sync(); return ret; } <|endoftext|>
<commit_before>/* Copyright 2015-2018 Egor Yusov * * 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 * * 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 OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "pch.h" #include "GLContextAndroid.h" #include "EngineGLAttribs.h" #ifndef EGL_CONTEXT_MINOR_VERSION_KHR #define EGL_CONTEXT_MINOR_VERSION_KHR 0x30FB #endif #ifndef EGL_CONTEXT_MAJOR_VERSION_KHR #define EGL_CONTEXT_MAJOR_VERSION_KHR EGL_CONTEXT_CLIENT_VERSION #endif namespace Diligent { bool GLContext::InitEGLSurface() { display_ = eglGetDisplay( EGL_DEFAULT_DISPLAY ); if( display_ == EGL_NO_DISPLAY ) { LOG_ERROR_AND_THROW( "No EGL display found" ); } auto success = eglInitialize( display_, 0, 0 ); if( !success ) { LOG_ERROR_AND_THROW( "Failed to initialise EGL" ); } /* * Here specify the attributes of the desired configuration. * Below, we select an EGLConfig with at least 8 bits per color * component compatible with on-screen windows */ color_size_ = 8; depth_size_ = 24; const EGLint attribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, //Request opengl ES2.0 EGL_SURFACE_TYPE, EGL_WINDOW_BIT, //EGL_COLORSPACE, EGL_COLORSPACE_sRGB, // does not work EGL_BLUE_SIZE, color_size_, EGL_GREEN_SIZE, color_size_, EGL_RED_SIZE, color_size_, EGL_ALPHA_SIZE, color_size_, EGL_DEPTH_SIZE, depth_size_, //EGL_SAMPLE_BUFFERS , 1, //EGL_SAMPLES , 4, EGL_NONE }; // Get a list of EGL frame buffer configurations that match specified attributes EGLint num_configs; success = eglChooseConfig( display_, attribs, &config_, 1, &num_configs ); if( !success ) { LOG_ERROR_AND_THROW( "Failed to choose config" ); } if( !num_configs ) { //Fall back to 16bit depth buffer depth_size_ = 16; const EGLint attribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, //Request opengl ES2.0 EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, color_size_, EGL_GREEN_SIZE, color_size_, EGL_RED_SIZE, color_size_, EGL_ALPHA_SIZE, color_size_, EGL_DEPTH_SIZE, depth_size_, EGL_NONE }; success = eglChooseConfig( display_, attribs, &config_, 1, &num_configs ); if( !success ) { LOG_ERROR_AND_THROW( "Failed to choose 16-bit depth config" ); } } if( !num_configs ) { LOG_ERROR_AND_THROW( "Unable to retrieve EGL config" ); } LOG_INFO_MESSAGE("Chosen EGL config: ", color_size_, " bit color, ", depth_size_, " bit depth"); surface_ = eglCreateWindowSurface( display_, config_, window_, NULL ); if( surface_ == EGL_NO_SURFACE ) { LOG_ERROR_AND_THROW( "Failed to create EGLSurface" ); } eglQuerySurface( display_, surface_, EGL_WIDTH, &screen_width_ ); eglQuerySurface( display_, surface_, EGL_HEIGHT, &screen_height_ ); /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). * As soon as we picked a EGLConfig, we can safely reconfigure the * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ EGLint format; eglGetConfigAttrib( display_, config_, EGL_NATIVE_VISUAL_ID, &format ); ANativeWindow_setBuffersGeometry( window_, 0, 0, format ); return true; } bool GLContext::InitEGLContext() { major_version_ = 3; minor_version_ = 1; const EGLint context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, major_version_, EGL_CONTEXT_MINOR_VERSION_KHR, minor_version_, EGL_NONE }; LOG_INFO_MESSAGE( "contextAttribs: ", context_attribs[0], ' ', context_attribs[1], '\n' ); LOG_INFO_MESSAGE( "contextAttribs: ", context_attribs[2], ' ', context_attribs[3], '\n' ); context_ = eglCreateContext( display_, config_, NULL, context_attribs ); if( context_ == EGL_NO_CONTEXT ) { LOG_ERROR_AND_THROW( "Failed to create EGLContext" ); } if( eglMakeCurrent( display_, surface_, surface_, context_ ) == EGL_FALSE ) { LOG_ERROR_AND_THROW( "Unable to eglMakeCurrent" ); } context_valid_ = true; return true; } void GLContext::AttachToCurrentEGLContext() { if( eglGetCurrentContext() == EGL_NO_CONTEXT ) { LOG_ERROR_AND_THROW( "Failed to attach to EGLContext: no active context" ); } context_valid_ = true; glGetIntegerv( GL_MAJOR_VERSION, &major_version_ ); glGetIntegerv( GL_MINOR_VERSION, &minor_version_ ); } GLContext::NativeGLContextType GLContext::GetCurrentNativeGLContext() { return eglGetCurrentContext(); } void GLContext::InitGLES() { if( gles_initialized_ ) return; // //Initialize OpenGL ES 3 if available // const char* versionStr = (const char*)glGetString( GL_VERSION ); LOG_INFO_MESSAGE( "GL Version: ", versionStr, '\n' ); LoadGLFunctions(); // When GL_FRAMEBUFFER_SRGB is enabled, and if the destination image is in the sRGB colorspace // then OpenGL will assume the shader's output is in the linear RGB colorspace. It will therefore // convert the output from linear RGB to sRGB. // Any writes to images that are not in the sRGB format should not be affected. // Thus this setting should be just set once and left that way glEnable(GL_FRAMEBUFFER_SRGB); if( glGetError() != GL_NO_ERROR ) LOG_ERROR_MESSAGE("Failed to enable SRGB framebuffers"); gles_initialized_ = true; } bool GLContext::Init( ANativeWindow* window ) { if( egl_context_initialized_ ) return true; // //Initialize EGL // window_ = window; if (window != nullptr) { InitEGLSurface(); InitEGLContext(); } else { AttachToCurrentEGLContext(); } InitGLES(); egl_context_initialized_ = true; return true; } GLContext::GLContext( const EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ) : display_( EGL_NO_DISPLAY ), surface_( EGL_NO_SURFACE ), context_( EGL_NO_CONTEXT ), egl_context_initialized_( false ), gles_initialized_( false ), major_version_(0), minor_version_(0) { auto *NativeWindow = reinterpret_cast<ANativeWindow*>(InitAttribs.pNativeWndHandle); Init( NativeWindow ); FillDeviceCaps(DeviceCaps); #if 0 // Creates table of supported extensions strings extensions.clear(); string tmp; sint32 begin, end; tmp = string( (char*)glGetString( GL_EXTENSIONS ) ); begin = 0; end = tmp.find( ' ', 0 ); DEBUG_PRINT( _L( "Checking Extensions" ) ); while( end != string::npos ) { DEBUG_PRINT( (_L( "extension %s" )), tmp.substr( begin, end - begin ).c_str() ); extensions.insert( extensions.end(), tmp.substr( begin, end - begin ) ); begin = end + 1; end = tmp.find( ' ', begin ); } if( supportExtension( "GL_INTEL_tessellation" ) ) { glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)eglGetProcAddress( "glPatchParameteri" ); DEBUG_PRINT( _L( "%s = %p" ), "glPatchParameteri", (void*)glPatchParameteri ); glPatchParameterfv = (PFNGLPATCHPARAMETERFVPROC)eglGetProcAddress( "glPatchParameterfv" ); DEBUG_PRINT( _L( "%s = %p" ), "glPatchParameterfv", (void*)glPatchParameterfv ); } //if(supportExtension("GL_INTEL_compute_shader")) { glDispatchCompute = (PFNGLDISPATCHCOMPUTEPROC)eglGetProcAddress( "glDispatchCompute" ); DEBUG_PRINT( _L( "%s = %p" ), "glDispatchCompute", (void*)glDispatchCompute ); glBindImageTexture = (PFNGLBINDIMAGETEXTUREPROC)eglGetProcAddress( "glBindImageTexture" ); DEBUG_PRINT( _L( "%s = %p" ), "glBindImageTexture", (void*)glBindImageTexture ); } #endif } GLContext::~GLContext() { Terminate(); } void GLContext::SwapBuffers() { bool b = eglSwapBuffers( display_, surface_ ); if( !b ) { EGLint err = eglGetError(); if( err == EGL_BAD_SURFACE ) { //Recreate surface InitEGLSurface(); //return EGL_SUCCESS; //Still consider glContext is valid } else if( err == EGL_CONTEXT_LOST || err == EGL_BAD_CONTEXT ) { //Context has been lost!! context_valid_ = false; Terminate(); InitEGLContext(); } //return err; } //return EGL_SUCCESS; } void GLContext::Terminate() { if( display_ != EGL_NO_DISPLAY ) { eglMakeCurrent( display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT ); if( context_ != EGL_NO_CONTEXT ) { eglDestroyContext( display_, context_ ); } if( surface_ != EGL_NO_SURFACE ) { eglDestroySurface( display_, surface_ ); } eglTerminate( display_ ); } display_ = EGL_NO_DISPLAY; context_ = EGL_NO_CONTEXT; surface_ = EGL_NO_SURFACE; context_valid_ = false; } EGLint GLContext::Resume( ANativeWindow* window ) { if( egl_context_initialized_ == false ) { Init( window ); return EGL_SUCCESS; } //Create surface window_ = window; surface_ = eglCreateWindowSurface( display_, config_, window_, NULL ); int32_t new_screen_width = 0; int32_t new_screen_height = 0; eglQuerySurface( display_, surface_, EGL_WIDTH, &new_screen_width ); eglQuerySurface( display_, surface_, EGL_HEIGHT, &new_screen_height ); if( new_screen_width != screen_width_ || new_screen_height != screen_height_ ) { //Screen resized LOG_INFO_MESSAGE( "Screen resized\n" ); } if( eglMakeCurrent( display_, surface_, surface_, context_ ) == EGL_TRUE ) return EGL_SUCCESS; EGLint err = eglGetError(); LOG_WARNING_MESSAGE( "Unable to eglMakeCurrent ", err, '\n' ); if( err == EGL_CONTEXT_LOST ) { //Recreate context LOG_INFO_MESSAGE( "Re-creating egl context\n" ); InitEGLContext(); } else { //Recreate surface Terminate(); InitEGLSurface(); InitEGLContext(); } return err; } void GLContext::Suspend() { if( surface_ != EGL_NO_SURFACE ) { eglDestroySurface( display_, surface_ ); surface_ = EGL_NO_SURFACE; } } bool GLContext::Invalidate() { Terminate(); egl_context_initialized_ = false; return true; } void GLContext::FillDeviceCaps( DeviceCaps &DeviceCaps ) { DeviceCaps.DevType = DeviceType::OpenGLES; DeviceCaps.MajorVersion = major_version_; DeviceCaps.MinorVersion = minor_version_; bool IsGLES31OrAbove = (major_version_ >= 4 || (major_version_ == 3 && minor_version_ >= 1) ); DeviceCaps.bSeparableProgramSupported = IsGLES31OrAbove; DeviceCaps.bIndirectRenderingSupported = IsGLES31OrAbove; auto &SamCaps = DeviceCaps.SamCaps; SamCaps.bBorderSamplingModeSupported = GL_TEXTURE_BORDER_COLOR && IsGLES31OrAbove; SamCaps.bAnisotropicFilteringSupported = GL_TEXTURE_MAX_ANISOTROPY_EXT && IsGLES31OrAbove; SamCaps.bLODBiasSupported = GL_TEXTURE_LOD_BIAS && IsGLES31OrAbove; auto &TexCaps = DeviceCaps.TexCaps; TexCaps.bTexture1DSupported = False; // Not supported in GLES 3.1 TexCaps.bTexture1DArraySupported = False; // Not supported in GLES 3.1 TexCaps.bTexture2DMSSupported = IsGLES31OrAbove; TexCaps.bTexture2DMSArraySupported = False; // Not supported in GLES 3.1 TexCaps.bTextureViewSupported = False; // Not supported in GLES 3.1 TexCaps.bCubemapArraysSupported = False; // Not supported in GLES 3.1 DeviceCaps.bMultithreadedResourceCreationSupported = False; } } <commit_msg>Fixed Android crash when SwapBuffers() is called after Suspend()<commit_after>/* Copyright 2015-2018 Egor Yusov * * 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 * * 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 OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "pch.h" #include "GLContextAndroid.h" #include "EngineGLAttribs.h" #ifndef EGL_CONTEXT_MINOR_VERSION_KHR #define EGL_CONTEXT_MINOR_VERSION_KHR 0x30FB #endif #ifndef EGL_CONTEXT_MAJOR_VERSION_KHR #define EGL_CONTEXT_MAJOR_VERSION_KHR EGL_CONTEXT_CLIENT_VERSION #endif namespace Diligent { bool GLContext::InitEGLSurface() { display_ = eglGetDisplay( EGL_DEFAULT_DISPLAY ); if( display_ == EGL_NO_DISPLAY ) { LOG_ERROR_AND_THROW( "No EGL display found" ); } auto success = eglInitialize( display_, 0, 0 ); if( !success ) { LOG_ERROR_AND_THROW( "Failed to initialise EGL" ); } /* * Here specify the attributes of the desired configuration. * Below, we select an EGLConfig with at least 8 bits per color * component compatible with on-screen windows */ color_size_ = 8; depth_size_ = 24; const EGLint attribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, //Request opengl ES2.0 EGL_SURFACE_TYPE, EGL_WINDOW_BIT, //EGL_COLORSPACE, EGL_COLORSPACE_sRGB, // does not work EGL_BLUE_SIZE, color_size_, EGL_GREEN_SIZE, color_size_, EGL_RED_SIZE, color_size_, EGL_ALPHA_SIZE, color_size_, EGL_DEPTH_SIZE, depth_size_, //EGL_SAMPLE_BUFFERS , 1, //EGL_SAMPLES , 4, EGL_NONE }; // Get a list of EGL frame buffer configurations that match specified attributes EGLint num_configs; success = eglChooseConfig( display_, attribs, &config_, 1, &num_configs ); if( !success ) { LOG_ERROR_AND_THROW( "Failed to choose config" ); } if( !num_configs ) { //Fall back to 16bit depth buffer depth_size_ = 16; const EGLint attribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, //Request opengl ES2.0 EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, color_size_, EGL_GREEN_SIZE, color_size_, EGL_RED_SIZE, color_size_, EGL_ALPHA_SIZE, color_size_, EGL_DEPTH_SIZE, depth_size_, EGL_NONE }; success = eglChooseConfig( display_, attribs, &config_, 1, &num_configs ); if( !success ) { LOG_ERROR_AND_THROW( "Failed to choose 16-bit depth config" ); } } if( !num_configs ) { LOG_ERROR_AND_THROW( "Unable to retrieve EGL config" ); } LOG_INFO_MESSAGE("Chosen EGL config: ", color_size_, " bit color, ", depth_size_, " bit depth"); surface_ = eglCreateWindowSurface( display_, config_, window_, NULL ); if( surface_ == EGL_NO_SURFACE ) { LOG_ERROR_AND_THROW( "Failed to create EGLSurface" ); } eglQuerySurface( display_, surface_, EGL_WIDTH, &screen_width_ ); eglQuerySurface( display_, surface_, EGL_HEIGHT, &screen_height_ ); /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). * As soon as we picked a EGLConfig, we can safely reconfigure the * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ EGLint format; eglGetConfigAttrib( display_, config_, EGL_NATIVE_VISUAL_ID, &format ); ANativeWindow_setBuffersGeometry( window_, 0, 0, format ); return true; } bool GLContext::InitEGLContext() { major_version_ = 3; minor_version_ = 1; const EGLint context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, major_version_, EGL_CONTEXT_MINOR_VERSION_KHR, minor_version_, EGL_NONE }; LOG_INFO_MESSAGE( "contextAttribs: ", context_attribs[0], ' ', context_attribs[1], '\n' ); LOG_INFO_MESSAGE( "contextAttribs: ", context_attribs[2], ' ', context_attribs[3], '\n' ); context_ = eglCreateContext( display_, config_, NULL, context_attribs ); if( context_ == EGL_NO_CONTEXT ) { LOG_ERROR_AND_THROW( "Failed to create EGLContext" ); } if( eglMakeCurrent( display_, surface_, surface_, context_ ) == EGL_FALSE ) { LOG_ERROR_AND_THROW( "Unable to eglMakeCurrent" ); } context_valid_ = true; return true; } void GLContext::AttachToCurrentEGLContext() { if( eglGetCurrentContext() == EGL_NO_CONTEXT ) { LOG_ERROR_AND_THROW( "Failed to attach to EGLContext: no active context" ); } context_valid_ = true; glGetIntegerv( GL_MAJOR_VERSION, &major_version_ ); glGetIntegerv( GL_MINOR_VERSION, &minor_version_ ); } GLContext::NativeGLContextType GLContext::GetCurrentNativeGLContext() { return eglGetCurrentContext(); } void GLContext::InitGLES() { if( gles_initialized_ ) return; // //Initialize OpenGL ES 3 if available // const char* versionStr = (const char*)glGetString( GL_VERSION ); LOG_INFO_MESSAGE( "GL Version: ", versionStr, '\n' ); LoadGLFunctions(); // When GL_FRAMEBUFFER_SRGB is enabled, and if the destination image is in the sRGB colorspace // then OpenGL will assume the shader's output is in the linear RGB colorspace. It will therefore // convert the output from linear RGB to sRGB. // Any writes to images that are not in the sRGB format should not be affected. // Thus this setting should be just set once and left that way glEnable(GL_FRAMEBUFFER_SRGB); if( glGetError() != GL_NO_ERROR ) LOG_ERROR_MESSAGE("Failed to enable SRGB framebuffers"); gles_initialized_ = true; } bool GLContext::Init( ANativeWindow* window ) { if( egl_context_initialized_ ) return true; // //Initialize EGL // window_ = window; if (window != nullptr) { InitEGLSurface(); InitEGLContext(); } else { AttachToCurrentEGLContext(); } InitGLES(); egl_context_initialized_ = true; return true; } GLContext::GLContext( const EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ) : display_( EGL_NO_DISPLAY ), surface_( EGL_NO_SURFACE ), context_( EGL_NO_CONTEXT ), egl_context_initialized_( false ), gles_initialized_( false ), major_version_(0), minor_version_(0) { auto *NativeWindow = reinterpret_cast<ANativeWindow*>(InitAttribs.pNativeWndHandle); Init( NativeWindow ); FillDeviceCaps(DeviceCaps); #if 0 // Creates table of supported extensions strings extensions.clear(); string tmp; sint32 begin, end; tmp = string( (char*)glGetString( GL_EXTENSIONS ) ); begin = 0; end = tmp.find( ' ', 0 ); DEBUG_PRINT( _L( "Checking Extensions" ) ); while( end != string::npos ) { DEBUG_PRINT( (_L( "extension %s" )), tmp.substr( begin, end - begin ).c_str() ); extensions.insert( extensions.end(), tmp.substr( begin, end - begin ) ); begin = end + 1; end = tmp.find( ' ', begin ); } if( supportExtension( "GL_INTEL_tessellation" ) ) { glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)eglGetProcAddress( "glPatchParameteri" ); DEBUG_PRINT( _L( "%s = %p" ), "glPatchParameteri", (void*)glPatchParameteri ); glPatchParameterfv = (PFNGLPATCHPARAMETERFVPROC)eglGetProcAddress( "glPatchParameterfv" ); DEBUG_PRINT( _L( "%s = %p" ), "glPatchParameterfv", (void*)glPatchParameterfv ); } //if(supportExtension("GL_INTEL_compute_shader")) { glDispatchCompute = (PFNGLDISPATCHCOMPUTEPROC)eglGetProcAddress( "glDispatchCompute" ); DEBUG_PRINT( _L( "%s = %p" ), "glDispatchCompute", (void*)glDispatchCompute ); glBindImageTexture = (PFNGLBINDIMAGETEXTUREPROC)eglGetProcAddress( "glBindImageTexture" ); DEBUG_PRINT( _L( "%s = %p" ), "glBindImageTexture", (void*)glBindImageTexture ); } #endif } GLContext::~GLContext() { Terminate(); } void GLContext::SwapBuffers() { if(surface_ == EGL_NO_SURFACE) { LOG_WARNING_MESSAGE("No EGL surface when swapping buffers. This happens when SwapBuffers() is called after Suspend(). The operation will be ignored."); return; } bool b = eglSwapBuffers( display_, surface_ ); if( !b ) { EGLint err = eglGetError(); if( err == EGL_BAD_SURFACE ) { LOG_INFO_MESSAGE("EGL surface has been lost. Attempting to recreate"); InitEGLSurface(); //return EGL_SUCCESS; //Still consider glContext is valid } else if( err == EGL_CONTEXT_LOST || err == EGL_BAD_CONTEXT ) { //Context has been lost!! context_valid_ = false; Terminate(); InitEGLContext(); } //return err; } //return EGL_SUCCESS; } void GLContext::Terminate() { if( display_ != EGL_NO_DISPLAY ) { eglMakeCurrent( display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT ); if( context_ != EGL_NO_CONTEXT ) { eglDestroyContext( display_, context_ ); } if( surface_ != EGL_NO_SURFACE ) { eglDestroySurface( display_, surface_ ); } eglTerminate( display_ ); } display_ = EGL_NO_DISPLAY; context_ = EGL_NO_CONTEXT; surface_ = EGL_NO_SURFACE; context_valid_ = false; } EGLint GLContext::Resume( ANativeWindow* window ) { LOG_INFO_MESSAGE( "Resuming gl context\n" ); if( egl_context_initialized_ == false ) { Init( window ); return EGL_SUCCESS; } //Create surface window_ = window; surface_ = eglCreateWindowSurface( display_, config_, window_, NULL ); int32_t new_screen_width = 0; int32_t new_screen_height = 0; eglQuerySurface( display_, surface_, EGL_WIDTH, &new_screen_width ); eglQuerySurface( display_, surface_, EGL_HEIGHT, &new_screen_height ); if( new_screen_width != screen_width_ || new_screen_height != screen_height_ ) { //Screen resized LOG_INFO_MESSAGE( "Screen resized\n" ); } if( eglMakeCurrent( display_, surface_, surface_, context_ ) == EGL_TRUE ) return EGL_SUCCESS; EGLint err = eglGetError(); LOG_WARNING_MESSAGE( "Unable to eglMakeCurrent ", err, '\n' ); if( err == EGL_CONTEXT_LOST ) { //Recreate context LOG_INFO_MESSAGE( "Re-creating egl context\n" ); InitEGLContext(); } else { //Recreate surface LOG_INFO_MESSAGE( "Re-creating egl context and surface\n" ); Terminate(); InitEGLSurface(); InitEGLContext(); } return err; } void GLContext::Suspend() { LOG_INFO_MESSAGE( "Suspending gl context\n" ); if( surface_ != EGL_NO_SURFACE ) { LOG_INFO_MESSAGE( "Destroying egl surface\n" ); eglDestroySurface( display_, surface_ ); surface_ = EGL_NO_SURFACE; } } bool GLContext::Invalidate() { LOG_INFO_MESSAGE( "Invalidating gl context\n" ); Terminate(); egl_context_initialized_ = false; return true; } void GLContext::FillDeviceCaps( DeviceCaps &DeviceCaps ) { DeviceCaps.DevType = DeviceType::OpenGLES; DeviceCaps.MajorVersion = major_version_; DeviceCaps.MinorVersion = minor_version_; bool IsGLES31OrAbove = (major_version_ >= 4 || (major_version_ == 3 && minor_version_ >= 1) ); DeviceCaps.bSeparableProgramSupported = IsGLES31OrAbove; DeviceCaps.bIndirectRenderingSupported = IsGLES31OrAbove; auto &SamCaps = DeviceCaps.SamCaps; SamCaps.bBorderSamplingModeSupported = GL_TEXTURE_BORDER_COLOR && IsGLES31OrAbove; SamCaps.bAnisotropicFilteringSupported = GL_TEXTURE_MAX_ANISOTROPY_EXT && IsGLES31OrAbove; SamCaps.bLODBiasSupported = GL_TEXTURE_LOD_BIAS && IsGLES31OrAbove; auto &TexCaps = DeviceCaps.TexCaps; TexCaps.bTexture1DSupported = False; // Not supported in GLES 3.1 TexCaps.bTexture1DArraySupported = False; // Not supported in GLES 3.1 TexCaps.bTexture2DMSSupported = IsGLES31OrAbove; TexCaps.bTexture2DMSArraySupported = False; // Not supported in GLES 3.1 TexCaps.bTextureViewSupported = False; // Not supported in GLES 3.1 TexCaps.bCubemapArraysSupported = False; // Not supported in GLES 3.1 DeviceCaps.bMultithreadedResourceCreationSupported = False; } } <|endoftext|>
<commit_before>#include "TestRunner.h" #include <atomic> #include <future> #include <limits> #include <mutex> #include <random> #include <vector> #include "DefaultReporter.h" #include "Fact.h" #include "TestCollection.h" #include "TestDetails.h" #include "xUnitAssert.h" namespace { class ActiveTests { public: struct TestInstance { TestInstance(const xUnitpp::TestDetails &testDetails, int id, int groupId, int groupSize, std::function<void()> test) : testDetails(testDetails) , id(id) , groupId(groupId) , groupSize(groupSize) , test(test) { } TestInstance(const TestInstance &other) : testDetails(other.testDetails) , id(other.id) , groupId(other.groupId) , groupSize(other.groupSize) , test(other.test) { } TestInstance(TestInstance &&other) { swap(*this, other); } TestInstance &operator =(TestInstance other) { swap(*this, other); return *this; } friend void swap(TestInstance &ti0, TestInstance &ti1) { using std::swap; swap(ti0.testDetails, ti1.testDetails); swap(ti0.id, ti1.id); swap(ti0.groupId, ti1.groupId); swap(ti0.groupSize, ti1.groupSize); swap(ti0.test, ti1.test); } xUnitpp::TestDetails testDetails; size_t id; size_t groupId; size_t groupSize; std::function<void()> test; }; ActiveTests(const std::vector<xUnitpp::Fact> &facts, const std::vector<xUnitpp::Theory> &theories, const std::string &suite) { size_t id = 0; size_t groupId = 0; for (auto &fact : facts) { if (suite == "" || fact.TestDetails().Suite == suite) { mTests.emplace_back(TestInstance(fact.TestDetails(), ++id, ++groupId, 1, fact.Test())); } } for (auto &theorySet : theories) { if (suite == "" || theorySet.TestDetails().Suite == suite) { ++groupId; for (auto &theory : theorySet.Theories()) { mTests.emplace_back(TestInstance(theorySet.TestDetails(), ++id, groupId, theorySet.Theories().size(), theory)); } } } std::shuffle(mTests.begin(), mTests.end(), std::default_random_engine(std::random_device()())); } std::vector<TestInstance>::iterator begin() { return mTests.begin(); } std::vector<TestInstance>::iterator end() { return mTests.end(); } private: std::vector<TestInstance> mTests; }; } namespace xUnitpp { class TestRunner::Impl { public: Impl(std::function<void(const TestDetails &)> onTestStart, std::function<void(const TestDetails &, const std::string &)> onTestFailure, std::function<void(const TestDetails &, std::chrono::milliseconds)> onTestFinish, std::function<void(int, int, int, std::chrono::milliseconds)> onAllTestsComplete) : mOnTestStart(onTestStart) , mOnTestFailure(onTestFailure) , mOnTestFinish(onTestFinish) , mOnAllTestsComplete(onAllTestsComplete) { } void OnTestStart(const TestDetails &details) { std::lock_guard<std::mutex> guard(mStartMtx); mOnTestStart(details); } void OnTestFailure(const TestDetails &details, const std::string &message) { std::lock_guard<std::mutex> guard(mFailureMtx); mOnTestFailure(details, message); } void OnTestFinish(const TestDetails &details, std::chrono::milliseconds time) { std::lock_guard<std::mutex> guard(mFinishMtx); mOnTestFinish(details, time); } void OnAllTestsComplete(int total, int skipped, int failed, std::chrono::milliseconds totalTime) { mOnAllTestsComplete(total, skipped, failed, totalTime); } private: std::function<void(const TestDetails &)> mOnTestStart; std::function<void(const TestDetails &, const std::string &)> mOnTestFailure; std::function<void(const TestDetails &, std::chrono::milliseconds)> mOnTestFinish; std::function<void(int, int, int, std::chrono::milliseconds)> mOnAllTestsComplete; std::mutex mStartMtx; std::mutex mFailureMtx; std::mutex mFinishMtx; }; size_t RunAllTests(const std::string &suite) { return RunAllTests(suite, std::chrono::milliseconds::zero()); } size_t RunAllTests(std::chrono::milliseconds maxTestRunTime) { return RunAllTests("", maxTestRunTime); } size_t RunAllTests(const std::string &suite, std::chrono::milliseconds maxTestRunTime, size_t maxConcurrent) { return TestRunner(&DefaultReporter::ReportStart, &DefaultReporter::ReportFailure, &DefaultReporter::ReportFinish, &DefaultReporter::ReportAllTestsComplete) .RunTests(TestCollection::Facts(), TestCollection::Theories(), suite, maxTestRunTime, maxConcurrent); } TestRunner::TestRunner(std::function<void(const TestDetails &)> onTestStart, std::function<void(const TestDetails &, const std::string &)> onTestFailure, std::function<void(const TestDetails &, std::chrono::milliseconds)> onTestFinish, std::function<void(int, int, int, std::chrono::milliseconds)> onAllTestsComplete) : mImpl(new Impl(onTestStart, onTestFailure, onTestFinish, onAllTestsComplete)) { } size_t TestRunner::RunTests(const std::vector<Fact> &facts, const std::vector<Theory> &theories, const std::string &suite, std::chrono::milliseconds maxTestRunTime, size_t maxConcurrent) { auto timeStart = std::chrono::system_clock::now(); ActiveTests activeTests(facts, theories, suite); if (maxConcurrent == 0) { maxConcurrent = std::numeric_limits<decltype(maxConcurrent)>::max(); } class ThreadCounter { public: ThreadCounter(size_t maxThreads) : maxThreads(maxThreads) , activeThreads(0) { } void operator++() { std::unique_lock<std::mutex> lock(mtx); condition.wait(lock, [&]() { return activeThreads < maxThreads; }); ++activeThreads; } void operator--() { std::lock_guard<std::mutex> guard(mtx); --activeThreads; } private: size_t maxThreads; size_t activeThreads; std::mutex mtx; std::condition_variable condition; } threadCounter(maxConcurrent); std::atomic<size_t> failedTests = 0; std::vector<std::future<void>> futures; for (auto &test : activeTests) { futures.push_back(std::async([&]() { struct CounterGuard { CounterGuard(ThreadCounter &tc) : tc(tc) { ++tc; } ~CounterGuard() { --tc; } private: ThreadCounter &tc; } counterGuard(threadCounter); auto actualTest = [&](bool reportEnd) -> TimeStamp { TimeStamp testStart; try { mImpl->OnTestStart(test.testDetails); testStart = Clock::now(); test.test(); } catch (std::exception &e) { mImpl->OnTestFailure(test.testDetails, e.what()); ++failedTests; } catch (...) { mImpl->OnTestFailure(test.testDetails, "Unknown exception caught: test has crashed"); ++failedTests; } if (reportEnd) { mImpl->OnTestFinish(test.testDetails, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - testStart)); } return testStart; }; auto testTimeLimit = test.testDetails.TimeLimit; if (testTimeLimit < std::chrono::milliseconds::zero()) { testTimeLimit = maxTestRunTime; } if (testTimeLimit > std::chrono::milliseconds::zero()) { // // note that forcing a test to run in under a certain amount of time is inherently fragile // there's no guarantee that a thread, once started, actually gets `maxTestRunTime` milliseconds of CPU TimeStamp testStart; std::mutex m; std::unique_lock<std::mutex> gate(m); auto threadStarted = std::make_shared<std::condition_variable>(); std::thread timedRunner([&, threadStarted]() { m.lock(); m.unlock(); testStart = actualTest(false); threadStarted->notify_all(); }); timedRunner.detach(); if (threadStarted->wait_for(gate, testTimeLimit) == std::cv_status::timeout) { mImpl->OnTestFailure(test.testDetails, "Test failed to complete within " + std::to_string(testTimeLimit.count()) + " milliseconds."); mImpl->OnTestFinish(test.testDetails, testTimeLimit); ++failedTests; } else { mImpl->OnTestFinish(test.testDetails, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - testStart)); } } else { actualTest(true); } })); } for (auto &test : futures) { test.get(); } mImpl->OnAllTestsComplete(futures.size(), failedTests, 0, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timeStart)); return -failedTests; } } <commit_msg>removing a warning about negating an unsigned<commit_after>#include "TestRunner.h" #include <atomic> #include <future> #include <limits> #include <mutex> #include <random> #include <vector> #include "DefaultReporter.h" #include "Fact.h" #include "TestCollection.h" #include "TestDetails.h" #include "xUnitAssert.h" namespace { class ActiveTests { public: struct TestInstance { TestInstance(const xUnitpp::TestDetails &testDetails, int id, int groupId, int groupSize, std::function<void()> test) : testDetails(testDetails) , id(id) , groupId(groupId) , groupSize(groupSize) , test(test) { } TestInstance(const TestInstance &other) : testDetails(other.testDetails) , id(other.id) , groupId(other.groupId) , groupSize(other.groupSize) , test(other.test) { } TestInstance(TestInstance &&other) { swap(*this, other); } TestInstance &operator =(TestInstance other) { swap(*this, other); return *this; } friend void swap(TestInstance &ti0, TestInstance &ti1) { using std::swap; swap(ti0.testDetails, ti1.testDetails); swap(ti0.id, ti1.id); swap(ti0.groupId, ti1.groupId); swap(ti0.groupSize, ti1.groupSize); swap(ti0.test, ti1.test); } xUnitpp::TestDetails testDetails; size_t id; size_t groupId; size_t groupSize; std::function<void()> test; }; ActiveTests(const std::vector<xUnitpp::Fact> &facts, const std::vector<xUnitpp::Theory> &theories, const std::string &suite) { size_t id = 0; size_t groupId = 0; for (auto &fact : facts) { if (suite == "" || fact.TestDetails().Suite == suite) { mTests.emplace_back(TestInstance(fact.TestDetails(), ++id, ++groupId, 1, fact.Test())); } } for (auto &theorySet : theories) { if (suite == "" || theorySet.TestDetails().Suite == suite) { ++groupId; for (auto &theory : theorySet.Theories()) { mTests.emplace_back(TestInstance(theorySet.TestDetails(), ++id, groupId, theorySet.Theories().size(), theory)); } } } std::shuffle(mTests.begin(), mTests.end(), std::default_random_engine(std::random_device()())); } std::vector<TestInstance>::iterator begin() { return mTests.begin(); } std::vector<TestInstance>::iterator end() { return mTests.end(); } private: std::vector<TestInstance> mTests; }; } namespace xUnitpp { class TestRunner::Impl { public: Impl(std::function<void(const TestDetails &)> onTestStart, std::function<void(const TestDetails &, const std::string &)> onTestFailure, std::function<void(const TestDetails &, std::chrono::milliseconds)> onTestFinish, std::function<void(int, int, int, std::chrono::milliseconds)> onAllTestsComplete) : mOnTestStart(onTestStart) , mOnTestFailure(onTestFailure) , mOnTestFinish(onTestFinish) , mOnAllTestsComplete(onAllTestsComplete) { } void OnTestStart(const TestDetails &details) { std::lock_guard<std::mutex> guard(mStartMtx); mOnTestStart(details); } void OnTestFailure(const TestDetails &details, const std::string &message) { std::lock_guard<std::mutex> guard(mFailureMtx); mOnTestFailure(details, message); } void OnTestFinish(const TestDetails &details, std::chrono::milliseconds time) { std::lock_guard<std::mutex> guard(mFinishMtx); mOnTestFinish(details, time); } void OnAllTestsComplete(int total, int skipped, int failed, std::chrono::milliseconds totalTime) { mOnAllTestsComplete(total, skipped, failed, totalTime); } private: std::function<void(const TestDetails &)> mOnTestStart; std::function<void(const TestDetails &, const std::string &)> mOnTestFailure; std::function<void(const TestDetails &, std::chrono::milliseconds)> mOnTestFinish; std::function<void(int, int, int, std::chrono::milliseconds)> mOnAllTestsComplete; std::mutex mStartMtx; std::mutex mFailureMtx; std::mutex mFinishMtx; }; size_t RunAllTests(const std::string &suite) { return RunAllTests(suite, std::chrono::milliseconds::zero()); } size_t RunAllTests(std::chrono::milliseconds maxTestRunTime) { return RunAllTests("", maxTestRunTime); } size_t RunAllTests(const std::string &suite, std::chrono::milliseconds maxTestRunTime, size_t maxConcurrent) { return TestRunner(&DefaultReporter::ReportStart, &DefaultReporter::ReportFailure, &DefaultReporter::ReportFinish, &DefaultReporter::ReportAllTestsComplete) .RunTests(TestCollection::Facts(), TestCollection::Theories(), suite, maxTestRunTime, maxConcurrent); } TestRunner::TestRunner(std::function<void(const TestDetails &)> onTestStart, std::function<void(const TestDetails &, const std::string &)> onTestFailure, std::function<void(const TestDetails &, std::chrono::milliseconds)> onTestFinish, std::function<void(int, int, int, std::chrono::milliseconds)> onAllTestsComplete) : mImpl(new Impl(onTestStart, onTestFailure, onTestFinish, onAllTestsComplete)) { } size_t TestRunner::RunTests(const std::vector<Fact> &facts, const std::vector<Theory> &theories, const std::string &suite, std::chrono::milliseconds maxTestRunTime, size_t maxConcurrent) { auto timeStart = std::chrono::system_clock::now(); ActiveTests activeTests(facts, theories, suite); if (maxConcurrent == 0) { maxConcurrent = std::numeric_limits<decltype(maxConcurrent)>::max(); } class ThreadCounter { public: ThreadCounter(size_t maxThreads) : maxThreads(maxThreads) , activeThreads(0) { } void operator++() { std::unique_lock<std::mutex> lock(mtx); condition.wait(lock, [&]() { return activeThreads < maxThreads; }); ++activeThreads; } void operator--() { std::lock_guard<std::mutex> guard(mtx); --activeThreads; } private: size_t maxThreads; size_t activeThreads; std::mutex mtx; std::condition_variable condition; } threadCounter(maxConcurrent); std::atomic<int> failedTests = 0; std::vector<std::future<void>> futures; for (auto &test : activeTests) { futures.push_back(std::async([&]() { struct CounterGuard { CounterGuard(ThreadCounter &tc) : tc(tc) { ++tc; } ~CounterGuard() { --tc; } private: ThreadCounter &tc; } counterGuard(threadCounter); auto actualTest = [&](bool reportEnd) -> TimeStamp { TimeStamp testStart; try { mImpl->OnTestStart(test.testDetails); testStart = Clock::now(); test.test(); } catch (std::exception &e) { mImpl->OnTestFailure(test.testDetails, e.what()); ++failedTests; } catch (...) { mImpl->OnTestFailure(test.testDetails, "Unknown exception caught: test has crashed"); ++failedTests; } if (reportEnd) { mImpl->OnTestFinish(test.testDetails, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - testStart)); } return testStart; }; auto testTimeLimit = test.testDetails.TimeLimit; if (testTimeLimit < std::chrono::milliseconds::zero()) { testTimeLimit = maxTestRunTime; } if (testTimeLimit > std::chrono::milliseconds::zero()) { // // note that forcing a test to run in under a certain amount of time is inherently fragile // there's no guarantee that a thread, once started, actually gets `maxTestRunTime` milliseconds of CPU TimeStamp testStart; std::mutex m; std::unique_lock<std::mutex> gate(m); auto threadStarted = std::make_shared<std::condition_variable>(); std::thread timedRunner([&, threadStarted]() { m.lock(); m.unlock(); testStart = actualTest(false); threadStarted->notify_all(); }); timedRunner.detach(); if (threadStarted->wait_for(gate, testTimeLimit) == std::cv_status::timeout) { mImpl->OnTestFailure(test.testDetails, "Test failed to complete within " + std::to_string(testTimeLimit.count()) + " milliseconds."); mImpl->OnTestFinish(test.testDetails, testTimeLimit); ++failedTests; } else { mImpl->OnTestFinish(test.testDetails, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - testStart)); } } else { actualTest(true); } })); } for (auto &test : futures) { test.get(); } mImpl->OnAllTestsComplete(futures.size(), failedTests, 0, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timeStart)); return -failedTests; } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #ifndef _Stroika_Foundation_Execution_Sleep_inl_ #define _Stroika_Foundation_Execution_Sleep_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #if qPlatform_Windows #include <windows.h> #elif qPlatform_POSIX #include <time.h> #include <unistd.h> #endif #include "../Debug/Assertions.h" namespace Stroika::Foundation::Execution { //redeclare to avoid having to include Thread code void CheckForThreadInterruption (); /* ******************************************************************************** ******************************** Execution::Sleep ****************************** ******************************************************************************** */ inline void Sleep (Time::DurationSecondsType seconds2Wait, Time::DurationSecondsType* remainingInSleep) { Require (seconds2Wait >= 0.0); RequireNotNull (remainingInSleep); // else call the over overload CheckForThreadInterruption (); // @todo lose if the #if stuff and use just if constexpr (but not working on msvc) #if qPlatform_POSIX if constexpr (qPlatform_POSIX) { const long kNanoSecondsPerSecond = 1000L * 1000L * 1000L; timespec ts; ts.tv_sec = static_cast<time_t> (seconds2Wait); ts.tv_nsec = static_cast<long> (kNanoSecondsPerSecond * (seconds2Wait - ts.tv_sec)); Assert (0 <= ts.tv_nsec and ts.tv_nsec < kNanoSecondsPerSecond); timespec nextTS; if (::nanosleep (&ts, &nextTS) == 0) { *remainingInSleep = 0; } else { *remainingInSleep = nextTS.tv_sec + static_cast<Time::DurationSecondsType> (ts.tv_nsec) / kNanoSecondsPerSecond; } } #elif qPlatform_Windows if constexpr (qPlatform_Windows) { Time::DurationSecondsType tc = Time::GetTickCount (); if (::SleepEx (static_cast<int> (seconds2Wait * 1000), true) == 0) { *remainingInSleep = 0; } else { Time::DurationSecondsType remaining = (tc + seconds2Wait) - Time::GetTickCount (); if (remaining < 0) { remaining = 0; } *remainingInSleep = remaining; } } #else AssertNotImplemented (); #endif Ensure (*remainingInSleep <= seconds2Wait); Ensure (*remainingInSleep >= 0); CheckForThreadInterruption (); } /* ******************************************************************************** *************************** Execution::SleepUntil ****************************** ******************************************************************************** */ inline void SleepUntil (Time::DurationSecondsType untilTickCount) { Time::DurationSecondsType waitMoreSeconds = untilTickCount - Time::GetTickCount (); if (waitMoreSeconds <= 0) { CheckForThreadInterruption (); } else { Sleep (waitMoreSeconds); } } } #endif /*_Stroika_Foundation_Execution_Sleep_inl_*/ <commit_msg>Execution::Sleep() - WeakAsserts() and workaround for bad values sometimes generated by nanosleep() on linux (under windows WSL - not clarly illegal)<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #ifndef _Stroika_Foundation_Execution_Sleep_inl_ #define _Stroika_Foundation_Execution_Sleep_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #if qPlatform_Windows #include <windows.h> #elif qPlatform_POSIX #include <time.h> #include <unistd.h> #endif #include "../Debug/Assertions.h" namespace Stroika::Foundation::Execution { //redeclare to avoid having to include Thread code void CheckForThreadInterruption (); /* ******************************************************************************** ******************************** Execution::Sleep ****************************** ******************************************************************************** */ inline void Sleep (Time::DurationSecondsType seconds2Wait, Time::DurationSecondsType* remainingInSleep) { Require (seconds2Wait >= 0.0); RequireNotNull (remainingInSleep); // else call the over overload CheckForThreadInterruption (); // @todo lose if the #if stuff and use just if constexpr (but not working on msvc) #if qPlatform_POSIX if constexpr (qPlatform_POSIX) { const long kNanoSecondsPerSecond = 1000L * 1000L * 1000L; timespec ts; ts.tv_sec = static_cast<time_t> (seconds2Wait); ts.tv_nsec = static_cast<long> (kNanoSecondsPerSecond * (seconds2Wait - ts.tv_sec)); Assert (0 <= ts.tv_sec); Assert (0 <= ts.tv_nsec and ts.tv_nsec < kNanoSecondsPerSecond); timespec nextTS; if (::nanosleep (&ts, &nextTS) == 0) { *remainingInSleep = 0; } else { // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/time.h.html doesn't clearly document allowed range for timespec // https://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html doesn't clearly document allowed range for output timespec // value (can it go negative) // On WSL 1 (WinVer 1909) nextTS sometimes goes negative (or blows up to be very large?), so check) WeakAssert (0 <= ts.tv_nsec and ts.tv_nsec < kNanoSecondsPerSecond); // not sure this should happen? - log for now... -- LGP 2020-05-29 WeakAssert (nextTS.tv_sec >= 0); // "" if ((nextTS.tv_sec < 0) or not(0 <= ts.tv_nsec and ts.tv_nsec < kNanoSecondsPerSecond)) { *remainingInSleep = 0; } else { *remainingInSleep = nextTS.tv_sec + static_cast<Time::DurationSecondsType> (ts.tv_nsec) / kNanoSecondsPerSecond; } if (*remainingInSleep <= seconds2Wait) { DbgTrace (L"*remainingInSleep <= seconds2Wait failure: remainingInSleep=%f, seconds2Wait=%f, nextTS.tv_sec=%ld, ts.tv_nsec=%ld, ts.tv_sec=%ld, nextTS.tv_nsec=%ld", *remainingInSleep, seconds2Wait, nextTS.tv_sec, ts.tv_nsec, ts.tv_sec, nextTS.tv_nsec); } } } #elif qPlatform_Windows if constexpr (qPlatform_Windows) { Time::DurationSecondsType tc = Time::GetTickCount (); if (::SleepEx (static_cast<int> (seconds2Wait * 1000), true) == 0) { *remainingInSleep = 0; } else { Time::DurationSecondsType remaining = (tc + seconds2Wait) - Time::GetTickCount (); if (remaining < 0) { remaining = 0; } *remainingInSleep = remaining; } } #else AssertNotImplemented (); #endif Ensure (*remainingInSleep <= seconds2Wait); Ensure (*remainingInSleep >= 0); CheckForThreadInterruption (); } /* ******************************************************************************** *************************** Execution::SleepUntil ****************************** ******************************************************************************** */ inline void SleepUntil (Time::DurationSecondsType untilTickCount) { Time::DurationSecondsType waitMoreSeconds = untilTickCount - Time::GetTickCount (); if (waitMoreSeconds <= 0) { CheckForThreadInterruption (); } else { Sleep (waitMoreSeconds); } } } #endif /*_Stroika_Foundation_Execution_Sleep_inl_*/ <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #ifndef _Stroika_Foundation_Traversal_Range_inl_ #define _Stroika_Foundation_Traversal_Range_inl_ #include "../Debug/Assertions.h" #include "../Math/Overlap.h" namespace Stroika { namespace Foundation { namespace Traversal { /* ******************************************************************************** RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE> ******************************************************************************** */ #if qCompilerAndStdLib_constexpr_Buggy template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE> const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound = MIN; template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE> const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound = MAX; #else template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE> constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound; template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE> constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound; #endif /* ******************************************************************************** ****************** RangeTraits::DefaultRangeTraits<T> ************************** ******************************************************************************** */ #if qCompilerAndStdLib_constexpr_Buggy template <typename T> const T RangeTraits::DefaultRangeTraits<T>::kLowerBound = numeric_limits<T>::lowest (); template <typename T> const T RangeTraits::DefaultRangeTraits<T>::kUpperBound = numeric_limits<T>::max (); #else template <typename T> constexpr T RangeTraits::DefaultRangeTraits<T>::kLowerBound; template <typename T> constexpr T RangeTraits::DefaultRangeTraits<T>::kUpperBound; #endif /* ******************************************************************************** ***************************** Range<T, TRAITS> ********************************* ******************************************************************************** */ template <typename T, typename TRAITS> #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif inline Range<T, TRAITS>::Range () : Range (TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Ensure (empty ()); #endif } template <typename T, typename TRAITS> template <typename T2, typename TRAITS2> #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif inline Range<T, TRAITS>::Range (const Range<T2, TRAITS>& src) : Range (src.GetLowerBound (), src.GetUpperBound (), src.GetLowerBoundOpenness (), src.GetUpperBoundOpenness ()) { } template <typename T, typename TRAITS> #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif inline Range<T, TRAITS>::Range (const T& begin, const T& end) : Range (begin, end, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness) { } template <typename T, typename TRAITS> inline Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end) : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness) { } template <typename T, typename TRAITS> #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif inline Range<T, TRAITS>::Range (Openness lhsOpen, Openness rhsOpen) : fBegin_ (TRAITS::kUpperBound) , fEnd_ (TRAITS::kLowerBound) , fBeginOpenness_ (lhsOpen) , fEndOpenness_ (rhsOpen) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Ensure (empty ()); #endif } template <typename T, typename TRAITS> #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif inline Range<T, TRAITS>::Range (const T& begin, const T& end, Openness lhsOpen, Openness rhsOpen) : fBegin_ (begin) , fEnd_ (end) , fBeginOpenness_ (lhsOpen) , fEndOpenness_ (rhsOpen) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (TRAITS::kLowerBound <= TRAITS::kUpperBound); // always required for class Require (TRAITS::kLowerBound <= begin); Require (begin <= end); Require (end <= TRAITS::kUpperBound); #endif } template <typename T, typename TRAITS> inline Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end, Openness lhsOpen, Openness rhsOpen) : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, lhsOpen, rhsOpen) { } template <typename T, typename TRAITS> inline constexpr Range<T, TRAITS> Range<T, TRAITS>::FullRange () { return Range<T, TRAITS> ( TraitsType::kLowerBound, TraitsType::kUpperBound, TraitsType::kLowerBoundOpenness, TraitsType::kUpperBoundOpenness ); } template <typename T, typename TRAITS> inline constexpr bool Range<T, TRAITS>::empty () const { #if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy return fBegin_ > fEnd_ ? true : ((fBegin_ == fEnd_) ? (fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen) : false ) ; #else if (fBegin_ > fEnd_) { // internal hack done in Range<T, TRAITS>::Range() - empty range - otherwise not possible to create this situation return true; } else if (fBegin_ == fEnd_) { return fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen; } return false; #endif } template <typename T, typename TRAITS> inline constexpr typename Range<T, TRAITS>::UnsignedDifferenceType Range<T, TRAITS>::GetDistanceSpanned () const { #if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy return empty () ? static_cast<UnsignedDifferenceType> (0) : (fEnd_ - fBegin_) ; #else if (empty ()) { return static_cast<UnsignedDifferenceType> (0); } return fEnd_ - fBegin_; #endif } template <typename T, typename TRAITS> inline constexpr T Range<T, TRAITS>::GetMidpoint () const { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (not empty ()); #endif return GetLowerBound () + GetDistanceSpanned () / 2; } template <typename T, typename TRAITS> inline constexpr bool Range<T, TRAITS>::Contains (const T& r) const { #if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy return empty () ? false : ( (fBegin_ < r and r < fEnd_) or (fBeginOpenness_ == Openness::eClosed and r == fBegin_) or (fEndOpenness_ == Openness::eClosed and r == fEnd_) ) ; #else if (empty ()) { return false; } if (fBegin_ < r and r < fEnd_) { return true; } if (fBeginOpenness_ == Openness::eClosed and r == fBegin_) { return true; } if (fEndOpenness_ == Openness::eClosed and r == fEnd_) { return true; } return false; #endif } template <typename T, typename TRAITS> template <typename T2, typename TRAITS2> inline bool Range<T, TRAITS>::Equals (const Range<T2, TRAITS2>& rhs) const { if (empty ()) { return rhs.empty (); } return fBegin_ == rhs.fBegin_ and fEnd_ == rhs.fEnd_ and fBeginOpenness_ == rhs.fBeginOpenness_ and fBeginOpenness_ == rhs.fBeginOpenness_; } #if 0 template <typename T, typename TRAITS> bool Range<T, TRAITS>::Overlaps (const Range<T, TRAITS>& rhs) const { /* * @todo RETHINK - because Range has semantics of exclude end - make sure overlap usuage * here is correct??? Unsure -- LGP 2013-07-05 */ return Math::Overlaps ( pair<T, T> (fBegin_, fEnd_), pair<T, T> (rhs.fBegin_, rhs.fEnd_) ); } #endif template <typename T, typename TRAITS> template <typename T2, typename TRAITS2> bool Range<T, TRAITS>::Intersects (const Range<T2, TRAITS2>& rhs) const { if (empty () or rhs.empty ()) { return false; } T l = max (fBegin_, rhs.GetLowerBound ()); T r = min (fEnd_, rhs.GetUpperBound ()); if (l < r) { return true; } else if (l == r) { // must check if the end that has 'l' for each Range that that end is closed. Contains() // is a shortcut for that return Contains (l) and rhs.Contains (l); } else { return false; } } template <typename T, typename TRAITS> Range<T, TRAITS> Range<T, TRAITS>::Intersection (const Range<T, TRAITS>& rhs) const { if (empty () or rhs.empty ()) { return Range (); } T l = max (fBegin_, rhs.fBegin_); T r = min (fEnd_, rhs.fEnd_); if (l <= r) { // lhs/rhs ends are closed iff BOTH lhs/rhs contains that point Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen; Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen; return Range<T, TRAITS> (l, r, lhsO, rhsO); } else { return Range (); } } template <typename T, typename TRAITS> Range<T, TRAITS> Range<T, TRAITS>::UnionBounds (const Range<T, TRAITS>& rhs) const { if (empty ()) { return rhs; } if (rhs.empty ()) { return *this; } T l = min (GetLowerBound (), rhs.GetLowerBound ()); T r = max (GetUpperBound (), rhs.GetUpperBound ()); Range<T, TRAITS> result; if (l <= r) { // lhs/rhs ends are closed iff BOTH lhs/rhs contains that point Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen; Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen; result = Range<T, TRAITS> (l, r, lhsO, rhsO); } Ensure (result.GetLowerBound () <= GetLowerBound ()); Ensure (result.GetLowerBound () <= GetUpperBound ()); Ensure (result.GetLowerBound () <= rhs.GetLowerBound ()); Ensure (result.GetLowerBound () <= rhs.GetUpperBound ()); Ensure (result.GetUpperBound () >= GetLowerBound ()); Ensure (result.GetUpperBound () >= GetUpperBound ()); Ensure (result.GetUpperBound () >= rhs.GetLowerBound ()); Ensure (result.GetUpperBound () >= rhs.GetUpperBound ()); return result; } template <typename T, typename TRAITS> inline constexpr T Range<T, TRAITS>::GetLowerBound () const { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (not empty ()); #endif return fBegin_; } template <typename T, typename TRAITS> inline constexpr Openness Range<T, TRAITS>::GetLowerBoundOpenness () const { return fBeginOpenness_; } template <typename T, typename TRAITS> inline constexpr T Range<T, TRAITS>::GetUpperBound () const { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (not empty ()); #endif return fEnd_; } template <typename T, typename TRAITS> inline constexpr Openness Range<T, TRAITS>::GetUpperBoundOpenness () const { return fEndOpenness_; } template <typename T, typename TRAITS> template <typename... ARGS> inline Characters::String Range<T, TRAITS>::Format (ARGS&& ... args) const { if (GetLowerBound () == GetUpperBound ()) { return GetLowerBound ().Format (forward<ARGS> (args)...); } else { return GetLowerBound ().Format (forward<ARGS> (args)...) + L" - " + GetUpperBound ().Format (forward<ARGS> (args)...); } } template <typename T, typename TRAITS> inline bool Range<T, TRAITS>::operator== (const Range<T, TRAITS>& rhs) const { return Equals (rhs); } template <typename T, typename TRAITS> inline bool Range<T, TRAITS>::operator!= (const Range<T, TRAITS>& rhs) const { return not Equals (rhs); } } } } #endif /* _Stroika_Foundation_Traversal_Range_inl_ */ <commit_msg>fixed #defines so asserts happen in range CTOR if qCompilerAndStdLib_constexpr_Buggy<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #ifndef _Stroika_Foundation_Traversal_Range_inl_ #define _Stroika_Foundation_Traversal_Range_inl_ #include "../Debug/Assertions.h" #include "../Math/Overlap.h" namespace Stroika { namespace Foundation { namespace Traversal { /* ******************************************************************************** RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE> ******************************************************************************** */ #if qCompilerAndStdLib_constexpr_Buggy template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE> const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound = MIN; template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE> const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound = MAX; #else template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE> constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound; template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE> constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound; #endif /* ******************************************************************************** ****************** RangeTraits::DefaultRangeTraits<T> ************************** ******************************************************************************** */ #if qCompilerAndStdLib_constexpr_Buggy template <typename T> const T RangeTraits::DefaultRangeTraits<T>::kLowerBound = numeric_limits<T>::lowest (); template <typename T> const T RangeTraits::DefaultRangeTraits<T>::kUpperBound = numeric_limits<T>::max (); #else template <typename T> constexpr T RangeTraits::DefaultRangeTraits<T>::kLowerBound; template <typename T> constexpr T RangeTraits::DefaultRangeTraits<T>::kUpperBound; #endif /* ******************************************************************************** ***************************** Range<T, TRAITS> ********************************* ******************************************************************************** */ template <typename T, typename TRAITS> #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif inline Range<T, TRAITS>::Range () : Range (TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Ensure (empty ()); #endif } template <typename T, typename TRAITS> template <typename T2, typename TRAITS2> #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif inline Range<T, TRAITS>::Range (const Range<T2, TRAITS>& src) : Range (src.GetLowerBound (), src.GetUpperBound (), src.GetLowerBoundOpenness (), src.GetUpperBoundOpenness ()) { } template <typename T, typename TRAITS> #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif inline Range<T, TRAITS>::Range (const T& begin, const T& end) : Range (begin, end, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness) { } template <typename T, typename TRAITS> inline Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end) : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness) { } template <typename T, typename TRAITS> #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif inline Range<T, TRAITS>::Range (Openness lhsOpen, Openness rhsOpen) : fBegin_ (TRAITS::kUpperBound) , fEnd_ (TRAITS::kLowerBound) , fBeginOpenness_ (lhsOpen) , fEndOpenness_ (rhsOpen) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Ensure (empty ()); #endif } template <typename T, typename TRAITS> #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif inline Range<T, TRAITS>::Range (const T& begin, const T& end, Openness lhsOpen, Openness rhsOpen) : fBegin_ (begin) , fEnd_ (end) , fBeginOpenness_ (lhsOpen) , fEndOpenness_ (rhsOpen) { #if qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (TRAITS::kLowerBound <= TRAITS::kUpperBound); // always required for class Require (TRAITS::kLowerBound <= begin); Require (begin <= end); Require (end <= TRAITS::kUpperBound); #endif } template <typename T, typename TRAITS> inline Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end, Openness lhsOpen, Openness rhsOpen) : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, lhsOpen, rhsOpen) { } template <typename T, typename TRAITS> inline constexpr Range<T, TRAITS> Range<T, TRAITS>::FullRange () { return Range<T, TRAITS> ( TraitsType::kLowerBound, TraitsType::kUpperBound, TraitsType::kLowerBoundOpenness, TraitsType::kUpperBoundOpenness ); } template <typename T, typename TRAITS> inline constexpr bool Range<T, TRAITS>::empty () const { #if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy return fBegin_ > fEnd_ ? true : ((fBegin_ == fEnd_) ? (fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen) : false ) ; #else if (fBegin_ > fEnd_) { // internal hack done in Range<T, TRAITS>::Range() - empty range - otherwise not possible to create this situation return true; } else if (fBegin_ == fEnd_) { return fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen; } return false; #endif } template <typename T, typename TRAITS> inline constexpr typename Range<T, TRAITS>::UnsignedDifferenceType Range<T, TRAITS>::GetDistanceSpanned () const { #if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy return empty () ? static_cast<UnsignedDifferenceType> (0) : (fEnd_ - fBegin_) ; #else if (empty ()) { return static_cast<UnsignedDifferenceType> (0); } return fEnd_ - fBegin_; #endif } template <typename T, typename TRAITS> inline constexpr T Range<T, TRAITS>::GetMidpoint () const { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (not empty ()); #endif return GetLowerBound () + GetDistanceSpanned () / 2; } template <typename T, typename TRAITS> inline constexpr bool Range<T, TRAITS>::Contains (const T& r) const { #if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy return empty () ? false : ( (fBegin_ < r and r < fEnd_) or (fBeginOpenness_ == Openness::eClosed and r == fBegin_) or (fEndOpenness_ == Openness::eClosed and r == fEnd_) ) ; #else if (empty ()) { return false; } if (fBegin_ < r and r < fEnd_) { return true; } if (fBeginOpenness_ == Openness::eClosed and r == fBegin_) { return true; } if (fEndOpenness_ == Openness::eClosed and r == fEnd_) { return true; } return false; #endif } template <typename T, typename TRAITS> template <typename T2, typename TRAITS2> inline bool Range<T, TRAITS>::Equals (const Range<T2, TRAITS2>& rhs) const { if (empty ()) { return rhs.empty (); } return fBegin_ == rhs.fBegin_ and fEnd_ == rhs.fEnd_ and fBeginOpenness_ == rhs.fBeginOpenness_ and fBeginOpenness_ == rhs.fBeginOpenness_; } #if 0 template <typename T, typename TRAITS> bool Range<T, TRAITS>::Overlaps (const Range<T, TRAITS>& rhs) const { /* * @todo RETHINK - because Range has semantics of exclude end - make sure overlap usuage * here is correct??? Unsure -- LGP 2013-07-05 */ return Math::Overlaps ( pair<T, T> (fBegin_, fEnd_), pair<T, T> (rhs.fBegin_, rhs.fEnd_) ); } #endif template <typename T, typename TRAITS> template <typename T2, typename TRAITS2> bool Range<T, TRAITS>::Intersects (const Range<T2, TRAITS2>& rhs) const { if (empty () or rhs.empty ()) { return false; } T l = max (fBegin_, rhs.GetLowerBound ()); T r = min (fEnd_, rhs.GetUpperBound ()); if (l < r) { return true; } else if (l == r) { // must check if the end that has 'l' for each Range that that end is closed. Contains() // is a shortcut for that return Contains (l) and rhs.Contains (l); } else { return false; } } template <typename T, typename TRAITS> Range<T, TRAITS> Range<T, TRAITS>::Intersection (const Range<T, TRAITS>& rhs) const { if (empty () or rhs.empty ()) { return Range (); } T l = max (fBegin_, rhs.fBegin_); T r = min (fEnd_, rhs.fEnd_); if (l <= r) { // lhs/rhs ends are closed iff BOTH lhs/rhs contains that point Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen; Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen; return Range<T, TRAITS> (l, r, lhsO, rhsO); } else { return Range (); } } template <typename T, typename TRAITS> Range<T, TRAITS> Range<T, TRAITS>::UnionBounds (const Range<T, TRAITS>& rhs) const { if (empty ()) { return rhs; } if (rhs.empty ()) { return *this; } T l = min (GetLowerBound (), rhs.GetLowerBound ()); T r = max (GetUpperBound (), rhs.GetUpperBound ()); Range<T, TRAITS> result; if (l <= r) { // lhs/rhs ends are closed iff BOTH lhs/rhs contains that point Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen; Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen; result = Range<T, TRAITS> (l, r, lhsO, rhsO); } Ensure (result.GetLowerBound () <= GetLowerBound ()); Ensure (result.GetLowerBound () <= GetUpperBound ()); Ensure (result.GetLowerBound () <= rhs.GetLowerBound ()); Ensure (result.GetLowerBound () <= rhs.GetUpperBound ()); Ensure (result.GetUpperBound () >= GetLowerBound ()); Ensure (result.GetUpperBound () >= GetUpperBound ()); Ensure (result.GetUpperBound () >= rhs.GetLowerBound ()); Ensure (result.GetUpperBound () >= rhs.GetUpperBound ()); return result; } template <typename T, typename TRAITS> inline constexpr T Range<T, TRAITS>::GetLowerBound () const { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (not empty ()); #endif return fBegin_; } template <typename T, typename TRAITS> inline constexpr Openness Range<T, TRAITS>::GetLowerBoundOpenness () const { return fBeginOpenness_; } template <typename T, typename TRAITS> inline constexpr T Range<T, TRAITS>::GetUpperBound () const { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (not empty ()); #endif return fEnd_; } template <typename T, typename TRAITS> inline constexpr Openness Range<T, TRAITS>::GetUpperBoundOpenness () const { return fEndOpenness_; } template <typename T, typename TRAITS> template <typename... ARGS> inline Characters::String Range<T, TRAITS>::Format (ARGS&& ... args) const { if (GetLowerBound () == GetUpperBound ()) { return GetLowerBound ().Format (forward<ARGS> (args)...); } else { return GetLowerBound ().Format (forward<ARGS> (args)...) + L" - " + GetUpperBound ().Format (forward<ARGS> (args)...); } } template <typename T, typename TRAITS> inline bool Range<T, TRAITS>::operator== (const Range<T, TRAITS>& rhs) const { return Equals (rhs); } template <typename T, typename TRAITS> inline bool Range<T, TRAITS>::operator!= (const Range<T, TRAITS>& rhs) const { return not Equals (rhs); } } } } #endif /* _Stroika_Foundation_Traversal_Range_inl_ */ <|endoftext|>
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH #define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH // std includes #include <vector> // local includes //#include "vector.hh" namespace Dune { namespace Detailed { namespace Discretizations { namespace Assembler { namespace Local { namespace Codim1 { template <class LocalOperatorImp> class Inner { public: typedef LocalOperatorImp LocalOperatorType; typedef Inner<LocalOperatorType> ThisType; typedef typename LocalOperatorType::RangeFieldType RangeFieldType; Inner(const LocalOperatorType& localOperator) : localOperator_(localOperator) { } const LocalOperatorType& localOperator() const { return localOperator_; } private: static const unsigned int numTmpObjectsRequired_ = 4; public: std::vector<unsigned int> numTmpObjectsRequired() const { std::vector<unsigned int> ret(2, 0); ret[0] = numTmpObjectsRequired_; ret[1] = localOperator_.numTmpObjectsRequired(); return ret; } // std::vector< unsigned int > numTmpObjectsRequired() const template <class IntersectionType, class InnerAnsatzSpaceType, class InnerTestSpaceType, class OuterAnsatzSpaceType, class OuterTestSpaceType, class MatrixBackendType, class LocalMatrixType> void assembleLocal(const IntersectionType& intersection, const InnerAnsatzSpaceType& innerAnsatzSpace, const InnerTestSpaceType& innerTestSpace, const OuterAnsatzSpaceType& outerAnsatzSpace, const OuterTestSpaceType& outerTestSpace, MatrixBackendType& innerInnerMatrix, MatrixBackendType& outerOuterMatrix, MatrixBackendType& innerOuterMatrix, MatrixBackendType& outerInnerMatrix, std::vector<std::vector<LocalMatrixType>>& tmpLocalMatricesContainer) const { // preparations assert(intersection.neighbor() && !intersection.boundary()); typedef typename IntersectionType::EntityPointer EntityPointerType; typedef typename IntersectionType::Entity EntityType; typedef typename InnerAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerAnsatzBaseFunctionSetType; typedef typename InnerTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerTestBaseFunctionSetType; typedef typename OuterAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterAnsatzBaseFunctionSetType; typedef typename OuterTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterTestBaseFunctionSetType; // get inside entity and basefunctionsets const EntityPointerType insideEntityPtr = intersection.inside(); const EntityType& insideEntity = *insideEntityPtr; const InnerAnsatzBaseFunctionSetType innerAnsatzBaseFunctionSet = innerAnsatzSpace.baseFunctionSet().local(insideEntity); const InnerTestBaseFunctionSetType innerTestBaseFunctionSet = innerTestSpace.baseFunctionSet().local(insideEntity); // get outside neighbor and basefunctionsets const EntityPointerType outsideNeighborPtr = intersection.outside(); const EntityType& outsideNeighbor = *outsideNeighborPtr; const OuterAnsatzBaseFunctionSetType outerAnsatzBaseFunctionSet = outerAnsatzSpace.baseFunctionSet().local(outsideNeighbor); const OuterTestBaseFunctionSetType outerTestBaseFunctionSet = outerTestSpace.baseFunctionSet().local(outsideNeighbor); // ensure enough tmp local matrices assert(tmpLocalMatricesContainer.size() > 1); std::vector<LocalMatrixType>& tmpLocalMatrices = tmpLocalMatricesContainer[0]; if (tmpLocalMatrices.size() < numTmpObjectsRequired_) { tmpLocalMatrices.resize( numTmpObjectsRequired_, LocalMatrixType(std::max(innerAnsatzSpace.map().maxLocalSize(), outerAnsatzSpace.map().maxLocalSize()), std::max(innerTestSpace.map().maxLocalSize(), outerTestSpace.map().maxLocalSize()), RangeFieldType(0.0))); } // ensure enough tmp local matrices // apply local operator localOperator_.applyLocal(innerAnsatzBaseFunctionSet, innerTestBaseFunctionSet, outerAnsatzBaseFunctionSet, outerTestBaseFunctionSet, intersection, tmpLocalMatrices[0], // inside/inside tmpLocalMatrices[1], // outside/outside tmpLocalMatrices[2], // inside/outside tmpLocalMatrices[3], // outside/inside tmpLocalMatricesContainer[1]); // write local matrices to global (see below) addToMatrix(innerAnsatzSpace, innerTestSpace, insideEntity, insideEntity, tmpLocalMatrices[0], innerInnerMatrix); addToMatrix( outerAnsatzSpace, outerTestSpace, outsideNeighbor, outsideNeighbor, tmpLocalMatrices[1], outerOuterMatrix); addToMatrix(innerAnsatzSpace, outerTestSpace, insideEntity, outsideNeighbor, tmpLocalMatrices[2], innerOuterMatrix); addToMatrix(outerAnsatzSpace, innerTestSpace, outsideNeighbor, insideEntity, tmpLocalMatrices[3], outerInnerMatrix); } // void assembleLocal() const private: //! assignment operator ThisType& operator=(const ThisType&); template <class AnsatzSpaceType, class TestSpaceType, class EntityType, class LocalMatrixType, class SystemMatrixType> void addToMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace, const EntityType& ansatzEntity, const EntityType& testEntity, const LocalMatrixType& localMatrix, SystemMatrixType& systemMatrix) const { unsigned int rows = ansatzSpace.baseFunctionSet().local(ansatzEntity).size(); unsigned int cols = testSpace.baseFunctionSet().local(testEntity).size(); for (unsigned int i = 0; i < rows; ++i) { for (unsigned int j = 0; j < cols; ++j) { const unsigned int globalI = ansatzSpace.map().toGlobal(ansatzEntity, i); const unsigned int globalJ = testSpace.map().toGlobal(testEntity, j); systemMatrix.add(globalI, globalJ, localMatrix[i][j]); } } } // end method addToMatrix const LocalOperatorType& localOperator_; }; // end class Inner } // end namespace Codim1 } // end namespace Local } // end namespace Assembler } // namespace Discretizations } // namespace Detailed } // end namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH <commit_msg>[assembler.local.codim1.matrix] added local boundary assembler<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH #define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH // std includes #include <vector> // local includes //#include "vector.hh" namespace Dune { namespace Detailed { namespace Discretizations { namespace Assembler { namespace Local { namespace Codim1 { template <class LocalOperatorImp> class Inner { public: typedef LocalOperatorImp LocalOperatorType; typedef Inner<LocalOperatorType> ThisType; typedef typename LocalOperatorType::RangeFieldType RangeFieldType; Inner(const LocalOperatorType& localOperator) : localOperator_(localOperator) { } const LocalOperatorType& localOperator() const { return localOperator_; } private: static const unsigned int numTmpObjectsRequired_ = 4; public: std::vector<unsigned int> numTmpObjectsRequired() const { std::vector<unsigned int> ret(2, 0); ret[0] = numTmpObjectsRequired_; ret[1] = localOperator_.numTmpObjectsRequired(); return ret; } // std::vector< unsigned int > numTmpObjectsRequired() const template <class IntersectionType, class InnerAnsatzSpaceType, class InnerTestSpaceType, class OuterAnsatzSpaceType, class OuterTestSpaceType, class MatrixBackendType, class LocalMatrixType> void assembleLocal(const IntersectionType& intersection, const InnerAnsatzSpaceType& innerAnsatzSpace, const InnerTestSpaceType& innerTestSpace, const OuterAnsatzSpaceType& outerAnsatzSpace, const OuterTestSpaceType& outerTestSpace, MatrixBackendType& innerInnerMatrix, MatrixBackendType& outerOuterMatrix, MatrixBackendType& innerOuterMatrix, MatrixBackendType& outerInnerMatrix, std::vector<std::vector<LocalMatrixType>>& tmpLocalMatricesContainer) const { // preparations assert(intersection.neighbor() && !intersection.boundary()); typedef typename IntersectionType::EntityPointer EntityPointerType; typedef typename IntersectionType::Entity EntityType; typedef typename InnerAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerAnsatzBaseFunctionSetType; typedef typename InnerTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerTestBaseFunctionSetType; typedef typename OuterAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterAnsatzBaseFunctionSetType; typedef typename OuterTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterTestBaseFunctionSetType; // get inside entity and basefunctionsets const EntityPointerType insideEntityPtr = intersection.inside(); const EntityType& insideEntity = *insideEntityPtr; const InnerAnsatzBaseFunctionSetType innerAnsatzBaseFunctionSet = innerAnsatzSpace.baseFunctionSet().local(insideEntity); const InnerTestBaseFunctionSetType innerTestBaseFunctionSet = innerTestSpace.baseFunctionSet().local(insideEntity); // get outside neighbor and basefunctionsets const EntityPointerType outsideNeighborPtr = intersection.outside(); const EntityType& outsideNeighbor = *outsideNeighborPtr; const OuterAnsatzBaseFunctionSetType outerAnsatzBaseFunctionSet = outerAnsatzSpace.baseFunctionSet().local(outsideNeighbor); const OuterTestBaseFunctionSetType outerTestBaseFunctionSet = outerTestSpace.baseFunctionSet().local(outsideNeighbor); // ensure enough tmp local matrices assert(tmpLocalMatricesContainer.size() > 1); std::vector<LocalMatrixType>& tmpLocalMatrices = tmpLocalMatricesContainer[0]; if (tmpLocalMatrices.size() < numTmpObjectsRequired_) { tmpLocalMatrices.resize( numTmpObjectsRequired_, LocalMatrixType(std::max(innerAnsatzSpace.map().maxLocalSize(), outerAnsatzSpace.map().maxLocalSize()), std::max(innerTestSpace.map().maxLocalSize(), outerTestSpace.map().maxLocalSize()), RangeFieldType(0.0))); } // ensure enough tmp local matrices // apply local operator localOperator_.applyLocal(innerAnsatzBaseFunctionSet, innerTestBaseFunctionSet, outerAnsatzBaseFunctionSet, outerTestBaseFunctionSet, intersection, tmpLocalMatrices[0], // inside/inside tmpLocalMatrices[1], // outside/outside tmpLocalMatrices[2], // inside/outside tmpLocalMatrices[3], // outside/inside tmpLocalMatricesContainer[1]); // write local matrices to global (see below) addToMatrix(innerAnsatzSpace, innerTestSpace, insideEntity, insideEntity, tmpLocalMatrices[0], innerInnerMatrix); addToMatrix( outerAnsatzSpace, outerTestSpace, outsideNeighbor, outsideNeighbor, tmpLocalMatrices[1], outerOuterMatrix); addToMatrix(innerAnsatzSpace, outerTestSpace, insideEntity, outsideNeighbor, tmpLocalMatrices[2], innerOuterMatrix); addToMatrix(outerAnsatzSpace, innerTestSpace, outsideNeighbor, insideEntity, tmpLocalMatrices[3], outerInnerMatrix); } // void assembleLocal() const private: //! assignment operator ThisType& operator=(const ThisType&); template <class AnsatzSpaceType, class TestSpaceType, class EntityType, class LocalMatrixType, class SystemMatrixType> void addToMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace, const EntityType& ansatzEntity, const EntityType& testEntity, const LocalMatrixType& localMatrix, SystemMatrixType& systemMatrix) const { unsigned int rows = ansatzSpace.baseFunctionSet().local(ansatzEntity).size(); unsigned int cols = testSpace.baseFunctionSet().local(testEntity).size(); for (unsigned int i = 0; i < rows; ++i) { for (unsigned int j = 0; j < cols; ++j) { const unsigned int globalI = ansatzSpace.map().toGlobal(ansatzEntity, i); const unsigned int globalJ = testSpace.map().toGlobal(testEntity, j); systemMatrix.add(globalI, globalJ, localMatrix[i][j]); } } } // end method addToMatrix const LocalOperatorType& localOperator_; }; // end class Inner template <class LocalOperatorImp> class Boundary { public: typedef LocalOperatorImp LocalOperatorType; typedef Boundary<LocalOperatorType> ThisType; typedef typename LocalOperatorType::RangeFieldType RangeFieldType; Boundary(const LocalOperatorType& localOperator) : localOperator_(localOperator) { } const LocalOperatorType& localOperator() const { return localOperator_; } private: static const unsigned int numTmpObjectsRequired_ = 4; public: std::vector<unsigned int> numTmpObjectsRequired() const { std::vector<unsigned int> ret(2, 0); ret[0] = numTmpObjectsRequired_; ret[1] = localOperator_.numTmpObjectsRequired(); return ret; } // std::vector< unsigned int > numTmpObjectsRequired() const template <class IntersectionType, class AnsatzSpaceType, class TestSpaceType, class MatrixBackendType, class LocalMatrixType> void assembleLocal(const IntersectionType& intersection, const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace, MatrixBackendType& matrix, std::vector<std::vector<LocalMatrixType>>& tmpLocalMatricesContainer) const { // preparations assert(intersection.boundary()); typedef typename IntersectionType::EntityPointer EntityPointerType; typedef typename IntersectionType::Entity EntityType; typedef typename AnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType LocalAnsatzBaseFunctionSetType; typedef typename TestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType LocalTestBaseFunctionSetType; // get inside entity and basefunctionsets const EntityPointerType entityPtr = intersection.inside(); const EntityType& entity = *entityPtr; const LocalAnsatzBaseFunctionSetType localAnsatzBaseFunctionSet = ansatzSpace.baseFunctionSet().local(entity); const LocalTestBaseFunctionSetType localTestBaseFunctionSet = testSpace.baseFunctionSet().local(entity); // ensure enough tmp local matrices assert(tmpLocalMatricesContainer.size() > 1); std::vector<LocalMatrixType>& tmpLocalMatrices = tmpLocalMatricesContainer[0]; if (tmpLocalMatrices.size() < numTmpObjectsRequired_) { tmpLocalMatrices.resize( numTmpObjectsRequired_, LocalMatrixType(ansatzSpace.map().maxLocalSize(), testSpace.map().maxLocalSize(), RangeFieldType(0.0))); } // ensure enough tmp local matrices // apply local operator localOperator_.applyLocal(localAnsatzBaseFunctionSet, localTestBaseFunctionSet, intersection, tmpLocalMatrices[0], tmpLocalMatricesContainer[1]); // write local matrices to global (see below) addToMatrix(ansatzSpace, testSpace, entity, entity, tmpLocalMatrices[0], matrix); } // void assembleLocal() const private: //! assignment operator ThisType& operator=(const ThisType&); template <class AnsatzSpaceType, class TestSpaceType, class EntityType, class LocalMatrixType, class SystemMatrixType> void addToMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace, const EntityType& ansatzEntity, const EntityType& testEntity, const LocalMatrixType& localMatrix, SystemMatrixType& systemMatrix) const { unsigned int rows = ansatzSpace.baseFunctionSet().local(ansatzEntity).size(); unsigned int cols = testSpace.baseFunctionSet().local(testEntity).size(); for (unsigned int i = 0; i < rows; ++i) { for (unsigned int j = 0; j < cols; ++j) { const unsigned int globalI = ansatzSpace.map().toGlobal(ansatzEntity, i); const unsigned int globalJ = testSpace.map().toGlobal(testEntity, j); systemMatrix.add(globalI, globalJ, localMatrix[i][j]); } } } // end method addToMatrix const LocalOperatorType& localOperator_; }; // end class Boundary } // end namespace Codim1 } // end namespace Local } // end namespace Assembler } // namespace Discretizations } // namespace Detailed } // end namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: macrodlg.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-07 20:06:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // #ifndef _MACRODLG_HXX #define _MACRODLG_HXX #ifndef _SVHEADER_HXX #include <svheader.hxx> #endif #include <bastype2.hxx> #include <bastype3.hxx> #ifndef _BASEDLGS_HXX //autogen #include <sfx2/basedlgs.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #define MACRO_CLOSE 10 #define MACRO_OK_RUN 11 #define MACRO_NEW 12 #define MACRO_EDIT 14 #define MACRO_ORGANIZE 15 #define MACRO_ASSIGN 16 #define MACROCHOOSER_ALL 1 #define MACROCHOOSER_CHOOSEONLY 2 #define MACROCHOOSER_RECORDING 3 class BasicManager; class MacroChooser : public SfxModalDialog { private: FixedText aMacroNameTxt; Edit aMacroNameEdit; FixedText aMacrosInTxt; String aMacrosInTxtBaseStr; SvTreeListBox aMacroBox; FixedText aMacroFromTxT; FixedText aMacrosSaveInTxt; BasicTreeListBox aBasicBox; PushButton aRunButton; CancelButton aCloseButton; PushButton aAssignButton; PushButton aEditButton; PushButton aNewDelButton; PushButton aOrganizeButton; HelpButton aHelpButton; PushButton aNewLibButton; PushButton aNewModButton; BOOL bNewDelIsDel; BOOL bForceStoreBasic; USHORT nMode; DECL_LINK( MacroSelectHdl, SvTreeListBox * ); DECL_LINK( MacroDoubleClickHdl, SvTreeListBox * ); DECL_LINK( BasicSelectHdl, SvTreeListBox * ); DECL_LINK( EditModifyHdl, Edit * ); DECL_LINK( ButtonHdl, Button * ); void CheckButtons(); void SaveSetCurEntry( SvTreeListBox& rBox, SvLBoxEntry* pEntry ); void UpdateFields(); void EnableButton( Button& rButton, BOOL bEnable ); String GetInfo( SbxVariable* pVar ); void StoreMacroDescription(); void RestoreMacroDescription(); public: MacroChooser( Window* pParent, BOOL bCreateEntries = TRUE ); ~MacroChooser(); SbMethod* GetMacro(); void DeleteMacro(); SbMethod* CreateMacro(); virtual short Execute(); void SetMode( USHORT nMode ); USHORT GetMode() const { return nMode; } }; #endif // _MACRODLG_HXX <commit_msg>INTEGRATION: CWS basmgr02 (1.8.146); FILE MERGED 2007/01/11 10:40:03 fs 1.8.146.1: during #i73329#: proper Z-(means: tab-)order<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: macrodlg.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2007-03-15 15:57:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // #ifndef _MACRODLG_HXX #define _MACRODLG_HXX #ifndef _SVHEADER_HXX #include <svheader.hxx> #endif #include <bastype2.hxx> #include <bastype3.hxx> #ifndef _BASEDLGS_HXX //autogen #include <sfx2/basedlgs.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #define MACRO_CLOSE 10 #define MACRO_OK_RUN 11 #define MACRO_NEW 12 #define MACRO_EDIT 14 #define MACRO_ORGANIZE 15 #define MACRO_ASSIGN 16 #define MACROCHOOSER_ALL 1 #define MACROCHOOSER_CHOOSEONLY 2 #define MACROCHOOSER_RECORDING 3 class BasicManager; class MacroChooser : public SfxModalDialog { private: FixedText aMacroNameTxt; Edit aMacroNameEdit; FixedText aMacroFromTxT; FixedText aMacrosSaveInTxt; BasicTreeListBox aBasicBox; FixedText aMacrosInTxt; String aMacrosInTxtBaseStr; SvTreeListBox aMacroBox; PushButton aRunButton; CancelButton aCloseButton; PushButton aAssignButton; PushButton aEditButton; PushButton aNewDelButton; PushButton aOrganizeButton; HelpButton aHelpButton; PushButton aNewLibButton; PushButton aNewModButton; BOOL bNewDelIsDel; BOOL bForceStoreBasic; USHORT nMode; DECL_LINK( MacroSelectHdl, SvTreeListBox * ); DECL_LINK( MacroDoubleClickHdl, SvTreeListBox * ); DECL_LINK( BasicSelectHdl, SvTreeListBox * ); DECL_LINK( EditModifyHdl, Edit * ); DECL_LINK( ButtonHdl, Button * ); void CheckButtons(); void SaveSetCurEntry( SvTreeListBox& rBox, SvLBoxEntry* pEntry ); void UpdateFields(); void EnableButton( Button& rButton, BOOL bEnable ); String GetInfo( SbxVariable* pVar ); void StoreMacroDescription(); void RestoreMacroDescription(); public: MacroChooser( Window* pParent, BOOL bCreateEntries = TRUE ); ~MacroChooser(); SbMethod* GetMacro(); void DeleteMacro(); SbMethod* CreateMacro(); virtual short Execute(); void SetMode( USHORT nMode ); USHORT GetMode() const { return nMode; } }; #endif // _MACRODLG_HXX <|endoftext|>
<commit_before>#include <set> #include <vector> #include "entitysystem.h" #include "cmapclient.h" #include "cmapserver.h" #include "connection.h" #include "systems/chatsystem.h" #include "systems/inventorysystem.h" #include "systems/luasystem.h" #include "systems/mapsystem.h" #include "systems/movementsystem.h" #include "systems/partysystem.h" #include "systems/updatesystem.h" #include "srv_npcchar.h" using namespace RoseCommon; EntitySystem::EntitySystem(CMapServer *server) : systemManager_(*this), server_(server) { systemManager_.add<Systems::MovementSystem>(); systemManager_.add<Systems::UpdateSystem>(); systemManager_.add<Systems::ChatSystem>(); systemManager_.add<Systems::InventorySystem>(); systemManager_.add<Systems::PartySystem>(); systemManager_.add<Systems::MapSystem>(); systemManager_.add<Systems::LuaSystem>(); } EntityManager& EntitySystem::getEntityManager() { return entityManager_; } Entity EntitySystem::buildItemEntity(Entity creator, RoseCommon::Item&& item) { Entity e = create(); e.assign<Item>(std::move(item)); auto pos = creator.component<Position>(); e.assign<Position>(pos->x_, pos->y_, pos->map_, 0); auto basic = e.assign<BasicInfo>(); basic->ownerId_ = creator.component<BasicInfo>()->id_; basic->id_ = id_manager_.get_free_id(); itemToEntity_[basic->id_] = e; return e; } void EntitySystem::registerEntity(Entity entity) { if (!entity) return; auto basic = entity.component<BasicInfo>(); if (!basic || basic->name_ == "" || !basic->id_) return; nameToEntity_[basic->name_] = entity; idToEntity_[basic->id_] = entity; } Entity EntitySystem::getItemEntity(uint32_t id) { return itemToEntity_[id]; } Entity EntitySystem::getEntity(const std::string& name) { return nameToEntity_[name]; } Entity EntitySystem::getEntity(uint32_t charId) { return idToEntity_[charId]; } void EntitySystem::update(double dt) { std::lock_guard<std::mutex> lock(access_); for (auto& it : create_commands_) { it->execute(*this); } create_commands_.clear(); while (toDispatch_.size()) { auto tmp = std::move(toDispatch_.front()); systemManager_.dispatch(tmp.first, *tmp.second); toDispatch_.pop(); } systemManager_.update(dt); for (auto& it : delete_commands_) { it->execute(*this); } delete_commands_.clear(); } void EntitySystem::destroy(Entity entity) { if (!entity) return; std::unique_ptr<CommandBase> ptr{new Command([this, entity] (EntitySystem &) mutable { if (!entity) return; if (!entity.component<Warpgate>()) { if (auto client = getClient(entity); client) SendPacket(client, CMapServer::eSendType::EVERYONE_BUT_ME, *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity)); else SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE, *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity)); if (!entity.component<Npc>()) { saveCharacter(entity.component<CharacterInfo>()->charId_, entity); auto basic = entity.component<BasicInfo>(); nameToEntity_.erase(basic->name_); idToEntity_.erase(basic->id_); id_manager_.release_id(basic->id_); } } entity.destroy(); })}; std::lock_guard<std::mutex> lock(access_); delete_commands_.emplace_back(std::move(ptr)); } Entity EntitySystem::create() { return entityManager_.create(); } bool EntitySystem::isNearby(Entity a, Entity b) { return systemManager_.get<Systems::MovementSystem>()->is_nearby(a, b); } bool EntitySystem::dispatch(Entity entity, std::unique_ptr<RoseCommon::CRosePacket> packet) { if (!entity) return false; if (systemManager_.wouldDispatch(*packet)) { std::lock_guard<std::mutex> lock(access_); toDispatch_.emplace(std::make_pair(entity, std::move(packet))); return true; } return false; } Entity EntitySystem::loadCharacter(uint32_t charId, bool platinium) { auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters{}; Core::InventoryTable inventoryTable{}; Core::SkillTable skillsTable{}; auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters)) .from(characters) .where(characters.id == charId)); std::lock_guard<std::mutex> lock(access_); auto entity = create(); if (static_cast<long>(charRes.front().count) != 1L) { entity.destroy(); return Entity(); } const auto& charRow = charRes.front(); entity.assign<Position>(charRow); entity.assign<BasicInfo>(charRow, id_manager_.get_free_id()); entity.assign<Stats>(charRow); entity.assign<AdvancedInfo>(charRow); entity.assign<CharacterGraphics>(charRow); entity.assign<CharacterInfo>(charRow, platinium, charId); // TODO : write the pat initialization code auto skills = entity.assign<Skills>(); auto skillRes = conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId)); skills->loadFromResult(skillRes); // TODO : write the hotbar table and loading code entity.assign<Hotbar>(); entity.assign<StatusEffects>(); entity.assign<RidingItems>(); entity.assign<BulletItems>(); // TODO : write the inventory code // auto luaSystem = systemManager_.get<Systems::LuaSystem>(); auto inventory = entity.assign<Inventory>(); auto invRes = conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId)); inventory->loadFromResult(invRes, get<Systems::InventorySystem>()); Systems::UpdateSystem::calculateSpeed(entity); entity.assign<Quests>(); Core::WishTable wish{}; auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId)); auto wishlist = entity.assign<Wishlist>(); wishlist->loadFromResult(wishRes, get<Systems::InventorySystem>()); // auto lua = entity.assign<EntityAPI>(); // luaSystem->loadScript(entity, "function onInit()\ndisplay('test')\nend"); // lua->onInit(); registerEntity(entity); return entity; } void EntitySystem::saveCharacter(uint32_t charId, Entity entity) { if (!entity) return; auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters{}; using sqlpp::parameter; auto update = sqlpp::dynamic_update(conn.get(), characters).dynamic_set().where(characters.id == charId); entity.component<Position>()->commitToUpdate<decltype(characters)>(update); entity.component<BasicInfo>()->commitToUpdate<decltype(characters)>(update); entity.component<Stats>()->commitToUpdate<decltype(characters)>(update); entity.component<AdvancedInfo>()->commitToUpdate<decltype(characters)>(update); // entity.component<CharacterGraphics>()->commitToUpdate(update); entity.component<CharacterInfo>()->commitToUpdate<decltype(characters)>(update); // entity.component<Hotbar>()->commitToUpdate(update); // entity.component<StatusEffects>()->commitToUpdate(update); // entity.component<RidingItems>()->commitToUpdate(update); // entity.component<BulletItems>()->commitToUpdate(update); conn->run(update); // entity.component<Skills>()->commitToUpdate(updateSkills); Core::InventoryTable inv{}; auto invRes = conn(sqlpp::select(sqlpp::all_of(inv)).from(inv).where(inv.charId == charId)); const auto& items = entity.component<Inventory>()->items_; std::vector<size_t> toDelete; std::vector<size_t> toUpdate; std::set<size_t> modified; std::vector<size_t> toInsert; for (const auto& row : invRes) { if (row.slot >= Inventory::maxItems) toDelete.emplace_back(row.slot); // FIXME: that should never happen else if (!items[row.slot]) toDelete.emplace_back(row.slot); else if (items[row.slot] != Item(row)) toUpdate.emplace_back(row.slot); modified.insert(row.slot); } size_t i = 0; for (const auto& item : items) { if (item && modified.find(i) == modified.end()) toInsert.emplace_back(i); ++i; } for (auto it : toDelete) conn(sqlpp::remove_from(inv).where(inv.charId == charId and inv.slot == it)); for (auto it : toUpdate) { auto update = sqlpp::dynamic_update(conn.get(), inv).dynamic_set().where(inv.charId == charId and inv.slot == it); items[it].commitToUpdate<decltype(inv)>(update); conn->run(update); } for (auto it : toInsert) { auto insert = sqlpp::dynamic_insert_into(conn.get(), inv).dynamic_set(); items[it].commitToInsert<decltype(inv)>(insert); insert.insert_list.add(inv.slot = it); insert.insert_list.add(inv.charId = charId); conn->run(insert); } } Entity EntitySystem::create_warpgate(std::string alias, int dest_map_id, float dest_x, float dest_y, float dest_z, int map_id, float x, float y, float z, float angle, float x_scale, float y_scale, float z_scale) { Entity e = create(); std::unique_ptr<CommandBase> ptr{new Command([alias, dest_map_id, dest_x, dest_y, dest_z, map_id, x, y, z, angle, x_scale, y_scale, z_scale, e] (EntitySystem &es) mutable { if (!e) return; e.assign<BasicInfo>(es.id_manager_.get_free_id()); auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0); pos->z_ = static_cast<uint16_t>(z); pos->angle_ = angle; auto dest = e.assign<Destination>(dest_x * 100, dest_y * 100, dest_map_id); dest->z_ = static_cast<uint16_t>(dest_z); })}; create_commands_.emplace_back(std::move(ptr)); return e; } Entity EntitySystem::create_npc(std::string npc_lua, int npc_id, int map_id, float x, float y, float z, float angle) { Entity e = create(); std::unique_ptr<CommandBase> ptr{new Command([npc_lua, npc_id, map_id, x, y, z, angle, e] (EntitySystem &es) mutable { if (!e) return; e.assign<BasicInfo>(es.id_manager_.get_free_id()); e.assign<AdvancedInfo>(); e.assign<CharacterInfo>(); uint16_t dialog_id = 0; if (!npc_lua.empty()) { dialog_id = std::stoi(npc_lua); } e.assign<Npc>(npc_id, dialog_id); auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0); pos->z_ = static_cast<uint16_t>(z); pos->angle_ = angle; //e.assign<EntityApi>(); // we send the new NPC to the existing clients es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE, *makePacket<ePacketType::PAKWC_NPC_CHAR>(e)); })}; create_commands_.emplace_back(std::move(ptr)); return e; } Entity EntitySystem::create_spawner(std::string alias, int mob_id, int mob_count, int spawner_limit, int spawner_interval, int spawner_range, int map_id, float x, float y, float z) { return {}; } void EntitySystem::bulk_destroy(const std::vector<Entity>& s) { std::unique_ptr<CommandBase> ptr{new Command([this, s] (EntitySystem &) mutable { for (auto entity : s) { if (!entity) continue; if (!entity.component<Warpgate>()) SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE, *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity)); entity.destroy(); } })}; std::lock_guard<std::mutex> lock(access_); delete_commands_.emplace_back(std::move(ptr)); } LuaScript::ScriptLoader& EntitySystem::get_script_loader() noexcept { return server_->get_script_loader(); } void EntitySystem::SendPacket(const std::shared_ptr<CMapClient>& sender, CMapServer::eSendType type, CRosePacket& _buffer) { server_->SendPacket(sender, type, _buffer); } void EntitySystem::SendPacket(const CMapClient& sender, CMapServer::eSendType type, CRosePacket& _buffer) { server_->SendPacket(sender, type, _buffer); } <commit_msg>Removed unecessary stuff<commit_after>#include <set> #include <vector> #include "entitysystem.h" #include "cmapclient.h" #include "cmapserver.h" #include "connection.h" #include "systems/chatsystem.h" #include "systems/inventorysystem.h" #include "systems/luasystem.h" #include "systems/mapsystem.h" #include "systems/movementsystem.h" #include "systems/partysystem.h" #include "systems/updatesystem.h" #include "srv_npcchar.h" using namespace RoseCommon; EntitySystem::EntitySystem(CMapServer *server) : systemManager_(*this), server_(server) { systemManager_.add<Systems::MovementSystem>(); systemManager_.add<Systems::UpdateSystem>(); systemManager_.add<Systems::ChatSystem>(); systemManager_.add<Systems::InventorySystem>(); systemManager_.add<Systems::PartySystem>(); systemManager_.add<Systems::MapSystem>(); systemManager_.add<Systems::LuaSystem>(); } EntityManager& EntitySystem::getEntityManager() { return entityManager_; } Entity EntitySystem::buildItemEntity(Entity creator, RoseCommon::Item&& item) { Entity e = create(); e.assign<Item>(std::move(item)); auto pos = creator.component<Position>(); e.assign<Position>(pos->x_, pos->y_, pos->map_, 0); auto basic = e.assign<BasicInfo>(); basic->ownerId_ = creator.component<BasicInfo>()->id_; basic->id_ = id_manager_.get_free_id(); itemToEntity_[basic->id_] = e; return e; } void EntitySystem::registerEntity(Entity entity) { if (!entity) return; auto basic = entity.component<BasicInfo>(); if (!basic || basic->name_ == "" || !basic->id_) return; nameToEntity_[basic->name_] = entity; idToEntity_[basic->id_] = entity; } Entity EntitySystem::getItemEntity(uint32_t id) { return itemToEntity_[id]; } Entity EntitySystem::getEntity(const std::string& name) { return nameToEntity_[name]; } Entity EntitySystem::getEntity(uint32_t charId) { return idToEntity_[charId]; } void EntitySystem::update(double dt) { std::lock_guard<std::mutex> lock(access_); for (auto& it : create_commands_) { it->execute(*this); } create_commands_.clear(); while (toDispatch_.size()) { auto tmp = std::move(toDispatch_.front()); systemManager_.dispatch(tmp.first, *tmp.second); toDispatch_.pop(); } systemManager_.update(dt); for (auto& it : delete_commands_) { it->execute(*this); } delete_commands_.clear(); } void EntitySystem::destroy(Entity entity) { if (!entity) return; std::unique_ptr<CommandBase> ptr{new Command([entity] (EntitySystem &es) mutable { if (!entity) return; if (!entity.component<Warpgate>()) { if (auto client = getClient(entity); client) es.SendPacket(client, CMapServer::eSendType::EVERYONE_BUT_ME, *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity)); else es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE, *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity)); if (!entity.component<Npc>()) { es.saveCharacter(entity.component<CharacterInfo>()->charId_, entity); auto basic = entity.component<BasicInfo>(); es.nameToEntity_.erase(basic->name_); es.idToEntity_.erase(basic->id_); es.id_manager_.release_id(basic->id_); } } entity.destroy(); })}; std::lock_guard<std::mutex> lock(access_); delete_commands_.emplace_back(std::move(ptr)); } Entity EntitySystem::create() { return entityManager_.create(); } bool EntitySystem::isNearby(Entity a, Entity b) { return systemManager_.get<Systems::MovementSystem>()->is_nearby(a, b); } bool EntitySystem::dispatch(Entity entity, std::unique_ptr<RoseCommon::CRosePacket> packet) { if (!entity) return false; if (systemManager_.wouldDispatch(*packet)) { std::lock_guard<std::mutex> lock(access_); toDispatch_.emplace(std::make_pair(entity, std::move(packet))); return true; } return false; } Entity EntitySystem::loadCharacter(uint32_t charId, bool platinium) { auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters{}; Core::InventoryTable inventoryTable{}; Core::SkillTable skillsTable{}; auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters)) .from(characters) .where(characters.id == charId)); std::lock_guard<std::mutex> lock(access_); auto entity = create(); if (static_cast<long>(charRes.front().count) != 1L) { entity.destroy(); return Entity(); } const auto& charRow = charRes.front(); entity.assign<Position>(charRow); entity.assign<BasicInfo>(charRow, id_manager_.get_free_id()); entity.assign<Stats>(charRow); entity.assign<AdvancedInfo>(charRow); entity.assign<CharacterGraphics>(charRow); entity.assign<CharacterInfo>(charRow, platinium, charId); // TODO : write the pat initialization code auto skills = entity.assign<Skills>(); auto skillRes = conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId)); skills->loadFromResult(skillRes); // TODO : write the hotbar table and loading code entity.assign<Hotbar>(); entity.assign<StatusEffects>(); entity.assign<RidingItems>(); entity.assign<BulletItems>(); // TODO : write the inventory code // auto luaSystem = systemManager_.get<Systems::LuaSystem>(); auto inventory = entity.assign<Inventory>(); auto invRes = conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId)); inventory->loadFromResult(invRes, get<Systems::InventorySystem>()); Systems::UpdateSystem::calculateSpeed(entity); entity.assign<Quests>(); Core::WishTable wish{}; auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId)); auto wishlist = entity.assign<Wishlist>(); wishlist->loadFromResult(wishRes, get<Systems::InventorySystem>()); // auto lua = entity.assign<EntityAPI>(); // luaSystem->loadScript(entity, "function onInit()\ndisplay('test')\nend"); // lua->onInit(); registerEntity(entity); return entity; } void EntitySystem::saveCharacter(uint32_t charId, Entity entity) { if (!entity) return; auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters{}; using sqlpp::parameter; auto update = sqlpp::dynamic_update(conn.get(), characters).dynamic_set().where(characters.id == charId); entity.component<Position>()->commitToUpdate<decltype(characters)>(update); entity.component<BasicInfo>()->commitToUpdate<decltype(characters)>(update); entity.component<Stats>()->commitToUpdate<decltype(characters)>(update); entity.component<AdvancedInfo>()->commitToUpdate<decltype(characters)>(update); // entity.component<CharacterGraphics>()->commitToUpdate(update); entity.component<CharacterInfo>()->commitToUpdate<decltype(characters)>(update); // entity.component<Hotbar>()->commitToUpdate(update); // entity.component<StatusEffects>()->commitToUpdate(update); // entity.component<RidingItems>()->commitToUpdate(update); // entity.component<BulletItems>()->commitToUpdate(update); conn->run(update); // entity.component<Skills>()->commitToUpdate(updateSkills); Core::InventoryTable inv{}; auto invRes = conn(sqlpp::select(sqlpp::all_of(inv)).from(inv).where(inv.charId == charId)); const auto& items = entity.component<Inventory>()->items_; std::vector<size_t> toDelete; std::vector<size_t> toUpdate; std::set<size_t> modified; std::vector<size_t> toInsert; for (const auto& row : invRes) { if (row.slot >= Inventory::maxItems) toDelete.emplace_back(row.slot); // FIXME: that should never happen else if (!items[row.slot]) toDelete.emplace_back(row.slot); else if (items[row.slot] != Item(row)) toUpdate.emplace_back(row.slot); modified.insert(row.slot); } size_t i = 0; for (const auto& item : items) { if (item && modified.find(i) == modified.end()) toInsert.emplace_back(i); ++i; } for (auto it : toDelete) conn(sqlpp::remove_from(inv).where(inv.charId == charId and inv.slot == it)); for (auto it : toUpdate) { auto update = sqlpp::dynamic_update(conn.get(), inv).dynamic_set().where(inv.charId == charId and inv.slot == it); items[it].commitToUpdate<decltype(inv)>(update); conn->run(update); } for (auto it : toInsert) { auto insert = sqlpp::dynamic_insert_into(conn.get(), inv).dynamic_set(); items[it].commitToInsert<decltype(inv)>(insert); insert.insert_list.add(inv.slot = it); insert.insert_list.add(inv.charId = charId); conn->run(insert); } } Entity EntitySystem::create_warpgate(std::string alias, int dest_map_id, float dest_x, float dest_y, float dest_z, int map_id, float x, float y, float z, float angle, float x_scale, float y_scale, float z_scale) { Entity e = create(); std::unique_ptr<CommandBase> ptr{new Command([alias, dest_map_id, dest_x, dest_y, dest_z, map_id, x, y, z, angle, x_scale, y_scale, z_scale, e] (EntitySystem &es) mutable { if (!e) return; e.assign<BasicInfo>(es.id_manager_.get_free_id()); auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0); pos->z_ = static_cast<uint16_t>(z); pos->angle_ = angle; auto dest = e.assign<Destination>(dest_x * 100, dest_y * 100, dest_map_id); dest->z_ = static_cast<uint16_t>(dest_z); })}; create_commands_.emplace_back(std::move(ptr)); return e; } Entity EntitySystem::create_npc(std::string npc_lua, int npc_id, int map_id, float x, float y, float z, float angle) { Entity e = create(); std::unique_ptr<CommandBase> ptr{new Command([npc_lua, npc_id, map_id, x, y, z, angle, e] (EntitySystem &es) mutable { if (!e) return; e.assign<BasicInfo>(es.id_manager_.get_free_id()); e.assign<AdvancedInfo>(); e.assign<CharacterInfo>(); uint16_t dialog_id = 0; if (!npc_lua.empty()) { dialog_id = std::stoi(npc_lua); } e.assign<Npc>(npc_id, dialog_id); auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0); pos->z_ = static_cast<uint16_t>(z); pos->angle_ = angle; //e.assign<EntityApi>(); // we send the new NPC to the existing clients es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE, *makePacket<ePacketType::PAKWC_NPC_CHAR>(e)); })}; create_commands_.emplace_back(std::move(ptr)); return e; } Entity EntitySystem::create_spawner(std::string alias, int mob_id, int mob_count, int spawner_limit, int spawner_interval, int spawner_range, int map_id, float x, float y, float z) { return {}; } void EntitySystem::bulk_destroy(const std::vector<Entity>& s) { std::unique_ptr<CommandBase> ptr{new Command([s] (EntitySystem &es) mutable { for (auto entity : s) { if (!entity) continue; if (!entity.component<Warpgate>()) es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE, *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity)); entity.destroy(); } })}; std::lock_guard<std::mutex> lock(access_); delete_commands_.emplace_back(std::move(ptr)); } LuaScript::ScriptLoader& EntitySystem::get_script_loader() noexcept { return server_->get_script_loader(); } void EntitySystem::SendPacket(const std::shared_ptr<CMapClient>& sender, CMapServer::eSendType type, CRosePacket& _buffer) { server_->SendPacket(sender, type, _buffer); } void EntitySystem::SendPacket(const CMapClient& sender, CMapServer::eSendType type, CRosePacket& _buffer) { server_->SendPacket(sender, type, _buffer); } <|endoftext|>
<commit_before>#include "ReverbModule.h" #include "../Random.h" #include <algorithm> #include <cstdlib> #include <cstdio> #include "SDL.h" ReverbModule::ReverbModule(ModularSynth& synth) :SynthModule(synth, moduleId, 2, 1, 0), mHead(0), mBuffer(NULL) { Random rnd; rnd.seed(rand()); for (int i = 0 ; i < numTaps ; ++i) { mTap[i].gain = 1.0f / (1 + i); mTap[i].delay = static_cast<float>(i) / numTaps + rnd.rndf() * 0.9f / numTaps + 0.01f; } } ReverbModule::~ReverbModule() { if (mBuffer != NULL) { delete[] mBuffer; } } void ReverbModule::cycle() { mBuffer[mHead] = getInput(0); float delay = std::max(0.0f, getInput(1)); float sum = 0; for (int i = 0 ; i < numTaps ; ++i) { sum += mBuffer[static_cast<int>(mHead - delay * mTap[i].delay * mSampleRate + mMaxBufferSize) % mMaxBufferSize] * mTap[i].gain; } setOutput(0, sum); ++mHead; if (mHead >= mMaxBufferSize) mHead = 0; } const char * ReverbModule::getInputName(int input) const { static const char *names[] = {"Input"}; return names[input]; } const char * ReverbModule::getOutputName(int output) const { static const char *names[] = {"Output"}; return names[output]; } const char * ReverbModule::getName() const { return "Reverb"; } SynthModule * ReverbModule::createModule(ModularSynth& synth) { return new ReverbModule(synth); } void ReverbModule::setSampleRate(int newRate) { SynthModule::setSampleRate(newRate); if (mBuffer != NULL) delete[] mBuffer; mMaxBufferSize = std::max(1, maxBufferSizeMs * newRate / 1000); printf("mMaxBufferSize = %d\n", mMaxBufferSize); mBuffer = new float[mMaxBufferSize]; SDL_memset(mBuffer, 0, mMaxBufferSize * sizeof(mBuffer[0])); mHead = 0; } <commit_msg>ReverbModule dry out<commit_after>#include "ReverbModule.h" #include "../Random.h" #include <algorithm> #include <cstdlib> #include <cstdio> #include "SDL.h" ReverbModule::ReverbModule(ModularSynth& synth) :SynthModule(synth, moduleId, 2, 2, 0), mHead(0), mBuffer(NULL) { Random rnd; rnd.seed(rand()); for (int i = 0 ; i < numTaps ; ++i) { mTap[i].gain = 1.0f / (1 + i); mTap[i].delay = static_cast<float>(i) / numTaps + rnd.rndf() * 0.9f / numTaps + 0.01f; } } ReverbModule::~ReverbModule() { if (mBuffer != NULL) { delete[] mBuffer; } } void ReverbModule::cycle() { mBuffer[mHead] = getInput(0); float delay = std::min(static_cast<float>(maxBufferSizeMs) / 1000, std::max(0.0f, getInput(1))); float sum = 0; for (int i = 0 ; i < numTaps ; ++i) { sum += mBuffer[static_cast<int>(mHead - delay * mTap[i].delay * mSampleRate + mMaxBufferSize) % mMaxBufferSize] * mTap[i].gain; } setOutput(0, sum); setOutput(1, getInput(0)); ++mHead; if (mHead >= mMaxBufferSize) mHead = 0; } const char * ReverbModule::getInputName(int input) const { static const char *names[] = {"Input", "Length"}; return names[input]; } const char * ReverbModule::getOutputName(int output) const { static const char *names[] = {"Reverb out", "Dry out"}; return names[output]; } const char * ReverbModule::getName() const { return "Reverb"; } SynthModule * ReverbModule::createModule(ModularSynth& synth) { return new ReverbModule(synth); } void ReverbModule::setSampleRate(int newRate) { SynthModule::setSampleRate(newRate); if (mBuffer != NULL) delete[] mBuffer; mMaxBufferSize = std::max(1, maxBufferSizeMs * newRate / 1000); mBuffer = new float[mMaxBufferSize]; SDL_memset(mBuffer, 0, mMaxBufferSize * sizeof(mBuffer[0])); mHead = 0; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Baozeng Ding <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "NullDerefProtectionTransformer.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/Expr.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Sema/Lookup.h" #include <bitset> using namespace clang; namespace { using namespace cling; class PointerCheckInjector : public RecursiveASTVisitor<PointerCheckInjector> { private: Interpreter& m_Interp; Sema& m_Sema; typedef llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > decl_map_t; llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > m_NonNullArgIndexs; ///\brief Needed for the AST transformations, owned by Sema. /// ASTContext& m_Context; ///\brief cling_runtime_internal_throwIfInvalidPointer cache. /// LookupResult* m_clingthrowIfInvalidPointerCache; bool IsTransparentThis(Expr* E) { if (llvm::isa<CXXThisExpr>(E)) return true; if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) return IsTransparentThis(ICE->getSubExpr()); return false; } public: PointerCheckInjector(Interpreter& I) : m_Interp(I), m_Sema(I.getCI()->getSema()), m_Context(I.getCI()->getASTContext()), m_clingthrowIfInvalidPointerCache(0) {} ~PointerCheckInjector() { delete m_clingthrowIfInvalidPointerCache; } bool VisitUnaryOperator(UnaryOperator* UnOp) { Expr* SubExpr = UnOp->getSubExpr(); VisitStmt(SubExpr); if (UnOp->getOpcode() == UO_Deref && !IsTransparentThis(SubExpr) && SubExpr->getType().getTypePtr()->isPointerType()) UnOp->setSubExpr(SynthesizeCheck(SubExpr)); return true; } bool VisitMemberExpr(MemberExpr* ME) { Expr* Base = ME->getBase(); VisitStmt(Base); if (ME->isArrow() && !IsTransparentThis(Base) && ME->getMemberDecl()->isCXXInstanceMember()) ME->setBase(SynthesizeCheck(Base)); return true; } bool VisitCallExpr(CallExpr* CE) { VisitStmt(CE->getCallee()); FunctionDecl* FDecl = CE->getDirectCallee(); if (FDecl && isDeclCandidate(FDecl)) { decl_map_t::const_iterator it = m_NonNullArgIndexs.find(FDecl); const std::bitset<32>& ArgIndexs = it->second; Sema::ContextRAII pushedDC(m_Sema, FDecl); for (int index = 0; index < 32; ++index) { if (ArgIndexs.test(index)) { // Get the argument with the nonnull attribute. Expr* Arg = CE->getArg(index); if (Arg->getType().getTypePtr()->isPointerType() && !IsTransparentThis(Arg)) CE->setArg(index, SynthesizeCheck(Arg)); } } } return true; } bool TraverseFunctionDecl(FunctionDecl* FD) { // We cannot synthesize when there is a const expr // and if it is a function template (we will do the transformation on // the instance). if (!FD->isConstexpr() && !FD->getDescribedFunctionTemplate()) RecursiveASTVisitor::TraverseFunctionDecl(FD); return true; } bool TraverseCXXMethodDecl(CXXMethodDecl* CXXMD) { // We cannot synthesize when there is a const expr. if (!CXXMD->isConstexpr()) RecursiveASTVisitor::TraverseCXXMethodDecl(CXXMD); return true; } private: Expr* SynthesizeCheck(Expr* Arg) { assert(Arg && "Cannot call with Arg=0"); if(!m_clingthrowIfInvalidPointerCache) FindAndCacheRuntimeLookupResult(); SourceLocation Loc = Arg->getBeginLoc(); Expr* VoidSemaArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema, m_Context.VoidPtrTy, (uintptr_t)&m_Interp); Expr* VoidExprArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema, m_Context.VoidPtrTy, (uintptr_t)Arg); Scope* S = m_Sema.getScopeForContext(m_Sema.CurContext); CXXScopeSpec CSS; Expr* checkCall = m_Sema.BuildDeclarationNameExpr(CSS, *m_clingthrowIfInvalidPointerCache, /*ADL*/ false).get(); const clang::FunctionProtoType* checkCallType = llvm::dyn_cast<const clang::FunctionProtoType>( checkCall->getType().getTypePtr()); TypeSourceInfo* constVoidPtrTSI = m_Context.getTrivialTypeSourceInfo( checkCallType->getParamType(2), Loc); // It is unclear whether this is the correct cast if the type // is dependent. Hence, For now, we do not expect SynthesizeCheck to // be run on a function template. It should be run only on function // instances. // When this is actually insert in a function template, it seems that // clang r272382 when instantiating the templates drops one of the part // of the implicit cast chain. // Namely in: /* `-ImplicitCastExpr 0x1010cea90 <col:4> 'const void *' <BitCast> `-ImplicitCastExpr 0x1026e0bc0 <col:4> 'const class TAttMarker *' <UncheckedDerivedToBase (TAttMarker)> `-ImplicitCastExpr 0x1026e0b48 <col:4> 'class TGraph *' <LValueToRValue> `-DeclRefExpr 0x1026e0b20 <col:4> 'class TGraph *' lvalue Var 0x1026e09c0 'g5' 'class TGraph *' */ // It drops the 2nd lines (ImplicitCastExpr UncheckedDerivedToBase) // clang r227800 seems to actually keep that lines during instantiation. Expr* voidPtrArg = m_Sema.BuildCStyleCastExpr(Loc, constVoidPtrTSI, Loc, Arg).get(); Expr *args[] = {VoidSemaArg, VoidExprArg, voidPtrArg}; if (Expr* call = m_Sema.ActOnCallExpr(S, checkCall, Loc, args, Loc).get()) { // It is unclear whether this is the correct cast if the type // is dependent. Hence, For now, we do not expect SynthesizeCheck to // be run on a function template. It should be run only on function // instances. clang::TypeSourceInfo* argTSI = m_Context.getTrivialTypeSourceInfo( Arg->getType(), Loc); Expr* castExpr = m_Sema.BuildCStyleCastExpr(Loc, argTSI, Loc, call).get(); return castExpr; } return voidPtrArg; } bool isDeclCandidate(FunctionDecl * FDecl) { if (m_NonNullArgIndexs.count(FDecl)) return true; if (llvm::isa<CXXRecordDecl>(FDecl)) return true; std::bitset<32> ArgIndexs; for (specific_attr_iterator<NonNullAttr> I = FDecl->specific_attr_begin<NonNullAttr>(), E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) { NonNullAttr *NonNull = *I; for (NonNullAttr::args_iterator i = NonNull->args_begin(), e = NonNull->args_end(); i != e; ++i) { ArgIndexs.set(*i); } } if (ArgIndexs.any()) { m_NonNullArgIndexs.insert(std::make_pair(FDecl, ArgIndexs)); return true; } return false; } void FindAndCacheRuntimeLookupResult() { assert(!m_clingthrowIfInvalidPointerCache && "Called multiple times!?"); DeclarationName Name = &m_Context.Idents.get("cling_runtime_internal_throwIfInvalidPointer"); SourceLocation noLoc; m_clingthrowIfInvalidPointerCache = new LookupResult(m_Sema, Name, noLoc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); m_Sema.LookupQualifiedName(*m_clingthrowIfInvalidPointerCache, m_Context.getTranslationUnitDecl()); assert(!m_clingthrowIfInvalidPointerCache->empty() && "Lookup of cling_runtime_internal_throwIfInvalidPointer failed!"); } }; static bool hasPtrCheckDisabledInContext(const Decl* D) { if (isa<TranslationUnitDecl>(D)) return false; for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) { if (Ann->getAnnotation() == "__cling__ptrcheck(off)") return true; else if (Ann->getAnnotation() == "__cling__ptrcheck(on)") return false; } const Decl* Parent = nullptr; for (auto DC = D->getDeclContext(); !Parent; DC = DC->getParent()) Parent = dyn_cast<Decl>(DC); assert(Parent && "Decl without context!"); return hasPtrCheckDisabledInContext(Parent); } } // unnamed namespace namespace cling { NullDerefProtectionTransformer::NullDerefProtectionTransformer(Interpreter* I) : ASTTransformer(&I->getCI()->getSema()), m_Interp(I) { } NullDerefProtectionTransformer::~NullDerefProtectionTransformer() { } bool NullDerefProtectionTransformer::shouldTransform(const clang::Decl* D) { if (D->isFromASTFile()) return false; if (D->isTemplateDecl()) return false; if (hasPtrCheckDisabledInContext(D)) return false; auto Loc = D->getLocation(); if (Loc.isInvalid()) return false; SourceManager& SM = m_Interp->getSema().getSourceManager(); auto Characteristic = SM.getFileCharacteristic(Loc); if (Characteristic != clang::SrcMgr::C_User) return false; auto FID = SM.getFileID(Loc); if (FID.isInvalid()) return false; auto FE = SM.getFileEntryForID(FID); if (!FE) return false; auto Dir = FE->getDir(); if (!Dir) return false; auto IterAndInserted = m_ShouldVisitDir.try_emplace(Dir, true); if (IterAndInserted.second == false) return IterAndInserted.first->second; if (llvm::sys::fs::can_write(Dir->getName())) return true; // `true` is already emplaced above. // Remember that this dir is not writable and should not be visited. IterAndInserted.first->second = false; return false; } ASTTransformer::Result NullDerefProtectionTransformer::Transform(clang::Decl* D) { if (getCompilationOpts().CheckPointerValidity && shouldTransform(D)) { PointerCheckInjector injector(*m_Interp); injector.TraverseDecl(D); } return Result(D, true); } } // end namespace cling <commit_msg>Index goes behind the getASTIndex interface.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Baozeng Ding <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "NullDerefProtectionTransformer.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/Expr.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Sema/Lookup.h" #include <bitset> using namespace clang; namespace { using namespace cling; class PointerCheckInjector : public RecursiveASTVisitor<PointerCheckInjector> { private: Interpreter& m_Interp; Sema& m_Sema; typedef llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > decl_map_t; llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > m_NonNullArgIndexs; ///\brief Needed for the AST transformations, owned by Sema. /// ASTContext& m_Context; ///\brief cling_runtime_internal_throwIfInvalidPointer cache. /// LookupResult* m_clingthrowIfInvalidPointerCache; bool IsTransparentThis(Expr* E) { if (llvm::isa<CXXThisExpr>(E)) return true; if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) return IsTransparentThis(ICE->getSubExpr()); return false; } public: PointerCheckInjector(Interpreter& I) : m_Interp(I), m_Sema(I.getCI()->getSema()), m_Context(I.getCI()->getASTContext()), m_clingthrowIfInvalidPointerCache(0) {} ~PointerCheckInjector() { delete m_clingthrowIfInvalidPointerCache; } bool VisitUnaryOperator(UnaryOperator* UnOp) { Expr* SubExpr = UnOp->getSubExpr(); VisitStmt(SubExpr); if (UnOp->getOpcode() == UO_Deref && !IsTransparentThis(SubExpr) && SubExpr->getType().getTypePtr()->isPointerType()) UnOp->setSubExpr(SynthesizeCheck(SubExpr)); return true; } bool VisitMemberExpr(MemberExpr* ME) { Expr* Base = ME->getBase(); VisitStmt(Base); if (ME->isArrow() && !IsTransparentThis(Base) && ME->getMemberDecl()->isCXXInstanceMember()) ME->setBase(SynthesizeCheck(Base)); return true; } bool VisitCallExpr(CallExpr* CE) { VisitStmt(CE->getCallee()); FunctionDecl* FDecl = CE->getDirectCallee(); if (FDecl && isDeclCandidate(FDecl)) { decl_map_t::const_iterator it = m_NonNullArgIndexs.find(FDecl); const std::bitset<32>& ArgIndexs = it->second; Sema::ContextRAII pushedDC(m_Sema, FDecl); for (int index = 0; index < 32; ++index) { if (ArgIndexs.test(index)) { // Get the argument with the nonnull attribute. Expr* Arg = CE->getArg(index); if (Arg->getType().getTypePtr()->isPointerType() && !IsTransparentThis(Arg)) CE->setArg(index, SynthesizeCheck(Arg)); } } } return true; } bool TraverseFunctionDecl(FunctionDecl* FD) { // We cannot synthesize when there is a const expr // and if it is a function template (we will do the transformation on // the instance). if (!FD->isConstexpr() && !FD->getDescribedFunctionTemplate()) RecursiveASTVisitor::TraverseFunctionDecl(FD); return true; } bool TraverseCXXMethodDecl(CXXMethodDecl* CXXMD) { // We cannot synthesize when there is a const expr. if (!CXXMD->isConstexpr()) RecursiveASTVisitor::TraverseCXXMethodDecl(CXXMD); return true; } private: Expr* SynthesizeCheck(Expr* Arg) { assert(Arg && "Cannot call with Arg=0"); if(!m_clingthrowIfInvalidPointerCache) FindAndCacheRuntimeLookupResult(); SourceLocation Loc = Arg->getBeginLoc(); Expr* VoidSemaArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema, m_Context.VoidPtrTy, (uintptr_t)&m_Interp); Expr* VoidExprArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema, m_Context.VoidPtrTy, (uintptr_t)Arg); Scope* S = m_Sema.getScopeForContext(m_Sema.CurContext); CXXScopeSpec CSS; Expr* checkCall = m_Sema.BuildDeclarationNameExpr(CSS, *m_clingthrowIfInvalidPointerCache, /*ADL*/ false).get(); const clang::FunctionProtoType* checkCallType = llvm::dyn_cast<const clang::FunctionProtoType>( checkCall->getType().getTypePtr()); TypeSourceInfo* constVoidPtrTSI = m_Context.getTrivialTypeSourceInfo( checkCallType->getParamType(2), Loc); // It is unclear whether this is the correct cast if the type // is dependent. Hence, For now, we do not expect SynthesizeCheck to // be run on a function template. It should be run only on function // instances. // When this is actually insert in a function template, it seems that // clang r272382 when instantiating the templates drops one of the part // of the implicit cast chain. // Namely in: /* `-ImplicitCastExpr 0x1010cea90 <col:4> 'const void *' <BitCast> `-ImplicitCastExpr 0x1026e0bc0 <col:4> 'const class TAttMarker *' <UncheckedDerivedToBase (TAttMarker)> `-ImplicitCastExpr 0x1026e0b48 <col:4> 'class TGraph *' <LValueToRValue> `-DeclRefExpr 0x1026e0b20 <col:4> 'class TGraph *' lvalue Var 0x1026e09c0 'g5' 'class TGraph *' */ // It drops the 2nd lines (ImplicitCastExpr UncheckedDerivedToBase) // clang r227800 seems to actually keep that lines during instantiation. Expr* voidPtrArg = m_Sema.BuildCStyleCastExpr(Loc, constVoidPtrTSI, Loc, Arg).get(); Expr *args[] = {VoidSemaArg, VoidExprArg, voidPtrArg}; if (Expr* call = m_Sema.ActOnCallExpr(S, checkCall, Loc, args, Loc).get()) { // It is unclear whether this is the correct cast if the type // is dependent. Hence, For now, we do not expect SynthesizeCheck to // be run on a function template. It should be run only on function // instances. clang::TypeSourceInfo* argTSI = m_Context.getTrivialTypeSourceInfo( Arg->getType(), Loc); Expr* castExpr = m_Sema.BuildCStyleCastExpr(Loc, argTSI, Loc, call).get(); return castExpr; } return voidPtrArg; } bool isDeclCandidate(FunctionDecl * FDecl) { if (m_NonNullArgIndexs.count(FDecl)) return true; if (llvm::isa<CXXRecordDecl>(FDecl)) return true; std::bitset<32> ArgIndexs; for (specific_attr_iterator<NonNullAttr> I = FDecl->specific_attr_begin<NonNullAttr>(), E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) { NonNullAttr *NonNull = *I; for (const auto &Idx : NonNull->args()) { ArgIndexs.set(Idx.getASTIndex()); } } if (ArgIndexs.any()) { m_NonNullArgIndexs.insert(std::make_pair(FDecl, ArgIndexs)); return true; } return false; } void FindAndCacheRuntimeLookupResult() { assert(!m_clingthrowIfInvalidPointerCache && "Called multiple times!?"); DeclarationName Name = &m_Context.Idents.get("cling_runtime_internal_throwIfInvalidPointer"); SourceLocation noLoc; m_clingthrowIfInvalidPointerCache = new LookupResult(m_Sema, Name, noLoc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); m_Sema.LookupQualifiedName(*m_clingthrowIfInvalidPointerCache, m_Context.getTranslationUnitDecl()); assert(!m_clingthrowIfInvalidPointerCache->empty() && "Lookup of cling_runtime_internal_throwIfInvalidPointer failed!"); } }; static bool hasPtrCheckDisabledInContext(const Decl* D) { if (isa<TranslationUnitDecl>(D)) return false; for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) { if (Ann->getAnnotation() == "__cling__ptrcheck(off)") return true; else if (Ann->getAnnotation() == "__cling__ptrcheck(on)") return false; } const Decl* Parent = nullptr; for (auto DC = D->getDeclContext(); !Parent; DC = DC->getParent()) Parent = dyn_cast<Decl>(DC); assert(Parent && "Decl without context!"); return hasPtrCheckDisabledInContext(Parent); } } // unnamed namespace namespace cling { NullDerefProtectionTransformer::NullDerefProtectionTransformer(Interpreter* I) : ASTTransformer(&I->getCI()->getSema()), m_Interp(I) { } NullDerefProtectionTransformer::~NullDerefProtectionTransformer() { } bool NullDerefProtectionTransformer::shouldTransform(const clang::Decl* D) { if (D->isFromASTFile()) return false; if (D->isTemplateDecl()) return false; if (hasPtrCheckDisabledInContext(D)) return false; auto Loc = D->getLocation(); if (Loc.isInvalid()) return false; SourceManager& SM = m_Interp->getSema().getSourceManager(); auto Characteristic = SM.getFileCharacteristic(Loc); if (Characteristic != clang::SrcMgr::C_User) return false; auto FID = SM.getFileID(Loc); if (FID.isInvalid()) return false; auto FE = SM.getFileEntryForID(FID); if (!FE) return false; auto Dir = FE->getDir(); if (!Dir) return false; auto IterAndInserted = m_ShouldVisitDir.try_emplace(Dir, true); if (IterAndInserted.second == false) return IterAndInserted.first->second; if (llvm::sys::fs::can_write(Dir->getName())) return true; // `true` is already emplaced above. // Remember that this dir is not writable and should not be visited. IterAndInserted.first->second = false; return false; } ASTTransformer::Result NullDerefProtectionTransformer::Transform(clang::Decl* D) { if (getCompilationOpts().CheckPointerValidity && shouldTransform(D)) { PointerCheckInjector injector(*m_Interp); injector.TraverseDecl(D); } return Result(D, true); } } // end namespace cling <|endoftext|>
<commit_before>#ifndef HTTP_CLIENT_HH #define HTTP_CLIENT_HH #include "http/http_message.hh" #include "shared_pool.hh" #include "buffer.hh" namespace ten { class http_client { private: std::shared_ptr<netsock> s; buffer buf; void ensure_connection() { if (s && s->valid()) return; s.reset(new netsock(AF_INET, SOCK_STREAM)); if (s->dial(host.c_str(), port) != 0) { throw errorx("dial %s:%d failed", host.c_str(), port); } } public: const std::string host; const uint16_t port; size_t max_content_length; http_client(const std::string &host_, uint16_t port_=80) : buf(4*1024), host(host_), port(port_), max_content_length(-1) {} http_response perform(const std::string &method, const std::string &path, const std::string &data="") { try { ensure_connection(); uri u; u.scheme = "http"; u.host = host; u.port = port; u.path = path; u.normalize(); http_request r(method, u.compose(true)); // HTTP/1.1 requires host header r.append("Host", u.host); r.append("Content-Length", data.size()); std::string hdata = r.data(); ssize_t nw = s->send(hdata.c_str(), hdata.size()); nw = s->send(data.c_str(), data.size()); http_parser parser; http_response resp; resp.parser_init(&parser); buf.clear(); while (!resp.complete) { buf.reserve(4*1024); ssize_t nr = s->recv(buf.back(), buf.available()); if (nr <= 0) { throw errorx("http get error"); } buf.commit(nr); size_t len = buf.size(); resp.parse(&parser, buf.front(), len); buf.remove(len); if (resp.body.size() >= max_content_length) { s.reset(); // close this socket, we won't read anymore return resp; } } // should not be any data left over in buf CHECK(buf.size() == 0); return resp; } catch (errorx &e) { s.reset(); throw; } } http_response get(const std::string &path) { return perform("GET", path); } http_response post(const std::string &path, const std::string &data) { return perform("POST", path, data); } }; class http_pool : public shared_pool<http_client> { public: http_pool(const std::string &host_, uint16_t port_, ssize_t max_conn) : shared_pool<http_client>("http://" + host_, std::bind(&http_pool::new_resource, this), max_conn ), host(host_), port(port_) {} protected: std::string host; uint16_t port; std::shared_ptr<http_client> new_resource() { VLOG(3) << "new http_client resource " << host; return std::make_shared<http_client>(host, port); } }; } // end namespace ten #endif // HTTP_CLIENT_HH <commit_msg>custom error type<commit_after>#ifndef HTTP_CLIENT_HH #define HTTP_CLIENT_HH #include "http/http_message.hh" #include "shared_pool.hh" #include "buffer.hh" namespace ten { class http_error : public errorx { public: http_error(const std::string &msg) : errorx(msg) {} }; class http_client { private: std::shared_ptr<netsock> s; buffer buf; void ensure_connection() { if (s && s->valid()) return; s.reset(new netsock(AF_INET, SOCK_STREAM)); if (s->dial(host.c_str(), port) != 0) { throw http_error("dial"); } } public: const std::string host; const uint16_t port; size_t max_content_length; http_client(const std::string &host_, uint16_t port_=80) : buf(4*1024), host(host_), port(port_), max_content_length(-1) {} http_response perform(const std::string &method, const std::string &path, const std::string &data="") { try { ensure_connection(); uri u; u.scheme = "http"; u.host = host; u.port = port; u.path = path; u.normalize(); http_request r(method, u.compose(true)); // HTTP/1.1 requires host header r.append("Host", u.host); r.append("Content-Length", data.size()); std::string hdata = r.data(); ssize_t nw = s->send(hdata.c_str(), hdata.size()); nw = s->send(data.c_str(), data.size()); http_parser parser; http_response resp; resp.parser_init(&parser); buf.clear(); while (!resp.complete) { buf.reserve(4*1024); ssize_t nr = s->recv(buf.back(), buf.available()); if (nr <= 0) { throw http_error("recv"); } buf.commit(nr); size_t len = buf.size(); resp.parse(&parser, buf.front(), len); buf.remove(len); if (resp.body.size() >= max_content_length) { s.reset(); // close this socket, we won't read anymore return resp; } } // should not be any data left over in buf CHECK(buf.size() == 0); return resp; } catch (errorx &e) { s.reset(); throw; } } http_response get(const std::string &path) { return perform("GET", path); } http_response post(const std::string &path, const std::string &data) { return perform("POST", path, data); } }; class http_pool : public shared_pool<http_client> { public: http_pool(const std::string &host_, uint16_t port_, ssize_t max_conn) : shared_pool<http_client>("http://" + host_, std::bind(&http_pool::new_resource, this), max_conn ), host(host_), port(port_) {} protected: std::string host; uint16_t port; std::shared_ptr<http_client> new_resource() { VLOG(3) << "new http_client resource " << host; return std::make_shared<http_client>(host, port); } }; } // end namespace ten #endif // HTTP_CLIENT_HH <|endoftext|>
<commit_before>/****************************************************************************** * $Id$ * * Project: libLAS - http://liblas.org - A BSD library for LAS format data. * Purpose: LAS Dimension implementation for C++ libLAS * Author: Howard Butler, [email protected] * ****************************************************************************** * Copyright (c) 2010, Howard Butler * * 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 Martin Isenburg or Iowa Department * of Natural Resources nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/Dimension.hpp> #include <pdal/GlobalEnvironment.hpp> #include <boost/algorithm/string.hpp> #include <boost/uuid/string_generator.hpp> #include <boost/uuid/random_generator.hpp> #include <boost/uuid/uuid_io.hpp> #include <map> #include <time.h> #include <cstdlib> namespace pdal { Dimension::Dimension(std::string const& name, dimension::Interpretation interpretation, dimension::size_type sizeInBytes, std::string description) : m_name(name) , m_flags(0) , m_endian(pdal::Endian_Little) , m_byteSize(sizeInBytes) , m_description(description) , m_min(0.0) , m_max(0.0) , m_numericScale(1.0) , m_numericOffset(0.0) , m_byteOffset(0) , m_position(-1) , m_interpretation(interpretation) , m_uuid(boost::uuids::nil_uuid()) , m_namespace(std::string("")) , m_parentDimensionID(boost::uuids::nil_uuid()) { if (!m_name.size()) { // Generate a random name from the time ::time_t seconds; ::time(&seconds); std::ostringstream oss; srand(static_cast<unsigned int>(seconds)); oss << "unnamed" << rand(); m_name = oss.str(); } } /// copy constructor Dimension::Dimension(Dimension const& other) : m_name(other.m_name) , m_flags(other.m_flags) , m_endian(other.m_endian) , m_byteSize(other.m_byteSize) , m_description(other.m_description) , m_min(other.m_min) , m_max(other.m_max) , m_numericScale(other.m_numericScale) , m_numericOffset(other.m_numericOffset) , m_byteOffset(other.m_byteOffset) , m_position(other.m_position) , m_interpretation(other.m_interpretation) , m_uuid(other.m_uuid) , m_namespace(other.m_namespace) , m_parentDimensionID(other.m_parentDimensionID) { return; } /// assignment operator Dimension& Dimension::operator=(Dimension const& rhs) { if (&rhs != this) { m_name = rhs.m_name; m_flags = rhs.m_flags; m_endian = rhs.m_endian; m_byteSize = rhs.m_byteSize; m_description = rhs.m_description; m_min = rhs.m_min; m_max = rhs.m_max; m_numericScale = rhs.m_numericScale; m_numericOffset = rhs.m_numericOffset; m_byteOffset = rhs.m_byteOffset; m_position = rhs.m_position; m_interpretation = rhs.m_interpretation; m_uuid = rhs.m_uuid; m_namespace = rhs.m_namespace; m_parentDimensionID = rhs.m_parentDimensionID; } return *this; } bool Dimension::operator==(const Dimension& other) const { if (boost::iequals(m_name, other.m_name) && m_flags == other.m_flags && m_endian == other.m_endian && m_byteSize == other.m_byteSize && boost::iequals(m_description, other.m_description) && Utils::compare_approx(m_min, other.m_min, (std::numeric_limits<double>::min)()) && Utils::compare_approx(m_max, other.m_max, (std::numeric_limits<double>::min)()) && Utils::compare_approx(m_numericScale, other.m_numericScale, (std::numeric_limits<double>::min)()) && Utils::compare_approx(m_numericOffset, other.m_numericOffset, (std::numeric_limits<double>::min)()) && m_byteOffset == other.m_byteOffset && m_position == other.m_position && m_interpretation == other.m_interpretation && m_uuid == other.m_uuid && m_parentDimensionID == other.m_parentDimensionID ) { return true; } return false; } bool Dimension::operator!=(const Dimension& other) const { return !(*this==other); } boost::property_tree::ptree Dimension::toPTree() const { using boost::property_tree::ptree; ptree dim; dim.put("name", getName()); dim.put("namespace", getNamespace()); dim.put("parent", getParent()); dim.put("description", getDescription()); dim.put("bytesize", getByteSize()); std::string e("little"); if (getEndianness() == Endian_Big) e = std::string("big"); dim.put("endianness", e); dim.put("minimum", getMinimum()); dim.put("maximum", getMaximum()); dim.put("scale", getNumericScale()); dim.put("offset", getNumericOffset()); dim.put("scale", getNumericScale()); dim.put("position", getPosition()); dim.put("byteoffset", getByteOffset()); dim.put("isIgnored", isIgnored()); std::stringstream oss; dimension::id t = getUUID(); oss << t; dim.put("uuid", oss.str()); return dim; } void Dimension::setUUID(std::string const& id) { boost::uuids::string_generator gen; m_uuid = gen(id); } void Dimension::createUUID() { // Global RNG GlobalEnvironment& env = pdal::GlobalEnvironment::get(); boost::uuids::basic_random_generator<boost::mt19937> gen(env.getRNG()); m_uuid = gen(); // Stack-allocated, uninitialized RNG // boost::mt19937 ran; // boost::uuids::basic_random_generator<boost::mt19937> gen(&ran); // m_uuid = gen(); // Single call, uninitialized RNG // m_uuid = boost::uuids::random_generator()(); } void Dimension::dump() const { std::cout << *this; } std::string Dimension::getInterpretationName() const { std::ostringstream type; dimension::Interpretation t = getInterpretation(); boost::uint32_t bytesize = getByteSize(); switch (t) { case dimension::SignedByte: if (bytesize == 1) type << "int8_t"; break; case dimension::UnsignedByte: if (bytesize == 1) type << "uint8_t"; break; case dimension::SignedInteger: if (bytesize == 1) type << "int8_t"; else if (bytesize == 2) type << "int16_t"; else if (bytesize == 4) type << "int32_t"; else if (bytesize == 8) type << "int64_t"; else type << "unknown"; break; case dimension::UnsignedInteger: if (bytesize == 1) type << "uint8_t"; else if (bytesize == 2) type << "uint16_t"; else if (bytesize == 4) type << "uint32_t"; else if (bytesize == 8) type << "uint64_t"; else type << "unknown"; break; case dimension::Float: if (bytesize == 4) type << "float"; else if (bytesize == 8) type << "double"; else type << "unknown"; break; case dimension::Pointer: type << "pointer"; break; case dimension::Undefined: type << "unknown"; break; } return type.str(); } dimension::Interpretation Dimension::getInterpretation(std::string const& interpretation) { if (boost::iequals(interpretation, "int8_t") || boost::iequals(interpretation, "int8")) return dimension::SignedInteger; if (boost::iequals(interpretation, "uint8_t") || boost::iequals(interpretation, "uint8")) return dimension::UnsignedInteger; if (boost::iequals(interpretation, "int16_t") || boost::iequals(interpretation, "int16")) return dimension::SignedInteger; if (boost::iequals(interpretation, "uint16_t") || boost::iequals(interpretation, "uint16")) return dimension::UnsignedInteger; if (boost::iequals(interpretation, "int32_t") || boost::iequals(interpretation, "int32")) return dimension::SignedInteger; if (boost::iequals(interpretation, "uint32_t") || boost::iequals(interpretation, "uint32")) return dimension::UnsignedInteger; if (boost::iequals(interpretation, "int64_t") || boost::iequals(interpretation, "int64")) return dimension::SignedInteger; if (boost::iequals(interpretation, "uint64_t") || boost::iequals(interpretation, "uint64")) return dimension::UnsignedInteger; if (boost::iequals(interpretation, "float")) return dimension::Float; if (boost::iequals(interpretation, "double")) return dimension::Float; return dimension::Undefined; } std::ostream& operator<<(std::ostream& os, pdal::Dimension const& d) { using boost::property_tree::ptree; ptree tree = d.toPTree(); std::string const name = tree.get<std::string>("name"); std::string const ns = tree.get<std::string>("namespace"); std::ostringstream quoted_name; if (ns.size()) quoted_name << "'" << ns << "." << name << "'"; else quoted_name << "'" << name << "'"; std::ostringstream pad; std::string const& cur = quoted_name.str(); std::string::size_type size = cur.size(); std::string::size_type buffer(24); std::string::size_type pad_size = buffer - size; if (size > buffer) pad_size = 4; for (std::string::size_type i=0; i != pad_size; i++) { pad << " "; } os << quoted_name.str() << pad.str() <<" -- "<< " size: " << tree.get<boost::uint32_t>("bytesize"); double scale = tree.get<double>("scale"); boost::uint32_t precision = Utils::getStreamPrecision(scale); os.setf(std::ios_base::fixed, std::ios_base::floatfield); os.precision(precision); os << " scale: " << scale; double offset = tree.get<double>("offset"); os << " offset: " << offset; os << " ignored: " << tree.get<bool>("isIgnored"); os << " uid: " << tree.get<std::string>("uuid"); os << " parent: " << tree.get<std::string>("parent"); os << std::endl; return os; } } // namespace pdal <commit_msg>flip back to old RNG initialization<commit_after>/****************************************************************************** * $Id$ * * Project: libLAS - http://liblas.org - A BSD library for LAS format data. * Purpose: LAS Dimension implementation for C++ libLAS * Author: Howard Butler, [email protected] * ****************************************************************************** * Copyright (c) 2010, Howard Butler * * 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 Martin Isenburg or Iowa Department * of Natural Resources nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/Dimension.hpp> #include <pdal/GlobalEnvironment.hpp> #include <boost/algorithm/string.hpp> #include <boost/uuid/string_generator.hpp> #include <boost/uuid/random_generator.hpp> #include <boost/uuid/uuid_io.hpp> #include <map> #include <time.h> #include <cstdlib> namespace pdal { Dimension::Dimension(std::string const& name, dimension::Interpretation interpretation, dimension::size_type sizeInBytes, std::string description) : m_name(name) , m_flags(0) , m_endian(pdal::Endian_Little) , m_byteSize(sizeInBytes) , m_description(description) , m_min(0.0) , m_max(0.0) , m_numericScale(1.0) , m_numericOffset(0.0) , m_byteOffset(0) , m_position(-1) , m_interpretation(interpretation) , m_uuid(boost::uuids::nil_uuid()) , m_namespace(std::string("")) , m_parentDimensionID(boost::uuids::nil_uuid()) { if (!m_name.size()) { // Generate a random name from the time ::time_t seconds; ::time(&seconds); std::ostringstream oss; srand(static_cast<unsigned int>(seconds)); oss << "unnamed" << rand(); m_name = oss.str(); } } /// copy constructor Dimension::Dimension(Dimension const& other) : m_name(other.m_name) , m_flags(other.m_flags) , m_endian(other.m_endian) , m_byteSize(other.m_byteSize) , m_description(other.m_description) , m_min(other.m_min) , m_max(other.m_max) , m_numericScale(other.m_numericScale) , m_numericOffset(other.m_numericOffset) , m_byteOffset(other.m_byteOffset) , m_position(other.m_position) , m_interpretation(other.m_interpretation) , m_uuid(other.m_uuid) , m_namespace(other.m_namespace) , m_parentDimensionID(other.m_parentDimensionID) { return; } /// assignment operator Dimension& Dimension::operator=(Dimension const& rhs) { if (&rhs != this) { m_name = rhs.m_name; m_flags = rhs.m_flags; m_endian = rhs.m_endian; m_byteSize = rhs.m_byteSize; m_description = rhs.m_description; m_min = rhs.m_min; m_max = rhs.m_max; m_numericScale = rhs.m_numericScale; m_numericOffset = rhs.m_numericOffset; m_byteOffset = rhs.m_byteOffset; m_position = rhs.m_position; m_interpretation = rhs.m_interpretation; m_uuid = rhs.m_uuid; m_namespace = rhs.m_namespace; m_parentDimensionID = rhs.m_parentDimensionID; } return *this; } bool Dimension::operator==(const Dimension& other) const { if (boost::iequals(m_name, other.m_name) && m_flags == other.m_flags && m_endian == other.m_endian && m_byteSize == other.m_byteSize && boost::iequals(m_description, other.m_description) && Utils::compare_approx(m_min, other.m_min, (std::numeric_limits<double>::min)()) && Utils::compare_approx(m_max, other.m_max, (std::numeric_limits<double>::min)()) && Utils::compare_approx(m_numericScale, other.m_numericScale, (std::numeric_limits<double>::min)()) && Utils::compare_approx(m_numericOffset, other.m_numericOffset, (std::numeric_limits<double>::min)()) && m_byteOffset == other.m_byteOffset && m_position == other.m_position && m_interpretation == other.m_interpretation && m_uuid == other.m_uuid && m_parentDimensionID == other.m_parentDimensionID ) { return true; } return false; } bool Dimension::operator!=(const Dimension& other) const { return !(*this==other); } boost::property_tree::ptree Dimension::toPTree() const { using boost::property_tree::ptree; ptree dim; dim.put("name", getName()); dim.put("namespace", getNamespace()); dim.put("parent", getParent()); dim.put("description", getDescription()); dim.put("bytesize", getByteSize()); std::string e("little"); if (getEndianness() == Endian_Big) e = std::string("big"); dim.put("endianness", e); dim.put("minimum", getMinimum()); dim.put("maximum", getMaximum()); dim.put("scale", getNumericScale()); dim.put("offset", getNumericOffset()); dim.put("scale", getNumericScale()); dim.put("position", getPosition()); dim.put("byteoffset", getByteOffset()); dim.put("isIgnored", isIgnored()); std::stringstream oss; dimension::id t = getUUID(); oss << t; dim.put("uuid", oss.str()); return dim; } void Dimension::setUUID(std::string const& id) { boost::uuids::string_generator gen; m_uuid = gen(id); } void Dimension::createUUID() { // Global RNG // GlobalEnvironment& env = pdal::GlobalEnvironment::get(); // boost::uuids::basic_random_generator<boost::mt19937> gen(env.getRNG()); // m_uuid = gen(); // Stack-allocated, uninitialized RNG // boost::mt19937 ran; // boost::uuids::basic_random_generator<boost::mt19937> gen(&ran); // m_uuid = gen(); // Single call, uninitialized RNG m_uuid = boost::uuids::random_generator()(); } void Dimension::dump() const { std::cout << *this; } std::string Dimension::getInterpretationName() const { std::ostringstream type; dimension::Interpretation t = getInterpretation(); boost::uint32_t bytesize = getByteSize(); switch (t) { case dimension::SignedByte: if (bytesize == 1) type << "int8_t"; break; case dimension::UnsignedByte: if (bytesize == 1) type << "uint8_t"; break; case dimension::SignedInteger: if (bytesize == 1) type << "int8_t"; else if (bytesize == 2) type << "int16_t"; else if (bytesize == 4) type << "int32_t"; else if (bytesize == 8) type << "int64_t"; else type << "unknown"; break; case dimension::UnsignedInteger: if (bytesize == 1) type << "uint8_t"; else if (bytesize == 2) type << "uint16_t"; else if (bytesize == 4) type << "uint32_t"; else if (bytesize == 8) type << "uint64_t"; else type << "unknown"; break; case dimension::Float: if (bytesize == 4) type << "float"; else if (bytesize == 8) type << "double"; else type << "unknown"; break; case dimension::Pointer: type << "pointer"; break; case dimension::Undefined: type << "unknown"; break; } return type.str(); } dimension::Interpretation Dimension::getInterpretation(std::string const& interpretation) { if (boost::iequals(interpretation, "int8_t") || boost::iequals(interpretation, "int8")) return dimension::SignedInteger; if (boost::iequals(interpretation, "uint8_t") || boost::iequals(interpretation, "uint8")) return dimension::UnsignedInteger; if (boost::iequals(interpretation, "int16_t") || boost::iequals(interpretation, "int16")) return dimension::SignedInteger; if (boost::iequals(interpretation, "uint16_t") || boost::iequals(interpretation, "uint16")) return dimension::UnsignedInteger; if (boost::iequals(interpretation, "int32_t") || boost::iequals(interpretation, "int32")) return dimension::SignedInteger; if (boost::iequals(interpretation, "uint32_t") || boost::iequals(interpretation, "uint32")) return dimension::UnsignedInteger; if (boost::iequals(interpretation, "int64_t") || boost::iequals(interpretation, "int64")) return dimension::SignedInteger; if (boost::iequals(interpretation, "uint64_t") || boost::iequals(interpretation, "uint64")) return dimension::UnsignedInteger; if (boost::iequals(interpretation, "float")) return dimension::Float; if (boost::iequals(interpretation, "double")) return dimension::Float; return dimension::Undefined; } std::ostream& operator<<(std::ostream& os, pdal::Dimension const& d) { using boost::property_tree::ptree; ptree tree = d.toPTree(); std::string const name = tree.get<std::string>("name"); std::string const ns = tree.get<std::string>("namespace"); std::ostringstream quoted_name; if (ns.size()) quoted_name << "'" << ns << "." << name << "'"; else quoted_name << "'" << name << "'"; std::ostringstream pad; std::string const& cur = quoted_name.str(); std::string::size_type size = cur.size(); std::string::size_type buffer(24); std::string::size_type pad_size = buffer - size; if (size > buffer) pad_size = 4; for (std::string::size_type i=0; i != pad_size; i++) { pad << " "; } os << quoted_name.str() << pad.str() <<" -- "<< " size: " << tree.get<boost::uint32_t>("bytesize"); double scale = tree.get<double>("scale"); boost::uint32_t precision = Utils::getStreamPrecision(scale); os.setf(std::ios_base::fixed, std::ios_base::floatfield); os.precision(precision); os << " scale: " << scale; double offset = tree.get<double>("offset"); os << " offset: " << offset; os << " ignored: " << tree.get<bool>("isIgnored"); os << " uid: " << tree.get<std::string>("uuid"); os << " parent: " << tree.get<std::string>("parent"); os << std::endl; return os; } } // namespace pdal <|endoftext|>
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <max_clique/tbmcsabin_max_clique.hh> #include <max_clique/colourise.hh> #include <max_clique/print_incumbent.hh> #include <threads/atomic_incumbent.hh> #include <threads/queue.hh> #include <graph/degree_sort.hh> #include <algorithm> #include <list> #include <functional> #include <vector> #include <thread> using namespace parasols; namespace { template <unsigned size_> struct QueueItem { FixedBitSet<size_> c; FixedBitSet<size_> p; std::array<unsigned, size_ * bits_per_word> p_order; std::array<unsigned, size_ * bits_per_word> colours; std::vector<int> position; }; /** * We've possibly found a new best. Update best_anywhere and our local * result, and do any necessary printing. */ template <unsigned size_> auto found_possible_new_best(const FixedBitGraph<size_> & graph, const std::vector<int> & o, const FixedBitSet<size_> & c, int c_popcount, const MaxCliqueParams & params, MaxCliqueResult & result, AtomicIncumbent & best_anywhere, const std::vector<int> & position) -> void { if (best_anywhere.update(c_popcount)) { result.size = c_popcount; result.members.clear(); for (int i = 0 ; i < graph.size() ; ++i) if (c.test(i)) result.members.insert(o[i]); print_incumbent(params, result.size, position); } } /** * Bound function. */ auto bound(unsigned c_popcount, unsigned cn, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere) -> bool { unsigned best_anywhere_value = best_anywhere.get(); return (c_popcount + cn <= best_anywhere_value || best_anywhere_value >= params.stop_after_finding); } template <unsigned size_> auto expand( const FixedBitGraph<size_> & graph, const std::vector<int> & o, // static vertex ordering Queue<QueueItem<size_> > & queue, const std::array<unsigned, size_ * bits_per_word> & p_order, const std::array<unsigned, size_ * bits_per_word> & colours, FixedBitSet<size_> & c, // current candidate clique FixedBitSet<size_> & p, // potential additions MaxCliqueResult & result, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere, std::vector<int> & position) -> void { auto c_popcount = c.popcount(); // for each v in p... (v comes later) int n = p.popcount() - 1; // bound, timeout or early exit? if (bound(c_popcount, colours[n], params, best_anywhere) || params.abort.load()) return; auto v = p_order[n]; // queue empty? enqueue "not taking v" bool enqueued_not_v = false; if (n > 5 && queue.want_donations()) { enqueued_not_v = true; auto alt_p = p; alt_p.unset(v); auto alt_position = position; ++alt_position.back(); queue.enqueue(QueueItem<size_>{ c, alt_p, p_order, colours, alt_position }); } // consider taking v c.set(v); ++c_popcount; ++position.back(); // filter p to contain vertices adjacent to v FixedBitSet<size_> new_p = p; new_p = p; graph.intersect_with_row(v, new_p); if (new_p.empty()) { found_possible_new_best(graph, o, c, c_popcount, params, result, best_anywhere, position); } else { std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours; colourise<size_>(graph, new_p, new_p_order, new_colours); ++result.nodes; // rough consistency... position.push_back(0); expand<size_>(graph, o, queue, new_p_order, new_colours, c, new_p, result, params, best_anywhere, position); position.pop_back(); } // now consider not taking v c.unset(v); p.unset(v); --c_popcount; if (n > 0 && ! enqueued_not_v) { expand<size_>(graph, o, queue, p_order, colours, c, p, result, params, best_anywhere, position); } } template <unsigned size_> auto max_clique(const FixedBitGraph<size_> & graph, const std::vector<int> & o, const MaxCliqueParams & params) -> MaxCliqueResult { Queue<QueueItem<size_> > queue{ params.n_threads, true }; // work queue MaxCliqueResult result; // global result std::mutex result_mutex; AtomicIncumbent best_anywhere; // global incumbent best_anywhere.update(params.initial_bound); std::list<std::thread> threads; // populating thread, and workers /* initial job */ { FixedBitSet<size_> tc; // local candidate clique tc.resize(graph.size()); FixedBitSet<size_> tp; // local potential additions tp.resize(graph.size()); tp.set_all(); std::vector<int> position; position.push_back(0); std::array<unsigned, size_ * bits_per_word> p_order, colours; colourise<size_>(graph, tp, p_order, colours); queue.enqueue(QueueItem<size_>{ tc, tp, p_order, colours, position }); queue.initial_producer_done(); } /* workers */ for (unsigned i = 0 ; i < params.n_threads ; ++i) { threads.push_back(std::thread([&, i] { auto start_time = std::chrono::steady_clock::now(); // local start time MaxCliqueResult tr; // local result while (true) { // get some work to do QueueItem<size_> args; if (! queue.dequeue_blocking(args)) break; // do some work expand<size_>(graph, o, queue, args.p_order, args.colours, args.c, args.p, tr, params, best_anywhere, args.position); // keep track of top nodes done if (! params.abort.load()) ++tr.top_nodes_done; } auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time); // merge results { std::unique_lock<std::mutex> guard(result_mutex); result.merge(tr); result.times.push_back(overall_time); } })); } // wait until they're done, and clean up threads for (auto & t : threads) t.join(); return result; } template <unsigned size_> auto tbmcsabin(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult { std::vector<int> o(graph.size()); // vertex ordering std::iota(o.begin(), o.end(), 0); degree_sort(graph, o, false); // re-encode graph as a bit graph FixedBitGraph<size_> bit_graph; bit_graph.resize(graph.size()); for (int i = 0 ; i < graph.size() ; ++i) for (int j = 0 ; j < graph.size() ; ++j) if (graph.adjacent(o[i], o[j])) bit_graph.add_edge(i, j); // go! return max_clique(bit_graph, o, params); } } auto parasols::tbmcsabin_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult { /* This is pretty horrible: in order to avoid dynamic allocation, select * the appropriate specialisation for our graph's size. */ static_assert(max_graph_words == 256, "Need to update here if max_graph_size is changed."); if (graph.size() < bits_per_word) return tbmcsabin<1>(graph, params); else if (graph.size() < 2 * bits_per_word) return tbmcsabin<2>(graph, params); else if (graph.size() < 4 * bits_per_word) return tbmcsabin<4>(graph, params); else if (graph.size() < 8 * bits_per_word) return tbmcsabin<8>(graph, params); else if (graph.size() < 16 * bits_per_word) return tbmcsabin<16>(graph, params); else if (graph.size() < 32 * bits_per_word) return tbmcsabin<32>(graph, params); else if (graph.size() < 64 * bits_per_word) return tbmcsabin<64>(graph, params); else if (graph.size() < 128 * bits_per_word) return tbmcsabin<128>(graph, params); else if (graph.size() < 256 * bits_per_word) return tbmcsabin<256>(graph, params); else throw GraphTooBig(); } <commit_msg>Don't queue things which will be eliminated<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <max_clique/tbmcsabin_max_clique.hh> #include <max_clique/colourise.hh> #include <max_clique/print_incumbent.hh> #include <threads/atomic_incumbent.hh> #include <threads/queue.hh> #include <graph/degree_sort.hh> #include <algorithm> #include <list> #include <functional> #include <vector> #include <thread> using namespace parasols; namespace { template <unsigned size_> struct QueueItem { FixedBitSet<size_> c; FixedBitSet<size_> p; std::array<unsigned, size_ * bits_per_word> p_order; std::array<unsigned, size_ * bits_per_word> colours; std::vector<int> position; }; /** * We've possibly found a new best. Update best_anywhere and our local * result, and do any necessary printing. */ template <unsigned size_> auto found_possible_new_best(const FixedBitGraph<size_> & graph, const std::vector<int> & o, const FixedBitSet<size_> & c, int c_popcount, const MaxCliqueParams & params, MaxCliqueResult & result, AtomicIncumbent & best_anywhere, const std::vector<int> & position) -> void { if (best_anywhere.update(c_popcount)) { result.size = c_popcount; result.members.clear(); for (int i = 0 ; i < graph.size() ; ++i) if (c.test(i)) result.members.insert(o[i]); print_incumbent(params, result.size, position); } } /** * Bound function. */ auto bound(unsigned c_popcount, unsigned cn, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere) -> bool { unsigned best_anywhere_value = best_anywhere.get(); return (c_popcount + cn <= best_anywhere_value || best_anywhere_value >= params.stop_after_finding); } template <unsigned size_> auto expand( const FixedBitGraph<size_> & graph, const std::vector<int> & o, // static vertex ordering Queue<QueueItem<size_> > & queue, const std::array<unsigned, size_ * bits_per_word> & p_order, const std::array<unsigned, size_ * bits_per_word> & colours, FixedBitSet<size_> & c, // current candidate clique FixedBitSet<size_> & p, // potential additions MaxCliqueResult & result, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere, std::vector<int> & position) -> void { auto c_popcount = c.popcount(); // for each v in p... (v comes later) int n = p.popcount() - 1; // bound, timeout or early exit? if (bound(c_popcount, colours[n], params, best_anywhere) || params.abort.load()) return; auto v = p_order[n]; // queue empty? enqueue "not taking v" bool enqueued_not_v = false; if (n > 5 && queue.want_donations() && ! bound(c_popcount, colours[n - 1], params, best_anywhere)) { enqueued_not_v = true; auto alt_p = p; alt_p.unset(v); auto alt_position = position; ++alt_position.back(); queue.enqueue(QueueItem<size_>{ c, alt_p, p_order, colours, alt_position }); } // consider taking v c.set(v); ++c_popcount; ++position.back(); // filter p to contain vertices adjacent to v FixedBitSet<size_> new_p = p; new_p = p; graph.intersect_with_row(v, new_p); if (new_p.empty()) { found_possible_new_best(graph, o, c, c_popcount, params, result, best_anywhere, position); } else { std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours; colourise<size_>(graph, new_p, new_p_order, new_colours); ++result.nodes; // rough consistency... position.push_back(0); expand<size_>(graph, o, queue, new_p_order, new_colours, c, new_p, result, params, best_anywhere, position); position.pop_back(); } // now consider not taking v c.unset(v); p.unset(v); --c_popcount; if (n > 0 && ! enqueued_not_v) { expand<size_>(graph, o, queue, p_order, colours, c, p, result, params, best_anywhere, position); } } template <unsigned size_> auto max_clique(const FixedBitGraph<size_> & graph, const std::vector<int> & o, const MaxCliqueParams & params) -> MaxCliqueResult { Queue<QueueItem<size_> > queue{ params.n_threads, true }; // work queue MaxCliqueResult result; // global result std::mutex result_mutex; AtomicIncumbent best_anywhere; // global incumbent best_anywhere.update(params.initial_bound); std::list<std::thread> threads; // populating thread, and workers /* initial job */ { FixedBitSet<size_> tc; // local candidate clique tc.resize(graph.size()); FixedBitSet<size_> tp; // local potential additions tp.resize(graph.size()); tp.set_all(); std::vector<int> position; position.push_back(0); std::array<unsigned, size_ * bits_per_word> p_order, colours; colourise<size_>(graph, tp, p_order, colours); queue.enqueue(QueueItem<size_>{ tc, tp, p_order, colours, position }); queue.initial_producer_done(); } /* workers */ for (unsigned i = 0 ; i < params.n_threads ; ++i) { threads.push_back(std::thread([&, i] { auto start_time = std::chrono::steady_clock::now(); // local start time MaxCliqueResult tr; // local result while (true) { // get some work to do QueueItem<size_> args; if (! queue.dequeue_blocking(args)) break; // do some work expand<size_>(graph, o, queue, args.p_order, args.colours, args.c, args.p, tr, params, best_anywhere, args.position); // keep track of top nodes done if (! params.abort.load()) ++tr.top_nodes_done; } auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time); // merge results { std::unique_lock<std::mutex> guard(result_mutex); result.merge(tr); result.times.push_back(overall_time); } })); } // wait until they're done, and clean up threads for (auto & t : threads) t.join(); return result; } template <unsigned size_> auto tbmcsabin(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult { std::vector<int> o(graph.size()); // vertex ordering std::iota(o.begin(), o.end(), 0); degree_sort(graph, o, false); // re-encode graph as a bit graph FixedBitGraph<size_> bit_graph; bit_graph.resize(graph.size()); for (int i = 0 ; i < graph.size() ; ++i) for (int j = 0 ; j < graph.size() ; ++j) if (graph.adjacent(o[i], o[j])) bit_graph.add_edge(i, j); // go! return max_clique(bit_graph, o, params); } } auto parasols::tbmcsabin_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult { /* This is pretty horrible: in order to avoid dynamic allocation, select * the appropriate specialisation for our graph's size. */ static_assert(max_graph_words == 256, "Need to update here if max_graph_size is changed."); if (graph.size() < bits_per_word) return tbmcsabin<1>(graph, params); else if (graph.size() < 2 * bits_per_word) return tbmcsabin<2>(graph, params); else if (graph.size() < 4 * bits_per_word) return tbmcsabin<4>(graph, params); else if (graph.size() < 8 * bits_per_word) return tbmcsabin<8>(graph, params); else if (graph.size() < 16 * bits_per_word) return tbmcsabin<16>(graph, params); else if (graph.size() < 32 * bits_per_word) return tbmcsabin<32>(graph, params); else if (graph.size() < 64 * bits_per_word) return tbmcsabin<64>(graph, params); else if (graph.size() < 128 * bits_per_word) return tbmcsabin<128>(graph, params); else if (graph.size() < 256 * bits_per_word) return tbmcsabin<256>(graph, params); else throw GraphTooBig(); } <|endoftext|>
<commit_before>/* The Next Great Finite Element Library. */ /* Copyright (C) 2003 Benjamin S. Kirk */ /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public */ /* License as published by the Free Software Foundation; either */ /* version 2.1 of the License, or (at your option) any later version. */ /* This library is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ /* Lesser General Public License for more details. */ /* You should have received a copy of the GNU Lesser General Public */ /* License along with this library; if not, write to the Free Software */ /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1> // // LibMesh provides interfaces to both Triangle and TetGen for generating // Delaunay triangulations and tetrahedralizations in two and three dimensions // (respectively). // Local header files #include "elem.h" #include "face_tri3.h" #include "mesh.h" #include "mesh_generation.h" #include "mesh_tetgen_interface.h" #include "mesh_triangle_holes.h" #include "mesh_triangle_interface.h" #include "node.h" #include "serial_mesh.h" // Bring in everything from the libMesh namespace using namespace libMesh; // Major functions called by main void triangulate_domain(); void tetrahedralize_domain(); // Helper routine for tetrahedralize_domain(). Adds the points and elements // of a convex hull generated by TetGen to the input mesh void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit); // Begin the main program. int main (int argc, char** argv) { // Initialize libMesh and any dependent libaries, like in example 2. LibMeshInit init (argc, argv); libmesh_example_assert(2 <= LIBMESH_DIM, "2D support"); std::cout << "Triangulating an L-shaped domain with holes" << std::endl; // 1.) 2D triangulation of L-shaped domain with three holes of different shape triangulate_domain(); libmesh_example_assert(3 <= LIBMESH_DIM, "3D support"); std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl; // 2.) 3D tetrahedralization of rectangular domain with hole. tetrahedralize_domain(); return 0; } void triangulate_domain() { #ifdef LIBMESH_HAVE_TRIANGLE // Use typedefs for slightly less typing. typedef TriangleInterface::Hole Hole; typedef TriangleInterface::PolygonHole PolygonHole; typedef TriangleInterface::ArbitraryHole ArbitraryHole; // Libmesh mesh that will eventually be created. Mesh mesh(2); // The points which make up the L-shape: mesh.add_point(Point( 0. , 0.)); mesh.add_point(Point( 0. , -1.)); mesh.add_point(Point(-1. , -1.)); mesh.add_point(Point(-1. , 1.)); mesh.add_point(Point( 1. , 1.)); mesh.add_point(Point( 1. , 0.)); // Declare the TriangleInterface object. This is where // we can set parameters of the triangulation and where the // actual triangulate function lives. TriangleInterface t(mesh); // Customize the variables for the triangulation t.desired_area() = .01; // A Planar Straight Line Graph (PSLG) is essentially a list // of segments which have to exist in the final triangulation. // For an L-shaped domain, Triangle will compute the convex // hull of boundary points if we do not specify the PSLG. // The PSLG algorithm is also required for triangulating domains // containing holes t.triangulation_type() = TriangleInterface::PSLG; // Turn on/off Laplacian mesh smoothing after generation. // By default this is on. t.smooth_after_generating() = true; // Define holes... // hole_1 is a circle (discretized by 50 points) PolygonHole hole_1(Point(-0.5, 0.5), // center 0.25, // radius 50); // n. points // hole_2 is itself a triangle PolygonHole hole_2(Point(0.5, 0.5), // center 0.1, // radius 3); // n. points // hole_3 is an ellipse of 100 points which we define here Point ellipse_center(-0.5, -0.5); const unsigned int n_ellipse_points=100; std::vector<Point> ellipse_points(n_ellipse_points); const Real dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points), a = .1, b = .2; for (unsigned int i=0; i<n_ellipse_points; ++i) ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta), ellipse_center(1)+b*sin(i*dtheta)); ArbitraryHole hole_3(ellipse_center, ellipse_points); // Create the vector of Hole*'s ... std::vector<Hole*> holes; holes.push_back(&hole_1); holes.push_back(&hole_2); holes.push_back(&hole_3); // ... and attach it to the triangulator object t.attach_hole_list(&holes); // Triangulate! t.triangulate(); // Write the result to file mesh.write("delaunay_l_shaped_hole.e"); #endif // LIBMESH_HAVE_TRIANGLE } void tetrahedralize_domain() { #ifdef LIBMESH_HAVE_TETGEN // The algorithm is broken up into several steps: // 1.) A convex hull is constructed for a rectangular hole. // 2.) A convex hull is constructed for the domain exterior. // 3.) Neighbor information is updated so TetGen knows there is a convex hull // 4.) A vector of hole points is created. // 5.) The domain is tetrahedralized, the mesh is written out, etc. // The mesh we will eventually generate SerialMesh mesh(3); // Lower and Upper bounding box limits for a rectangular hole within the unit cube. Point hole_lower_limit(0.2, 0.2, 0.4); Point hole_upper_limit(0.8, 0.8, 0.6); // 1.) Construct a convex hull for the hole add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit); // 2.) Generate elements comprising the outer boundary of the domain. add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.)); // 3.) Update neighbor information so that TetGen can verify there is a convex hull. mesh.find_neighbors(); // 4.) Set up vector of hole points std::vector<Point> hole(1); hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) ); // 5.) Set parameters and tetrahedralize the domain // 0 means "use TetGen default value" Real quality_constraint = 2.0; // The volume constraint determines the max-allowed tetrahedral // volume in the Mesh. TetGen will split cells which are larger than // this size Real volume_constraint = 0.001; // Construct the Delaunay tetrahedralization TetGenMeshInterface t(mesh); t.triangulate_conformingDelaunayMesh_carvehole(hole, quality_constraint, volume_constraint); // Find neighbors, etc in preparation for writing out the Mesh mesh.prepare_for_use(); // Finally, write out the result mesh.write("hole_3D.e"); #endif // LIBMESH_HAVE_TETGEN } void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit) { #ifdef LIBMESH_HAVE_TETGEN Mesh cube_mesh(3); unsigned n_elem = 1; MeshTools::Generation::build_cube(cube_mesh, n_elem,n_elem,n_elem, // n. elements in each direction lower_limit(0), upper_limit(0), lower_limit(1), upper_limit(1), lower_limit(2), upper_limit(2), HEX8); // The pointset_convexhull() algorithm will ignore the Hex8s // in the Mesh, and just construct the triangulation // of the convex hull. TetGenMeshInterface t(cube_mesh); t.pointset_convexhull(); // Now add all nodes from the boundary of the cube_mesh to the input mesh. // Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted // with a dummy value, later to be assigned a value by the input mesh. std::map<unsigned,unsigned> node_id_map; typedef std::map<unsigned,unsigned>::iterator iterator; { MeshBase::element_iterator it = cube_mesh.elements_begin(); const MeshBase::element_iterator end = cube_mesh.elements_end(); for ( ; it != end; ++it) { Elem* elem = *it; for (unsigned s=0; s<elem->n_sides(); ++s) if (elem->neighbor(s) == NULL) { // Add the node IDs of this side to the set AutoPtr<Elem> side = elem->side(s); for (unsigned n=0; n<side->n_nodes(); ++n) node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) ); } } } // For each node in the map, insert it into the input mesh and keep // track of the ID assigned. for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it) { // Id of the node in the cube mesh unsigned id = (*it).first; // Pointer to node in the cube mesh Node* old_node = cube_mesh.node_ptr(id); // Add geometric point to input mesh Node* new_node = mesh.add_point ( *old_node ); // Track ID value of new_node in map (*it).second = new_node->id(); } // With the points added and the map data structure in place, we are // ready to add each TRI3 element of the cube_mesh to the input Mesh // with proper node assignments { MeshBase::element_iterator el = cube_mesh.elements_begin(); const MeshBase::element_iterator end_el = cube_mesh.elements_end(); for (; el != end_el; ++el) { Elem* old_elem = *el; if (old_elem->type() == TRI3) { Elem* new_elem = mesh.add_elem(new Tri3); // Assign nodes in new elements. Since this is an example, // we'll do it in several steps. for (unsigned i=0; i<old_elem->n_nodes(); ++i) { // Locate old node ID in the map iterator it = node_id_map.find(old_elem->node(i)); // Check for not found if (it == node_id_map.end()) { libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl; libmesh_error(); } // Mapping to node ID in input mesh unsigned new_node_id = (*it).second; // Node pointer assigned from input mesh new_elem->set_node(i) = mesh.node_ptr(new_node_id); } } } } #endif // LIBMESH_HAVE_TETGEN } <commit_msg>Using SerialMesh with TetGen for now<commit_after>/* The Next Great Finite Element Library. */ /* Copyright (C) 2003 Benjamin S. Kirk */ /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public */ /* License as published by the Free Software Foundation; either */ /* version 2.1 of the License, or (at your option) any later version. */ /* This library is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ /* Lesser General Public License for more details. */ /* You should have received a copy of the GNU Lesser General Public */ /* License along with this library; if not, write to the Free Software */ /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1> // // LibMesh provides interfaces to both Triangle and TetGen for generating // Delaunay triangulations and tetrahedralizations in two and three dimensions // (respectively). // Local header files #include "elem.h" #include "face_tri3.h" #include "mesh.h" #include "mesh_generation.h" #include "mesh_tetgen_interface.h" #include "mesh_triangle_holes.h" #include "mesh_triangle_interface.h" #include "node.h" #include "serial_mesh.h" // Bring in everything from the libMesh namespace using namespace libMesh; // Major functions called by main void triangulate_domain(); void tetrahedralize_domain(); // Helper routine for tetrahedralize_domain(). Adds the points and elements // of a convex hull generated by TetGen to the input mesh void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit); // Begin the main program. int main (int argc, char** argv) { // Initialize libMesh and any dependent libaries, like in example 2. LibMeshInit init (argc, argv); libmesh_example_assert(2 <= LIBMESH_DIM, "2D support"); std::cout << "Triangulating an L-shaped domain with holes" << std::endl; // 1.) 2D triangulation of L-shaped domain with three holes of different shape triangulate_domain(); libmesh_example_assert(3 <= LIBMESH_DIM, "3D support"); std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl; // 2.) 3D tetrahedralization of rectangular domain with hole. tetrahedralize_domain(); return 0; } void triangulate_domain() { #ifdef LIBMESH_HAVE_TRIANGLE // Use typedefs for slightly less typing. typedef TriangleInterface::Hole Hole; typedef TriangleInterface::PolygonHole PolygonHole; typedef TriangleInterface::ArbitraryHole ArbitraryHole; // Libmesh mesh that will eventually be created. Mesh mesh(2); // The points which make up the L-shape: mesh.add_point(Point( 0. , 0.)); mesh.add_point(Point( 0. , -1.)); mesh.add_point(Point(-1. , -1.)); mesh.add_point(Point(-1. , 1.)); mesh.add_point(Point( 1. , 1.)); mesh.add_point(Point( 1. , 0.)); // Declare the TriangleInterface object. This is where // we can set parameters of the triangulation and where the // actual triangulate function lives. TriangleInterface t(mesh); // Customize the variables for the triangulation t.desired_area() = .01; // A Planar Straight Line Graph (PSLG) is essentially a list // of segments which have to exist in the final triangulation. // For an L-shaped domain, Triangle will compute the convex // hull of boundary points if we do not specify the PSLG. // The PSLG algorithm is also required for triangulating domains // containing holes t.triangulation_type() = TriangleInterface::PSLG; // Turn on/off Laplacian mesh smoothing after generation. // By default this is on. t.smooth_after_generating() = true; // Define holes... // hole_1 is a circle (discretized by 50 points) PolygonHole hole_1(Point(-0.5, 0.5), // center 0.25, // radius 50); // n. points // hole_2 is itself a triangle PolygonHole hole_2(Point(0.5, 0.5), // center 0.1, // radius 3); // n. points // hole_3 is an ellipse of 100 points which we define here Point ellipse_center(-0.5, -0.5); const unsigned int n_ellipse_points=100; std::vector<Point> ellipse_points(n_ellipse_points); const Real dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points), a = .1, b = .2; for (unsigned int i=0; i<n_ellipse_points; ++i) ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta), ellipse_center(1)+b*sin(i*dtheta)); ArbitraryHole hole_3(ellipse_center, ellipse_points); // Create the vector of Hole*'s ... std::vector<Hole*> holes; holes.push_back(&hole_1); holes.push_back(&hole_2); holes.push_back(&hole_3); // ... and attach it to the triangulator object t.attach_hole_list(&holes); // Triangulate! t.triangulate(); // Write the result to file mesh.write("delaunay_l_shaped_hole.e"); #endif // LIBMESH_HAVE_TRIANGLE } void tetrahedralize_domain() { #ifdef LIBMESH_HAVE_TETGEN // The algorithm is broken up into several steps: // 1.) A convex hull is constructed for a rectangular hole. // 2.) A convex hull is constructed for the domain exterior. // 3.) Neighbor information is updated so TetGen knows there is a convex hull // 4.) A vector of hole points is created. // 5.) The domain is tetrahedralized, the mesh is written out, etc. // The mesh we will eventually generate SerialMesh mesh(3); // Lower and Upper bounding box limits for a rectangular hole within the unit cube. Point hole_lower_limit(0.2, 0.2, 0.4); Point hole_upper_limit(0.8, 0.8, 0.6); // 1.) Construct a convex hull for the hole add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit); // 2.) Generate elements comprising the outer boundary of the domain. add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.)); // 3.) Update neighbor information so that TetGen can verify there is a convex hull. mesh.find_neighbors(); // 4.) Set up vector of hole points std::vector<Point> hole(1); hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) ); // 5.) Set parameters and tetrahedralize the domain // 0 means "use TetGen default value" Real quality_constraint = 2.0; // The volume constraint determines the max-allowed tetrahedral // volume in the Mesh. TetGen will split cells which are larger than // this size Real volume_constraint = 0.001; // Construct the Delaunay tetrahedralization TetGenMeshInterface t(mesh); t.triangulate_conformingDelaunayMesh_carvehole(hole, quality_constraint, volume_constraint); // Find neighbors, etc in preparation for writing out the Mesh mesh.prepare_for_use(); // Finally, write out the result mesh.write("hole_3D.e"); #endif // LIBMESH_HAVE_TETGEN } void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit) { #ifdef LIBMESH_HAVE_TETGEN SerialMesh cube_mesh(3); unsigned n_elem = 1; MeshTools::Generation::build_cube(cube_mesh, n_elem,n_elem,n_elem, // n. elements in each direction lower_limit(0), upper_limit(0), lower_limit(1), upper_limit(1), lower_limit(2), upper_limit(2), HEX8); // The pointset_convexhull() algorithm will ignore the Hex8s // in the Mesh, and just construct the triangulation // of the convex hull. TetGenMeshInterface t(cube_mesh); t.pointset_convexhull(); // Now add all nodes from the boundary of the cube_mesh to the input mesh. // Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted // with a dummy value, later to be assigned a value by the input mesh. std::map<unsigned,unsigned> node_id_map; typedef std::map<unsigned,unsigned>::iterator iterator; { MeshBase::element_iterator it = cube_mesh.elements_begin(); const MeshBase::element_iterator end = cube_mesh.elements_end(); for ( ; it != end; ++it) { Elem* elem = *it; for (unsigned s=0; s<elem->n_sides(); ++s) if (elem->neighbor(s) == NULL) { // Add the node IDs of this side to the set AutoPtr<Elem> side = elem->side(s); for (unsigned n=0; n<side->n_nodes(); ++n) node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) ); } } } // For each node in the map, insert it into the input mesh and keep // track of the ID assigned. for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it) { // Id of the node in the cube mesh unsigned id = (*it).first; // Pointer to node in the cube mesh Node* old_node = cube_mesh.node_ptr(id); // Add geometric point to input mesh Node* new_node = mesh.add_point ( *old_node ); // Track ID value of new_node in map (*it).second = new_node->id(); } // With the points added and the map data structure in place, we are // ready to add each TRI3 element of the cube_mesh to the input Mesh // with proper node assignments { MeshBase::element_iterator el = cube_mesh.elements_begin(); const MeshBase::element_iterator end_el = cube_mesh.elements_end(); for (; el != end_el; ++el) { Elem* old_elem = *el; if (old_elem->type() == TRI3) { Elem* new_elem = mesh.add_elem(new Tri3); // Assign nodes in new elements. Since this is an example, // we'll do it in several steps. for (unsigned i=0; i<old_elem->n_nodes(); ++i) { // Locate old node ID in the map iterator it = node_id_map.find(old_elem->node(i)); // Check for not found if (it == node_id_map.end()) { libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl; libmesh_error(); } // Mapping to node ID in input mesh unsigned new_node_id = (*it).second; // Node pointer assigned from input mesh new_elem->set_node(i) = mesh.node_ptr(new_node_id); } } } } #endif // LIBMESH_HAVE_TETGEN } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved */ #include "../StroikaPreComp.h" #include <set> #include "StroikaConfig.h" #include "../Characters/Format.h" #include "../Characters/SDKString.h" #include "../Execution/Exceptions.h" #include "../Execution/Throw.h" #include "Locale.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Configuration; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** *********** Configuration::UsePlatformDefaultLocaleAsDefaultLocale ************* ******************************************************************************** */ void Configuration::UsePlatformDefaultLocaleAsDefaultLocale () { locale::global (GetPlatformDefaultLocale ()); } /* ******************************************************************************** ************************* Configuration::GetAvailableLocales ******************* ******************************************************************************** */ #if 0 EnumSystemLocales(EnumLocalesProc, LCID_INSTALLED); // the enumeration callback function BOOL CALLBACK EnumLocalesProc(LPTSTR lpLocaleString) { LCID uiCurLocale; TCHAR szCurNam[STR_LEN]; if (!lpLocaleString) return FALSE; // This enumeration returns the LCID as a character string while // we will be using numbers in other NLS calls. uiCurLocale = uiConvertStrToInt(lpLocaleString); // Get the language name associated with this locale ID. GetLocaleInfo(uiCurLocale, LOCALE_SLANGUAGE, szCurName, STR_LEN); return TRUE; } #endif vector<Characters::String> Configuration::GetAvailableLocales () { // @todo // horrible!!!! - see TOOD vector<Characters::String> result; result.reserve (10); IgnoreExceptionsForCall (result.push_back (FindLocaleName (L"en"sv, L"us"sv))); return result; } /* ******************************************************************************** ************************* Configuration::FindLocaleName ************************ ******************************************************************************** */ Characters::String Configuration::FindLocaleName (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode) { if (auto r = FindLocaleNameQuietly (iso2LetterLanguageCode, iso2LetterTerritoryCode)) { return *r; } Execution::Throw (Execution::RuntimeErrorException{Characters::Format (L"Locale (%s-%s) not found", iso2LetterLanguageCode.c_str (), iso2LetterTerritoryCode.c_str ())}); } optional<Characters::String> Configuration::FindLocaleNameQuietly (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode) { using namespace Characters; Require (iso2LetterLanguageCode.length () == 2); Require (iso2LetterTerritoryCode.length () == 2); // may lift this in the future and make it optional #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Configuration::FindLocaleName"); DbgTrace (L"(%s,%s)", iso2LetterLanguageCode.c_str (), iso2LetterTerritoryCode.c_str ()); #endif // This is a HORRIBLE way - but I know of no better (especially no better portable way). // See todo for planned fixes // --LGP 2013-03-02 // // Could make less heinous with memoizing, but not currently used much, and I plan todo much better impl... set<String> part1{ iso2LetterLanguageCode, iso2LetterLanguageCode.ToLowerCase (), iso2LetterLanguageCode.ToUpperCase (), }; static const set<String> part2{ L"-"sv, L"_"sv, L"."sv, L" "sv, }; set<String> part3{ iso2LetterTerritoryCode, iso2LetterTerritoryCode.ToLowerCase (), iso2LetterTerritoryCode.ToUpperCase (), }; static const set<String> part4{ String{}, L".utf8"sv, }; for (const auto& i1 : part1) { for (const auto& i2 : part2) { for (const auto& i3 : part3) { for (const auto& i4 : part4) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***trying locale (i1 + i2 + i3 + i4).AsUTF8 ().c_str ()=%s", (i1 + i2 + i3 + i4).c_str ()); #endif IgnoreExceptionsForCall (return String::FromNarrowSDKString (locale{(i1 + i2 + i3 + i4).AsUTF8 ().c_str ()}.name ())); } } } } return nullopt; } /* ******************************************************************************** *************************** Configuration::FindNamedLocale ********************* ******************************************************************************** */ locale Configuration::FindNamedLocale (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode) { return locale{FindLocaleName (iso2LetterLanguageCode, iso2LetterTerritoryCode).AsNarrowSDKString ().c_str ()}; } <commit_msg>cosmetic<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved */ #include "../StroikaPreComp.h" #include <set> #include "StroikaConfig.h" #include "../Characters/Format.h" #include "../Characters/SDKString.h" #include "../Execution/Exceptions.h" #include "../Execution/Throw.h" #include "Locale.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Configuration; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** *********** Configuration::UsePlatformDefaultLocaleAsDefaultLocale ************* ******************************************************************************** */ void Configuration::UsePlatformDefaultLocaleAsDefaultLocale () { locale::global (GetPlatformDefaultLocale ()); } /* ******************************************************************************** ************************* Configuration::GetAvailableLocales ******************* ******************************************************************************** */ #if 0 EnumSystemLocales(EnumLocalesProc, LCID_INSTALLED); // the enumeration callback function BOOL CALLBACK EnumLocalesProc(LPTSTR lpLocaleString) { LCID uiCurLocale; TCHAR szCurNam[STR_LEN]; if (!lpLocaleString) return FALSE; // This enumeration returns the LCID as a character string while // we will be using numbers in other NLS calls. uiCurLocale = uiConvertStrToInt(lpLocaleString); // Get the language name associated with this locale ID. GetLocaleInfo(uiCurLocale, LOCALE_SLANGUAGE, szCurName, STR_LEN); return TRUE; } #endif vector<Characters::String> Configuration::GetAvailableLocales () { // @todo // horrible!!!! - see TOOD vector<Characters::String> result; result.reserve (10); IgnoreExceptionsForCall (result.push_back (FindLocaleName (L"en"sv, L"us"sv))); return result; } /* ******************************************************************************** ************************* Configuration::FindLocaleName ************************ ******************************************************************************** */ Characters::String Configuration::FindLocaleName (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode) { if (auto r = FindLocaleNameQuietly (iso2LetterLanguageCode, iso2LetterTerritoryCode)) { return *r; } Execution::Throw (Execution::RuntimeErrorException{Characters::Format (L"Locale (%s-%s) not found", iso2LetterLanguageCode.c_str (), iso2LetterTerritoryCode.c_str ())}); } optional<Characters::String> Configuration::FindLocaleNameQuietly (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode) { using namespace Characters; Require (iso2LetterLanguageCode.length () == 2); Require (iso2LetterTerritoryCode.length () == 2); // may lift this in the future and make it optional #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx{"Configuration::FindLocaleName"}; DbgTrace (L"(%s,%s)", iso2LetterLanguageCode.c_str (), iso2LetterTerritoryCode.c_str ()); #endif // This is a HORRIBLE way - but I know of no better (especially no better portable way). // See todo for planned fixes // --LGP 2013-03-02 // // Could make less heinous with memoizing, but not currently used much, and I plan todo much better impl... set<String> part1{ iso2LetterLanguageCode, iso2LetterLanguageCode.ToLowerCase (), iso2LetterLanguageCode.ToUpperCase (), }; static const set<String> part2{ L"-"sv, L"_"sv, L"."sv, L" "sv, }; set<String> part3{ iso2LetterTerritoryCode, iso2LetterTerritoryCode.ToLowerCase (), iso2LetterTerritoryCode.ToUpperCase (), }; static const set<String> part4{ String{}, L".utf8"sv, }; for (const auto& i1 : part1) { for (const auto& i2 : part2) { for (const auto& i3 : part3) { for (const auto& i4 : part4) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***trying locale (i1 + i2 + i3 + i4).AsUTF8 ().c_str ()=%s", (i1 + i2 + i3 + i4).c_str ()); #endif IgnoreExceptionsForCall (return String::FromNarrowSDKString (locale{(i1 + i2 + i3 + i4).AsUTF8 ().c_str ()}.name ())); } } } } return nullopt; } /* ******************************************************************************** *************************** Configuration::FindNamedLocale ********************* ******************************************************************************** */ locale Configuration::FindNamedLocale (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode) { return locale{FindLocaleName (iso2LetterLanguageCode, iso2LetterTerritoryCode).AsNarrowSDKString ().c_str ()}; } <|endoftext|>
<commit_before>/* open source routing machine Copyright (C) Dennis Luxen, others 2010 This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO General Public License as published by the Free Software Foundation; either version 3 of the License, or 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 Affero 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 or see http://www.gnu.org/licenses/agpl.txt. */ #ifdef STXXL_VERBOSE_LEVEL #undef STXXL_VERBOSE_LEVEL #endif #define STXXL_VERBOSE_LEVEL -1000 #include <algorithm> #include <cassert> #include <climits> #include <cstdio> #include <cstdlib> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <libxml/xmlreader.h> #include <google/sparse_hash_map> #include <unistd.h> #include <stxxl.h> #include "typedefs.h" #include "DataStructures/InputReaderFactory.h" #include "DataStructures/ExtractorCallBacks.h" #include "DataStructures/ExtractorStructs.h" #include "DataStructures/PBFParser.h" #include "DataStructures/XMLParser.h" #include "Util/BaseConfiguration.h" #include "Util/InputFileUtil.h" typedef BaseConfiguration ExtractorConfiguration; unsigned globalRelationCounter = 0; ExtractorCallbacks * extractCallBacks; bool nodeFunction(_Node n); bool adressFunction(_Node n, HashTable<std::string, std::string> keyVals); bool relationFunction(_Relation r); bool wayFunction(_Way w); template<class ClassT> bool removeIfUnused(ClassT n) { return (false == n.used); } int main (int argc, char *argv[]) { if(argc <= 1) { std::cerr << "usage: " << endl << argv[0] << " <file.osm>" << std::endl; exit(-1); } std::cout << "[extractor] extracting data from input file " << argv[1] << std::endl; bool isPBF = false; std::string outputFileName(argv[1]); std::string::size_type pos = outputFileName.find(".osm.bz2"); if(pos==string::npos) { pos = outputFileName.find(".osm.pbf"); if(pos!=string::npos) { isPBF = true; } } if(pos!=string::npos) { outputFileName.replace(pos, 8, ".osrm"); } else { pos=outputFileName.find(".osm"); if(pos!=string::npos) { outputFileName.replace(pos, 5, ".osrm"); } else { outputFileName.append(".osrm"); } } std::string adressFileName(outputFileName); unsigned amountOfRAM = 1; unsigned installedRAM = (sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE)); if(installedRAM < 2097422336) { std::cout << "[Warning] Machine has less than 2GB RAM." << std::endl; } if(testDataFile("extractor.ini")) { ExtractorConfiguration extractorConfig("extractor.ini"); unsigned memoryAmountFromFile = atoi(extractorConfig.GetParameter("Memory").c_str()); if( memoryAmountFromFile != 0 && memoryAmountFromFile <= installedRAM/(1024*1024*1024)) amountOfRAM = memoryAmountFromFile; std::cout << "[extractor] using " << amountOfRAM << " GB of RAM for buffers" << std::endl; } STXXLNodeIDVector usedNodeIDs; STXXLNodeVector allNodes; STXXLEdgeVector allEdges; STXXLAddressVector adressVector; STXXLStringVector nameVector; unsigned usedNodeCounter = 0; unsigned usedEdgeCounter = 0; StringMap * stringMap = new StringMap(); Settings settings; settings.speedProfile.names.insert(settings.speedProfile.names.begin(), names, names+14); settings.speedProfile.speed.insert(settings.speedProfile.speed.begin(), speeds, speeds+14); double time = get_timestamp(); stringMap->set_empty_key(GetRandomString()); stringMap->insert(std::make_pair("", 0)); extractCallBacks = new ExtractorCallbacks(&allNodes, &usedNodeIDs, &allEdges, &nameVector, &adressVector, settings, stringMap); BaseParser<_Node, _Relation, _Way> * parser; if(isPBF) { parser = new PBFParser(argv[1]); } else { parser = new XMLParser(argv[1]); } parser->RegisterCallbacks(&nodeFunction, &relationFunction, &wayFunction, &adressFunction); if(parser->Init()) { parser->Parse(); } else { std::cerr << "[error] parser not initialized!" << std::endl; exit(-1); } delete parser; try { // std::cout << "[info] raw no. of names: " << nameVector.size() << std::endl; // std::cout << "[info] raw no. of nodes: " << allNodes.size() << std::endl; // std::cout << "[info] no. of used nodes: " << usedNodeIDs.size() << std::endl; // std::cout << "[info] raw no. of edges: " << allEdges.size() << std::endl; // std::cout << "[info] raw no. of relations: " << globalRelationCounter << std::endl; // std::cout << "[info] raw no. of addresses: " << adressVector.size() << std::endl; std::cout << "[extractor] parsing finished after " << get_timestamp() - time << "seconds" << std::endl; time = get_timestamp(); unsigned memory_to_use = amountOfRAM * 1024 * 1024 * 1024; std::cout << "[extractor] Sorting used nodes ... " << std::flush; stxxl::sort(usedNodeIDs.begin(), usedNodeIDs.end(), Cmp(), memory_to_use); std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::cout << "[extractor] Erasing duplicate nodes ... " << std::flush; stxxl::vector<NodeID>::iterator NewEnd = unique ( usedNodeIDs.begin(),usedNodeIDs.end() ) ; usedNodeIDs.resize ( NewEnd - usedNodeIDs.begin() ); cout << "ok, after " << get_timestamp() - time << "s" << endl; time = get_timestamp(); std::cout << "[extractor] Sorting all nodes ... " << std::flush; stxxl::sort(allNodes.begin(), allNodes.end(), CmpNodeByID(), memory_to_use); std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::ofstream fout; fout.open(outputFileName.c_str(), std::ios::binary); fout.write((char*)&usedNodeCounter, sizeof(unsigned)); std::cout << "[extractor] Confirming used nodes ... " << std::flush; STXXLNodeVector::iterator nodesIT = allNodes.begin(); STXXLNodeIDVector::iterator usedNodeIDsIT = usedNodeIDs.begin(); while(usedNodeIDsIT != usedNodeIDs.end() && nodesIT != allNodes.end()) { if(*usedNodeIDsIT < nodesIT->id){ usedNodeIDsIT++; continue; } if(*usedNodeIDsIT > nodesIT->id) { nodesIT++; continue; } if(*usedNodeIDsIT == nodesIT->id) { fout.write((char*)&(nodesIT->id), sizeof(unsigned)); fout.write((char*)&(nodesIT->lon), sizeof(int)); fout.write((char*)&(nodesIT->lat), sizeof(int)); usedNodeCounter++; usedNodeIDsIT++; nodesIT++; } } std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::cout << "[extractor] setting number of nodes ... " << std::flush; std::ios::pos_type positionInFile = fout.tellp(); fout.seekp(std::ios::beg); fout.write((char*)&usedNodeCounter, sizeof(unsigned)); fout.seekp(positionInFile); std::cout << "ok" << std::endl; time = get_timestamp(); // Sort edges by start. std::cout << "[extractor] Sorting edges by start ... " << std::flush; stxxl::sort(allEdges.begin(), allEdges.end(), CmpEdgeByStartID(), memory_to_use); std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::cout << "[extractor] Setting start coords ... " << std::flush; fout.write((char*)&usedEdgeCounter, sizeof(unsigned)); // Traverse list of edges and nodes in parallel and set start coord nodesIT = allNodes.begin(); STXXLEdgeVector::iterator edgeIT = allEdges.begin(); while(edgeIT != allEdges.end() && nodesIT != allNodes.end()) { if(edgeIT->start < nodesIT->id){ edgeIT++; continue; } if(edgeIT->start > nodesIT->id) { nodesIT++; continue; } if(edgeIT->start == nodesIT->id) { edgeIT->startCoord.lat = nodesIT->lat; edgeIT->startCoord.lon = nodesIT->lon; edgeIT++; } } std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); // Sort Edges by target std::cout << "[extractor] Sorting edges by target ... " << std::flush; stxxl::sort(allEdges.begin(), allEdges.end(), CmpEdgeByTargetID(), memory_to_use); std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::cout << "[extractor] Setting target coords ... " << std::flush; // Traverse list of edges and nodes in parallel and set target coord nodesIT = allNodes.begin(); edgeIT = allEdges.begin(); while(edgeIT != allEdges.end() && nodesIT != allNodes.end()) { if(edgeIT->target < nodesIT->id){ edgeIT++; continue; } if(edgeIT->target > nodesIT->id) { nodesIT++; continue; } if(edgeIT->startCoord.lat != INT_MIN && edgeIT->target == nodesIT->id) { edgeIT->targetCoord.lat = nodesIT->lat; edgeIT->targetCoord.lon = nodesIT->lon; double distance = ApproximateDistance(edgeIT->startCoord.lat, edgeIT->startCoord.lon, nodesIT->lat, nodesIT->lon); if(edgeIT->speed == -1) edgeIT->speed = settings.speedProfile.speed[edgeIT->type]; double weight = ( distance * 10. ) / (edgeIT->speed / 3.6); int intWeight = max(1, (int) weight); int intDist = max(1, (int)distance); int ferryIndex = settings.indexInAccessListOf("ferry"); assert(ferryIndex != -1); short zero = 0; short one = 1; fout.write((char*)&edgeIT->start, sizeof(unsigned)); fout.write((char*)&edgeIT->target, sizeof(unsigned)); fout.write((char*)&intDist, sizeof(int)); switch(edgeIT->direction) { case _Way::notSure: fout.write((char*)&zero, sizeof(short)); break; case _Way::oneway: fout.write((char*)&one, sizeof(short)); break; case _Way::bidirectional: fout.write((char*)&zero, sizeof(short)); break; case _Way::opposite: fout.write((char*)&one, sizeof(short)); break; default: std::cerr << "[error] edge with no direction: " << edgeIT->direction << std::endl; assert(false); break; } fout.write((char*)&intWeight, sizeof(int)); short edgeType = edgeIT->type; fout.write((char*)&edgeType, sizeof(short)); fout.write((char*)&edgeIT->nameID, sizeof(unsigned)); usedEdgeCounter++; edgeIT++; } } std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::cout << "[extractor] setting number of edges ... " << std::flush; fout.seekp(positionInFile); fout.write((char*)&usedEdgeCounter, sizeof(unsigned)); fout.close(); std::cout << "ok" << std::endl; time = get_timestamp(); std::cout << "[extractor] writing street name index ... " << std::flush; std::vector<unsigned> * nameIndex = new std::vector<unsigned>(nameVector.size()+1, 0); outputFileName.append(".names"); std::ofstream nameOutFile(outputFileName.c_str(), std::ios::binary); unsigned sizeOfNameIndex = nameIndex->size(); nameOutFile.write((char *)&(sizeOfNameIndex), sizeof(unsigned)); for(STXXLStringVector::iterator it = nameVector.begin(); it != nameVector.end(); it++) { unsigned lengthOfRawString = strlen(it->c_str()); nameOutFile.write((char *)&(lengthOfRawString), sizeof(unsigned)); nameOutFile.write(it->c_str(), lengthOfRawString); } nameOutFile.close(); delete nameIndex; std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; // time = get_timestamp(); // std::cout << "[extractor] writing address list ... " << std::flush; // // adressFileName.append(".address"); // std::ofstream addressOutFile(adressFileName.c_str()); // for(STXXLAddressVector::iterator it = adressVector.begin(); it != adressVector.end(); it++) { // addressOutFile << it->node.id << "|" << it->node.lat << "|" << it->node.lon << "|" << it->city << "|" << it->street << "|" << it->housenumber << "|" << it->state << "|" << it->country << "\n"; // } // addressOutFile.close(); // std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; } catch ( const std::exception& e ) { std::cerr << "Caught Execption:" << e.what() << std::endl; return false; } delete extractCallBacks; std::cout << "[extractor] finished." << std::endl; return 0; } bool nodeFunction(_Node n) { extractCallBacks->nodeFunction(n); return true; } bool adressFunction(_Node n, HashTable<std::string, std::string> keyVals){ extractCallBacks->adressFunction(n, keyVals); return true; } bool relationFunction(_Relation r) { globalRelationCounter++; return true; } bool wayFunction(_Way w) { extractCallBacks->wayFunction(w); return true; } <commit_msg>fixing a silly endless loop that occurred when an edge had a starting node that was not present in node data (Thanks Frederik)<commit_after>/* open source routing machine Copyright (C) Dennis Luxen, others 2010 This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO General Public License as published by the Free Software Foundation; either version 3 of the License, or 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 Affero 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 or see http://www.gnu.org/licenses/agpl.txt. */ #ifdef STXXL_VERBOSE_LEVEL #undef STXXL_VERBOSE_LEVEL #endif #define STXXL_VERBOSE_LEVEL -1000 #include <algorithm> #include <cassert> #include <climits> #include <cstdio> #include <cstdlib> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <libxml/xmlreader.h> #include <google/sparse_hash_map> #include <unistd.h> #include <stxxl.h> #include "typedefs.h" #include "DataStructures/InputReaderFactory.h" #include "DataStructures/ExtractorCallBacks.h" #include "DataStructures/ExtractorStructs.h" #include "DataStructures/PBFParser.h" #include "DataStructures/XMLParser.h" #include "Util/BaseConfiguration.h" #include "Util/InputFileUtil.h" typedef BaseConfiguration ExtractorConfiguration; unsigned globalRelationCounter = 0; ExtractorCallbacks * extractCallBacks; bool nodeFunction(_Node n); bool adressFunction(_Node n, HashTable<std::string, std::string> keyVals); bool relationFunction(_Relation r); bool wayFunction(_Way w); template<class ClassT> bool removeIfUnused(ClassT n) { return (false == n.used); } int main (int argc, char *argv[]) { if(argc <= 1) { std::cerr << "usage: " << endl << argv[0] << " <file.osm>" << std::endl; exit(-1); } std::cout << "[extractor] extracting data from input file " << argv[1] << std::endl; bool isPBF = false; std::string outputFileName(argv[1]); std::string::size_type pos = outputFileName.find(".osm.bz2"); if(pos==string::npos) { pos = outputFileName.find(".osm.pbf"); if(pos!=string::npos) { isPBF = true; } } if(pos!=string::npos) { outputFileName.replace(pos, 8, ".osrm"); } else { pos=outputFileName.find(".osm"); if(pos!=string::npos) { outputFileName.replace(pos, 5, ".osrm"); } else { outputFileName.append(".osrm"); } } std::string adressFileName(outputFileName); unsigned amountOfRAM = 1; unsigned installedRAM = (sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE)); if(installedRAM < 2097422336) { std::cout << "[Warning] Machine has less than 2GB RAM." << std::endl; } if(testDataFile("extractor.ini")) { ExtractorConfiguration extractorConfig("extractor.ini"); unsigned memoryAmountFromFile = atoi(extractorConfig.GetParameter("Memory").c_str()); if( memoryAmountFromFile != 0 && memoryAmountFromFile <= installedRAM/(1024*1024*1024)) amountOfRAM = memoryAmountFromFile; std::cout << "[extractor] using " << amountOfRAM << " GB of RAM for buffers" << std::endl; } STXXLNodeIDVector usedNodeIDs; STXXLNodeVector allNodes; STXXLEdgeVector allEdges; STXXLAddressVector adressVector; STXXLStringVector nameVector; unsigned usedNodeCounter = 0; unsigned usedEdgeCounter = 0; StringMap * stringMap = new StringMap(); Settings settings; settings.speedProfile.names.insert(settings.speedProfile.names.begin(), names, names+14); settings.speedProfile.speed.insert(settings.speedProfile.speed.begin(), speeds, speeds+14); double time = get_timestamp(); stringMap->set_empty_key(GetRandomString()); stringMap->insert(std::make_pair("", 0)); extractCallBacks = new ExtractorCallbacks(&allNodes, &usedNodeIDs, &allEdges, &nameVector, &adressVector, settings, stringMap); BaseParser<_Node, _Relation, _Way> * parser; if(isPBF) { parser = new PBFParser(argv[1]); } else { parser = new XMLParser(argv[1]); } parser->RegisterCallbacks(&nodeFunction, &relationFunction, &wayFunction, &adressFunction); if(parser->Init()) { parser->Parse(); } else { std::cerr << "[error] parser not initialized!" << std::endl; exit(-1); } delete parser; try { // std::cout << "[info] raw no. of names: " << nameVector.size() << std::endl; // std::cout << "[info] raw no. of nodes: " << allNodes.size() << std::endl; // std::cout << "[info] no. of used nodes: " << usedNodeIDs.size() << std::endl; // std::cout << "[info] raw no. of edges: " << allEdges.size() << std::endl; // std::cout << "[info] raw no. of relations: " << globalRelationCounter << std::endl; // std::cout << "[info] raw no. of addresses: " << adressVector.size() << std::endl; std::cout << "[extractor] parsing finished after " << get_timestamp() - time << "seconds" << std::endl; time = get_timestamp(); unsigned memory_to_use = amountOfRAM * 1024 * 1024 * 1024; std::cout << "[extractor] Sorting used nodes ... " << std::flush; stxxl::sort(usedNodeIDs.begin(), usedNodeIDs.end(), Cmp(), memory_to_use); std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::cout << "[extractor] Erasing duplicate nodes ... " << std::flush; stxxl::vector<NodeID>::iterator NewEnd = unique ( usedNodeIDs.begin(),usedNodeIDs.end() ) ; usedNodeIDs.resize ( NewEnd - usedNodeIDs.begin() ); cout << "ok, after " << get_timestamp() - time << "s" << endl; time = get_timestamp(); std::cout << "[extractor] Sorting all nodes ... " << std::flush; stxxl::sort(allNodes.begin(), allNodes.end(), CmpNodeByID(), memory_to_use); std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::ofstream fout; fout.open(outputFileName.c_str(), std::ios::binary); fout.write((char*)&usedNodeCounter, sizeof(unsigned)); std::cout << "[extractor] Confirming used nodes ... " << std::flush; STXXLNodeVector::iterator nodesIT = allNodes.begin(); STXXLNodeIDVector::iterator usedNodeIDsIT = usedNodeIDs.begin(); while(usedNodeIDsIT != usedNodeIDs.end() && nodesIT != allNodes.end()) { if(*usedNodeIDsIT < nodesIT->id){ usedNodeIDsIT++; continue; } if(*usedNodeIDsIT > nodesIT->id) { nodesIT++; continue; } if(*usedNodeIDsIT == nodesIT->id) { fout.write((char*)&(nodesIT->id), sizeof(unsigned)); fout.write((char*)&(nodesIT->lon), sizeof(int)); fout.write((char*)&(nodesIT->lat), sizeof(int)); usedNodeCounter++; usedNodeIDsIT++; nodesIT++; } } std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::cout << "[extractor] setting number of nodes ... " << std::flush; std::ios::pos_type positionInFile = fout.tellp(); fout.seekp(std::ios::beg); fout.write((char*)&usedNodeCounter, sizeof(unsigned)); fout.seekp(positionInFile); std::cout << "ok" << std::endl; time = get_timestamp(); // Sort edges by start. std::cout << "[extractor] Sorting edges by start ... " << std::flush; stxxl::sort(allEdges.begin(), allEdges.end(), CmpEdgeByStartID(), memory_to_use); std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::cout << "[extractor] Setting start coords ... " << std::flush; fout.write((char*)&usedEdgeCounter, sizeof(unsigned)); // Traverse list of edges and nodes in parallel and set start coord nodesIT = allNodes.begin(); STXXLEdgeVector::iterator edgeIT = allEdges.begin(); while(edgeIT != allEdges.end() && nodesIT != allNodes.end()) { if(edgeIT->start < nodesIT->id){ edgeIT++; continue; } if(edgeIT->start > nodesIT->id) { nodesIT++; continue; } if(edgeIT->start == nodesIT->id) { edgeIT->startCoord.lat = nodesIT->lat; edgeIT->startCoord.lon = nodesIT->lon; edgeIT++; } } std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); // Sort Edges by target std::cout << "[extractor] Sorting edges by target ... " << std::flush; stxxl::sort(allEdges.begin(), allEdges.end(), CmpEdgeByTargetID(), memory_to_use); std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::cout << "[extractor] Setting target coords ... " << std::flush; // Traverse list of edges and nodes in parallel and set target coord nodesIT = allNodes.begin(); edgeIT = allEdges.begin(); while(edgeIT != allEdges.end() && nodesIT != allNodes.end()) { if(edgeIT->target < nodesIT->id){ edgeIT++; continue; } if(edgeIT->target > nodesIT->id) { nodesIT++; continue; } if(edgeIT->target == nodesIT->id) { if(edgeIT->startCoord.lat != INT_MIN) { edgeIT->targetCoord.lat = nodesIT->lat; edgeIT->targetCoord.lon = nodesIT->lon; double distance = ApproximateDistance(edgeIT->startCoord.lat, edgeIT->startCoord.lon, nodesIT->lat, nodesIT->lon); if(edgeIT->speed == -1) edgeIT->speed = settings.speedProfile.speed[edgeIT->type]; double weight = ( distance * 10. ) / (edgeIT->speed / 3.6); int intWeight = max(1, (int) weight); int intDist = max(1, (int)distance); int ferryIndex = settings.indexInAccessListOf("ferry"); assert(ferryIndex != -1); short zero = 0; short one = 1; fout.write((char*)&edgeIT->start, sizeof(unsigned)); fout.write((char*)&edgeIT->target, sizeof(unsigned)); fout.write((char*)&intDist, sizeof(int)); switch(edgeIT->direction) { case _Way::notSure: fout.write((char*)&zero, sizeof(short)); break; case _Way::oneway: fout.write((char*)&one, sizeof(short)); break; case _Way::bidirectional: fout.write((char*)&zero, sizeof(short)); break; case _Way::opposite: fout.write((char*)&one, sizeof(short)); break; default: std::cerr << "[error] edge with no direction: " << edgeIT->direction << std::endl; assert(false); break; } fout.write((char*)&intWeight, sizeof(int)); short edgeType = edgeIT->type; fout.write((char*)&edgeType, sizeof(short)); fout.write((char*)&edgeIT->nameID, sizeof(unsigned)); } usedEdgeCounter++; edgeIT++; } } std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; time = get_timestamp(); std::cout << "[extractor] setting number of edges ... " << std::flush; fout.seekp(positionInFile); fout.write((char*)&usedEdgeCounter, sizeof(unsigned)); fout.close(); std::cout << "ok" << std::endl; time = get_timestamp(); std::cout << "[extractor] writing street name index ... " << std::flush; std::vector<unsigned> * nameIndex = new std::vector<unsigned>(nameVector.size()+1, 0); outputFileName.append(".names"); std::ofstream nameOutFile(outputFileName.c_str(), std::ios::binary); unsigned sizeOfNameIndex = nameIndex->size(); nameOutFile.write((char *)&(sizeOfNameIndex), sizeof(unsigned)); for(STXXLStringVector::iterator it = nameVector.begin(); it != nameVector.end(); it++) { unsigned lengthOfRawString = strlen(it->c_str()); nameOutFile.write((char *)&(lengthOfRawString), sizeof(unsigned)); nameOutFile.write(it->c_str(), lengthOfRawString); } nameOutFile.close(); delete nameIndex; std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; // time = get_timestamp(); // std::cout << "[extractor] writing address list ... " << std::flush; // // adressFileName.append(".address"); // std::ofstream addressOutFile(adressFileName.c_str()); // for(STXXLAddressVector::iterator it = adressVector.begin(); it != adressVector.end(); it++) { // addressOutFile << it->node.id << "|" << it->node.lat << "|" << it->node.lon << "|" << it->city << "|" << it->street << "|" << it->housenumber << "|" << it->state << "|" << it->country << "\n"; // } // addressOutFile.close(); // std::cout << "ok, after " << get_timestamp() - time << "s" << std::endl; } catch ( const std::exception& e ) { std::cerr << "Caught Execption:" << e.what() << std::endl; return false; } delete extractCallBacks; std::cout << "[extractor] finished." << std::endl; return 0; } bool nodeFunction(_Node n) { extractCallBacks->nodeFunction(n); return true; } bool adressFunction(_Node n, HashTable<std::string, std::string> keyVals){ extractCallBacks->adressFunction(n, keyVals); return true; } bool relationFunction(_Relation r) { globalRelationCounter++; return true; } bool wayFunction(_Way w) { extractCallBacks->wayFunction(w); return true; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Leiden University Medical Center, Erasmus University Medical * Center and contributors * * 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.txt * * 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 "selxSuperElastixFilterCustomComponents.h" #include "selxRegistrationController.h" #include "selxNiftyregReadImageComponent.h" #include "selxNiftyregWriteImageComponent.h" #include "selxNiftyregWriteImageComponent.h" #include "selxItkToNiftiImageSourceReferenceComponent.h" #include "selxNiftiToItkImageSinkComponent.h" #include "selxItkImageSource.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "selxNiftyregf3dComponent.h" #include "selxDataManager.h" #include "gtest/gtest.h" namespace selx { class NiftyregComponentTest : public ::testing::Test { public: typedef std::unique_ptr< Blueprint > BlueprintPointer; typedef itk::UniquePointerDataObjectDecorator< Blueprint > BlueprintITKType; typedef BlueprintITKType::Pointer BlueprintITKPointer; typedef Blueprint::ParameterMapType ParameterMapType; typedef Blueprint::ParameterValueType ParameterValueType; typedef DataManager DataManagerType; /** register all example components */ typedef TypeList < Niftyregf3dComponent< float >, NiftyregReadImageComponent< float >, NiftyregWriteImageComponent< float >, ItkToNiftiImageSourceReferenceComponent< 3, float >, NiftiToItkImageSinkComponent<3, float>, ItkImageSourceComponent<3, float>, RegistrationControllerComponent< >> RegisterComponents; typedef SuperElastixFilterCustomComponents< RegisterComponents > SuperElastixFilterType; virtual void SetUp() { // Instantiate SuperElastixFilter before each test and // register the components we want to have available in SuperElastix superElastixFilter = SuperElastixFilterType::New(); dataManager = DataManagerType::New(); } virtual void TearDown() { // Unregister all components after each test itk::ObjectFactoryBase::UnRegisterAllFactories(); // Delete the SuperElastixFilter after each test superElastixFilter = nullptr; } // Blueprint holds a configuration for SuperElastix BlueprintPointer blueprint; SuperElastixFilterBase::Pointer superElastixFilter; // Data manager provides the paths to the input and output data for unit tests DataManagerType::Pointer dataManager; }; TEST_F( NiftyregComponentTest, Register2d ) { /** make example blueprint configuration */ BlueprintPointer blueprint = BlueprintPointer( new Blueprint() ); blueprint->SetComponent( "FixedImage", { { "NameOfClass", { "NiftyregReadImageComponent" } }, { "FileName", { this->dataManager->GetInputFile( "r16slice.nii.gz" ) } } } ); blueprint->SetComponent( "MovingImage", { { "NameOfClass", { "NiftyregReadImageComponent" } }, { "FileName", { this->dataManager->GetInputFile( "r64slice.nii.gz" ) } } } ); blueprint->SetComponent( "RegistrationMethod", { { "NameOfClass", { "Niftyregf3dComponent" } } } ); blueprint->SetComponent( "ResultImage", { { "NameOfClass", { "NiftyregWriteImageComponent" } }, { "FileName", { this->dataManager->GetOutputFile("Nifty_warped_r64to16.nii.gz") } } }); blueprint->SetComponent( "Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } } ); blueprint->SetConnection("FixedImage", "RegistrationMethod", { { "NameOfInterface", { "NiftyregReferenceImageInterface" } } }); blueprint->SetConnection( "MovingImage", "RegistrationMethod", { { "NameOfInterface", { "NiftyregFloatingImageInterface" } } }); blueprint->SetConnection("RegistrationMethod", "ResultImage", { {} }); //{ { "NameOfInterface", { "NiftyregWarpedImageInterface" } } }); blueprint->SetConnection( "RegistrationMethod", "Controller", { {} } ); blueprint->SetConnection("ResultImage", "Controller", { {} }); BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New(); superElastixFilterBlueprint->Set( blueprint ); EXPECT_NO_THROW( superElastixFilter->SetBlueprint( superElastixFilterBlueprint ) ); EXPECT_NO_THROW( superElastixFilter->Update() ); } TEST_F(NiftyregComponentTest, ItkToNiftiImage) { /** make example blueprint configuration */ BlueprintPointer blueprint = BlueprintPointer(new Blueprint()); blueprint->SetComponent("FixedImage", { { "NameOfClass", { "ItkToNiftiImageSourceReferenceComponent" } }, { "Dimensionality", { "3" } }, { "PixelType", { "float" } } } ); blueprint->SetComponent("ResultImage", { { "NameOfClass", { "NiftyregWriteImageComponent" } }, { "FileName", { this->dataManager->GetOutputFile("ItkToNiftiImage_converted.nii.gz") } } }); blueprint->SetComponent("Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } }); blueprint->SetConnection("FixedImage", "ResultImage", { { "NameOfInterface", { "NiftyregWarpedImageInterface" } } }); blueprint->SetConnection("ResultImage", "Controller", { { "NameOfInterface", { "AfterRegistrationInterface" } } }); BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New(); superElastixFilterBlueprint->Set(blueprint); EXPECT_NO_THROW(superElastixFilter->SetBlueprint(superElastixFilterBlueprint)); // Set up the readers and writers auto fixedImageReader = itk::ImageFileReader<itk::Image<float, 3>>::New(); fixedImageReader->SetFileName(dataManager->GetInputFile("sphereA3d.mhd")); // Connect SuperElastix in an itk pipeline superElastixFilter->SetInput("FixedImage", fixedImageReader->GetOutput()); //EXPECT_NO_THROW(superElastixFilter->Update()); superElastixFilter->Update(); } TEST_F(NiftyregComponentTest, NiftiToItkImage) { /** make example blueprint configuration */ BlueprintPointer blueprint = BlueprintPointer(new Blueprint()); // TODO proper 3d nii.gz input data //blueprint->SetComponent("FixedImage", { { "NameOfClass", { "NiftyregReadImageComponent" } }, { "FileName", { this->dataManager->GetInputFile("r16slice.nii.gz") } } }); blueprint->SetComponent("FixedImage", { { "NameOfClass", { "NiftyregReadImageComponent" } }, { "FileName", { this->dataManager->GetOutputFile("ItkToNiftiImage_converted.nii.gz") } } }); blueprint->SetComponent("ResultDomainImage", { { "NameOfClass", { "ItkImageSourceComponent" } } }); blueprint->SetComponent("ResultImage", { { "NameOfClass", { "NiftiToItkImageSinkComponent" } }, { "Dimensionality", { "3" } }, { "PixelType", { "float" } } }); blueprint->SetComponent("Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } }); blueprint->SetConnection("FixedImage", "ResultImage", { { "NameOfInterface", { "NiftyregWarpedImageInterface" } } }); blueprint->SetConnection("ResultDomainImage", "ResultImage", { { "NameOfInterface", { "itkImageDomainFixedInterface" } } }); blueprint->SetConnection("ResultImage", "Controller", { { "NameOfInterface", { "AfterRegistrationInterface" } } }); BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New(); superElastixFilterBlueprint->Set(blueprint); EXPECT_NO_THROW(superElastixFilter->SetBlueprint(superElastixFilterBlueprint)); // Set up the readers and writers auto fixedDomainImageReader = itk::ImageFileReader<itk::Image<float, 3>>::New(); fixedDomainImageReader->SetFileName(this->dataManager->GetOutputFile("ItkToNiftiImage_converted.nii.gz")); superElastixFilter->SetInput("ResultDomainImage", fixedDomainImageReader->GetOutput()); auto fixedImageWriter = itk::ImageFileWriter<itk::Image<float, 3>>::New(); fixedImageWriter->SetFileName(dataManager->GetOutputFile("NiftiToItkImage_converted.mhd")); // Connect SuperElastix in an itk pipeline fixedImageWriter->SetInput(superElastixFilter->GetOutput<itk::Image<float, 3>>("ResultImage") ); //EXPECT_NO_THROW(superElastixFilter->Update()); fixedImageWriter->Update(); } } <commit_msg>ENH: added niftyreg test running on WBIR demo data. #45<commit_after>/*========================================================================= * * Copyright Leiden University Medical Center, Erasmus University Medical * Center and contributors * * 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.txt * * 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 "selxSuperElastixFilterCustomComponents.h" #include "selxRegistrationController.h" #include "selxNiftyregReadImageComponent.h" #include "selxNiftyregWriteImageComponent.h" #include "selxNiftyregWriteImageComponent.h" #include "selxItkToNiftiImageSourceReferenceComponent.h" #include "selxNiftiToItkImageSinkComponent.h" #include "selxItkImageSource.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "selxNiftyregf3dComponent.h" #include "selxDataManager.h" #include "gtest/gtest.h" namespace selx { class NiftyregComponentTest : public ::testing::Test { public: typedef std::unique_ptr< Blueprint > BlueprintPointer; typedef itk::UniquePointerDataObjectDecorator< Blueprint > BlueprintITKType; typedef BlueprintITKType::Pointer BlueprintITKPointer; typedef Blueprint::ParameterMapType ParameterMapType; typedef Blueprint::ParameterValueType ParameterValueType; typedef DataManager DataManagerType; /** register all example components */ typedef TypeList < Niftyregf3dComponent< float >, NiftyregReadImageComponent< float >, NiftyregWriteImageComponent< float >, ItkToNiftiImageSourceReferenceComponent< 2, float >, NiftiToItkImageSinkComponent<2, float>, ItkImageSourceComponent<2, float>, ItkToNiftiImageSourceReferenceComponent< 3, float >, NiftiToItkImageSinkComponent<3, float>, ItkImageSourceComponent<3, float>, RegistrationControllerComponent< >> RegisterComponents; typedef SuperElastixFilterCustomComponents< RegisterComponents > SuperElastixFilterType; virtual void SetUp() { // Instantiate SuperElastixFilter before each test and // register the components we want to have available in SuperElastix superElastixFilter = SuperElastixFilterType::New(); dataManager = DataManagerType::New(); } virtual void TearDown() { // Unregister all components after each test itk::ObjectFactoryBase::UnRegisterAllFactories(); // Delete the SuperElastixFilter after each test superElastixFilter = nullptr; } // Blueprint holds a configuration for SuperElastix BlueprintPointer blueprint; SuperElastixFilterBase::Pointer superElastixFilter; // Data manager provides the paths to the input and output data for unit tests DataManagerType::Pointer dataManager; }; TEST_F( NiftyregComponentTest, Register2d_nifti ) { /** make example blueprint configuration */ BlueprintPointer blueprint = BlueprintPointer( new Blueprint() ); blueprint->SetComponent( "FixedImage", { { "NameOfClass", { "NiftyregReadImageComponent" } }, { "FileName", { this->dataManager->GetInputFile( "r16slice.nii.gz" ) } } } ); blueprint->SetComponent( "MovingImage", { { "NameOfClass", { "NiftyregReadImageComponent" } }, { "FileName", { this->dataManager->GetInputFile( "r64slice.nii.gz" ) } } } ); blueprint->SetComponent( "RegistrationMethod", { { "NameOfClass", { "Niftyregf3dComponent" } } } ); blueprint->SetComponent( "ResultImage", { { "NameOfClass", { "NiftyregWriteImageComponent" } }, { "FileName", { this->dataManager->GetOutputFile("Nifty_warped_r64to16.nii.gz") } } }); blueprint->SetComponent( "Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } } ); blueprint->SetConnection("FixedImage", "RegistrationMethod", { { "NameOfInterface", { "NiftyregReferenceImageInterface" } } }); blueprint->SetConnection( "MovingImage", "RegistrationMethod", { { "NameOfInterface", { "NiftyregFloatingImageInterface" } } }); blueprint->SetConnection("RegistrationMethod", "ResultImage", { {} }); //{ { "NameOfInterface", { "NiftyregWarpedImageInterface" } } }); blueprint->SetConnection( "RegistrationMethod", "Controller", { {} } ); blueprint->SetConnection("ResultImage", "Controller", { {} }); BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New(); superElastixFilterBlueprint->Set( blueprint ); EXPECT_NO_THROW( superElastixFilter->SetBlueprint( superElastixFilterBlueprint ) ); EXPECT_NO_THROW( superElastixFilter->Update() ); } TEST_F(NiftyregComponentTest, ItkToNiftiImage) { /** make example blueprint configuration */ BlueprintPointer blueprint = BlueprintPointer(new Blueprint()); blueprint->SetComponent("FixedImage", { { "NameOfClass", { "ItkToNiftiImageSourceReferenceComponent" } }, { "Dimensionality", { "3" } }, { "PixelType", { "float" } } } ); blueprint->SetComponent("ResultImage", { { "NameOfClass", { "NiftyregWriteImageComponent" } }, { "FileName", { this->dataManager->GetOutputFile("ItkToNiftiImage_converted.nii.gz") } } }); blueprint->SetComponent("Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } }); blueprint->SetConnection("FixedImage", "ResultImage", { { "NameOfInterface", { "NiftyregWarpedImageInterface" } } }); blueprint->SetConnection("ResultImage", "Controller", { { "NameOfInterface", { "AfterRegistrationInterface" } } }); BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New(); superElastixFilterBlueprint->Set(blueprint); EXPECT_NO_THROW(superElastixFilter->SetBlueprint(superElastixFilterBlueprint)); // Set up the readers and writers auto fixedImageReader = itk::ImageFileReader<itk::Image<float, 3>>::New(); fixedImageReader->SetFileName(dataManager->GetInputFile("sphereA3d.mhd")); // Connect SuperElastix in an itk pipeline superElastixFilter->SetInput("FixedImage", fixedImageReader->GetOutput()); //EXPECT_NO_THROW(superElastixFilter->Update()); superElastixFilter->Update(); } TEST_F(NiftyregComponentTest, NiftiToItkImage) { /** make example blueprint configuration */ BlueprintPointer blueprint = BlueprintPointer(new Blueprint()); // TODO proper 3d nii.gz input data //blueprint->SetComponent("FixedImage", { { "NameOfClass", { "NiftyregReadImageComponent" } }, { "FileName", { this->dataManager->GetInputFile("r16slice.nii.gz") } } }); blueprint->SetComponent("FixedImage", { { "NameOfClass", { "NiftyregReadImageComponent" } }, { "FileName", { this->dataManager->GetOutputFile("ItkToNiftiImage_converted.nii.gz") } } }); blueprint->SetComponent("ResultDomainImage", { { "NameOfClass", { "ItkImageSourceComponent" } } }); blueprint->SetComponent("ResultImage", { { "NameOfClass", { "NiftiToItkImageSinkComponent" } }, { "Dimensionality", { "3" } }, { "PixelType", { "float" } } }); blueprint->SetComponent("Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } }); blueprint->SetConnection("FixedImage", "ResultImage", { { "NameOfInterface", { "NiftyregWarpedImageInterface" } } }); blueprint->SetConnection("ResultDomainImage", "ResultImage", { { "NameOfInterface", { "itkImageDomainFixedInterface" } } }); blueprint->SetConnection("ResultImage", "Controller", { { "NameOfInterface", { "AfterRegistrationInterface" } } }); BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New(); superElastixFilterBlueprint->Set(blueprint); EXPECT_NO_THROW(superElastixFilter->SetBlueprint(superElastixFilterBlueprint)); // Set up the readers and writers auto fixedDomainImageReader = itk::ImageFileReader<itk::Image<float, 3>>::New(); fixedDomainImageReader->SetFileName(this->dataManager->GetOutputFile("ItkToNiftiImage_converted.nii.gz")); superElastixFilter->SetInput("ResultDomainImage", fixedDomainImageReader->GetOutput()); auto fixedImageWriter = itk::ImageFileWriter<itk::Image<float, 3>>::New(); fixedImageWriter->SetFileName(dataManager->GetOutputFile("NiftiToItkImage_converted.mhd")); // Connect SuperElastix in an itk pipeline fixedImageWriter->SetInput(superElastixFilter->GetOutput<itk::Image<float, 3>>("ResultImage") ); //EXPECT_NO_THROW(superElastixFilter->Update()); fixedImageWriter->Update(); } TEST_F(NiftyregComponentTest, Register2d_itkImages) { /** make example blueprint configuration */ // todo: like WBIRDEMO, but set max iterations to 1 for speedy tests. } TEST_F(NiftyregComponentTest, WBIRDemo) { /** make example blueprint configuration */ BlueprintPointer blueprint = BlueprintPointer(new Blueprint()); blueprint->SetComponent("RegistrationMethod", { { "NameOfClass", { "Niftyregf3dComponent" } } }); blueprint->SetComponent("FixedImage", { { "NameOfClass", { "ItkToNiftiImageSourceReferenceComponent" } }, { "Dimensionality", { "2" } }, { "PixelType", { "float" } } }); blueprint->SetComponent("MovingImage", { { "NameOfClass", { "ItkToNiftiImageSourceReferenceComponent" } }, { "Dimensionality", { "2" } }, { "PixelType", { "float" } } }); blueprint->SetComponent("ResultImage", { { "NameOfClass", { "NiftiToItkImageSinkComponent" } }, { "Dimensionality", { "2" } }, { "PixelType", { "float" } } }); blueprint->SetComponent("Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } }); blueprint->SetConnection("FixedImage", "RegistrationMethod", { { "NameOfInterface", { "NiftyregReferenceImageInterface" } } }); blueprint->SetConnection("MovingImage", "RegistrationMethod", { { "NameOfInterface", { "NiftyregFloatingImageInterface" } } }); blueprint->SetConnection("FixedImage", "ResultImage", { { "NameOfInterface", { "itkImageDomainFixedInterface" } } }); blueprint->SetConnection("RegistrationMethod", "ResultImage", { { "NameOfInterface", { "NiftyregWarpedImageInterface" } } }); blueprint->SetConnection("RegistrationMethod", "Controller", { {} }); blueprint->SetConnection("ResultImage", "Controller", { {} }); blueprint->Write(dataManager->GetOutputFile("Niftyreg_WBIR.dot")); // Set up the readers and writers typedef itk::Image< float, 2 > Image2DType; typedef itk::ImageFileReader< Image2DType > ImageReader2DType; typedef itk::ImageFileWriter< Image2DType > ImageWriter2DType; ImageReader2DType::Pointer fixedImageReader = ImageReader2DType::New(); fixedImageReader->SetFileName(dataManager->GetInputFile("coneA2d64.mhd")); ImageReader2DType::Pointer movingImageReader = ImageReader2DType::New(); movingImageReader->SetFileName(dataManager->GetInputFile("coneB2d64.mhd")); ImageWriter2DType::Pointer resultImageWriter = ImageWriter2DType::New(); resultImageWriter->SetFileName(dataManager->GetOutputFile("Niftyreg_WBIR_Image.mhd")); //DisplacementImageWriter2DType::Pointer resultDisplacementWriter = DisplacementImageWriter2DType::New(); //resultDisplacementWriter->SetFileName(dataManager->GetOutputFile("Niftyreg_WBIR_Displacement.mhd")); // Connect SuperElastix in an itk pipeline superElastixFilter->SetInput("FixedImage", fixedImageReader->GetOutput()); superElastixFilter->SetInput("MovingImage", movingImageReader->GetOutput()); resultImageWriter->SetInput(superElastixFilter->GetOutput< Image2DType >("ResultImage")); //resultDisplacementWriter->SetInput(superElastixFilter->GetOutput< DisplacementImage2DType >("ResultDisplacementFieldSink")); BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New(); superElastixFilterBlueprint->Set(blueprint); EXPECT_NO_THROW(superElastixFilter->SetBlueprint(superElastixFilterBlueprint)); //Optional Update call //superElastixFilter->Update(); // Update call on the writers triggers SuperElastix to configure and execute EXPECT_NO_THROW(resultImageWriter->Update()); //EXPECT_NO_THROW(resultDisplacementWriter->Update()); } } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2010 Shantanu Tushar <[email protected]> * Copyright (C) 2010 Laszlo Papp <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "commentitemsmodel.h" #include "allgameitemsmodel.h" #include "gamemanager.h" #include "serviceprovider.h" #include <commentslistjob.h> #include <commentuploadjob.h> #include <engine/gameproject.h> #include <core/gluonobject.h> #include <core/gdlserializer.h> #include <gluon_global.h> #include <attica/listjob.h> #include <QtCore/QStringList> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QDir> using namespace GluonCore; using namespace GluonPlayer; class CommentItemsModel::Private { public: Private() { } GluonCore::GluonObject* m_rootNode; QStringList m_columnNames; bool m_isOnline; QString m_gameId; QList<GluonCore::GluonObject*> m_nodes; }; CommentItemsModel::CommentItemsModel( QString gameId, QObject* parent ) : QAbstractListModel( parent ) , d(new Private) { d->m_rootNode = new GluonObject( "Comment", this ); d->m_isOnline = false; d->m_gameId = gameId; d->m_columnNames << tr( "Author" ) << tr( "Title" ) << tr( "Body" ) << tr( "DateTime" ) << tr( "Rating" ); loadData(); // Load comments stored locally updateData(); // Fetch latest comments from the web service } QHash<int, QByteArray> CommentItemsModel::roleNames() const { QHash<int, QByteArray> roles; roles[AuthorRole] = "author"; roles[TitleRole] = "title"; roles[BodyRole] = "body"; roles[DateTimeRole] = "dateTime"; roles[RatingRole] = "rating"; roles[DepthRole] = "depth"; roles[ParentIdRole] = "parentId"; return roles; } void CommentItemsModel::updateData() { clear(); CommentsListJob *commentListJob = ServiceProvider::instance()->fetchCommentList(d->m_gameId, 0, 0); connect(commentListJob, SIGNAL(succeeded()), SLOT(processFetchedComments())); connect(commentListJob, SIGNAL(failed()), SIGNAL(commentListFetchFailed())); commentListJob->start(); } void CommentItemsModel::processFetchedComments() { QList<CommentItem*> list = qobject_cast<CommentsListJob*>(sender())->data().value< QList<CommentItem*> >(); qDebug() << list.count() << " comments Successfully Fetched from the server!"; foreach(CommentItem *comment, list) { addComment(comment, d->m_rootNode); } beginResetModel(); treeTraversal(d->m_rootNode); endResetModel(); d->m_isOnline = true; } void CommentItemsModel::addCommentFinished( Attica::BaseJob* job ) { Attica::ListJob<Attica::Comment> *commentsJob = static_cast<Attica::ListJob<Attica::Comment>*>( job ); if( commentsJob->metadata().error() == Attica::Metadata::NoError ) { updateData(); } else { emit addCommentFailed(); } } GluonObject* CommentItemsModel::addComment( CommentItem* comment, GluonObject* parent ) { GluonObject* newComment = new GluonObject( comment->id(), parent ); newComment->setProperty( "Author", comment->user() ); newComment->setProperty( "Title", comment->subject() ); newComment->setProperty( "Body", comment->text() ); newComment->setProperty( "DateTime", comment->dateTime().toString() ); newComment->setProperty( "Rating", comment->score() ); newComment->setProperty( "Depth", parent->property("Depth").toInt() + 1 ); newComment->setProperty( "ParentId", parent->name() ); foreach( QObject *child, comment->children() ) { addComment( static_cast<CommentItem*>(child), newComment ); } return newComment; } void CommentItemsModel::treeTraversal( GluonCore::GluonObject* obj ) { if( !obj ) return; foreach( QObject * child, obj->children() ) { GluonObject* gobj = qobject_cast<GluonObject*>( child ); if( gobj ) { d->m_nodes.append( gobj ); treeTraversal( gobj ); } } } bool dateTimeLessThan( GluonCore::GluonObject* go1, GluonCore::GluonObject* go2 ) { return go1->property( "DateTime" ).toString() < go2->property( "DateTime" ).toString(); } void CommentItemsModel::loadData() { AllGameItemsModel *model = qobject_cast<AllGameItemsModel*>(GameManager::instance()->allGamesModel()); QString gameCachePath = model->data(d->m_gameId, AllGameItemsModel::CacheUriRole).toUrl().toLocalFile(); GluonCore::GluonObjectList list; if( gameCachePath.isEmpty() || !GluonCore::GDLSerializer::instance()->read( QUrl( gameCachePath + "/comments.gdl" ), list ) ) return; d->m_rootNode = list.at( 0 ); treeTraversal( d->m_rootNode ); qSort( d->m_nodes.begin(), d->m_nodes.end(), dateTimeLessThan ); } void CommentItemsModel::saveData() { if (d->m_gameId.isEmpty()) { qDebug() << "Failed to save the comment data for empty game id."; return; } qDebug() << "Saving data!"; AllGameItemsModel *model = qobject_cast<AllGameItemsModel*>(GameManager::instance()->allGamesModel()); QString gameCachePath = model->data(d->m_gameId, AllGameItemsModel::CacheUriRole).toUrl().toLocalFile(); QDir gameCacheDir; gameCacheDir.mkpath( gameCachePath ); gameCacheDir.cd( gameCachePath ); QString filename = gameCacheDir.absoluteFilePath( "comments.gdl" ); GluonCore::GDLSerializer::instance()->write( QUrl::fromLocalFile(filename), GluonCore::GluonObjectList() << d->m_rootNode ); } CommentItemsModel::~CommentItemsModel() { saveData(); //Save data before exiting } QVariant CommentItemsModel::data( const QModelIndex& index, int role ) const { if (index.row() >= rowCount()) return QVariant(); switch (role) { case AuthorRole: return d->m_nodes.at(index.row())->property( "Author" ); case TitleRole: return d->m_nodes.at(index.row())->property( "Title" ); case BodyRole: return d->m_nodes.at(index.row())->property( "Body" ); case DateTimeRole: return d->m_nodes.at(index.row())->property( "DateTime" ); case RatingRole: return d->m_nodes.at(index.row())->property( "Rating" ); case DepthRole: return d->m_nodes.at(index.row())->property( "Depth" ); case ParentIdRole: return d->m_nodes.at(index.row())->property( "ParentId" ); } return QVariant(); } int CommentItemsModel::rowCount( const QModelIndex& /* parent */ ) const { return d->m_nodes.count(); } QVariant CommentItemsModel::headerData( int section, Qt::Orientation orientation, int role ) const { if( orientation == Qt::Horizontal && role == Qt::DisplayRole ) return d->m_columnNames.at( section ); return QVariant(); } Qt::ItemFlags CommentItemsModel::flags( const QModelIndex& index ) const { if( !index.isValid() ) return Qt::ItemIsEnabled; return QAbstractItemModel::flags( index ); } void CommentItemsModel::uploadComment( const QModelIndex& parentIndex, const QString& subject, const QString& message ) { uploadComment(d->m_nodes.at(parentIndex.row())->name(), subject, message); } void CommentItemsModel::uploadComment( const QString &parentId, const QString& subject, const QString& message ) { if( d->m_gameId.isEmpty() ) { qDebug() << "Invalid game id, can't upload comment"; return; } else { qDebug() << "id: " << parentId << " | subject:" << subject << " | message:" << message << "\n"; } CommentUploadJob *commentsUploadJob = ServiceProvider::instance()->uploadComment(d->m_gameId, parentId, subject, message); connect(commentsUploadJob, SIGNAL(succeeded()), SLOT(uploadCommentFinished())); connect(commentsUploadJob, SIGNAL(failed()), SIGNAL(addCommentFailed())); commentsUploadJob->start(); } QString CommentItemsModel::gameId() const { return d->m_gameId; } void CommentItemsModel::setGameId( const QString& id ) { if (id.isEmpty()) return; d->m_gameId = id; updateData(); // Fetch latest comments from the web serviceprovider emit gameIdChanged(); } void CommentItemsModel::clear() { if (d->m_rootNode) { qDeleteAll(d->m_rootNode->children()); } d->m_nodes.clear(); } void CommentItemsModel::uploadCommentFinished() { qDebug() << "upload comment went well"; updateData(); } <commit_msg>deleted 2 useless qdebugs<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2010 Shantanu Tushar <[email protected]> * Copyright (C) 2010 Laszlo Papp <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "commentitemsmodel.h" #include "allgameitemsmodel.h" #include "gamemanager.h" #include "serviceprovider.h" #include <commentslistjob.h> #include <commentuploadjob.h> #include <engine/gameproject.h> #include <core/gluonobject.h> #include <core/gdlserializer.h> #include <gluon_global.h> #include <attica/listjob.h> #include <QtCore/QStringList> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QDir> using namespace GluonCore; using namespace GluonPlayer; class CommentItemsModel::Private { public: Private() { } GluonCore::GluonObject* m_rootNode; QStringList m_columnNames; bool m_isOnline; QString m_gameId; QList<GluonCore::GluonObject*> m_nodes; }; CommentItemsModel::CommentItemsModel( QString gameId, QObject* parent ) : QAbstractListModel( parent ) , d(new Private) { d->m_rootNode = new GluonObject( "Comment", this ); d->m_isOnline = false; d->m_gameId = gameId; d->m_columnNames << tr( "Author" ) << tr( "Title" ) << tr( "Body" ) << tr( "DateTime" ) << tr( "Rating" ); loadData(); // Load comments stored locally updateData(); // Fetch latest comments from the web service } QHash<int, QByteArray> CommentItemsModel::roleNames() const { QHash<int, QByteArray> roles; roles[AuthorRole] = "author"; roles[TitleRole] = "title"; roles[BodyRole] = "body"; roles[DateTimeRole] = "dateTime"; roles[RatingRole] = "rating"; roles[DepthRole] = "depth"; roles[ParentIdRole] = "parentId"; return roles; } void CommentItemsModel::updateData() { clear(); CommentsListJob *commentListJob = ServiceProvider::instance()->fetchCommentList(d->m_gameId, 0, 0); connect(commentListJob, SIGNAL(succeeded()), SLOT(processFetchedComments())); connect(commentListJob, SIGNAL(failed()), SIGNAL(commentListFetchFailed())); commentListJob->start(); } void CommentItemsModel::processFetchedComments() { QList<CommentItem*> list = qobject_cast<CommentsListJob*>(sender())->data().value< QList<CommentItem*> >(); qDebug() << list.count() << " comments Successfully Fetched from the server!"; foreach(CommentItem *comment, list) { addComment(comment, d->m_rootNode); } beginResetModel(); treeTraversal(d->m_rootNode); endResetModel(); d->m_isOnline = true; } void CommentItemsModel::addCommentFinished( Attica::BaseJob* job ) { Attica::ListJob<Attica::Comment> *commentsJob = static_cast<Attica::ListJob<Attica::Comment>*>( job ); if( commentsJob->metadata().error() == Attica::Metadata::NoError ) { updateData(); } else { emit addCommentFailed(); } } GluonObject* CommentItemsModel::addComment( CommentItem* comment, GluonObject* parent ) { GluonObject* newComment = new GluonObject( comment->id(), parent ); newComment->setProperty( "Author", comment->user() ); newComment->setProperty( "Title", comment->subject() ); newComment->setProperty( "Body", comment->text() ); newComment->setProperty( "DateTime", comment->dateTime().toString() ); newComment->setProperty( "Rating", comment->score() ); newComment->setProperty( "Depth", parent->property("Depth").toInt() + 1 ); newComment->setProperty( "ParentId", parent->name() ); foreach( QObject *child, comment->children() ) { addComment( static_cast<CommentItem*>(child), newComment ); } return newComment; } void CommentItemsModel::treeTraversal( GluonCore::GluonObject* obj ) { if( !obj ) return; foreach( QObject * child, obj->children() ) { GluonObject* gobj = qobject_cast<GluonObject*>( child ); if( gobj ) { d->m_nodes.append( gobj ); treeTraversal( gobj ); } } } bool dateTimeLessThan( GluonCore::GluonObject* go1, GluonCore::GluonObject* go2 ) { return go1->property( "DateTime" ).toString() < go2->property( "DateTime" ).toString(); } void CommentItemsModel::loadData() { AllGameItemsModel *model = qobject_cast<AllGameItemsModel*>(GameManager::instance()->allGamesModel()); QString gameCachePath = model->data(d->m_gameId, AllGameItemsModel::CacheUriRole).toUrl().toLocalFile(); GluonCore::GluonObjectList list; if( gameCachePath.isEmpty() || !GluonCore::GDLSerializer::instance()->read( QUrl( gameCachePath + "/comments.gdl" ), list ) ) return; d->m_rootNode = list.at( 0 ); treeTraversal( d->m_rootNode ); qSort( d->m_nodes.begin(), d->m_nodes.end(), dateTimeLessThan ); } void CommentItemsModel::saveData() { if (d->m_gameId.isEmpty()) { qDebug() << "Failed to save the comment data for empty game id."; return; } qDebug() << "Saving data!"; AllGameItemsModel *model = qobject_cast<AllGameItemsModel*>(GameManager::instance()->allGamesModel()); QString gameCachePath = model->data(d->m_gameId, AllGameItemsModel::CacheUriRole).toUrl().toLocalFile(); QDir gameCacheDir; gameCacheDir.mkpath( gameCachePath ); gameCacheDir.cd( gameCachePath ); QString filename = gameCacheDir.absoluteFilePath( "comments.gdl" ); GluonCore::GDLSerializer::instance()->write( QUrl::fromLocalFile(filename), GluonCore::GluonObjectList() << d->m_rootNode ); } CommentItemsModel::~CommentItemsModel() { saveData(); //Save data before exiting } QVariant CommentItemsModel::data( const QModelIndex& index, int role ) const { if (index.row() >= rowCount()) return QVariant(); switch (role) { case AuthorRole: return d->m_nodes.at(index.row())->property( "Author" ); case TitleRole: return d->m_nodes.at(index.row())->property( "Title" ); case BodyRole: return d->m_nodes.at(index.row())->property( "Body" ); case DateTimeRole: return d->m_nodes.at(index.row())->property( "DateTime" ); case RatingRole: return d->m_nodes.at(index.row())->property( "Rating" ); case DepthRole: return d->m_nodes.at(index.row())->property( "Depth" ); case ParentIdRole: return d->m_nodes.at(index.row())->property( "ParentId" ); } return QVariant(); } int CommentItemsModel::rowCount( const QModelIndex& /* parent */ ) const { return d->m_nodes.count(); } QVariant CommentItemsModel::headerData( int section, Qt::Orientation orientation, int role ) const { if( orientation == Qt::Horizontal && role == Qt::DisplayRole ) return d->m_columnNames.at( section ); return QVariant(); } Qt::ItemFlags CommentItemsModel::flags( const QModelIndex& index ) const { if( !index.isValid() ) return Qt::ItemIsEnabled; return QAbstractItemModel::flags( index ); } void CommentItemsModel::uploadComment( const QModelIndex& parentIndex, const QString& subject, const QString& message ) { uploadComment(d->m_nodes.at(parentIndex.row())->name(), subject, message); } void CommentItemsModel::uploadComment( const QString &parentId, const QString& subject, const QString& message ) { if( d->m_gameId.isEmpty() ) { qDebug() << "Invalid game id, can't upload comment"; return; } CommentUploadJob *commentsUploadJob = ServiceProvider::instance()->uploadComment(d->m_gameId, parentId, subject, message); connect(commentsUploadJob, SIGNAL(succeeded()), SLOT(uploadCommentFinished())); connect(commentsUploadJob, SIGNAL(failed()), SIGNAL(addCommentFailed())); commentsUploadJob->start(); } QString CommentItemsModel::gameId() const { return d->m_gameId; } void CommentItemsModel::setGameId( const QString& id ) { if (id.isEmpty()) return; d->m_gameId = id; updateData(); // Fetch latest comments from the web serviceprovider emit gameIdChanged(); } void CommentItemsModel::clear() { if (d->m_rootNode) { qDeleteAll(d->m_rootNode->children()); } d->m_nodes.clear(); } void CommentItemsModel::uploadCommentFinished() { updateData(); } <|endoftext|>
<commit_before>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <mitkContourModelMapper3D.h> #include <vtkCellArray.h> #include <vtkPoints.h> #include <vtkProperty.h> mitk::ContourModelMapper3D::ContourModelMapper3D() { } mitk::ContourModelMapper3D::~ContourModelMapper3D() { } const mitk::ContourModel *mitk::ContourModelMapper3D::GetInput(void) { // convient way to get the data from the dataNode return static_cast<const mitk::ContourModel *>(GetDataNode()->GetData()); } vtkProp *mitk::ContourModelMapper3D::GetVtkProp(mitk::BaseRenderer *renderer) { // return the actor corresponding to the renderer return m_LSH.GetLocalStorage(renderer)->m_Actor; } void mitk::ContourModelMapper3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { /* First convert the contourModel to vtkPolyData, then tube filter it and * set it input for our mapper */ LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); auto *inputContour = static_cast<mitk::ContourModel *>(GetDataNode()->GetData()); localStorage->m_OutlinePolyData = this->CreateVtkPolyDataFromContour(inputContour); this->ApplyContourProperties(renderer); // tube filter the polyData localStorage->m_TubeFilter->SetInputData(localStorage->m_OutlinePolyData); float lineWidth(1.0); if (this->GetDataNode()->GetFloatProperty("contour.3D.width", lineWidth, renderer)) { localStorage->m_TubeFilter->SetRadius(lineWidth); } else { localStorage->m_TubeFilter->SetRadius(0.5); } localStorage->m_TubeFilter->CappingOn(); localStorage->m_TubeFilter->SetNumberOfSides(10); localStorage->m_TubeFilter->Update(); localStorage->m_Mapper->SetInputConnection(localStorage->m_TubeFilter->GetOutputPort()); } void mitk::ContourModelMapper3D::Update(mitk::BaseRenderer *renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); auto *data = static_cast<mitk::ContourModel *>(GetDataNode()->GetData()); if (data == nullptr) { return; } // Calculate time step of the input data for the specified renderer (integer value) this->CalculateTimeStep(renderer); LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); // Check if time step is valid const TimeGeometry *dataTimeGeometry = data->GetTimeGeometry(); if ((dataTimeGeometry == nullptr) || (dataTimeGeometry->CountTimeSteps() == 0) || (!dataTimeGeometry->IsValidTimeStep(renderer->GetTimeStep())) || (this->GetTimestep() == -1)) { // clear the rendered polydata localStorage->m_Mapper->SetInputData(vtkSmartPointer<vtkPolyData>::New()); return; } const DataNode *node = this->GetDataNode(); data->UpdateOutputInformation(); // check if something important has changed and we need to rerender if ((localStorage->m_LastUpdateTime < node->GetMTime()) // was the node modified? || (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) // Was the data modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometryUpdateTime()) // was the geometry modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometry()->GetMTime()) || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) // was a property modified? || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime())) { this->GenerateDataForRenderer(renderer); } // since we have checked that nothing important has changed, we can set // m_LastUpdateTime to the current time localStorage->m_LastUpdateTime.Modified(); } vtkSmartPointer<vtkPolyData> mitk::ContourModelMapper3D::CreateVtkPolyDataFromContour(mitk::ContourModel *inputContour) { unsigned int timestep = this->GetTimestep(); // the points to draw vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); // the lines to connect the points vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); // Create a polydata to store everything in vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); // iterate over the control points auto current = inputContour->IteratorBegin(timestep); auto next = inputContour->IteratorBegin(timestep); if (next != inputContour->IteratorEnd(timestep)) { next++; auto end = inputContour->IteratorEnd(timestep); while (next != end) { mitk::ContourModel::VertexType *currentControlPoint = *current; mitk::ContourModel::VertexType *nextControlPoint = *next; if (!(currentControlPoint->Coordinates[0] == nextControlPoint->Coordinates[0] && currentControlPoint->Coordinates[1] == nextControlPoint->Coordinates[1] && currentControlPoint->Coordinates[2] == nextControlPoint->Coordinates[2])) { vtkIdType p1 = points->InsertNextPoint(currentControlPoint->Coordinates[0], currentControlPoint->Coordinates[1], currentControlPoint->Coordinates[2]); vtkIdType p2 = points->InsertNextPoint( nextControlPoint->Coordinates[0], nextControlPoint->Coordinates[1], nextControlPoint->Coordinates[2]); // add the line between both contorlPoints lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } current++; next++; } if (inputContour->IsClosed(timestep)) { // If the contour is closed add a line from the last to the first control point mitk::ContourModel::VertexType *firstControlPoint = *(inputContour->IteratorBegin(timestep)); mitk::ContourModel::VertexType *lastControlPoint = *(--(inputContour->IteratorEnd(timestep))); if (lastControlPoint->Coordinates[0] != firstControlPoint->Coordinates[0] || lastControlPoint->Coordinates[1] != firstControlPoint->Coordinates[1] || lastControlPoint->Coordinates[2] != firstControlPoint->Coordinates[2]) { vtkIdType p2 = points->InsertNextPoint( lastControlPoint->Coordinates[0], lastControlPoint->Coordinates[1], lastControlPoint->Coordinates[2]); vtkIdType p1 = points->InsertNextPoint( firstControlPoint->Coordinates[0], firstControlPoint->Coordinates[1], firstControlPoint->Coordinates[2]); // add the line to the cellArray lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } } // Add the points to the dataset polyData->SetPoints(points); // Add the lines to the dataset polyData->SetLines(lines); } return polyData; } void mitk::ContourModelMapper3D::ApplyContourProperties(mitk::BaseRenderer *renderer) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty *>(GetDataNode()->GetProperty("contour.color", renderer)); if (colorprop) { // set the color of the contour double red = colorprop->GetColor().GetRed(); double green = colorprop->GetColor().GetGreen(); double blue = colorprop->GetColor().GetBlue(); localStorage->m_Actor->GetProperty()->SetColor(red, green, blue); } } /*+++++++++++++++++++ LocalStorage part +++++++++++++++++++++++++*/ mitk::ContourModelMapper3D::LocalStorage *mitk::ContourModelMapper3D::GetLocalStorage(mitk::BaseRenderer *renderer) { return m_LSH.GetLocalStorage(renderer); } mitk::ContourModelMapper3D::LocalStorage::LocalStorage() { m_Mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); m_Actor = vtkSmartPointer<vtkActor>::New(); m_OutlinePolyData = vtkSmartPointer<vtkPolyData>::New(); m_TubeFilter = vtkSmartPointer<vtkTubeFilter>::New(); // set the mapper for the actor m_Actor->SetMapper(m_Mapper); } void mitk::ContourModelMapper3D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { node->AddProperty("color", ColorProperty::New(1.0, 0.0, 0.0), renderer, overwrite); node->AddProperty("contour.3D.width", mitk::FloatProperty::New(0.5), renderer, overwrite); Superclass::SetDefaultProperties(node, renderer, overwrite); } <commit_msg>Fixed T27517<commit_after>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <mitkContourModelMapper3D.h> #include <vtkCellArray.h> #include <vtkPoints.h> #include <vtkProperty.h> mitk::ContourModelMapper3D::ContourModelMapper3D() { } mitk::ContourModelMapper3D::~ContourModelMapper3D() { } const mitk::ContourModel *mitk::ContourModelMapper3D::GetInput(void) { // convient way to get the data from the dataNode return static_cast<const mitk::ContourModel *>(GetDataNode()->GetData()); } vtkProp *mitk::ContourModelMapper3D::GetVtkProp(mitk::BaseRenderer *renderer) { // return the actor corresponding to the renderer return m_LSH.GetLocalStorage(renderer)->m_Actor; } void mitk::ContourModelMapper3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { /* First convert the contourModel to vtkPolyData, then tube filter it and * set it input for our mapper */ LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); auto *inputContour = static_cast<mitk::ContourModel *>(GetDataNode()->GetData()); localStorage->m_OutlinePolyData = this->CreateVtkPolyDataFromContour(inputContour); this->ApplyContourProperties(renderer); // tube filter the polyData localStorage->m_TubeFilter->SetInputData(localStorage->m_OutlinePolyData); float lineWidth(1.0); if (this->GetDataNode()->GetFloatProperty("contour.3D.width", lineWidth, renderer)) { localStorage->m_TubeFilter->SetRadius(lineWidth); } else { localStorage->m_TubeFilter->SetRadius(0.5); } localStorage->m_TubeFilter->CappingOn(); localStorage->m_TubeFilter->SetNumberOfSides(10); localStorage->m_TubeFilter->Update(); localStorage->m_Mapper->SetInputConnection(localStorage->m_TubeFilter->GetOutputPort()); } void mitk::ContourModelMapper3D::Update(mitk::BaseRenderer *renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); auto *data = static_cast<mitk::ContourModel *>(GetDataNode()->GetData()); if (data == nullptr) { return; } // Calculate time step of the input data for the specified renderer (integer value) this->CalculateTimeStep(renderer); LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); // Check if time step is valid const TimeGeometry *dataTimeGeometry = data->GetTimeGeometry(); if ((dataTimeGeometry == nullptr) || (dataTimeGeometry->CountTimeSteps() == 0) || (!dataTimeGeometry->IsValidTimePoint(renderer->GetTime())) || (this->GetTimestep() == -1)) { // clear the rendered polydata localStorage->m_Mapper->SetInputData(vtkSmartPointer<vtkPolyData>::New()); return; } const DataNode *node = this->GetDataNode(); data->UpdateOutputInformation(); // check if something important has changed and we need to rerender if ((localStorage->m_LastUpdateTime < node->GetMTime()) // was the node modified? || (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) // Was the data modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometryUpdateTime()) // was the geometry modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometry()->GetMTime()) || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) // was a property modified? || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime())) { this->GenerateDataForRenderer(renderer); } // since we have checked that nothing important has changed, we can set // m_LastUpdateTime to the current time localStorage->m_LastUpdateTime.Modified(); } vtkSmartPointer<vtkPolyData> mitk::ContourModelMapper3D::CreateVtkPolyDataFromContour(mitk::ContourModel *inputContour) { unsigned int timestep = this->GetTimestep(); // the points to draw vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); // the lines to connect the points vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); // Create a polydata to store everything in vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); // iterate over the control points auto current = inputContour->IteratorBegin(timestep); auto next = inputContour->IteratorBegin(timestep); if (next != inputContour->IteratorEnd(timestep)) { next++; auto end = inputContour->IteratorEnd(timestep); while (next != end) { mitk::ContourModel::VertexType *currentControlPoint = *current; mitk::ContourModel::VertexType *nextControlPoint = *next; if (!(currentControlPoint->Coordinates[0] == nextControlPoint->Coordinates[0] && currentControlPoint->Coordinates[1] == nextControlPoint->Coordinates[1] && currentControlPoint->Coordinates[2] == nextControlPoint->Coordinates[2])) { vtkIdType p1 = points->InsertNextPoint(currentControlPoint->Coordinates[0], currentControlPoint->Coordinates[1], currentControlPoint->Coordinates[2]); vtkIdType p2 = points->InsertNextPoint( nextControlPoint->Coordinates[0], nextControlPoint->Coordinates[1], nextControlPoint->Coordinates[2]); // add the line between both contorlPoints lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } current++; next++; } if (inputContour->IsClosed(timestep)) { // If the contour is closed add a line from the last to the first control point mitk::ContourModel::VertexType *firstControlPoint = *(inputContour->IteratorBegin(timestep)); mitk::ContourModel::VertexType *lastControlPoint = *(--(inputContour->IteratorEnd(timestep))); if (lastControlPoint->Coordinates[0] != firstControlPoint->Coordinates[0] || lastControlPoint->Coordinates[1] != firstControlPoint->Coordinates[1] || lastControlPoint->Coordinates[2] != firstControlPoint->Coordinates[2]) { vtkIdType p2 = points->InsertNextPoint( lastControlPoint->Coordinates[0], lastControlPoint->Coordinates[1], lastControlPoint->Coordinates[2]); vtkIdType p1 = points->InsertNextPoint( firstControlPoint->Coordinates[0], firstControlPoint->Coordinates[1], firstControlPoint->Coordinates[2]); // add the line to the cellArray lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } } // Add the points to the dataset polyData->SetPoints(points); // Add the lines to the dataset polyData->SetLines(lines); } return polyData; } void mitk::ContourModelMapper3D::ApplyContourProperties(mitk::BaseRenderer *renderer) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty *>(GetDataNode()->GetProperty("contour.color", renderer)); if (colorprop) { // set the color of the contour double red = colorprop->GetColor().GetRed(); double green = colorprop->GetColor().GetGreen(); double blue = colorprop->GetColor().GetBlue(); localStorage->m_Actor->GetProperty()->SetColor(red, green, blue); } } /*+++++++++++++++++++ LocalStorage part +++++++++++++++++++++++++*/ mitk::ContourModelMapper3D::LocalStorage *mitk::ContourModelMapper3D::GetLocalStorage(mitk::BaseRenderer *renderer) { return m_LSH.GetLocalStorage(renderer); } mitk::ContourModelMapper3D::LocalStorage::LocalStorage() { m_Mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); m_Actor = vtkSmartPointer<vtkActor>::New(); m_OutlinePolyData = vtkSmartPointer<vtkPolyData>::New(); m_TubeFilter = vtkSmartPointer<vtkTubeFilter>::New(); // set the mapper for the actor m_Actor->SetMapper(m_Mapper); } void mitk::ContourModelMapper3D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { node->AddProperty("color", ColorProperty::New(1.0, 0.0, 0.0), renderer, overwrite); node->AddProperty("contour.3D.width", mitk::FloatProperty::New(0.5), renderer, overwrite); Superclass::SetDefaultProperties(node, renderer, overwrite); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkInternalTrackingTool.h" #include <itkMutexLockHolder.h> typedef itk::MutexLockHolder<itk::FastMutexLock> MutexLockHolder; mitk::InternalTrackingTool::InternalTrackingTool() : TrackingTool(), m_TrackingError(0.0f), m_Enabled(true), m_DataValid(false), m_ToolTipSet(false) { m_Position[0] = 0.0f; m_Position[1] = 0.0f; m_Position[2] = 0.0f; m_Orientation[0] = 0.0f; m_Orientation[1] = 0.0f; m_Orientation[2] = 0.0f; m_Orientation[3] = 0.0f; // this should not be necessary as the tools bring their own tooltip transformation m_ToolTip[0] = 0.0f; m_ToolTip[1] = 0.0f; m_ToolTip[2] = 0.0f; m_ToolTipRotation[0] = 0.0f; m_ToolTipRotation[1] = 0.0f; m_ToolTipRotation[2] = 0.0f; m_ToolTipRotation[3] = 1.0f; } mitk::InternalTrackingTool::~InternalTrackingTool() { } void mitk::InternalTrackingTool::SetToolName(const char* _arg) { itkDebugMacro("setting m_ToolName to " << _arg); MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if ( _arg && (_arg == this->m_ToolName) ) { return; } if (_arg) { this->m_ToolName= _arg; } else { this->m_ToolName= ""; } this->Modified(); } void mitk::InternalTrackingTool::SetToolName( const std::string _arg ) { this->SetToolName(_arg.c_str()); } void mitk::InternalTrackingTool::GetPosition(mitk::Point3D& position) const { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if (m_ToolTipSet) { // Compute the position of tool tip in the coordinate frame of the // tracking device: Rotate the position of the tip into the tracking // device coordinate frame then add to the position of the tracking // sensor vnl_vector<float> pos_vnl = m_Position.Get_vnl_vector() + m_Orientation.rotate( m_ToolTip.Get_vnl_vector() ) ; position[0] = pos_vnl[0]; position[1] = pos_vnl[1]; position[2] = pos_vnl[2]; } else { position[0] = m_Position[0]; position[1] = m_Position[1]; position[2] = m_Position[2]; } this->Modified(); } void mitk::InternalTrackingTool::SetPosition(mitk::Point3D position, mitk::ScalarType eps) { itkDebugMacro("setting m_Position to " << position); if (!Equal(m_Position, position, eps)) { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex m_Position = position; this->Modified(); } } void mitk::InternalTrackingTool::GetOrientation(mitk::Quaternion& orientation) const { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if (m_ToolTipSet) { // Compute the orientation of the tool tip in the coordinate frame of // the tracking device. // // * m_Orientation is the orientation of the sensor relative to the transmitter // * m_ToolTipRotation is the orientation of the tool tip relative to the sensor orientation = m_Orientation * m_ToolTipRotation; } else { orientation = m_Orientation; } } void mitk::InternalTrackingTool::SetToolTip(mitk::Point3D toolTipPosition, mitk::Quaternion orientation, mitk::ScalarType eps) { if ( !Equal(m_ToolTip, toolTipPosition, eps) || !Equal(m_ToolTipRotation, orientation, eps) ) { if( (toolTipPosition[0] == 0) && (toolTipPosition[1] == 0) && (toolTipPosition[2] == 0) && (orientation.x() == 0) && (orientation.y() == 0) && (orientation.z() == 0) && (orientation.r() == 1)) { m_ToolTipSet = false; } else { m_ToolTipSet = true; } m_ToolTip = toolTipPosition; m_ToolTipRotation = orientation; this->Modified(); } } void mitk::InternalTrackingTool::SetOrientation(mitk::Quaternion orientation, mitk::ScalarType eps) { itkDebugMacro("setting m_Orientation to " << orientation); if (!Equal(m_Orientation, orientation, eps)) { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex m_Orientation = orientation; this->Modified(); } } void mitk::InternalTrackingTool::SetTrackingError(float error) { itkDebugMacro("setting m_TrackingError to " << error); MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if (error == m_TrackingError) { return; } m_TrackingError = error; this->Modified(); } float mitk::InternalTrackingTool::GetTrackingError() const { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex float r = m_TrackingError; return r; } bool mitk::InternalTrackingTool::Enable() { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if (m_Enabled == false) { this->m_Enabled = true; this->Modified(); } return true; } bool mitk::InternalTrackingTool::Disable() { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if (m_Enabled == true) { this->m_Enabled = false; this->Modified(); } return true; } bool mitk::InternalTrackingTool::IsEnabled() const { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex return m_Enabled; } bool mitk::InternalTrackingTool::IsDataValid() const { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex return m_DataValid; } void mitk::InternalTrackingTool::SetDataValid(bool _arg) { itkDebugMacro("setting m_DataValid to " << _arg); if (this->m_DataValid != _arg) { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex this->m_DataValid = _arg; this->Modified(); } } void mitk::InternalTrackingTool::SetErrorMessage(const char* _arg) { itkDebugMacro("setting m_ErrorMessage to " << _arg); MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if ((_arg == NULL) || (_arg == this->m_ErrorMessage)) return; if (_arg != NULL) this->m_ErrorMessage = _arg; else this->m_ErrorMessage = ""; this->Modified(); } <commit_msg>Add mitk::InternalTrackingTool::PrintSelf<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkInternalTrackingTool.h" #include <itkMutexLockHolder.h> typedef itk::MutexLockHolder<itk::FastMutexLock> MutexLockHolder; mitk::InternalTrackingTool::InternalTrackingTool() : TrackingTool(), m_TrackingError(0.0f), m_Enabled(true), m_DataValid(false), m_ToolTipSet(false) { m_Position[0] = 0.0f; m_Position[1] = 0.0f; m_Position[2] = 0.0f; m_Orientation[0] = 0.0f; m_Orientation[1] = 0.0f; m_Orientation[2] = 0.0f; m_Orientation[3] = 0.0f; // this should not be necessary as the tools bring their own tooltip transformation m_ToolTip[0] = 0.0f; m_ToolTip[1] = 0.0f; m_ToolTip[2] = 0.0f; m_ToolTipRotation[0] = 0.0f; m_ToolTipRotation[1] = 0.0f; m_ToolTipRotation[2] = 0.0f; m_ToolTipRotation[3] = 1.0f; } mitk::InternalTrackingTool::~InternalTrackingTool() { } void mitk::InternalTrackingTool::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Position: " << m_Position << std::endl; os << indent << "Orientation: " << m_Orientation << std::endl; os << indent << "TrackingError: " << m_TrackingError << std::endl; os << indent << "Enabled: " << m_Enabled << std::endl; os << indent << "DataValid: " << m_DataValid << std::endl; os << indent << "ToolTip: " << m_ToolTip << std::endl; os << indent << "ToolTipRotation: " << m_ToolTipRotation << std::endl; os << indent << "ToolTipSet: " << m_ToolTipSet << std::endl; } void mitk::InternalTrackingTool::SetToolName(const char* _arg) { itkDebugMacro("setting m_ToolName to " << _arg); MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if ( _arg && (_arg == this->m_ToolName) ) { return; } if (_arg) { this->m_ToolName= _arg; } else { this->m_ToolName= ""; } this->Modified(); } void mitk::InternalTrackingTool::SetToolName( const std::string _arg ) { this->SetToolName(_arg.c_str()); } void mitk::InternalTrackingTool::GetPosition(mitk::Point3D& position) const { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if (m_ToolTipSet) { // Compute the position of tool tip in the coordinate frame of the // tracking device: Rotate the position of the tip into the tracking // device coordinate frame then add to the position of the tracking // sensor vnl_vector<float> pos_vnl = m_Position.Get_vnl_vector() + m_Orientation.rotate( m_ToolTip.Get_vnl_vector() ) ; position[0] = pos_vnl[0]; position[1] = pos_vnl[1]; position[2] = pos_vnl[2]; } else { position[0] = m_Position[0]; position[1] = m_Position[1]; position[2] = m_Position[2]; } this->Modified(); } void mitk::InternalTrackingTool::SetPosition(mitk::Point3D position, mitk::ScalarType eps) { itkDebugMacro("setting m_Position to " << position); if (!Equal(m_Position, position, eps)) { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex m_Position = position; this->Modified(); } } void mitk::InternalTrackingTool::GetOrientation(mitk::Quaternion& orientation) const { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if (m_ToolTipSet) { // Compute the orientation of the tool tip in the coordinate frame of // the tracking device. // // * m_Orientation is the orientation of the sensor relative to the transmitter // * m_ToolTipRotation is the orientation of the tool tip relative to the sensor orientation = m_Orientation * m_ToolTipRotation; } else { orientation = m_Orientation; } } void mitk::InternalTrackingTool::SetToolTip(mitk::Point3D toolTipPosition, mitk::Quaternion orientation, mitk::ScalarType eps) { if ( !Equal(m_ToolTip, toolTipPosition, eps) || !Equal(m_ToolTipRotation, orientation, eps) ) { if( (toolTipPosition[0] == 0) && (toolTipPosition[1] == 0) && (toolTipPosition[2] == 0) && (orientation.x() == 0) && (orientation.y() == 0) && (orientation.z() == 0) && (orientation.r() == 1)) { m_ToolTipSet = false; } else { m_ToolTipSet = true; } m_ToolTip = toolTipPosition; m_ToolTipRotation = orientation; this->Modified(); } } void mitk::InternalTrackingTool::SetOrientation(mitk::Quaternion orientation, mitk::ScalarType eps) { itkDebugMacro("setting m_Orientation to " << orientation); if (!Equal(m_Orientation, orientation, eps)) { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex m_Orientation = orientation; this->Modified(); } } void mitk::InternalTrackingTool::SetTrackingError(float error) { itkDebugMacro("setting m_TrackingError to " << error); MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if (error == m_TrackingError) { return; } m_TrackingError = error; this->Modified(); } float mitk::InternalTrackingTool::GetTrackingError() const { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex float r = m_TrackingError; return r; } bool mitk::InternalTrackingTool::Enable() { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if (m_Enabled == false) { this->m_Enabled = true; this->Modified(); } return true; } bool mitk::InternalTrackingTool::Disable() { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if (m_Enabled == true) { this->m_Enabled = false; this->Modified(); } return true; } bool mitk::InternalTrackingTool::IsEnabled() const { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex return m_Enabled; } bool mitk::InternalTrackingTool::IsDataValid() const { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex return m_DataValid; } void mitk::InternalTrackingTool::SetDataValid(bool _arg) { itkDebugMacro("setting m_DataValid to " << _arg); if (this->m_DataValid != _arg) { MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex this->m_DataValid = _arg; this->Modified(); } } void mitk::InternalTrackingTool::SetErrorMessage(const char* _arg) { itkDebugMacro("setting m_ErrorMessage to " << _arg); MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex if ((_arg == NULL) || (_arg == this->m_ErrorMessage)) return; if (_arg != NULL) this->m_ErrorMessage = _arg; else this->m_ErrorMessage = ""; this->Modified(); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <soa.h> void print_soa_iis(const SoA<int, std::string, int> &soa_iis) { for (int i = 0; i < soa_iis.size(); ++i) { std::cout << "(" << i << "): " << soa_iis.get<0>(i) << ", \"" << soa_iis.get<1>(i) << "\", " << soa_iis.get<2>(i) << std::endl; } } int main() { SoA<int, std::string, int> soa_iis; std::cout << "size: " << soa_iis.size() << std::endl; std::cout << "empty: " << soa_iis.empty() << std::endl; soa_iis.push_back(22, "Kitty", 4); soa_iis.push_back(0, "Hi", 2); std::cout << "size: " << soa_iis.size() << std::endl; std::cout << "empty: " << soa_iis.empty() << std::endl; std::cout << std::endl; // Iterate the arrays and print out the elements. std::cout << "Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << std::endl; // Swap the elements. soa_iis.swap(0, 1); std::cout << "Swapped first two elements. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << std::endl; // Modify an element soa_iis.get<1>(0) = "I am changed!"; std::cout << "Modified the 0th element. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << std::endl; // Erase an element. soa_iis.erase(0); std::cout << "Erased 0th element. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << std::endl; // Add two new elements... soa_iis.push_back(1, "Hi... for now...", 5); soa_iis.push_back(80, "I'll survive!'", 20); std::cout << "Added 2 new elements. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << std::endl; // And erase the first two. soa_iis.erase(0, 2); std::cout << "Erased first 2 elements. Arrays now contain:\n"; print_soa_iis(soa_iis); // Kill the arrays via resize. soa_iis.resize(0); std::cout << "Resized to 0. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << "size: " << soa_iis.size() << std::endl; std::cout << "empty: " << soa_iis.empty() << std::endl; std::cout << std::endl; // Resize to have some new elements. soa_iis.resize(5); std::cout << "Resized to 5. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << "size: " << soa_iis.size() << std::endl; std::cout << "empty: " << soa_iis.empty() << std::endl; std::cout << std::endl; // Modify an element and insert an element. soa_iis.get<1>(3) = "Oh hai!"; soa_iis.get<2>(3) = 11; soa_iis.get<0>(3) = 22; soa_iis.push_back(100, "I'm new!.", 20); std::cout << "Modified the 4th element and added a new one. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << "size: " << soa_iis.size() << std::endl; std::cout << "empty: " << soa_iis.empty() << std::endl; std::cout << std::endl; // Get arrays and print them. std::cout << "Printing arrays individually:\n"; int *ints0 = soa_iis.array<0>(); std::string *strings = soa_iis.array<1>(); int *ints1 = soa_iis.array<2>(); for (int i = 0; i < soa_iis.size(); ++i) { std::cout << "Index: " << i << ": "; std::cout << ints0[i] << ", \""; std::cout << strings[i] << "\", "; std::cout << ints1[i] << std::endl; } } <commit_msg>Ran clang format on soa_example.cc<commit_after>#include <iostream> #include <string> #include <soa.h> void print_soa_iis(const SoA<int, std::string, int>& soa_iis) { for (int i = 0; i < soa_iis.size(); ++i) { std::cout << "(" << i << "): " << soa_iis.get<0>(i) << ", \"" << soa_iis.get<1>(i) << "\", " << soa_iis.get<2>(i) << std::endl; } } int main() { SoA<int, std::string, int> soa_iis; std::cout << "size: " << soa_iis.size() << std::endl; std::cout << "empty: " << soa_iis.empty() << std::endl; soa_iis.push_back(22, "Kitty", 4); soa_iis.push_back(0, "Hi", 2); std::cout << "size: " << soa_iis.size() << std::endl; std::cout << "empty: " << soa_iis.empty() << std::endl; std::cout << std::endl; // Iterate the arrays and print out the elements. std::cout << "Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << std::endl; // Swap the elements. soa_iis.swap(0, 1); std::cout << "Swapped first two elements. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << std::endl; // Modify an element soa_iis.get<1>(0) = "I am changed!"; std::cout << "Modified the 0th element. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << std::endl; // Erase an element. soa_iis.erase(0); std::cout << "Erased 0th element. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << std::endl; // Add two new elements... soa_iis.push_back(1, "Hi... for now...", 5); soa_iis.push_back(80, "I'll survive!'", 20); std::cout << "Added 2 new elements. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << std::endl; // And erase the first two. soa_iis.erase(0, 2); std::cout << "Erased first 2 elements. Arrays now contain:\n"; print_soa_iis(soa_iis); // Kill the arrays via resize. soa_iis.resize(0); std::cout << "Resized to 0. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << "size: " << soa_iis.size() << std::endl; std::cout << "empty: " << soa_iis.empty() << std::endl; std::cout << std::endl; // Resize to have some new elements. soa_iis.resize(5); std::cout << "Resized to 5. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << "size: " << soa_iis.size() << std::endl; std::cout << "empty: " << soa_iis.empty() << std::endl; std::cout << std::endl; // Modify an element and insert an element. soa_iis.get<1>(3) = "Oh hai!"; soa_iis.get<2>(3) = 11; soa_iis.get<0>(3) = 22; soa_iis.push_back(100, "I'm new!.", 20); std::cout << "Modified the 4th element and added a new one. Arrays now contain:\n"; print_soa_iis(soa_iis); std::cout << "size: " << soa_iis.size() << std::endl; std::cout << "empty: " << soa_iis.empty() << std::endl; std::cout << std::endl; // Get arrays and print them. std::cout << "Printing arrays individually:\n"; int* ints0 = soa_iis.array<0>(); std::string* strings = soa_iis.array<1>(); int* ints1 = soa_iis.array<2>(); for (int i = 0; i < soa_iis.size(); ++i) { std::cout << "Index: " << i << ": "; std::cout << ints0[i] << ", \""; std::cout << strings[i] << "\", "; std::cout << ints1[i] << std::endl; } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbCvRTreesWrapper.h" #include <algorithm> #include <functional> namespace otb { CvRTreesWrapper::CvRTreesWrapper() { #ifdef OTB_OPENCV_3 m_Impl = cv::ml::RTrees::create(); #endif } CvRTreesWrapper::~CvRTreesWrapper() { } void CvRTreesWrapper::get_votes(const cv::Mat& sample, const cv::Mat& missing, CvRTreesWrapper::VotesVectorType& vote_count) const { #ifdef OTB_OPENCV_3 (void) sample; (void) missing; (void) vote_count; // TODO #else vote_count.resize(nclasses); for( int k = 0; k < ntrees; k++ ) { CvDTreeNode* predicted_node = trees[k]->predict( sample, missing ); int class_idx = predicted_node->class_idx; CV_Assert( 0 <= class_idx && class_idx < nclasses ); ++vote_count[class_idx]; } #endif } float CvRTreesWrapper::predict_margin(const cv::Mat& sample, const cv::Mat& missing) const { #ifdef OTB_OPENCV_3 (void) sample; (void) missing; // TODO return 0.; #else // Sanity check (division by ntrees later on) if(ntrees == 0) { return 0.; } std::vector<unsigned int> classVotes; this->get_votes(sample, missing, classVotes); // We only sort the 2 greatest elements std::nth_element(classVotes.begin(), classVotes.begin()+1, classVotes.end(), std::greater<unsigned int>()); float margin = static_cast<float>(classVotes[0]-classVotes[1])/ntrees; return margin; #endif } float CvRTreesWrapper::predict_confidence(const cv::Mat& sample, const cv::Mat& missing) const { #ifdef OTB_OPENCV_3 (void) sample; (void) missing; // TODO return 0.; #else // Sanity check (division by ntrees later on) if(ntrees == 0) { return 0.; } std::vector<unsigned int> classVotes; this->get_votes(sample, missing, classVotes); unsigned int max_votes = *(std::max_element(classVotes.begin(), classVotes.end())); float confidence = static_cast<float>(max_votes)/ntrees; return confidence; #endif } #ifdef OTB_OPENCV_3 #define OTB_CV_WRAP_IMPL(type,name) \ type CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } \ void CvRTreesWrapper::set##name(type val) \ { m_Impl->set##name(val); } #define OTB_CV_WRAP_IMPL_REF(type,name) \ type CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } \ void CvRTreesWrapper::set##name(const type &val) \ { m_Impl->set##name(val); } #define OTB_CV_WRAP_IMPL_CSTREF_GET(type, name) \ const type& CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } // TODO : wrap all method used OTB_CV_WRAP_IMPL(int, MaxCategories) OTB_CV_WRAP_IMPL(int, MaxDepth) OTB_CV_WRAP_IMPL(int, MinSampleCount) OTB_CV_WRAP_IMPL(bool, UseSurrogates) OTB_CV_WRAP_IMPL(int, CVFolds) OTB_CV_WRAP_IMPL(bool, Use1SERule) OTB_CV_WRAP_IMPL(bool,TruncatePrunedTree) OTB_CV_WRAP_IMPL(float, RegressionAccuracy) OTB_CV_WRAP_IMPL(bool, CalculateVarImportance) OTB_CV_WRAP_IMPL(int, ActiveVarCount) OTB_CV_WRAP_IMPL_REF(cv::Mat, Priors) OTB_CV_WRAP_IMPL_REF(cv::TermCriteria, TermCriteria) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Roots) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Node>, Nodes) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Split>, Splits) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Subsets) int CvRTreesWrapper::getVarCount() const { return m_Impl->getVarCount(); } bool CvRTreesWrapper::isTrained() const { return m_Impl->isTrained(); } bool CvRTreesWrapper::isClassifier() const { return m_Impl->isClassifier(); } cv::Mat CvRTreesWrapper::getVarImportance() const { return m_Impl->getVarImportance(); } cv::String CvRTreesWrapper::getDefaultName () const { return m_Impl->getDefaultName(); } void CvRTreesWrapper::read (const cv::FileNode &fn) { m_Impl->read(fn); } void CvRTreesWrapper::write (cv::FileStorage &fs) const { m_Impl->write(fs); } void CvRTreesWrapper::save (const cv::String &filename) const { m_Impl->save(filename); } bool CvRTreesWrapper::train(cv::InputArray samples, int layout, cv::InputArray responses) { return m_Impl->train(samples,layout, responses); } bool CvRTreesWrapper::train( const cv::Ptr<cv::ml::TrainData>& trainData, int flags ) { return m_Impl->train(trainData, flags); } float CvRTreesWrapper::predict (cv::InputArray samples, cv::OutputArray results, int flags) const { return m_Impl->predict(samples, results, flags); } cv::Ptr<CvRTreesWrapper> CvRTreesWrapper::create() { return cv::makePtr<CvRTreesWrapper>(); } #undef OTB_CV_WRAP_IMPL #undef OTB_CV_WRAP_IMPL_REF #undef OTB_CV_WRAP_IMPL_CSTREF_GET #endif } <commit_msg>ENH: implement margin and confidence prediction for CvRTreesWrapper<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbCvRTreesWrapper.h" #include <algorithm> #include <functional> namespace otb { CvRTreesWrapper::CvRTreesWrapper() { #ifdef OTB_OPENCV_3 m_Impl = cv::ml::RTrees::create(); #endif } CvRTreesWrapper::~CvRTreesWrapper() { } void CvRTreesWrapper::get_votes(const cv::Mat& sample, const cv::Mat& missing, CvRTreesWrapper::VotesVectorType& vote_count) const { #ifdef OTB_OPENCV_3 // missing samples not implemented yet (void) missing; // Here we have to re-implement a basic "predict_tree()" since the function is // not exposed anymore const std::vector< cv::ml::DTrees::Node > &nodes = m_Impl->getNodes(); const std::vector< cv::ml::DTrees::Split > &splits = m_Impl->getSplits(); const std::vector<int> &roots = m_Impl->getRoots(); int ntrees = roots.size(); int nodeIdx, prevNodeIdx; int predictedClass = -1; const float* samplePtr = sample.ptr<float>(); std::map<int, unsigned int> votes; for (int t=0; t<ntrees ; t++) { nodeIdx = roots[t]; prevNodeIdx = nodeIdx; while(1) { prevNodeIdx = nodeIdx; const cv::ml::DTrees::Node &curNode = nodes[nodeIdx]; // test if this node is a leaf if (curNode.split < 0) break; const cv::ml::DTrees::Split& split = splits[curNode.split]; int varIdx = split.varIdx; float val = samplePtr[varIdx]; nodeIdx = val <= split.c ? curNode.left : curNode.right; } predictedClass = nodes[prevNodeIdx].classIdx; votes[predictedClass] += 1; } vote_count.resize(votes.size()); int pos=0; for (std::map<int, unsigned int>::const_iterator it=votes.begin() ; it != votes.end() ; ++it) { vote_count[pos] = it->second; pos++; } if (vote_count.size() == 1) { // give at least 2 classes vote_count.push_back(0); } #else vote_count.resize(nclasses); for( int k = 0; k < ntrees; k++ ) { CvDTreeNode* predicted_node = trees[k]->predict( sample, missing ); int class_idx = predicted_node->class_idx; CV_Assert( 0 <= class_idx && class_idx < nclasses ); ++vote_count[class_idx]; } #endif } float CvRTreesWrapper::predict_margin(const cv::Mat& sample, const cv::Mat& missing) const { #ifdef OTB_OPENCV_3 int ntrees = m_Impl->getRoots().size(); #endif // Sanity check (division by ntrees later on) if(ntrees == 0) { return 0.; } std::vector<unsigned int> classVotes; this->get_votes(sample, missing, classVotes); // We only sort the 2 greatest elements std::nth_element(classVotes.begin(), classVotes.begin()+1, classVotes.end(), std::greater<unsigned int>()); float margin = static_cast<float>(classVotes[0]-classVotes[1])/ntrees; return margin; } float CvRTreesWrapper::predict_confidence(const cv::Mat& sample, const cv::Mat& missing) const { #ifdef OTB_OPENCV_3 int ntrees = m_Impl->getRoots().size(); #endif // Sanity check (division by ntrees later on) if(ntrees == 0) { return 0.; } std::vector<unsigned int> classVotes; this->get_votes(sample, missing, classVotes); unsigned int max_votes = *(std::max_element(classVotes.begin(), classVotes.end())); float confidence = static_cast<float>(max_votes)/ntrees; return confidence; } #ifdef OTB_OPENCV_3 #define OTB_CV_WRAP_IMPL(type,name) \ type CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } \ void CvRTreesWrapper::set##name(type val) \ { m_Impl->set##name(val); } #define OTB_CV_WRAP_IMPL_REF(type,name) \ type CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } \ void CvRTreesWrapper::set##name(const type &val) \ { m_Impl->set##name(val); } #define OTB_CV_WRAP_IMPL_CSTREF_GET(type, name) \ const type& CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } // TODO : wrap all method used OTB_CV_WRAP_IMPL(int, MaxCategories) OTB_CV_WRAP_IMPL(int, MaxDepth) OTB_CV_WRAP_IMPL(int, MinSampleCount) OTB_CV_WRAP_IMPL(bool, UseSurrogates) OTB_CV_WRAP_IMPL(int, CVFolds) OTB_CV_WRAP_IMPL(bool, Use1SERule) OTB_CV_WRAP_IMPL(bool,TruncatePrunedTree) OTB_CV_WRAP_IMPL(float, RegressionAccuracy) OTB_CV_WRAP_IMPL(bool, CalculateVarImportance) OTB_CV_WRAP_IMPL(int, ActiveVarCount) OTB_CV_WRAP_IMPL_REF(cv::Mat, Priors) OTB_CV_WRAP_IMPL_REF(cv::TermCriteria, TermCriteria) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Roots) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Node>, Nodes) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Split>, Splits) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Subsets) int CvRTreesWrapper::getVarCount() const { return m_Impl->getVarCount(); } bool CvRTreesWrapper::isTrained() const { return m_Impl->isTrained(); } bool CvRTreesWrapper::isClassifier() const { return m_Impl->isClassifier(); } cv::Mat CvRTreesWrapper::getVarImportance() const { return m_Impl->getVarImportance(); } cv::String CvRTreesWrapper::getDefaultName () const { return m_Impl->getDefaultName(); } void CvRTreesWrapper::read (const cv::FileNode &fn) { m_Impl->read(fn); } void CvRTreesWrapper::write (cv::FileStorage &fs) const { m_Impl->write(fs); } void CvRTreesWrapper::save (const cv::String &filename) const { m_Impl->save(filename); } bool CvRTreesWrapper::train(cv::InputArray samples, int layout, cv::InputArray responses) { return m_Impl->train(samples,layout, responses); } bool CvRTreesWrapper::train( const cv::Ptr<cv::ml::TrainData>& trainData, int flags ) { return m_Impl->train(trainData, flags); } float CvRTreesWrapper::predict (cv::InputArray samples, cv::OutputArray results, int flags) const { return m_Impl->predict(samples, results, flags); } cv::Ptr<CvRTreesWrapper> CvRTreesWrapper::create() { return cv::makePtr<CvRTreesWrapper>(); } #undef OTB_CV_WRAP_IMPL #undef OTB_CV_WRAP_IMPL_REF #undef OTB_CV_WRAP_IMPL_CSTREF_GET #endif } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright David Doria 2012 [email protected] * * 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.txt * * 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 LinearSearchBestStrategySelection_HPP #define LinearSearchBestStrategySelection_HPP #include "HistogramDifference.hpp" #include <Utilities/Histogram/HistogramHelpers.hpp> #include <Utilities/Histogram/HistogramDifferences.hpp> #include <Utilities/PatchHelpers.h> /** * This function template is similar to std::min_element but can be used when the comparison * involves computing a derived quantity (a.k.a. distance). This algorithm will search for the * the element in the range [first,last) which has the "smallest" distance (of course, both the * distance metric and comparison can be overriden to perform something other than the canonical * Euclidean distance and less-than comparison, which would yield the element with minimum distance). * \tparam DistanceValueType The value-type for the distance measures. * \tparam DistanceFunctionType The functor type to compute the distance measure. * \tparam CompareFunctionType The functor type that can compare two distance measures (strict weak-ordering). */ template <typename PropertyMapType, typename TImage> class LinearSearchBestStrategySelection { PropertyMapType PropertyMap; TImage* Image; Mask* MaskImage; unsigned int Iteration; public: /** Constructor. This class requires the property map, an image, and a mask. */ LinearSearchBestStrategySelection(PropertyMapType propertyMap, TImage* const image, Mask* const mask) : PropertyMap(propertyMap), Image(image), MaskImage(mask), Iteration(0) {} /** * \param first Start of the range in which to search. * \param last One element past the last element in the range in which to search. * \param query The element to compare to. * \return The iterator to the best element in the range (best is defined as the one which would compare favorably to all * the elements in the range with respect to the distance metric). */ template <typename TIterator> typename TIterator::value_type operator()(const TIterator first, const TIterator last, typename TIterator::value_type query) { std::cout << "LinearSearchBestStrategySelection iteration: " << this->Iteration << std::endl; // If the input element range is empty, there is nothing to do. if(first == last) { std::cerr << "LinearSearchBestStrategySelection: Nothing to do..." << std::endl; return *last; } PatchHelpers::WriteTopPatches(this->Image, this->PropertyMap, first, last, "BestPatches", this->Iteration); typedef float BinValueType; typedef QuadrantHistogramProperties<typename TImage::PixelType> QuadrantHistogramPropertiesType; typedef MaskedHistogramGenerator<BinValueType, QuadrantHistogramPropertiesType> MaskedHistogramGeneratorType; typedef typename MaskedHistogramGeneratorType::QuadrantHistogramType QuadrantHistogramType; itk::ImageRegion<2> queryRegion = get(this->PropertyMap, query).GetRegion(); // We must construct the bounds using the pixels from the entire valid region, otherwise the quadrant histogram // bins will not correspond to each other! bool useProvidedRanges = true; typename TImage::PixelType minValue = 0; typename TImage::PixelType maxValue = 255; // Use the range of the valid region of the target patch for the histograms. This is not necessarily the right thing // to do, because we might have a pretty solid "sky" patch that has more white in one of the quadrants than blue so // these quadrant histograms would match poorly even though the whole valid region was "sky" without any hard lines. // typename TImage::PixelType minValue; // MaskOperations::FindMinimumValueInMaskedRegion(this->Image, this->MaskImage, // queryRegion, this->MaskImage->GetValidValue(), minValue); // typename TImage::PixelType maxValue; // MaskOperations::FindMaximumValueInMaskedRegion(this->Image, this->MaskImage, // queryRegion, this->MaskImage->GetValidValue(), maxValue); QuadrantHistogramProperties<typename TImage::PixelType> quadrantHistogramProperties; quadrantHistogramProperties.SetAllMinRanges(minValue); quadrantHistogramProperties.SetAllMaxRanges(maxValue); QuadrantHistogramType targetQuadrantHistogram = MaskedHistogramGeneratorType::ComputeQuadrantMaskedImage1DHistogramAdaptive(this->Image, queryRegion, this->MaskImage, queryRegion, quadrantHistogramProperties, useProvidedRanges, this->MaskImage->GetValidValue()); targetQuadrantHistogram.NormalizeHistograms(); std::vector<float> distances; for(unsigned int i = 0; i < 4; ++i) { if(!targetQuadrantHistogram.Properties.Valid[i]) { continue; } for(unsigned int j = 0; j < 4; ++j) { if(i == j) { continue; } if(!targetQuadrantHistogram.Properties.Valid[j]) { continue; } typedef typename MaskedHistogramGeneratorType::HistogramType HistogramType; float distance = HistogramDifferences::HistogramDifference(targetQuadrantHistogram.Histograms[i], targetQuadrantHistogram.Histograms[j]); // std::cout << "distance " << i << " " << j << " " << distance << std::endl; distances.push_back(distance); } } std::string logFileName = "StrategySelection.txt"; std::ofstream fout(logFileName.c_str(), std::ios::app); // If there were no valid histograms to compare, just use the best SSD patch if(distances.size() == 0) { std::cout << "Using best SSD patch (not enough valid histogram quadrants)..." << std::endl; fout << "F " << Helpers::ZeroPad(this->Iteration, 3) << std::endl; // 'F'ail fout.close(); this->Iteration++; return *first; } float maxDistance = Helpers::Max(distances); std::cout << "maxDistance: " << maxDistance << std::endl; bool useHistogramComparison = false; if(maxDistance < 0.5f) { useHistogramComparison = true; } if(useHistogramComparison) { std::cout << "Using histogram comparison with minValue: " << minValue << " maxValue: " << maxValue << std::endl; // LinearSearchBestHistogramDifference<PropertyMapType, TImage, TIterator> // histogramCheck(this->PropertyMap, this->Image, this->MaskImage); LinearSearchBestDualHistogramDifference<PropertyMapType, TImage, TIterator> histogramCheck(this->PropertyMap, this->Image, this->MaskImage); histogramCheck.SetRangeMin(minValue); histogramCheck.SetRangeMax(maxValue); histogramCheck.SetNumberOfBinsPerDimension(30); fout << "H " << Helpers::ZeroPad(this->Iteration, 3) << " " << maxDistance << " : " << distances << std::endl; // 'H'istogram fout.close(); this->Iteration++; return histogramCheck(first, last, query); } else // Just use the best SSD match { std::cout << "Using best SSD patch..." << std::endl; fout << "S " << Helpers::ZeroPad(this->Iteration, 3) << " " << maxDistance << " : " << distances << std::endl; // 'S'SD fout.close(); this->Iteration++; return *first; } } }; // end class #endif <commit_msg>Breakout histogram similarity test in preparation for adding more strategies.<commit_after>/*========================================================================= * * Copyright David Doria 2012 [email protected] * * 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.txt * * 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 LinearSearchBestStrategySelection_HPP #define LinearSearchBestStrategySelection_HPP #include "HistogramDifference.hpp" #include <Utilities/Histogram/HistogramHelpers.hpp> #include <Utilities/Histogram/HistogramDifferences.hpp> #include <Utilities/PatchHelpers.h> /** * This function template is similar to std::min_element but can be used when the comparison * involves computing a derived quantity (a.k.a. distance). This algorithm will search for the * the element in the range [first,last) which has the "smallest" distance (of course, both the * distance metric and comparison can be overriden to perform something other than the canonical * Euclidean distance and less-than comparison, which would yield the element with minimum distance). * \tparam DistanceValueType The value-type for the distance measures. * \tparam DistanceFunctionType The functor type to compute the distance measure. * \tparam CompareFunctionType The functor type that can compare two distance measures (strict weak-ordering). */ template <typename PropertyMapType, typename TImage> class LinearSearchBestStrategySelection { PropertyMapType PropertyMap; TImage* Image; Mask* MaskImage; unsigned int Iteration; public: /** Constructor. This class requires the property map, an image, and a mask. */ LinearSearchBestStrategySelection(PropertyMapType propertyMap, TImage* const image, Mask* const mask) : PropertyMap(propertyMap), Image(image), MaskImage(mask), Iteration(0) {} typedef QuadrantHistogramProperties<typename TImage::PixelType> QuadrantHistogramPropertiesType; typedef std::pair<bool, QuadrantHistogramPropertiesType> UseHistogramReturnPairType; UseHistogramReturnPairType UseHistogramComparison(const itk::ImageRegion<2>& queryRegion) { typedef float BinValueType; typedef MaskedHistogramGenerator<BinValueType, QuadrantHistogramPropertiesType> MaskedHistogramGeneratorType; typedef typename MaskedHistogramGeneratorType::QuadrantHistogramType QuadrantHistogramType; // We must construct the bounds using the pixels from the entire valid region, otherwise the quadrant histogram // bins will not correspond to each other! bool useProvidedRanges = true; typename TImage::PixelType minValue = 0; typename TImage::PixelType maxValue = 255; // Use the range of the valid region of the target patch for the histograms. This is not necessarily the right thing // to do, because we might have a pretty solid "sky" patch that has more white in one of the quadrants than blue so // these quadrant histograms would match poorly even though the whole valid region was "sky" without any hard lines. // typename TImage::PixelType minValue; // MaskOperations::FindMinimumValueInMaskedRegion(this->Image, this->MaskImage, // queryRegion, this->MaskImage->GetValidValue(), minValue); // typename TImage::PixelType maxValue; // MaskOperations::FindMaximumValueInMaskedRegion(this->Image, this->MaskImage, // queryRegion, this->MaskImage->GetValidValue(), maxValue); QuadrantHistogramPropertiesType quadrantHistogramProperties; quadrantHistogramProperties.SetAllMinRanges(minValue); quadrantHistogramProperties.SetAllMaxRanges(maxValue); QuadrantHistogramType targetQuadrantHistogram = MaskedHistogramGeneratorType::ComputeQuadrantMaskedImage1DHistogramAdaptive(this->Image, queryRegion, this->MaskImage, queryRegion, quadrantHistogramProperties, useProvidedRanges, this->MaskImage->GetValidValue()); targetQuadrantHistogram.NormalizeHistograms(); std::vector<float> distances; for(unsigned int i = 0; i < 4; ++i) { if(!targetQuadrantHistogram.Properties.Valid[i]) { continue; } for(unsigned int j = 0; j < 4; ++j) { if(i == j) { continue; } if(!targetQuadrantHistogram.Properties.Valid[j]) { continue; } typedef typename MaskedHistogramGeneratorType::HistogramType HistogramType; float distance = HistogramDifferences::HistogramDifference(targetQuadrantHistogram.Histograms[i], targetQuadrantHistogram.Histograms[j]); // std::cout << "distance " << i << " " << j << " " << distance << std::endl; distances.push_back(distance); } } std::string logFileName = "StrategySelection.txt"; std::ofstream fout(logFileName.c_str(), std::ios::app); // If there were no valid histograms to compare, just use the best SSD patch if(distances.size() == 0) { std::cout << "Using best SSD patch (not enough valid histogram quadrants)..." << std::endl; fout << "F " << Helpers::ZeroPad(this->Iteration, 3) << std::endl; // 'F'ail fout.close(); this->Iteration++; return UseHistogramReturnPairType(false, quadrantHistogramProperties); } float maxDistance = Helpers::Max(distances); std::cout << "maxDistance: " << maxDistance << std::endl; if(maxDistance < 0.5f) { std::cout << "Using histogram comparison with minValue: " << minValue << " maxValue: " << maxValue << std::endl; return UseHistogramReturnPairType(true, quadrantHistogramProperties); } else { return UseHistogramReturnPairType(false, quadrantHistogramProperties); } } /** * \param first Start of the range in which to search. * \param last One element past the last element in the range in which to search. * \param query The element to compare to. * \return The iterator to the best element in the range (best is defined as the one which would compare favorably to all * the elements in the range with respect to the distance metric). */ template <typename TIterator> typename TIterator::value_type operator()(const TIterator first, const TIterator last, typename TIterator::value_type query) { std::cout << "LinearSearchBestStrategySelection iteration: " << this->Iteration << std::endl; // If the input element range is empty, there is nothing to do. if(first == last) { std::cerr << "LinearSearchBestStrategySelection: Nothing to do..." << std::endl; return *last; } PatchHelpers::WriteTopPatches(this->Image, this->PropertyMap, first, last, "BestPatches", this->Iteration); itk::ImageRegion<2> queryRegion = get(this->PropertyMap, query).GetRegion(); UseHistogramReturnPairType useHistogramComparison = UseHistogramComparison(queryRegion); QuadrantHistogramPropertiesType quadrantHistogramProperties = useHistogramComparison.second; if(useHistogramComparison.first) { // LinearSearchBestHistogramDifference<PropertyMapType, TImage, TIterator> // histogramCheck(this->PropertyMap, this->Image, this->MaskImage); LinearSearchBestDualHistogramDifference<PropertyMapType, TImage, TIterator> histogramCheck(this->PropertyMap, this->Image, this->MaskImage); // This is a single histogram comparison, so we use the ranges of the 0th quadrant of the quadrant histogram. This is // only reasonable as long as the same range is used for each quadrant (which it is in UseHistogramComparison()). histogramCheck.SetRangeMin(quadrantHistogramProperties.QuadrantMinRanges[0]); histogramCheck.SetRangeMax(quadrantHistogramProperties.QuadrantMaxRanges[0]); histogramCheck.SetNumberOfBinsPerDimension(30); // fout << "H " << Helpers::ZeroPad(this->Iteration, 3) // << " " << maxDistance << " : " << distances << std::endl; // 'H'istogram // fout.close(); this->Iteration++; return histogramCheck(first, last, query); } else // Just use the best SSD match { // std::cout << "Using best SSD patch..." << std::endl; // fout << "S " << Helpers::ZeroPad(this->Iteration, 3) // << " " << maxDistance << " : " << distances << std::endl; // 'S'SD // fout.close(); this->Iteration++; return *first; } } }; // end class #endif <|endoftext|>
<commit_before>/* $Id$ */ // Script to create calibration parameters and store them into CDB // Two sets of calibration parameters can be created: // 1) equal parameters // 2) randomly distributed parameters for decalibrated detector silumations #if !defined(__CINT__) #include "TControlBar.h" #include "TString.h" #include "TRandom.h" #include "TH2F.h" #include "TCanvas.h" #include "AliRun.h" #include "AliPHOSCalibData.h" #include "AliCDBMetaData.h" #include "AliCDBId.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliCDBStorage.h" #endif static const Int_t nMod = 5; static const Int_t nCol = 56; static const Int_t nRow = 64; void AliPHOSSetCDB() { TControlBar *menu = new TControlBar("vertical","PHOS CDB"); menu->AddButton("Help to run PHOS CDB","Help()", "Explains how to use PHOS CDS menus"); menu->AddButton("Equal CC","SetCC(0)", "Set equal calibration coefficients"); menu->AddButton("Decalibrate","SetCC(1)", "Set random decalibration calibration coefficients"); menu->AddButton("Set calibration equal to invers decalibration coefficients","SetCC(2)", "Set calibration coefficients inverse to decalibration ones"); menu->AddButton("Residual calibration","SetCC(3)", "Set residual decalibration calibration coefficients"); menu->AddButton("Read equal CC","GetCC(0)", "Read initial equal calibration coefficients"); menu->AddButton("Read random CC","GetCC(1)", "Read random decalibration calibration coefficients"); menu->AddButton("Read inverse CC","GetCC(2)", "Read calibration coefficients inverse to decalibration ones"); menu->AddButton("Read residual CC","GetCC(3)", "Read residial calibration coefficients"); menu->Show(); } //------------------------------------------------------------------------ void Help() { char *string = "\nSet calibration parameters and write them into ALICE CDB. Press button \"Equal CC\" to create equal pedestals and gain factors. Press button \"Decalibrate\" to create random pedestals and gain factors to imitate decalibrated detector\n"; printf(string); } //------------------------------------------------------------------------ void SetCC(Int_t flag=0) { // Writing calibration coefficients into the Calibration DB // Arguments: // flag=0: all calibration coefficients are equal // flag=1: decalibration coefficients // flag=2: calibration coefficients equal to inverse decalibration ones // Author: Boris Polishchuk (Boris.Polichtchouk at cern.ch) TString DBFolder; Int_t firstRun = 0; Int_t lastRun = 0; Int_t beamPeriod = 1; char* objFormat = ""; AliPHOSCalibData* cdb = 0; if (flag == 0) { DBFolder ="local://InitCalibDB"; firstRun = 0; lastRun = 999999; objFormat = "PHOS initial pedestals and ADC gain factors (5x64x56)"; cdb = new AliPHOSCalibData(); cdb->CreateNew(); } else if (flag == 1) { DBFolder ="local://DeCalibDB"; firstRun = 0; lastRun = 999999; objFormat = "PHOS decalibration pedestals and ADC gain factors (5x64x56)"; cdb = new AliPHOSCalibData(); cdb->RandomEmc(); cdb->RandomCpv(); } else if (flag == 2) { // First read decalibration DB AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT"); AliCDBManager::Instance()->SetSpecificStorage("PHOS/*","local://DeCalibDB"); AliPHOSCalibData* cdbDecalib = new AliPHOSCalibData(100); DBFolder ="local://InverseCalibDB"; firstRun = 0; lastRun = 999999; objFormat = "PHOS calibration parameters equal to inverse decalibration ones (5x64x56)"; cdb = new AliPHOSCalibData(); // Read EMC decalibration parameters and put inverse values to a new artificial CDB for (Int_t module=1; module<=nMod; module++) { for (Int_t column=1; column<=nCol; column++) { for (Int_t row=1; row<=nRow; row++) { Float_t valueGain = cdbDecalib->GetADCchannelEmc (module,column,row); Float_t valuePed = cdbDecalib->GetADCpedestalEmc(module,column,row); cdb->SetADCchannelEmc(module,column,row,1./valueGain); cdb->SetADCpedestalEmc(module,column,row,valuePed); } } } // Read CPV decalibration parameters and put inverse values to a new artificial CDB for (Int_t module=1; module<=nMod; module++) { for (Int_t column=1; column<=nCol*2; column++) { for (Int_t row=1; row<=nRow; row++) { Float_t valueGain = cdbDecalib->GetADCchannelCpv (module,column,row); Float_t valuePed = cdbDecalib->GetADCpedestalCpv(module,column,row); cdb->SetADCchannelCpv(module,column,row,1./valueGain); cdb->SetADCpedestalCpv(module,column,row,valuePed); } } } } else if (flag == 3) { DBFolder ="local://ResidualCalibDB"; firstRun = 0; lastRun = 999999; objFormat = "PHOS residual ADC gain factors (5x64x56)"; cdb = new AliPHOSCalibData(); cdb->RandomEmc(0.98,1.02); cdb->RandomCpv(0.00115,0.00125); } //Store calibration data into database AliCDBMetaData md; md.SetComment(objFormat); md.SetBeamPeriod(beamPeriod); md.SetResponsible("Boris Polichtchouk"); AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT"); AliCDBManager::Instance()->SetSpecificStorage("PHOS/*",DBFolder.Data()); cdb->WriteEmc(firstRun,lastRun,&md); cdb->WriteCpv(firstRun,lastRun,&md); } //------------------------------------------------------------------------ void GetCC(Int_t flag=0) { // Read calibration coefficients into the Calibration DB // Arguments: // flag=0: all calibration coefficients are equal // flag=1: decalibration coefficients // flag=2: calibration coefficients equal to inverse decalibration ones // Author: Yuri.Kharlov at cern.ch TString DBFolder; Int_t runNumber; if (flag == 0) { DBFolder ="local://InitCalibDB"; runNumber = 0; } else if (flag == 1) { DBFolder ="local://DeCalibDB"; runNumber = 100; } else if (flag == 2) { DBFolder ="local://InverseCalibDB"; runNumber = 200; } else if (flag == 2) { DBFolder ="local://ResidualCalibDB"; runNumber = 0; } AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT"); AliCDBManager::Instance()->SetSpecificStorage("PHOS/*",DBFolder.Data()); AliPHOSCalibData* clb = new AliPHOSCalibData(runNumber); TH2::AddDirectory(kFALSE); TH2F* hPed[5]; TH2F* hGain[5]; TCanvas *cPed = new TCanvas("cPed" ,"PHOS EMC Pedestals" , 10,10,400,800); TCanvas *cGain = new TCanvas("cGain","PHOS EMC Gain factors",410,10,400,800); cPed ->Divide(1,5); cGain->Divide(1,5); for (Int_t module=1; module<=nMod; module++) { TString namePed="hPed"; namePed+=module; TString titlePed="Pedestals in module "; titlePed+=module; hPed[module-1] = new TH2F(namePed.Data(),titlePed.Data(), nCol,1.,1.*nCol,nRow,1.,1.*nRow); TString nameGain="hGain"; nameGain+=module; TString titleGain="Gain factors in module "; titleGain+=module; hGain[module-1] = new TH2F(nameGain.Data(),titleGain.Data(), nCol,1.,1.*nCol,nRow,1.,1.*nRow); for (Int_t column=1; column<=nCol; column++) { for (Int_t row=1; row<=nRow; row++) { Float_t ped = clb->GetADCpedestalEmc(module,column,row); Float_t gain = clb->GetADCchannelEmc (module,column,row); hPed[module-1]->SetBinContent(column,row,ped); hGain[module-1]->SetBinContent(column,row,gain); } } cPed ->cd(module); hPed[module-1]->Draw("lego2"); cGain->cd(module); hGain[module-1]->Draw("lego2"); } cPed ->Print("pedestals.eps"); cGain->Print("gains.eps"); } <commit_msg>New ideal set of calibration parameters and bad channel map, along with a script creating them<commit_after>/* $Id$ */ // Script to create calibration parameters and store them into CDB // Two sets of calibration parameters can be created: // 1) equal parameters // 2) randomly distributed parameters for decalibrated detector silumations #if !defined(__CINT__) #include "TControlBar.h" #include "TString.h" #include "TRandom.h" #include "TH2F.h" #include "TCanvas.h" #include "AliRun.h" #include "AliPHOSCalibData.h" #include "AliCDBMetaData.h" #include "AliCDBId.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliCDBStorage.h" #endif static const Int_t nMod = 5; static const Int_t nCol = 56; static const Int_t nRow = 64; void AliPHOSSetCDB() { TControlBar *menu = new TControlBar("vertical","PHOS CDB"); menu->AddButton("Help to run PHOS CDB","Help()", "Explains how to use PHOS CDB menus"); menu->AddButton("Equal CC","SetCC(0)", "Set equal CC"); menu->AddButton("Full decalibration","SetCC(1)", "Set random decalibration CC"); menu->AddButton("Residual decalibration","SetCC(2)", "Set residual decalibration calibration coefficients"); menu->AddButton("Read equal CC","GetCC(0)", "Read equal calibration coefficients"); menu->AddButton("Read random CC","GetCC(1)", "Read random decalibration calibration coefficients"); menu->AddButton("Read residual CC","GetCC(2)", "Read residial calibration coefficients"); menu->AddButton("Exit","gApplication->Terminate(0)","Quit aliroot session"); menu->Show(); } //------------------------------------------------------------------------ void Help() { TString string="\nSet calibration parameters and write them into ALICE OCDB:"; string += "\n\tPress button \"Equal CC\" to create equal calibration coefficients;"; string += "\n\tPress button \"Full decalibration\" to create \n\t random calibration coefficients with 20\% spread \n\t to imitate fully decalibrated detector;"; string += "\n\tPress button \"Residual decalibration\" to create \n\t random calibration coefficients with +-2\% spread\n\t to imitate decalibrated detector after initial calibration.\n"; printf("%s",string.Data()); } //------------------------------------------------------------------------ void SetCC(Int_t flag=0) { // Writing calibration coefficients into the Calibration DB // Arguments: // flag=0: all calibration coefficients are equal // flag=1: decalibration coefficients // flag=2: calibration coefficients equal to inverse decalibration ones // Author: Boris Polishchuk (Boris.Polichtchouk at cern.ch) TString DBFolder; Int_t firstRun = 0; Int_t lastRun = 0; Int_t beamPeriod = 1; char* objFormat = ""; AliPHOSCalibData* cdb = 0; if (flag == 0) { DBFolder ="local://InitCalibDB"; firstRun = 0; lastRun = 999999; objFormat = "PHOS initial pedestals and ADC gain factors (5x64x56)"; cdb = new AliPHOSCalibData(); cdb->CreateNew(); } else if (flag == 1) { DBFolder ="local://FullDecalibDB"; firstRun = 0; lastRun = 999999; objFormat = "PHOS fully decalibrated calibration coefficients (5x64x56)"; cdb = new AliPHOSCalibData(); cdb->RandomEmc(0.8,1.2); cdb->RandomCpv(0.0008,0.0016); } else if (flag == 2) { DBFolder ="local://ResidualCalibDB"; firstRun = 0; lastRun = 999999; objFormat = "PHOS residual calibration coefficients (5x64x56)"; cdb = new AliPHOSCalibData(); cdb->RandomEmc(0.98,1.02); cdb->RandomCpv(0.00115,0.00125); } //Store calibration data into database AliCDBMetaData md; md.SetComment(objFormat); md.SetBeamPeriod(beamPeriod); md.SetResponsible("Boris Polichtchouk"); AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT"); if(gSystem->Getenv("STORAGE")){ cout << "Setting specific storage" << endl; AliCDBManager::Instance()->SetSpecificStorage("PHOS/*",DBFolder.Data()); } cdb->WriteEmc(firstRun,lastRun,&md); cdb->WriteCpv(firstRun,lastRun,&md); cdb->WriteEmcBadChannelsMap(firstRun,lastRun,&md); } //------------------------------------------------------------------------ void GetCC(Int_t flag=0) { // Read calibration coefficients into the Calibration DB // Arguments: // flag=0: all calibration coefficients are equal // flag=1: decalibration coefficients // flag=2: calibration coefficients equal to inverse decalibration ones // Author: Yuri.Kharlov at cern.ch gStyle->SetPalette(1); gStyle->SetOptStat(0); TString DBFolder; Int_t runNumber; if (flag == 0) { DBFolder ="local://InitCalibDB"; runNumber = 0; } else if (flag == 1) { DBFolder ="local://FullDecalibDB"; runNumber = 0; } else if (flag == 2) { DBFolder ="local://ResidualCalibDB"; runNumber = 0; } AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT"); if(gSystem->Getenv("STORAGE")){ cout << "Setting specific storage" << endl; AliCDBManager::Instance()->SetSpecificStorage("PHOS/*",DBFolder.Data()); } AliPHOSCalibData* clb = new AliPHOSCalibData(runNumber); TH2::AddDirectory(kFALSE); TH2F* hGain[5]; TCanvas *cGain = new TCanvas("cGain","PHOS EMC Gain factors",10,10,700,500); cGain->Divide(3,2); for (Int_t module=1; module<=nMod; module++) { TString nameGain="hGain"; nameGain+=module; TString titleGain="Gain factors in module "; titleGain+=module; hGain[module-1] = new TH2F(nameGain.Data(),titleGain.Data(), nCol,1.,1.*nCol,nRow,1.,1.*nRow); for (Int_t column=1; column<=nCol; column++) { for (Int_t row=1; row<=nRow; row++) { Float_t gain = clb->GetADCchannelEmc (module,column,row); hGain[module-1]->SetBinContent(column,row,gain); } } cGain->cd(module); hGain[module-1]->SetMinimum(0); hGain[module-1]->Draw("colz"); } cGain->Print("gains.eps"); } <|endoftext|>
<commit_before> void ProofEnableAliRoot(const char* location = "/usr/local/grid/AliRoot/v4-05-Release") { // enables a locally deployed AliRoot in a PROOF cluster printf("Load libraries: %s \n",location); gProof->Exec(Form("TString str(gSystem->ExpandPathName(\"%s\")); gSystem->Setenv(\"ALICE_ROOT\", str);", location), kTRUE); gProof->AddIncludePath(Form("%s/include", location)); gProof->AddIncludePath(Form("%s/TPC", location)); gProof->AddIncludePath(Form("%s/PWG0", location)); gProof->AddIncludePath(Form("%s/PWG0/dNdPt", location)); gProof->AddIncludePath(Form("%s/ANALYSIS", location)); gProof->AddDynamicPath(Form("%s/lib/tgt_linuxx8664gcc", location)); // load all libraries gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/PWG0/dNdPt/macros/LoadMyLibs.C\")",kTRUE); } <commit_msg>small correction<commit_after> void ProofEnableAliRootGSI(const char* location = "/usr/local/grid/AliRoot/v4-05-Release") { // enables a locally deployed AliRoot in a PROOF cluster printf("Load libraries: %s \n",location); gProof->Exec(Form("TString str(gSystem->ExpandPathName(\"%s\")); gSystem->Setenv(\"ALICE_ROOT\", str);", location), kTRUE); gProof->AddIncludePath(Form("%s/include", location)); gProof->AddIncludePath(Form("%s/TPC", location)); gProof->AddIncludePath(Form("%s/PWG0", location)); gProof->AddIncludePath(Form("%s/PWG0/dNdPt", location)); gProof->AddIncludePath(Form("%s/ANALYSIS", location)); gProof->AddDynamicPath(Form("%s/lib/tgt_linuxx8664gcc", location)); // load all libraries gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/PWG0/dNdPt/macros/LoadMyLibs.C\")",kTRUE); } <|endoftext|>
<commit_before>AliFourPion *AddTaskFourPion( Bool_t MCcase=kFALSE, Bool_t TabulatePairs=kFALSE, Int_t CentBinLowLimit=0, Int_t CentBinHighLimit=1, TString StWeightName="alien:///alice/cern.ch/user/d/dgangadh/WeightFile_FourPion.root", TString StMomResName="alien:///alice/cern.ch/user/d/dgangadh/MomResFile_FourPion.root", TString StKName="alien:///alice/cern.ch/user/d/dgangadh/KFile_FourPion.root", TString StMuonName="alien:///alice/cern.ch/user/d/dgangadh/MuonCorrection_FourPion.root", TString StEAName="alien:///alice/cern.ch/user/d/dgangadh/c3EAfile.root" ) { //=========================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskFourPion", "No analysis manager to connect to."); return NULL; } //____________________________________________// // Create task AliFourPion *FourPionTask = new AliFourPion("FourPionTask"); if(!FourPionTask) return NULL; FourPionTask->SetLEGOCase(kTRUE); FourPionTask->SetMCdecision(MCcase); FourPionTask->SetCollisionType(0); FourPionTask->SetGenerateSignal(kFALSE); FourPionTask->SetTabulatePairs(TabulatePairs); FourPionTask->SetInterpolationType(kFALSE); FourPionTask->SetCentBinRange(CentBinLowLimit, CentBinHighLimit); FourPionTask->SetRMax(11); FourPionTask->SetfcSq(0.7); FourPionTask->SetFilterBit(7); FourPionTask->SetMaxChi2NDF(10); FourPionTask->SetMinTPCncls(0); FourPionTask->SetPairSeparationCutEta(0.02); FourPionTask->SetPairSeparationCutPhi(0.045); FourPionTask->SetNsigmaTPC(2.0); FourPionTask->SetNsigmaTOF(2.0); // FourPionTask->SetMixedChargeCut(kFALSE); FourPionTask->SetMinPt(0.16); FourPionTask->SetMaxPt(1.0); FourPionTask->SetKT3transition(0.3); FourPionTask->SetKT4transition(0.3); mgr->AddTask(FourPionTask); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== TString outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName += ":PWGCF.outputFourPionAnalysis.root"; AliAnalysisDataContainer *coutFourPion = mgr->CreateContainer("FourPionOutput", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data()); mgr->ConnectInput(FourPionTask, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(FourPionTask, 1, coutFourPion); TFile *inputFileWeight = 0; TFile *inputFileMomRes = 0; TFile *inputFileFSI = 0; TFile *inputFileMuon = 0; TFile *inputFileEA = 0; if(!TabulatePairs){ inputFileWeight = TFile::Open(StWeightName,"OLD"); if (!inputFileWeight){ cout << "Requested file:" << inputFileWeight << " was not opened. ABORT." << endl; return NULL; } //////////////////////////////////////////////////// // C2 Weight File const Int_t ktbins_temp = FourPionTask->GetNumKtBins(); const Int_t cbins_temp = FourPionTask->GetNumCentBins(); const Int_t ktbins = ktbins_temp; const Int_t cbins = cbins_temp; TH3F *weightHisto[ktbins][cbins]; for(Int_t i=0; i<ktbins; i++){ for(Int_t j=0; j<cbins; j++){ TString name = "Weight_Kt_"; name += i; name += "_Ky_0_M_"; name += j; name += "_ED_0"; weightHisto[i][j] = (TH3F*)inputFileWeight->Get(name); } } FourPionTask->SetWeightArrays( kTRUE, weightHisto ); // // inputFileEA = TFile::Open(StEAName,"OLD"); if (!inputFileEA){ cout << "Requested file:" << inputFileEA << " was not opened. ABORT." << endl; return NULL; } TH3D *PbPbEA = 0; TH3D *pPbEA = 0; TH3D *ppEA = 0; PbPbEA = (TH3D*)inputFileEA->Get("PbPbEA"); pPbEA = (TH3D*)inputFileEA->Get("pPbEA"); ppEA = (TH3D*)inputFileEA->Get("ppEA"); FourPionTask->Setc3FitEAs( kTRUE, PbPbEA, pPbEA, ppEA ); //////////////////////////////////////////////////// }// TabulatePairs check if(!MCcase && !TabulatePairs){ inputFileMomRes = TFile::Open(StMomResName,"OLD"); if (!inputFileMomRes){ cout << "Requested file:" << inputFileMomRes << " was not opened. ABORT." << endl; return NULL; } //////////////////////////////////////////////////// // Momentum Resolution File TH2D *momResHisto2DSC = 0; TH2D *momResHisto2DMC = 0; momResHisto2DSC = (TH2D*)inputFileMomRes->Get("MRC_C2_SC"); momResHisto2DMC = (TH2D*)inputFileMomRes->Get("MRC_C2_MC"); FourPionTask->SetMomResCorrections( kTRUE, momResHisto2DSC, momResHisto2DMC ); //////////////////////////////////////////////////// // Muon corrections inputFileMuon = TFile::Open(StMuonName,"OLD"); if (!inputFileMuon){ cout << "Requested file:" << inputFileMuon << " was not opened. ABORT." << endl; return NULL; } TH2D *muonHisto2D = 0; muonHisto2D = (TH2D*)inputFileMuon->Get("WeightmuonCorrection"); FourPionTask->SetMuonCorrections( kTRUE, muonHisto2D); }// MCcase and TabulatePairs check //////////////////////////////////////////////////// // FSI File inputFileFSI = TFile::Open(StKName,"OLD"); if (!inputFileFSI){ cout << "Requested file:" << inputFileFSI << " was not opened. ABORT." << endl; return NULL; } TH1D *FSIss[12]; TH1D *FSIos[12]; for(Int_t index=0; index<12; index++) { TString *nameSS=new TString("K2ss_"); *nameSS += index; FSIss[index] = (TH1D*)inputFileFSI->Get(nameSS->Data()); TString *nameOS=new TString("K2os_"); *nameOS += index; FSIos[index] = (TH1D*)inputFileFSI->Get(nameOS->Data()); // FSIss[index]->SetDirectory(0); FSIos[index]->SetDirectory(0); } // FourPionTask->SetFSICorrelations( kTRUE, FSIss, FSIos ); //////////////////////////////////////////////////// // Return the task pointer return FourPionTask; } <commit_msg>Include extra FSI bin for pp and pPb<commit_after>AliFourPion *AddTaskFourPion( Bool_t MCcase=kFALSE, Bool_t TabulatePairs=kFALSE, Int_t CentBinLowLimit=0, Int_t CentBinHighLimit=1, TString StWeightName="alien:///alice/cern.ch/user/d/dgangadh/WeightFile_FourPion.root", TString StMomResName="alien:///alice/cern.ch/user/d/dgangadh/MomResFile_FourPion.root", TString StKName="alien:///alice/cern.ch/user/d/dgangadh/KFile_FourPion.root", TString StMuonName="alien:///alice/cern.ch/user/d/dgangadh/MuonCorrection_FourPion.root", TString StEAName="alien:///alice/cern.ch/user/d/dgangadh/c3EAfile.root" ) { //=========================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskFourPion", "No analysis manager to connect to."); return NULL; } //____________________________________________// // Create task AliFourPion *FourPionTask = new AliFourPion("FourPionTask"); if(!FourPionTask) return NULL; FourPionTask->SetLEGOCase(kTRUE); FourPionTask->SetMCdecision(MCcase); FourPionTask->SetCollisionType(0); FourPionTask->SetGenerateSignal(kFALSE); FourPionTask->SetTabulatePairs(TabulatePairs); FourPionTask->SetInterpolationType(kFALSE); FourPionTask->SetCentBinRange(CentBinLowLimit, CentBinHighLimit); FourPionTask->SetRMax(11); FourPionTask->SetfcSq(0.7); FourPionTask->SetFilterBit(7); FourPionTask->SetMaxChi2NDF(10); FourPionTask->SetMinTPCncls(0); FourPionTask->SetPairSeparationCutEta(0.02); FourPionTask->SetPairSeparationCutPhi(0.045); FourPionTask->SetNsigmaTPC(2.0); FourPionTask->SetNsigmaTOF(2.0); // FourPionTask->SetMixedChargeCut(kFALSE); FourPionTask->SetMinPt(0.16); FourPionTask->SetMaxPt(1.0); FourPionTask->SetKT3transition(0.3); FourPionTask->SetKT4transition(0.3); mgr->AddTask(FourPionTask); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== TString outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName += ":PWGCF.outputFourPionAnalysis.root"; AliAnalysisDataContainer *coutFourPion = mgr->CreateContainer("FourPionOutput", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data()); mgr->ConnectInput(FourPionTask, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(FourPionTask, 1, coutFourPion); TFile *inputFileWeight = 0; TFile *inputFileMomRes = 0; TFile *inputFileFSI = 0; TFile *inputFileMuon = 0; TFile *inputFileEA = 0; if(!TabulatePairs){ inputFileWeight = TFile::Open(StWeightName,"OLD"); if (!inputFileWeight){ cout << "Requested file:" << inputFileWeight << " was not opened. ABORT." << endl; return NULL; } //////////////////////////////////////////////////// // C2 Weight File const Int_t ktbins_temp = FourPionTask->GetNumKtBins(); const Int_t cbins_temp = FourPionTask->GetNumCentBins(); const Int_t ktbins = ktbins_temp; const Int_t cbins = cbins_temp; TH3F *weightHisto[ktbins][cbins]; for(Int_t i=0; i<ktbins; i++){ for(Int_t j=0; j<cbins; j++){ TString name = "Weight_Kt_"; name += i; name += "_Ky_0_M_"; name += j; name += "_ED_0"; weightHisto[i][j] = (TH3F*)inputFileWeight->Get(name); } } FourPionTask->SetWeightArrays( kTRUE, weightHisto ); // // inputFileEA = TFile::Open(StEAName,"OLD"); if (!inputFileEA){ cout << "Requested file:" << inputFileEA << " was not opened. ABORT." << endl; return NULL; } TH3D *PbPbEA = 0; TH3D *pPbEA = 0; TH3D *ppEA = 0; PbPbEA = (TH3D*)inputFileEA->Get("PbPbEA"); pPbEA = (TH3D*)inputFileEA->Get("pPbEA"); ppEA = (TH3D*)inputFileEA->Get("ppEA"); FourPionTask->Setc3FitEAs( kTRUE, PbPbEA, pPbEA, ppEA ); //////////////////////////////////////////////////// }// TabulatePairs check if(!MCcase && !TabulatePairs){ inputFileMomRes = TFile::Open(StMomResName,"OLD"); if (!inputFileMomRes){ cout << "Requested file:" << inputFileMomRes << " was not opened. ABORT." << endl; return NULL; } //////////////////////////////////////////////////// // Momentum Resolution File TH2D *momResHisto2DSC = 0; TH2D *momResHisto2DMC = 0; momResHisto2DSC = (TH2D*)inputFileMomRes->Get("MRC_C2_SC"); momResHisto2DMC = (TH2D*)inputFileMomRes->Get("MRC_C2_MC"); FourPionTask->SetMomResCorrections( kTRUE, momResHisto2DSC, momResHisto2DMC ); //////////////////////////////////////////////////// // Muon corrections inputFileMuon = TFile::Open(StMuonName,"OLD"); if (!inputFileMuon){ cout << "Requested file:" << inputFileMuon << " was not opened. ABORT." << endl; return NULL; } TH2D *muonHisto2D = 0; muonHisto2D = (TH2D*)inputFileMuon->Get("WeightmuonCorrection"); FourPionTask->SetMuonCorrections( kTRUE, muonHisto2D); }// MCcase and TabulatePairs check //////////////////////////////////////////////////// // FSI File inputFileFSI = TFile::Open(StKName,"OLD"); if (!inputFileFSI){ cout << "Requested file:" << inputFileFSI << " was not opened. ABORT." << endl; return NULL; } TH1D *FSIss[13]; TH1D *FSIos[13]; for(Int_t index=0; index<13; index++) { TString *nameSS=new TString("K2ss_"); *nameSS += index; FSIss[index] = (TH1D*)inputFileFSI->Get(nameSS->Data()); TString *nameOS=new TString("K2os_"); *nameOS += index; FSIos[index] = (TH1D*)inputFileFSI->Get(nameOS->Data()); // FSIss[index]->SetDirectory(0); FSIos[index]->SetDirectory(0); } // FourPionTask->SetFSICorrelations( kTRUE, FSIss, FSIos ); //////////////////////////////////////////////////// // Return the task pointer return FourPionTask; } <|endoftext|>
<commit_before>/* * File: Scene.hpp * Author: Benedikt Vogler * * Created on 8. Juli 2014, 18:54 */ #ifndef SCENE_HPP #define SCENE_HPP #include "Material.hpp" #include "Camera.hpp" #include "LightPoint.hpp" #include "RenderObject.hpp" #include <map> struct Scene { std::map<std::string, Material> materials; std::map<std::string, LightPoint> lights; std::map<std::string, std::shared_ptr<RenderObject>> renderObjects; Camera camera; std::string camname; int resX; int resY; std::string outputFile; Color amb; int antialiase; bool random; // //manual destructor needed? // ~Scene(){ // for (auto itr=materials.begin(); itr !=materials.end();++itr) { // materials.erase(itr); // } // for (auto itr=lights.begin(); itr !=lights.end();++itr) { // lights.erase(itr); // } // for (auto itr=renderObjects.begin(); itr !=renderObjects.end();++itr) { // renderObjects.erase(itr); // } // } }; #endif /* SCENE_HPP */ <commit_msg>Compatible with VS<commit_after>/* * File: Scene.hpp * Author: Benedikt Vogler * * Created on 8. Juli 2014, 18:54 */ #ifndef SCENE_HPP #define SCENE_HPP #include "Material.hpp" #include "Camera.hpp" #include "LightPoint.hpp" #include "RenderObject.hpp" #include <map> #include <memory> struct Scene { std::map<std::string, Material> materials; std::map<std::string, LightPoint> lights; std::map<std::string, std::shared_ptr<RenderObject>> renderObjects; Camera camera; std::string camname; int resX; int resY; std::string outputFile; Color amb; int antialiase; bool random; // //manual destructor needed? // ~Scene(){ // for (auto itr=materials.begin(); itr !=materials.end();++itr) { // materials.erase(itr); // } // for (auto itr=lights.begin(); itr !=lights.end();++itr) { // lights.erase(itr); // } // for (auto itr=renderObjects.begin(); itr !=renderObjects.end();++itr) { // renderObjects.erase(itr); // } // } }; #endif /* SCENE_HPP */ <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "swissknife_lease_curl.h" #include "cvmfs_config.h" size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) { CurlBuffer* my_buffer = static_cast<CurlBuffer*>(userp); if (size * nmemb < 1) { return 0; } my_buffer->data = static_cast<char*>(buffer); return my_buffer->data.size(); } CURL* PrepareCurl(const char* method) { const char* user_agent_string = "cvmfs/" VERSION; CURL* h_curl = curl_easy_init(); if (h_curl) { curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(h_curl, CURLOPT_USERAGENT, user_agent_string); curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L); curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, method); curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L); } return h_curl; } bool MakeAcquireRequest(const std::string& user_name, const std::string& repo_path, const std::string& repo_service_url, CurlBuffer* buffer) { CURLcode ret = static_cast<CURLcode>(0); CURL* h_curl = PrepareCurl("POST"); if (!h_curl) { return false; } // Make request to acquire lease from repo services curl_easy_setopt(h_curl, CURLOPT_URL, (repo_service_url + REPO_SERVICES_API_ROOT + "/leases?user=" + user_name + "&path=" + repo_path) .c_str()); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(0)); curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB); curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer); ret = curl_easy_perform(h_curl); curl_easy_cleanup(h_curl); h_curl = NULL; return !ret; } bool MakeDeleteRequest(const std::string& session_token, const std::string& repo_service_url, CurlBuffer* buffer) { CURLcode ret = static_cast<CURLcode>(0); CURL* h_curl = PrepareCurl("DELETE"); if (!h_curl) { return false; } curl_easy_setopt( h_curl, CURLOPT_URL, (repo_service_url + REPO_SERVICES_API_ROOT + "/leases/" + session_token) .c_str()); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(0)); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, 0); curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB); curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer); ret = curl_easy_perform(h_curl); curl_easy_cleanup(h_curl); h_curl = NULL; return !ret; } <commit_msg>cvmfs_swissknife lease - modify MakeAcquireRequest to use JSON body<commit_after>/** * This file is part of the CernVM File System. */ #include "swissknife_lease_curl.h" #include "cvmfs_config.h" size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) { CurlBuffer* my_buffer = static_cast<CurlBuffer*>(userp); if (size * nmemb < 1) { return 0; } my_buffer->data = static_cast<char*>(buffer); return my_buffer->data.size(); } CURL* PrepareCurl(const char* method) { const char* user_agent_string = "cvmfs/" VERSION; CURL* h_curl = curl_easy_init(); if (h_curl) { curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(h_curl, CURLOPT_USERAGENT, user_agent_string); curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L); curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, method); curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L); } return h_curl; } bool MakeAcquireRequest(const std::string& user_name, const std::string& repo_path, const std::string& repo_service_url, CurlBuffer* buffer) { CURLcode ret = static_cast<CURLcode>(0); CURL* h_curl = PrepareCurl("POST"); if (!h_curl) { return false; } // Prepare payload const std::string payload = "{\"user\" : \"" + user_name + "\", \"path\" : \"" + repo_path + "\"}"; // Make request to acquire lease from repo services curl_easy_setopt( h_curl, CURLOPT_URL, (repo_service_url + REPO_SERVICES_API_ROOT + "/leases").c_str()); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(payload.length())); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, payload.c_str()); curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB); curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer); ret = curl_easy_perform(h_curl); curl_easy_cleanup(h_curl); h_curl = NULL; return !ret; } bool MakeDeleteRequest(const std::string& session_token, const std::string& repo_service_url, CurlBuffer* buffer) { CURLcode ret = static_cast<CURLcode>(0); CURL* h_curl = PrepareCurl("DELETE"); if (!h_curl) { return false; } curl_easy_setopt( h_curl, CURLOPT_URL, (repo_service_url + REPO_SERVICES_API_ROOT + "/leases/" + session_token) .c_str()); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(0)); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, 0); curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB); curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer); ret = curl_easy_perform(h_curl); curl_easy_cleanup(h_curl); h_curl = NULL; return !ret; } <|endoftext|>
<commit_before>/* * Copyright 2016 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 * * 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 "app/src/include/firebase/util.h" #include <assert.h> #include <map> #include <string> #include <vector> #include "app/src/include/firebase/internal/platform.h" #if FIREBASE_PLATFORM_ANDROID #include "app/src/include/google_play_services/availability.h" #endif // FIREBASE_PLATFORM_ANDROID #include "app/src/include/firebase/internal/mutex.h" #include "app/src/log.h" #include "app/src/reference_counted_future_impl.h" #include "app/src/util.h" namespace firebase { enum ModuleInitializerFn { kModuleInitializerInitialize, kModuleInitializerCount }; struct ModuleInitializerData { ModuleInitializerData() : future_impl(kModuleInitializerCount), app(nullptr), context(nullptr), init_fn_idx(0) {} // Futures implementation. ReferenceCountedFutureImpl future_impl; // Handle to the Initialize() future. SafeFutureHandle<void> future_handle_init; // Data we will pass to the user's callbacks. App* app; void* context; // Initialization callbacks. These will each be called in order, but if any // of them returns kInitResultFailedMissingDependency, we'll stop and update, // then resume where we left off. std::vector<ModuleInitializer::InitializerFn> init_fns; // Where we are in the initializer function list. int init_fn_idx; }; ModuleInitializer::ModuleInitializer() { data_ = new ModuleInitializerData; } ModuleInitializer::~ModuleInitializer() { delete data_; data_ = nullptr; } static void PerformInitialize(ModuleInitializerData* data) { while (data->init_fn_idx < data->init_fns.size()) { InitResult init_result; init_result = data->init_fns[data->init_fn_idx](data->app, data->context); #if FIREBASE_PLATFORM_ANDROID if (init_result == kInitResultFailedMissingDependency) { // On Android, we need to update or activate Google Play services // before we can initialize this Firebase module. LogWarning("Google Play services unavailable, trying to fix."); Future<void> make_available = google_play_services::MakeAvailable( data->app->GetJNIEnv(), data->app->activity()); make_available.OnCompletion( [](const Future<void>& result, void* ptr) { ModuleInitializerData* data = reinterpret_cast<ModuleInitializerData*>(ptr); if (result.status() == kFutureStatusComplete) { if (result.error() == 0) { LogInfo("Google Play services now available, continuing."); PerformInitialize(data); } else { LogError("Google Play services still unavailable."); int num_remaining = data->init_fns.size() - data->init_fn_idx; data->future_impl.Complete( data->future_handle_init, num_remaining, "Unable to initialize due to missing Google Play services " "dependency."); } } }, data); } #else // !FIREBASE_PLATFORM_ANDROID // Outside of Android, we shouldn't get kInitResultFailedMissingDependency. FIREBASE_ASSERT(init_result != kInitResultFailedMissingDependency); #endif // FIREBASE_PLATFORM_ANDROID if (init_result == kInitResultSuccess) { data->init_fn_idx++; // This function succeeded, move on to the next one. } else { return; // If initialization failed, we will be trying again later, after // the MakeAvailable() Future completes. (or, if that future fails, then // we will just abort and return an error.) } } data->future_impl.Complete(data->future_handle_init, 0); } Future<void> ModuleInitializer::Initialize( App* app, void* context, ModuleInitializer::InitializerFn init_fn) { FIREBASE_ASSERT(app != nullptr); FIREBASE_ASSERT(init_fn != nullptr); return Initialize(app, context, &init_fn, 1); } Future<void> ModuleInitializer::Initialize( App* app, void* context, const ModuleInitializer::InitializerFn* init_fns, size_t init_fns_count) { FIREBASE_ASSERT(app != nullptr); FIREBASE_ASSERT(init_fns != nullptr); if (!data_->future_impl.ValidFuture(data_->future_handle_init)) { data_->future_handle_init = data_->future_impl.SafeAlloc<void>(kModuleInitializerInitialize); data_->app = app; data_->init_fn_idx = 0; data_->init_fns.clear(); for (size_t i = 0; i < init_fns_count; i++) { data_->init_fns.push_back(init_fns[i]); } data_->context = context; PerformInitialize(data_); } return InitializeLastResult(); } Future<void> ModuleInitializer::InitializeLastResult() { return static_cast<const Future<void>&>( data_->future_impl.LastResult(kModuleInitializerInitialize)); } std::map<std::string, AppCallback*>* AppCallback::callbacks_; Mutex* AppCallback::callbacks_mutex_ = new Mutex(); void AppCallback::NotifyAllAppCreated( firebase::App* app, std::map<std::string, InitResult>* results) { if (results) results->clear(); MutexLock lock(*callbacks_mutex_); if (!callbacks_) return; for (std::map<std::string, AppCallback*>::const_iterator it = callbacks_->begin(); it != callbacks_->end(); ++it) { const AppCallback* callback = it->second; if (callback->enabled()) { InitResult result = callback->NotifyAppCreated(app); if (results) (*results)[it->first] = result; } } } void AppCallback::NotifyAllAppDestroyed(firebase::App* app) { MutexLock lock(*callbacks_mutex_); if (!callbacks_) return; for (std::map<std::string, AppCallback*>::const_iterator it = callbacks_->begin(); it != callbacks_->end(); ++it) { const AppCallback* callback = it->second; if (callback->enabled()) callback->NotifyAppDestroyed(app); } } // Determine whether a module callback is enabled, by name. bool AppCallback::GetEnabledByName(const char* name) { MutexLock lock(*callbacks_mutex_); if (!callbacks_) return false; std::map<std::string, AppCallback*>::const_iterator it = callbacks_->find(std::string(name)); if (it == callbacks_->end()) { return false; } return it->second->enabled(); } // Enable a module callback by name. void AppCallback::SetEnabledByName(const char* name, bool enable) { MutexLock lock(*callbacks_mutex_); if (!callbacks_) return; std::map<std::string, AppCallback*>::const_iterator it = callbacks_->find(std::string(name)); if (it == callbacks_->end()) { LogDebug("App initializer %s not found, failed to enable.", name); return; } LogDebug("%s app initializer %s", name, enable ? "Enabling" : "Disabling"); it->second->set_enabled(enable); } void AppCallback::SetEnabledAll(bool enable) { MutexLock lock(*callbacks_mutex_); if (!callbacks_) return; LogDebug("%s all app initializers", enable ? "Enabling" : "Disabling"); for (std::map<std::string, AppCallback*>::const_iterator it = callbacks_->begin(); it != callbacks_->end(); ++it) { LogDebug("%s %s", enable ? "Enable" : "Disable", it->second->module_name()); it->second->set_enabled(enable); } } void AppCallback::AddCallback(AppCallback* callback) { if (!callbacks_) { callbacks_ = new std::map<std::string, AppCallback*>(); } std::string name = callback->module_name(); if (callbacks_->find(name) != callbacks_->end()) { LogWarning( "%s is already registered for callbacks on app initialization, " "ignoring.", name.c_str()); } else { LogDebug("Registered app initializer %s (enabled: %d)", name.c_str(), callback->enabled() ? 1 : 0); (*callbacks_)[name] = callback; } } Mutex* StaticFutureData::s_futures_mutex_ = new Mutex(); std::map<const void*, StaticFutureData*>* StaticFutureData::s_future_datas_; // static void StaticFutureData::CleanupFutureDataForModule( const void* module_identifier) { MutexLock lock(*s_futures_mutex_); if (s_future_datas_ == nullptr) return; auto it = s_future_datas_->find(module_identifier); if (it != s_future_datas_->end()) { StaticFutureData* existing_data = it->second; if (existing_data != nullptr) delete existing_data; s_future_datas_->erase(it); } } // static StaticFutureData* StaticFutureData::GetFutureDataForModule( const void* module_identifier, int num_functions) { MutexLock lock(*s_futures_mutex_); if (s_future_datas_ == nullptr) { s_future_datas_ = new std::map<const void*, StaticFutureData*>; } auto found_value = s_future_datas_->find(module_identifier); if (found_value != s_future_datas_->end()) { StaticFutureData* existing_data = found_value->second; if (existing_data != nullptr) { return existing_data; } } StaticFutureData* new_data = CreateNewData(module_identifier, num_functions); (*s_future_datas_)[module_identifier] = new_data; return new_data; } // static StaticFutureData* StaticFutureData::CreateNewData(const void* module_identifier, int num_functions) { StaticFutureData* new_data = new StaticFutureData(num_functions); return new_data; } std::vector<std::string> SplitString(const std::string& s, const char delimiter) { size_t pos = 0; // This index is used as the starting index to search the delimiters from. size_t delimiter_search_start = 0; // Skip any leading delimiters while (s[delimiter_search_start] == delimiter) { delimiter_search_start++; } std::vector<std::string> split_parts; size_t len = s.size(); // Can't proceed if input string consists of just delimiters if (pos >= len) { return split_parts; } while ((pos = s.find(delimiter, delimiter_search_start)) != std::string::npos) { split_parts.push_back( s.substr(delimiter_search_start, pos - delimiter_search_start)); while (s[pos] == delimiter && pos < len) { pos++; delimiter_search_start = pos; } } // If the input string doesn't end with a delimiter we need to push the last // token into our return vector if (delimiter_search_start != len) { split_parts.push_back( s.substr(delimiter_search_start, len - delimiter_search_start)); } return split_parts; } // NOLINTNEXTLINE - allow namespace overridden } // namespace firebase <commit_msg>Disable logging during AddCallback, which initializes too early. (#827)<commit_after>/* * Copyright 2016 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 * * 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 "app/src/include/firebase/util.h" #include <assert.h> #include <map> #include <string> #include <vector> #include "app/src/include/firebase/internal/platform.h" #if FIREBASE_PLATFORM_ANDROID #include "app/src/include/google_play_services/availability.h" #endif // FIREBASE_PLATFORM_ANDROID #include "app/src/include/firebase/internal/mutex.h" #include "app/src/log.h" #include "app/src/reference_counted_future_impl.h" #include "app/src/util.h" namespace firebase { enum ModuleInitializerFn { kModuleInitializerInitialize, kModuleInitializerCount }; struct ModuleInitializerData { ModuleInitializerData() : future_impl(kModuleInitializerCount), app(nullptr), context(nullptr), init_fn_idx(0) {} // Futures implementation. ReferenceCountedFutureImpl future_impl; // Handle to the Initialize() future. SafeFutureHandle<void> future_handle_init; // Data we will pass to the user's callbacks. App* app; void* context; // Initialization callbacks. These will each be called in order, but if any // of them returns kInitResultFailedMissingDependency, we'll stop and update, // then resume where we left off. std::vector<ModuleInitializer::InitializerFn> init_fns; // Where we are in the initializer function list. int init_fn_idx; }; ModuleInitializer::ModuleInitializer() { data_ = new ModuleInitializerData; } ModuleInitializer::~ModuleInitializer() { delete data_; data_ = nullptr; } static void PerformInitialize(ModuleInitializerData* data) { while (data->init_fn_idx < data->init_fns.size()) { InitResult init_result; init_result = data->init_fns[data->init_fn_idx](data->app, data->context); #if FIREBASE_PLATFORM_ANDROID if (init_result == kInitResultFailedMissingDependency) { // On Android, we need to update or activate Google Play services // before we can initialize this Firebase module. LogWarning("Google Play services unavailable, trying to fix."); Future<void> make_available = google_play_services::MakeAvailable( data->app->GetJNIEnv(), data->app->activity()); make_available.OnCompletion( [](const Future<void>& result, void* ptr) { ModuleInitializerData* data = reinterpret_cast<ModuleInitializerData*>(ptr); if (result.status() == kFutureStatusComplete) { if (result.error() == 0) { LogInfo("Google Play services now available, continuing."); PerformInitialize(data); } else { LogError("Google Play services still unavailable."); int num_remaining = data->init_fns.size() - data->init_fn_idx; data->future_impl.Complete( data->future_handle_init, num_remaining, "Unable to initialize due to missing Google Play services " "dependency."); } } }, data); } #else // !FIREBASE_PLATFORM_ANDROID // Outside of Android, we shouldn't get kInitResultFailedMissingDependency. FIREBASE_ASSERT(init_result != kInitResultFailedMissingDependency); #endif // FIREBASE_PLATFORM_ANDROID if (init_result == kInitResultSuccess) { data->init_fn_idx++; // This function succeeded, move on to the next one. } else { return; // If initialization failed, we will be trying again later, after // the MakeAvailable() Future completes. (or, if that future fails, then // we will just abort and return an error.) } } data->future_impl.Complete(data->future_handle_init, 0); } Future<void> ModuleInitializer::Initialize( App* app, void* context, ModuleInitializer::InitializerFn init_fn) { FIREBASE_ASSERT(app != nullptr); FIREBASE_ASSERT(init_fn != nullptr); return Initialize(app, context, &init_fn, 1); } Future<void> ModuleInitializer::Initialize( App* app, void* context, const ModuleInitializer::InitializerFn* init_fns, size_t init_fns_count) { FIREBASE_ASSERT(app != nullptr); FIREBASE_ASSERT(init_fns != nullptr); if (!data_->future_impl.ValidFuture(data_->future_handle_init)) { data_->future_handle_init = data_->future_impl.SafeAlloc<void>(kModuleInitializerInitialize); data_->app = app; data_->init_fn_idx = 0; data_->init_fns.clear(); for (size_t i = 0; i < init_fns_count; i++) { data_->init_fns.push_back(init_fns[i]); } data_->context = context; PerformInitialize(data_); } return InitializeLastResult(); } Future<void> ModuleInitializer::InitializeLastResult() { return static_cast<const Future<void>&>( data_->future_impl.LastResult(kModuleInitializerInitialize)); } std::map<std::string, AppCallback*>* AppCallback::callbacks_; Mutex* AppCallback::callbacks_mutex_ = new Mutex(); void AppCallback::NotifyAllAppCreated( firebase::App* app, std::map<std::string, InitResult>* results) { if (results) results->clear(); MutexLock lock(*callbacks_mutex_); if (!callbacks_) return; for (std::map<std::string, AppCallback*>::const_iterator it = callbacks_->begin(); it != callbacks_->end(); ++it) { const AppCallback* callback = it->second; if (callback->enabled()) { InitResult result = callback->NotifyAppCreated(app); if (results) (*results)[it->first] = result; } } } void AppCallback::NotifyAllAppDestroyed(firebase::App* app) { MutexLock lock(*callbacks_mutex_); if (!callbacks_) return; for (std::map<std::string, AppCallback*>::const_iterator it = callbacks_->begin(); it != callbacks_->end(); ++it) { const AppCallback* callback = it->second; if (callback->enabled()) callback->NotifyAppDestroyed(app); } } // Determine whether a module callback is enabled, by name. bool AppCallback::GetEnabledByName(const char* name) { MutexLock lock(*callbacks_mutex_); if (!callbacks_) return false; std::map<std::string, AppCallback*>::const_iterator it = callbacks_->find(std::string(name)); if (it == callbacks_->end()) { return false; } return it->second->enabled(); } // Enable a module callback by name. void AppCallback::SetEnabledByName(const char* name, bool enable) { MutexLock lock(*callbacks_mutex_); if (!callbacks_) return; std::map<std::string, AppCallback*>::const_iterator it = callbacks_->find(std::string(name)); if (it == callbacks_->end()) { LogDebug("App initializer %s not found, failed to enable.", name); return; } LogDebug("%s app initializer %s", name, enable ? "Enabling" : "Disabling"); it->second->set_enabled(enable); } void AppCallback::SetEnabledAll(bool enable) { MutexLock lock(*callbacks_mutex_); if (!callbacks_) return; LogDebug("%s all app initializers", enable ? "Enabling" : "Disabling"); for (std::map<std::string, AppCallback*>::const_iterator it = callbacks_->begin(); it != callbacks_->end(); ++it) { LogDebug("%s %s", enable ? "Enable" : "Disable", it->second->module_name()); it->second->set_enabled(enable); } } void AppCallback::AddCallback(AppCallback* callback) { if (!callbacks_) { callbacks_ = new std::map<std::string, AppCallback*>(); } std::string name = callback->module_name(); if (callbacks_->find(name) != callbacks_->end()) { } else { (*callbacks_)[name] = callback; } } Mutex* StaticFutureData::s_futures_mutex_ = new Mutex(); std::map<const void*, StaticFutureData*>* StaticFutureData::s_future_datas_; // static void StaticFutureData::CleanupFutureDataForModule( const void* module_identifier) { MutexLock lock(*s_futures_mutex_); if (s_future_datas_ == nullptr) return; auto it = s_future_datas_->find(module_identifier); if (it != s_future_datas_->end()) { StaticFutureData* existing_data = it->second; if (existing_data != nullptr) delete existing_data; s_future_datas_->erase(it); } } // static StaticFutureData* StaticFutureData::GetFutureDataForModule( const void* module_identifier, int num_functions) { MutexLock lock(*s_futures_mutex_); if (s_future_datas_ == nullptr) { s_future_datas_ = new std::map<const void*, StaticFutureData*>; } auto found_value = s_future_datas_->find(module_identifier); if (found_value != s_future_datas_->end()) { StaticFutureData* existing_data = found_value->second; if (existing_data != nullptr) { return existing_data; } } StaticFutureData* new_data = CreateNewData(module_identifier, num_functions); (*s_future_datas_)[module_identifier] = new_data; return new_data; } // static StaticFutureData* StaticFutureData::CreateNewData(const void* module_identifier, int num_functions) { StaticFutureData* new_data = new StaticFutureData(num_functions); return new_data; } std::vector<std::string> SplitString(const std::string& s, const char delimiter) { size_t pos = 0; // This index is used as the starting index to search the delimiters from. size_t delimiter_search_start = 0; // Skip any leading delimiters while (s[delimiter_search_start] == delimiter) { delimiter_search_start++; } std::vector<std::string> split_parts; size_t len = s.size(); // Can't proceed if input string consists of just delimiters if (pos >= len) { return split_parts; } while ((pos = s.find(delimiter, delimiter_search_start)) != std::string::npos) { split_parts.push_back( s.substr(delimiter_search_start, pos - delimiter_search_start)); while (s[pos] == delimiter && pos < len) { pos++; delimiter_search_start = pos; } } // If the input string doesn't end with a delimiter we need to push the last // token into our return vector if (delimiter_search_start != len) { split_parts.push_back( s.substr(delimiter_search_start, len - delimiter_search_start)); } return split_parts; } // NOLINTNEXTLINE - allow namespace overridden } // namespace firebase <|endoftext|>
<commit_before>#include "framework/trace.h" #include <fstream> #include <memory> #include <mutex> #include <sstream> #include <thread> namespace { using OpenApoc::UString; enum class EventType { Begin, End, }; class TraceEvent { public: EventType type; UString name; std::vector<std::pair<UString, UString>> args; uint64_t timeNS; TraceEvent(EventType type, const UString &name, const std::vector<std::pair<UString, UString>> &args, uint64_t timeNS) : type(type), name(name), args(args), timeNS(timeNS) { } }; class EventList { public: UString tid; std::vector<TraceEvent> events; }; class TraceManager { public: // We need a list of all the EventLists created for each thread to dump out & free at // TraceManager destructor time std::list<std::unique_ptr<EventList>> lists; std::mutex listMutex; EventList *createThreadEventList() { std::stringstream ss; listMutex.lock(); EventList *list = new EventList; ss << std::this_thread::get_id(); list->tid = ss.str(); lists.emplace_back(list); listMutex.unlock(); return list; } ~TraceManager(); void write(); }; static std::unique_ptr<TraceManager> trace_manager; #if defined(PTHREADS_AVAILABLE) #include <pthread.h> #endif // thread_local isn't implemented until msvc 2015 (_MSC_VER 1900) #if defined(_MSC_VER) && _MSC_VER < 1900 static __declspec(thread) EventList *events = nullptr; #else #if defined(BROKEN_THREAD_LOCAL) #warning Using pthread path static pthread_key_t eventListKey; #else static thread_local EventList *events = nullptr; #endif #endif static std::chrono::time_point<std::chrono::high_resolution_clock> traceStartTime; } // anonymous namespace TraceManager::~TraceManager() { if (OpenApoc::Trace::enabled) this->write(); } void TraceManager::write() { assert(OpenApoc::Trace::enabled); OpenApoc::Trace::enabled = false; std::ofstream outFile("openapoc_trace.json"); // FIXME: Use proper json parser instead of magically constructing from strings? outFile << "{\"traceEvents\":[\n"; bool firstEvent = true; listMutex.lock(); for (auto &eventList : lists) { for (auto &event : eventList->events) { if (!firstEvent) outFile << ",\n"; firstEvent = false; outFile << "{" << "\"pid\":1," << "\"tid\":\"" << eventList->tid.str() << "\"," // Time is in microseconds, not nanoseconds << "\"ts\":" << event.timeNS / 1000 << "," << "\"name\":\"" << event.name.str() << "\","; switch (event.type) { case EventType::Begin: { outFile << "\"ph\":\"B\""; if (!event.args.empty()) { outFile << ",\"args\":{"; bool firstArg = true; for (auto &arg : event.args) { if (!firstArg) outFile << ","; firstArg = false; outFile << "\"" << arg.first.str() << "\":\"" << arg.second.str() << "\""; } outFile << "}"; } break; } case EventType::End: outFile << "\"ph\":\"E\""; break; } outFile << "}"; } } listMutex.unlock(); outFile << "]}\n"; outFile.flush(); } namespace OpenApoc { bool Trace::enabled = false; void Trace::enable() { assert(!trace_manager); trace_manager.reset(new TraceManager); #if defined(BROKEN_THREAD_LOCAL) pthread_key_create(&eventListKey, NULL); #endif Trace::enabled = true; traceStartTime = std::chrono::high_resolution_clock::now(); } void Trace::disable() { assert(trace_manager); trace_manager->write(); trace_manager.reset(nullptr); #if defined(BROKEN_THREAD_LOCAL) pthread_key_delete(&eventListKey); #endif Trace::enabled = false; } void Trace::setThreadName(const UString &name) { #if defined(PTHREADS_AVAILABLE) pthread_setname_np(pthread_self(), name.c_str()); #endif if (!Trace::enabled) return; #if defined(BROKEN_THREAD_LOCAL) EventList *events = (EventList *)pthread_getspecific(eventListKey); if (!events) { events = trace_manager->createThreadEventList(); pthread_setspecific(eventListKey, events); } #else if (!events) events = trace_manager->createThreadEventList(); #endif events->tid = name; } void Trace::start(const UString &name, const std::vector<std::pair<UString, UString>> &args) { if (!Trace::enabled) return; #if defined(BROKEN_THREAD_LOCAL) EventList *events = (EventList *)pthread_getspecific(eventListKey); if (!events) { events = trace_manager->createThreadEventList(); pthread_setspecific(eventListKey, events); } #else if (!events) events = trace_manager->createThreadEventList(); #endif auto timeNow = std::chrono::high_resolution_clock::now(); uint64_t timeNS = std::chrono::duration<uint64_t, std::nano>(timeNow - traceStartTime).count(); events->events.emplace_back(EventType::Begin, name, args, timeNS); } void Trace::end(const UString &name) { if (!Trace::enabled) return; #if defined(BROKEN_THREAD_LOCAL) EventList *events = (EventList *)pthread_getspecific(eventListKey); if (!events) { events = trace_manager->createThreadEventList(); pthread_setspecific(eventListKey, events); } #else if (!events) events = trace_manager->createThreadEventList(); #endif auto timeNow = std::chrono::high_resolution_clock::now(); uint64_t timeNS = std::chrono::duration<uint64_t, std::nano>(timeNow - traceStartTime).count(); events->events.emplace_back(EventType::End, name, std::vector<std::pair<UString, UString>>{}, timeNS); } } // namespace OpenApoc <commit_msg>Fix typo in trace.cpp<commit_after>#include "framework/trace.h" #include <fstream> #include <memory> #include <mutex> #include <sstream> #include <thread> namespace { using OpenApoc::UString; enum class EventType { Begin, End, }; class TraceEvent { public: EventType type; UString name; std::vector<std::pair<UString, UString>> args; uint64_t timeNS; TraceEvent(EventType type, const UString &name, const std::vector<std::pair<UString, UString>> &args, uint64_t timeNS) : type(type), name(name), args(args), timeNS(timeNS) { } }; class EventList { public: UString tid; std::vector<TraceEvent> events; }; class TraceManager { public: // We need a list of all the EventLists created for each thread to dump out & free at // TraceManager destructor time std::list<std::unique_ptr<EventList>> lists; std::mutex listMutex; EventList *createThreadEventList() { std::stringstream ss; listMutex.lock(); EventList *list = new EventList; ss << std::this_thread::get_id(); list->tid = ss.str(); lists.emplace_back(list); listMutex.unlock(); return list; } ~TraceManager(); void write(); }; static std::unique_ptr<TraceManager> trace_manager; #if defined(PTHREADS_AVAILABLE) #include <pthread.h> #endif // thread_local isn't implemented until msvc 2015 (_MSC_VER 1900) #if defined(_MSC_VER) && _MSC_VER < 1900 static __declspec(thread) EventList *events = nullptr; #else #if defined(BROKEN_THREAD_LOCAL) #warning Using pthread path static pthread_key_t eventListKey; #else static thread_local EventList *events = nullptr; #endif #endif static std::chrono::time_point<std::chrono::high_resolution_clock> traceStartTime; } // anonymous namespace TraceManager::~TraceManager() { if (OpenApoc::Trace::enabled) this->write(); } void TraceManager::write() { assert(OpenApoc::Trace::enabled); OpenApoc::Trace::enabled = false; std::ofstream outFile("openapoc_trace.json"); // FIXME: Use proper json parser instead of magically constructing from strings? outFile << "{\"traceEvents\":[\n"; bool firstEvent = true; listMutex.lock(); for (auto &eventList : lists) { for (auto &event : eventList->events) { if (!firstEvent) outFile << ",\n"; firstEvent = false; outFile << "{" << "\"pid\":1," << "\"tid\":\"" << eventList->tid.str() << "\"," // Time is in microseconds, not nanoseconds << "\"ts\":" << event.timeNS / 1000 << "," << "\"name\":\"" << event.name.str() << "\","; switch (event.type) { case EventType::Begin: { outFile << "\"ph\":\"B\""; if (!event.args.empty()) { outFile << ",\"args\":{"; bool firstArg = true; for (auto &arg : event.args) { if (!firstArg) outFile << ","; firstArg = false; outFile << "\"" << arg.first.str() << "\":\"" << arg.second.str() << "\""; } outFile << "}"; } break; } case EventType::End: outFile << "\"ph\":\"E\""; break; } outFile << "}"; } } listMutex.unlock(); outFile << "]}\n"; outFile.flush(); } namespace OpenApoc { bool Trace::enabled = false; void Trace::enable() { assert(!trace_manager); trace_manager.reset(new TraceManager); #if defined(BROKEN_THREAD_LOCAL) pthread_key_create(&eventListKey, NULL); #endif Trace::enabled = true; traceStartTime = std::chrono::high_resolution_clock::now(); } void Trace::disable() { assert(trace_manager); trace_manager->write(); trace_manager.reset(nullptr); #if defined(BROKEN_THREAD_LOCAL) pthread_key_delete(eventListKey); #endif Trace::enabled = false; } void Trace::setThreadName(const UString &name) { #if defined(PTHREADS_AVAILABLE) pthread_setname_np(pthread_self(), name.c_str()); #endif if (!Trace::enabled) return; #if defined(BROKEN_THREAD_LOCAL) EventList *events = (EventList *)pthread_getspecific(eventListKey); if (!events) { events = trace_manager->createThreadEventList(); pthread_setspecific(eventListKey, events); } #else if (!events) events = trace_manager->createThreadEventList(); #endif events->tid = name; } void Trace::start(const UString &name, const std::vector<std::pair<UString, UString>> &args) { if (!Trace::enabled) return; #if defined(BROKEN_THREAD_LOCAL) EventList *events = (EventList *)pthread_getspecific(eventListKey); if (!events) { events = trace_manager->createThreadEventList(); pthread_setspecific(eventListKey, events); } #else if (!events) events = trace_manager->createThreadEventList(); #endif auto timeNow = std::chrono::high_resolution_clock::now(); uint64_t timeNS = std::chrono::duration<uint64_t, std::nano>(timeNow - traceStartTime).count(); events->events.emplace_back(EventType::Begin, name, args, timeNS); } void Trace::end(const UString &name) { if (!Trace::enabled) return; #if defined(BROKEN_THREAD_LOCAL) EventList *events = (EventList *)pthread_getspecific(eventListKey); if (!events) { events = trace_manager->createThreadEventList(); pthread_setspecific(eventListKey, events); } #else if (!events) events = trace_manager->createThreadEventList(); #endif auto timeNow = std::chrono::high_resolution_clock::now(); uint64_t timeNS = std::chrono::duration<uint64_t, std::nano>(timeNow - traceStartTime).count(); events->events.emplace_back(EventType::End, name, std::vector<std::pair<UString, UString>>{}, timeNS); } } // namespace OpenApoc <|endoftext|>
<commit_before>#include <iostream> using namespace std; class Solution { public: int myAtoi(string str) { int begin = 0; while (str[begin] == ' ') { begin++; } long max_int = INT_MAX; long min_int = INT_MIN; bool negative = false; if (str[begin] == '-') { negative = true; begin++; } else if (str[begin] == '+') { begin++; } long number = 0; while (begin < str.size()) { char c = str[begin]; int d = c - 48; if (d < 0 || d > 9) { break; } number = number * 10 + d; begin++; if (negative == true) { if (-number <= min_int) { return min_int; } } else { if (number >= max_int) { return max_int; } } } if (negative == true) { number = -number; } if (number >= max_int) { return max_int; } if (number <= min_int) { return min_int; } return number; } }; <commit_msg>update<commit_after>#include <iostream> using namespace std; class Solution { public: int myAtoi(string str) { int begin = 0; while (str[begin] == ' ') { begin++; } long max_int = INT_MAX; long min_int = INT_MIN; bool negative = false; if (str[begin] == '-') { negative = true; begin++; } else if (str[begin] == '+') { begin++; } long number = 0; while (begin < str.size()) { char c = str[begin]; int d = c - 48; if (d < 0 || d > 9) { break; } number = number * 10 + d; begin++; if (negative == true) { if (-number <= min_int) { return min_int; } } else { if (number >= max_int) { return max_int; } } } if (negative == true) { number = -number; } if (number >= max_int) { return max_int; } if (number <= min_int) { return min_int; } return number; } }; class Solution { public: int myAtoi(string str) { int idx = 0; while (str[idx] == ' ') { idx++; } bool negative = false; if (str[idx] == '-') { negative = true; idx++; } else if (str[idx] == '+') { idx++; } int num = 0; while (idx < str.size()) { int d = str[idx] - 48; if (d < 0 || d > 9) { break; } int new_num = num * 10 + d; if (new_num / 10 != num) { // overflow if (negative == true) { return INT_MIN; } else { return INT_MAX; } } num = new_num; idx++; } if (negative == true) { num = -num; } return num; } }; <|endoftext|>
<commit_before>#include "ray/gcs/redis_context.h" #include <unistd.h> #include <sstream> extern "C" { #include "hiredis/adapters/ae.h" #include "hiredis/async.h" #include "hiredis/hiredis.h" } // TODO(pcm): Integrate into the C++ tree. #include "state/ray_config.h" namespace { /// A helper function to call the callback and delete it from the callback /// manager if necessary. void ProcessCallback(int64_t callback_index, const std::string &data) { if (callback_index >= 0) { bool delete_callback = ray::gcs::RedisCallbackManager::instance().get(callback_index)(data); // Delete the callback if necessary. if (delete_callback) { ray::gcs::RedisCallbackManager::instance().remove(callback_index); } } } } // namespace namespace ray { namespace gcs { // This is a global redis callback which will be registered for every // asynchronous redis call. It dispatches the appropriate callback // that was registered with the RedisCallbackManager. void GlobalRedisCallback(void *c, void *r, void *privdata) { if (r == nullptr) { return; } int64_t callback_index = reinterpret_cast<int64_t>(privdata); redisReply *reply = reinterpret_cast<redisReply *>(r); std::string data = ""; // Parse the response. switch (reply->type) { case (REDIS_REPLY_NIL): { // Do not add any data for a nil response. } break; case (REDIS_REPLY_STRING): { data = std::string(reply->str, reply->len); } break; case (REDIS_REPLY_STATUS): { } break; case (REDIS_REPLY_ERROR): { RAY_LOG(ERROR) << "Redis error " << reply->str; } break; case (REDIS_REPLY_INTEGER): { data = std::to_string(reply->integer); break; } default: RAY_LOG(FATAL) << "Fatal redis error of type " << reply->type << " and with string " << reply->str; } ProcessCallback(callback_index, data); } void SubscribeRedisCallback(void *c, void *r, void *privdata) { if (r == nullptr) { return; } int64_t callback_index = reinterpret_cast<int64_t>(privdata); redisReply *reply = reinterpret_cast<redisReply *>(r); std::string data = ""; // Parse the response. switch (reply->type) { case (REDIS_REPLY_ARRAY): { // Parse the published message. redisReply *message_type = reply->element[0]; if (strcmp(message_type->str, "subscribe") == 0) { // If the message is for the initial subscription call, return the empty // string as a response to signify that subscription was successful. } else if (strcmp(message_type->str, "message") == 0) { // If the message is from a PUBLISH, make sure the data is nonempty. redisReply *message = reply->element[reply->elements - 1]; auto notification = std::string(message->str, message->len); RAY_CHECK(!notification.empty()) << "Empty message received on subscribe channel"; data = notification; } else { RAY_LOG(FATAL) << "Fatal redis error during subscribe" << message_type->str; } } break; case (REDIS_REPLY_ERROR): { RAY_LOG(ERROR) << "Redis error " << reply->str; } break; default: RAY_LOG(FATAL) << "Fatal redis error of type " << reply->type << " and with string " << reply->str; } ProcessCallback(callback_index, data); } int64_t RedisCallbackManager::add(const RedisCallback &function) { callbacks_.emplace(num_callbacks_, function); return num_callbacks_++; } RedisCallback &RedisCallbackManager::get(int64_t callback_index) { RAY_CHECK(callbacks_.find(callback_index) != callbacks_.end()); return callbacks_[callback_index]; } void RedisCallbackManager::remove(int64_t callback_index) { callbacks_.erase(callback_index); } #define REDIS_CHECK_ERROR(CONTEXT, REPLY) \ if (REPLY == nullptr || REPLY->type == REDIS_REPLY_ERROR) { \ return Status::RedisError(CONTEXT->errstr); \ } RedisContext::~RedisContext() { if (context_) { redisFree(context_); } if (async_context_) { redisAsyncFree(async_context_); } if (subscribe_context_) { redisAsyncFree(subscribe_context_); } } Status AuthenticateRedis(redisContext *context, const std::string &password) { if (password == "") { return Status::OK(); } redisReply *reply = reinterpret_cast<redisReply *>(redisCommand(context, "AUTH %s", password.c_str())); REDIS_CHECK_ERROR(context, reply); freeReplyObject(reply); return Status::OK(); } Status AuthenticateRedis(redisAsyncContext *context, const std::string &password) { if (password == "") { return Status::OK(); } int status = redisAsyncCommand(context, NULL, NULL, "AUTH %s", password.c_str()); if (status == REDIS_ERR) { return Status::RedisError(std::string(context->errstr)); } return Status::OK(); } Status RedisContext::Connect(const std::string &address, int port, bool sharding, const std::string &password = "") { int connection_attempts = 0; context_ = redisConnect(address.c_str(), port); while (context_ == nullptr || context_->err) { if (connection_attempts >= RayConfig::instance().redis_db_connect_retries()) { if (context_ == nullptr) { RAY_LOG(FATAL) << "Could not allocate redis context."; } if (context_->err) { RAY_LOG(FATAL) << "Could not establish connection to redis " << address << ":" << port; } break; } RAY_LOG(WARNING) << "Failed to connect to Redis, retrying."; // Sleep for a little. usleep(RayConfig::instance().redis_db_connect_wait_milliseconds() * 1000); context_ = redisConnect(address.c_str(), port); connection_attempts += 1; } RAY_CHECK_OK(AuthenticateRedis(context_, password)); redisReply *reply = reinterpret_cast<redisReply *>( redisCommand(context_, "CONFIG SET notify-keyspace-events Kl")); REDIS_CHECK_ERROR(context_, reply); freeReplyObject(reply); // Connect to async context async_context_ = redisAsyncConnect(address.c_str(), port); if (async_context_ == nullptr || async_context_->err) { RAY_LOG(FATAL) << "Could not establish connection to redis " << address << ":" << port; } RAY_CHECK_OK(AuthenticateRedis(async_context_, password)); // Connect to subscribe context subscribe_context_ = redisAsyncConnect(address.c_str(), port); if (subscribe_context_ == nullptr || subscribe_context_->err) { RAY_LOG(FATAL) << "Could not establish subscribe connection to redis " << address << ":" << port; } RAY_CHECK_OK(AuthenticateRedis(subscribe_context_, password)); return Status::OK(); } Status RedisContext::AttachToEventLoop(aeEventLoop *loop) { if (redisAeAttach(loop, async_context_) != REDIS_OK || redisAeAttach(loop, subscribe_context_) != REDIS_OK) { return Status::RedisError("could not attach redis event loop"); } else { return Status::OK(); } } Status RedisContext::RunAsync(const std::string &command, const UniqueID &id, const uint8_t *data, int64_t length, const TablePrefix prefix, const TablePubsub pubsub_channel, RedisCallback redisCallback, int log_length) { int64_t callback_index = redisCallback != nullptr ? RedisCallbackManager::instance().add(redisCallback) : -1; if (length > 0) { if (log_length >= 0) { std::string redis_command = command + " %d %d %b %b %d"; int status = redisAsyncCommand( async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback), reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix, pubsub_channel, id.data(), id.size(), data, length, log_length); if (status == REDIS_ERR) { return Status::RedisError(std::string(async_context_->errstr)); } } else { std::string redis_command = command + " %d %d %b %b"; int status = redisAsyncCommand( async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback), reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix, pubsub_channel, id.data(), id.size(), data, length); if (status == REDIS_ERR) { return Status::RedisError(std::string(async_context_->errstr)); } } } else { RAY_CHECK(log_length == -1); std::string redis_command = command + " %d %d %b"; int status = redisAsyncCommand( async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback), reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix, pubsub_channel, id.data(), id.size()); if (status == REDIS_ERR) { return Status::RedisError(std::string(async_context_->errstr)); } } return Status::OK(); } Status RedisContext::RunArgvAsync(const std::vector<std::string> &args) { // Build the arguments. std::vector<const char *> argv; std::vector<size_t> argc; for (size_t i = 0; i < args.size(); ++i) { argv.push_back(args[i].data()); argc.push_back(args[i].size()); } // Run the Redis command. int status; status = redisAsyncCommandArgv(async_context_, nullptr, nullptr, args.size(), argv.data(), argc.data()); if (status == REDIS_ERR) { return Status::RedisError(std::string(async_context_->errstr)); } return Status::OK(); } Status RedisContext::SubscribeAsync(const ClientID &client_id, const TablePubsub pubsub_channel, const RedisCallback &redisCallback, int64_t *out_callback_index) { RAY_CHECK(pubsub_channel != TablePubsub::NO_PUBLISH) << "Client requested subscribe on a table that does not support pubsub"; int64_t callback_index = RedisCallbackManager::instance().add(redisCallback); RAY_CHECK(out_callback_index != nullptr); *out_callback_index = callback_index; int status = 0; if (client_id.is_nil()) { // Subscribe to all messages. std::string redis_command = "SUBSCRIBE %d"; status = redisAsyncCommand( subscribe_context_, reinterpret_cast<redisCallbackFn *>(&SubscribeRedisCallback), reinterpret_cast<void *>(callback_index), redis_command.c_str(), pubsub_channel); } else { // Subscribe only to messages sent to this client. std::string redis_command = "SUBSCRIBE %d:%b"; status = redisAsyncCommand( subscribe_context_, reinterpret_cast<redisCallbackFn *>(&SubscribeRedisCallback), reinterpret_cast<void *>(callback_index), redis_command.c_str(), pubsub_channel, client_id.data(), client_id.size()); } if (status == REDIS_ERR) { return Status::RedisError(std::string(subscribe_context_->errstr)); } return Status::OK(); } } // namespace gcs } // namespace ray <commit_msg>Retry connections to redis for async and subscribe contexts (#3105)<commit_after>#include "ray/gcs/redis_context.h" #include <unistd.h> #include <sstream> extern "C" { #include "hiredis/adapters/ae.h" #include "hiredis/async.h" #include "hiredis/hiredis.h" } // TODO(pcm): Integrate into the C++ tree. #include "state/ray_config.h" namespace { /// A helper function to call the callback and delete it from the callback /// manager if necessary. void ProcessCallback(int64_t callback_index, const std::string &data) { if (callback_index >= 0) { bool delete_callback = ray::gcs::RedisCallbackManager::instance().get(callback_index)(data); // Delete the callback if necessary. if (delete_callback) { ray::gcs::RedisCallbackManager::instance().remove(callback_index); } } } } // namespace namespace ray { namespace gcs { // This is a global redis callback which will be registered for every // asynchronous redis call. It dispatches the appropriate callback // that was registered with the RedisCallbackManager. void GlobalRedisCallback(void *c, void *r, void *privdata) { if (r == nullptr) { return; } int64_t callback_index = reinterpret_cast<int64_t>(privdata); redisReply *reply = reinterpret_cast<redisReply *>(r); std::string data = ""; // Parse the response. switch (reply->type) { case (REDIS_REPLY_NIL): { // Do not add any data for a nil response. } break; case (REDIS_REPLY_STRING): { data = std::string(reply->str, reply->len); } break; case (REDIS_REPLY_STATUS): { } break; case (REDIS_REPLY_ERROR): { RAY_LOG(ERROR) << "Redis error " << reply->str; } break; case (REDIS_REPLY_INTEGER): { data = std::to_string(reply->integer); break; } default: RAY_LOG(FATAL) << "Fatal redis error of type " << reply->type << " and with string " << reply->str; } ProcessCallback(callback_index, data); } void SubscribeRedisCallback(void *c, void *r, void *privdata) { if (r == nullptr) { return; } int64_t callback_index = reinterpret_cast<int64_t>(privdata); redisReply *reply = reinterpret_cast<redisReply *>(r); std::string data = ""; // Parse the response. switch (reply->type) { case (REDIS_REPLY_ARRAY): { // Parse the published message. redisReply *message_type = reply->element[0]; if (strcmp(message_type->str, "subscribe") == 0) { // If the message is for the initial subscription call, return the empty // string as a response to signify that subscription was successful. } else if (strcmp(message_type->str, "message") == 0) { // If the message is from a PUBLISH, make sure the data is nonempty. redisReply *message = reply->element[reply->elements - 1]; auto notification = std::string(message->str, message->len); RAY_CHECK(!notification.empty()) << "Empty message received on subscribe channel"; data = notification; } else { RAY_LOG(FATAL) << "Fatal redis error during subscribe" << message_type->str; } } break; case (REDIS_REPLY_ERROR): { RAY_LOG(ERROR) << "Redis error " << reply->str; } break; default: RAY_LOG(FATAL) << "Fatal redis error of type " << reply->type << " and with string " << reply->str; } ProcessCallback(callback_index, data); } int64_t RedisCallbackManager::add(const RedisCallback &function) { callbacks_.emplace(num_callbacks_, function); return num_callbacks_++; } RedisCallback &RedisCallbackManager::get(int64_t callback_index) { RAY_CHECK(callbacks_.find(callback_index) != callbacks_.end()); return callbacks_[callback_index]; } void RedisCallbackManager::remove(int64_t callback_index) { callbacks_.erase(callback_index); } #define REDIS_CHECK_ERROR(CONTEXT, REPLY) \ if (REPLY == nullptr || REPLY->type == REDIS_REPLY_ERROR) { \ return Status::RedisError(CONTEXT->errstr); \ } RedisContext::~RedisContext() { if (context_) { redisFree(context_); } if (async_context_) { redisAsyncFree(async_context_); } if (subscribe_context_) { redisAsyncFree(subscribe_context_); } } Status AuthenticateRedis(redisContext *context, const std::string &password) { if (password == "") { return Status::OK(); } redisReply *reply = reinterpret_cast<redisReply *>(redisCommand(context, "AUTH %s", password.c_str())); REDIS_CHECK_ERROR(context, reply); freeReplyObject(reply); return Status::OK(); } Status AuthenticateRedis(redisAsyncContext *context, const std::string &password) { if (password == "") { return Status::OK(); } int status = redisAsyncCommand(context, NULL, NULL, "AUTH %s", password.c_str()); if (status == REDIS_ERR) { return Status::RedisError(std::string(context->errstr)); } return Status::OK(); } template <typename RedisContext, typename RedisConnectFunction> Status ConnectWithRetries(const std::string &address, int port, const RedisConnectFunction &connect_function, RedisContext **context) { int connection_attempts = 0; *context = connect_function(address.c_str(), port); while (*context == nullptr || (*context)->err) { if (connection_attempts >= RayConfig::instance().redis_db_connect_retries()) { if (*context == nullptr) { RAY_LOG(FATAL) << "Could not allocate redis context."; } if ((*context)->err) { RAY_LOG(FATAL) << "Could not establish connection to redis " << address << ":" << port << " (context.err = " << (*context)->err << ")"; } break; } RAY_LOG(WARNING) << "Failed to connect to Redis, retrying."; // Sleep for a little. usleep(RayConfig::instance().redis_db_connect_wait_milliseconds() * 1000); *context = connect_function(address.c_str(), port); connection_attempts += 1; } return Status::OK(); } Status RedisContext::Connect(const std::string &address, int port, bool sharding, const std::string &password = "") { RAY_CHECK_OK(ConnectWithRetries(address, port, redisConnect, &context_)); RAY_CHECK_OK(AuthenticateRedis(context_, password)); redisReply *reply = reinterpret_cast<redisReply *>( redisCommand(context_, "CONFIG SET notify-keyspace-events Kl")); REDIS_CHECK_ERROR(context_, reply); freeReplyObject(reply); // Connect to async context RAY_CHECK_OK(ConnectWithRetries(address, port, redisAsyncConnect, &async_context_)); RAY_CHECK_OK(AuthenticateRedis(async_context_, password)); // Connect to subscribe context RAY_CHECK_OK(ConnectWithRetries(address, port, redisAsyncConnect, &subscribe_context_)); RAY_CHECK_OK(AuthenticateRedis(subscribe_context_, password)); return Status::OK(); } Status RedisContext::AttachToEventLoop(aeEventLoop *loop) { if (redisAeAttach(loop, async_context_) != REDIS_OK || redisAeAttach(loop, subscribe_context_) != REDIS_OK) { return Status::RedisError("could not attach redis event loop"); } else { return Status::OK(); } } Status RedisContext::RunAsync(const std::string &command, const UniqueID &id, const uint8_t *data, int64_t length, const TablePrefix prefix, const TablePubsub pubsub_channel, RedisCallback redisCallback, int log_length) { int64_t callback_index = redisCallback != nullptr ? RedisCallbackManager::instance().add(redisCallback) : -1; if (length > 0) { if (log_length >= 0) { std::string redis_command = command + " %d %d %b %b %d"; int status = redisAsyncCommand( async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback), reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix, pubsub_channel, id.data(), id.size(), data, length, log_length); if (status == REDIS_ERR) { return Status::RedisError(std::string(async_context_->errstr)); } } else { std::string redis_command = command + " %d %d %b %b"; int status = redisAsyncCommand( async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback), reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix, pubsub_channel, id.data(), id.size(), data, length); if (status == REDIS_ERR) { return Status::RedisError(std::string(async_context_->errstr)); } } } else { RAY_CHECK(log_length == -1); std::string redis_command = command + " %d %d %b"; int status = redisAsyncCommand( async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback), reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix, pubsub_channel, id.data(), id.size()); if (status == REDIS_ERR) { return Status::RedisError(std::string(async_context_->errstr)); } } return Status::OK(); } Status RedisContext::RunArgvAsync(const std::vector<std::string> &args) { // Build the arguments. std::vector<const char *> argv; std::vector<size_t> argc; for (size_t i = 0; i < args.size(); ++i) { argv.push_back(args[i].data()); argc.push_back(args[i].size()); } // Run the Redis command. int status; status = redisAsyncCommandArgv(async_context_, nullptr, nullptr, args.size(), argv.data(), argc.data()); if (status == REDIS_ERR) { return Status::RedisError(std::string(async_context_->errstr)); } return Status::OK(); } Status RedisContext::SubscribeAsync(const ClientID &client_id, const TablePubsub pubsub_channel, const RedisCallback &redisCallback, int64_t *out_callback_index) { RAY_CHECK(pubsub_channel != TablePubsub::NO_PUBLISH) << "Client requested subscribe on a table that does not support pubsub"; int64_t callback_index = RedisCallbackManager::instance().add(redisCallback); RAY_CHECK(out_callback_index != nullptr); *out_callback_index = callback_index; int status = 0; if (client_id.is_nil()) { // Subscribe to all messages. std::string redis_command = "SUBSCRIBE %d"; status = redisAsyncCommand( subscribe_context_, reinterpret_cast<redisCallbackFn *>(&SubscribeRedisCallback), reinterpret_cast<void *>(callback_index), redis_command.c_str(), pubsub_channel); } else { // Subscribe only to messages sent to this client. std::string redis_command = "SUBSCRIBE %d:%b"; status = redisAsyncCommand( subscribe_context_, reinterpret_cast<redisCallbackFn *>(&SubscribeRedisCallback), reinterpret_cast<void *>(callback_index), redis_command.c_str(), pubsub_channel, client_id.data(), client_id.size()); } if (status == REDIS_ERR) { return Status::RedisError(std::string(subscribe_context_->errstr)); } return Status::OK(); } } // namespace gcs } // namespace ray <|endoftext|>
<commit_before>/* * Copyright (C) 2004 Justin Karneges * Copyright (C) 2004 Brad Hards <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "qcaprovider.h" #include <qstringlist.h> #include <openssl/sha.h> #include <openssl/md2.h> #include <openssl/md4.h> #include <openssl/md5.h> #include <openssl/ripemd.h> #include <openssl/hmac.h> class MD2Context : public QCA::HashContext { public: MD2_CTX c; MD2Context(QCA::Provider *p) : HashContext(p, "md2") { clear(); } Context *clone() const { return new MD2Context(*this); } void clear() { MD2_Init(&c); } void update(const QSecureArray &a) { MD2_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray a(MD2_DIGEST_LENGTH); MD2_Final((unsigned char *)a.data(), &c); return a; } }; class MD4Context : public QCA::HashContext { public: MD4_CTX c; MD4Context(QCA::Provider *p) : HashContext(p, "md4") { clear(); } Context *clone() const { return new MD4Context(*this); } void clear() { MD4_Init(&c); } void update(const QSecureArray &a) { MD4_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray a(MD4_DIGEST_LENGTH); MD4_Final((unsigned char *)a.data(), &c); return a; } }; class MD5Context : public QCA::HashContext { public: MD5_CTX c; MD5Context(QCA::Provider *p) : HashContext(p, "md5") { clear(); } Context *clone() const { return new MD5Context(*this); } void clear() { MD5_Init(&c); } void update(const QSecureArray &a) { MD5_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray a(MD5_DIGEST_LENGTH); MD5_Final((unsigned char *)a.data(), &c); return a; } }; class SHA0Context : public QCA::HashContext { public: SHA_CTX c; SHA0Context(QCA::Provider *p) : HashContext(p, "sha0") { clear(); } Context *clone() const { return new SHA0Context(*this); } void clear() { SHA_Init(&c); } void update(const QSecureArray &a) { SHA_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray a(SHA_DIGEST_LENGTH); SHA_Final((unsigned char *)a.data(), &c); return a; } }; class SHA1Context : public QCA::HashContext { public: SHA_CTX c; SHA1Context(QCA::Provider *p) : HashContext(p, "sha1") { clear(); } Context *clone() const { return new SHA1Context(*this); } void clear() { SHA1_Init(&c); } void update(const QSecureArray &a) { SHA1_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray a(SHA_DIGEST_LENGTH); SHA1_Final((unsigned char *)a.data(), &c); return a; } }; class RIPEMD160Context : public QCA::HashContext { public: RIPEMD160_CTX c; RIPEMD160Context(QCA::Provider *p) : HashContext(p, "ripemd160") { clear(); } Context *clone() const { return new RIPEMD160Context(*this); } void clear() { RIPEMD160_Init(&c); } void update(const QSecureArray &a) { RIPEMD160_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray result(RIPEMD160_DIGEST_LENGTH); RIPEMD160_Final((unsigned char *)result.data(), &c); return result; } }; class HMACMD5Context : public QCA::MACContext { public: HMAC_CTX c; HMACMD5Context(QCA::Provider *p) : MACContext( p, "hmac(md5)" ) { HMAC_CTX_init( &c ); } Context *clone() const { return new HMACMD5Context(*this); } void setup(const QCA::SymmetricKey &key) { HMAC_Init_ex( &c, key.data(), key.size(), EVP_md5(), 0 ); } QCA::KeyLength keyLength() const { } void update(const QSecureArray &a) { HMAC_Update( &c, (unsigned char *)a.data(), a.size() ); } void final( QSecureArray *out) { unsigned int outSize; out->resize( MD5_DIGEST_LENGTH ); HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) ); HMAC_CTX_cleanup(&c); } }; class HMACSHA1Context : public QCA::MACContext { public: HMAC_CTX c; HMACSHA1Context(QCA::Provider *p) : MACContext( p, "hmac(sha1)" ) { HMAC_CTX_init( &c ); } Context *clone() const { return new HMACSHA1Context(*this); } void setup(const QCA::SymmetricKey &key) { HMAC_Init_ex( &c, key.data(), key.size(), EVP_sha1(), 0 ); } QCA::KeyLength keyLength() const { } void update(const QSecureArray &a) { HMAC_Update( &c, (unsigned char *)a.data(), a.size() ); } void final( QSecureArray *out) { unsigned int outSize; out->resize( SHA_DIGEST_LENGTH ); HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) ); HMAC_CTX_cleanup(&c); } }; class HMACRIPEMD160Context : public QCA::MACContext { public: HMAC_CTX c; HMACRIPEMD160Context(QCA::Provider *p) : MACContext( p, "hmac(ripemd160)" ) { HMAC_CTX_init( &c ); } Context *clone() const { return new HMACRIPEMD160Context(*this); } void setup(const QCA::SymmetricKey &key) { HMAC_Init_ex( &c, key.data(), key.size(), EVP_ripemd160(), 0 ); } QCA::KeyLength keyLength() const { } void update(const QSecureArray &a) { HMAC_Update( &c, (unsigned char *)a.data(), a.size() ); } void final( QSecureArray *out) { unsigned int outSize; out->resize( RIPEMD160_DIGEST_LENGTH ); HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) ); HMAC_CTX_cleanup(&c); } }; class opensslProvider : public QCA::Provider { public: void init() { } QString name() const { return "qca-openssl"; } QStringList features() const { QStringList list; list += "sha0"; list += "sha1"; list += "ripemd160"; list += "md2"; list += "md4"; list += "md5"; list += "hmac(md5)"; list += "hmac(sha1)"; list += "hmac(ripemd160)"; return list; } Context *createContext(const QString &type) { if ( type == "sha0" ) return new SHA0Context( this ); else if ( type == "sha1" ) return new SHA1Context( this ); else if ( type == "ripemd160" ) return new RIPEMD160Context( this ); else if ( type == "md2" ) return new MD2Context( this ); else if ( type == "md4" ) return new MD4Context( this ); else if ( type == "md5" ) return new MD5Context( this ); else if ( type == "hmac(md5)" ) return new HMACMD5Context( this ); else if ( type == "hmac(sha1)" ) return new HMACSHA1Context( this ); else if ( type == "hmac(ripemd160)" ) return new HMACRIPEMD160Context( this ); else return 0; } }; QCA_EXPORT_PLUGIN(opensslProvider); <commit_msg>KeyLength fixes.<commit_after>/* * Copyright (C) 2004 Justin Karneges * Copyright (C) 2004 Brad Hards <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "qcaprovider.h" #include <qstringlist.h> #include <openssl/sha.h> #include <openssl/md2.h> #include <openssl/md4.h> #include <openssl/md5.h> #include <openssl/ripemd.h> #include <openssl/hmac.h> class MD2Context : public QCA::HashContext { public: MD2_CTX c; MD2Context(QCA::Provider *p) : HashContext(p, "md2") { clear(); } Context *clone() const { return new MD2Context(*this); } void clear() { MD2_Init(&c); } void update(const QSecureArray &a) { MD2_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray a(MD2_DIGEST_LENGTH); MD2_Final((unsigned char *)a.data(), &c); return a; } }; class MD4Context : public QCA::HashContext { public: MD4_CTX c; MD4Context(QCA::Provider *p) : HashContext(p, "md4") { clear(); } Context *clone() const { return new MD4Context(*this); } void clear() { MD4_Init(&c); } void update(const QSecureArray &a) { MD4_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray a(MD4_DIGEST_LENGTH); MD4_Final((unsigned char *)a.data(), &c); return a; } }; class MD5Context : public QCA::HashContext { public: MD5_CTX c; MD5Context(QCA::Provider *p) : HashContext(p, "md5") { clear(); } Context *clone() const { return new MD5Context(*this); } void clear() { MD5_Init(&c); } void update(const QSecureArray &a) { MD5_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray a(MD5_DIGEST_LENGTH); MD5_Final((unsigned char *)a.data(), &c); return a; } }; class SHA0Context : public QCA::HashContext { public: SHA_CTX c; SHA0Context(QCA::Provider *p) : HashContext(p, "sha0") { clear(); } Context *clone() const { return new SHA0Context(*this); } void clear() { SHA_Init(&c); } void update(const QSecureArray &a) { SHA_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray a(SHA_DIGEST_LENGTH); SHA_Final((unsigned char *)a.data(), &c); return a; } }; class SHA1Context : public QCA::HashContext { public: SHA_CTX c; SHA1Context(QCA::Provider *p) : HashContext(p, "sha1") { clear(); } Context *clone() const { return new SHA1Context(*this); } void clear() { SHA1_Init(&c); } void update(const QSecureArray &a) { SHA1_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray a(SHA_DIGEST_LENGTH); SHA1_Final((unsigned char *)a.data(), &c); return a; } }; class RIPEMD160Context : public QCA::HashContext { public: RIPEMD160_CTX c; RIPEMD160Context(QCA::Provider *p) : HashContext(p, "ripemd160") { clear(); } Context *clone() const { return new RIPEMD160Context(*this); } void clear() { RIPEMD160_Init(&c); } void update(const QSecureArray &a) { RIPEMD160_Update(&c, (unsigned char *)a.data(), a.size()); } QSecureArray final() { QSecureArray result(RIPEMD160_DIGEST_LENGTH); RIPEMD160_Final((unsigned char *)result.data(), &c); return result; } }; class HMACMD5Context : public QCA::MACContext { public: HMAC_CTX c; HMACMD5Context(QCA::Provider *p) : MACContext( p, "hmac(md5)" ) { HMAC_CTX_init( &c ); } Context *clone() const { return new HMACMD5Context(*this); } void setup(const QCA::SymmetricKey &key) { HMAC_Init_ex( &c, key.data(), key.size(), EVP_md5(), 0 ); } QCA::KeyLength keyLength() const { return anyKeyLength(); } void update(const QSecureArray &a) { HMAC_Update( &c, (unsigned char *)a.data(), a.size() ); } void final( QSecureArray *out) { unsigned int outSize; out->resize( MD5_DIGEST_LENGTH ); HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) ); HMAC_CTX_cleanup(&c); } }; class HMACSHA1Context : public QCA::MACContext { public: HMAC_CTX c; HMACSHA1Context(QCA::Provider *p) : MACContext( p, "hmac(sha1)" ) { HMAC_CTX_init( &c ); } Context *clone() const { return new HMACSHA1Context(*this); } void setup(const QCA::SymmetricKey &key) { HMAC_Init_ex( &c, key.data(), key.size(), EVP_sha1(), 0 ); } QCA::KeyLength keyLength() const { return anyKeyLength(); } void update(const QSecureArray &a) { HMAC_Update( &c, (unsigned char *)a.data(), a.size() ); } void final( QSecureArray *out) { unsigned int outSize; out->resize( SHA_DIGEST_LENGTH ); HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) ); HMAC_CTX_cleanup(&c); } }; class HMACRIPEMD160Context : public QCA::MACContext { public: HMAC_CTX c; HMACRIPEMD160Context(QCA::Provider *p) : MACContext( p, "hmac(ripemd160)" ) { HMAC_CTX_init( &c ); } Context *clone() const { return new HMACRIPEMD160Context(*this); } void setup(const QCA::SymmetricKey &key) { HMAC_Init_ex( &c, key.data(), key.size(), EVP_ripemd160(), 0 ); } QCA::KeyLength keyLength() const { return anyKeyLength(); } void update(const QSecureArray &a) { HMAC_Update( &c, (unsigned char *)a.data(), a.size() ); } void final( QSecureArray *out) { unsigned int outSize; out->resize( RIPEMD160_DIGEST_LENGTH ); HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) ); HMAC_CTX_cleanup(&c); } }; class opensslProvider : public QCA::Provider { public: void init() { } QString name() const { return "qca-openssl"; } QStringList features() const { QStringList list; list += "sha0"; list += "sha1"; list += "ripemd160"; list += "md2"; list += "md4"; list += "md5"; list += "hmac(md5)"; list += "hmac(sha1)"; list += "hmac(ripemd160)"; return list; } Context *createContext(const QString &type) { if ( type == "sha0" ) return new SHA0Context( this ); else if ( type == "sha1" ) return new SHA1Context( this ); else if ( type == "ripemd160" ) return new RIPEMD160Context( this ); else if ( type == "md2" ) return new MD2Context( this ); else if ( type == "md4" ) return new MD4Context( this ); else if ( type == "md5" ) return new MD5Context( this ); else if ( type == "hmac(md5)" ) return new HMACMD5Context( this ); else if ( type == "hmac(sha1)" ) return new HMACSHA1Context( this ); else if ( type == "hmac(ripemd160)" ) return new HMACRIPEMD160Context( this ); else return 0; } }; QCA_EXPORT_PLUGIN(opensslProvider); <|endoftext|>
<commit_before>/* * 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 Library 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. * * UsbWidget.cpp * Read and Write to a USB Widget. * Copyright (C) 2010 Simon Newton */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/stat.h> #include <sys/types.h> #include <termios.h> #include <unistd.h> #include <string> #include "ola/Logging.h" #include "plugins/usbpro/UsbWidget.h" namespace ola { namespace plugin { namespace usbpro { UsbWidget::UsbWidget(ola::network::ConnectedSocket *socket) : m_callback(NULL), m_socket(socket), m_state(PRE_SOM), m_bytes_received(0) { m_socket->SetOnData(NewCallback(this, &UsbWidget::SocketReady)); } UsbWidget::~UsbWidget() { if (m_callback) delete m_callback; // don't delete because ownership is transferred to the ss so that device // removal works correctly. If you delete the socket the OnClose closure will // be deleted, which breaks if it's already running. m_socket->Close(); m_socket = NULL; } /** * Set the closure to be called when we receive a message from the widget * @param callback the closure to run, ownership is transferred. */ void UsbWidget::SetMessageHandler( ola::Callback3<void, uint8_t, const uint8_t*, unsigned int> *callback) { if (m_callback) delete m_callback; m_callback = callback; } /* * Set the onRemove handler */ void UsbWidget::SetOnRemove(ola::SingleUseCallback0<void> *on_close) { m_socket->SetOnClose(on_close); } /* * Read data from the widget */ void UsbWidget::SocketReady() { while (m_socket->DataRemaining() > 0) { ReceiveMessage(); } } /* * Send the msg * @return true if successful, false otherwise */ bool UsbWidget::SendMessage(uint8_t label, const uint8_t *data, unsigned int length) const { if (length && !data) return false; message_header header; header.som = SOM; header.label = label; header.len = length & 0xFF; header.len_hi = (length & 0xFF00) >> 8; // should really use writev here instead ssize_t bytes_sent = m_socket->Send(reinterpret_cast<uint8_t*>(&header), sizeof(header)); if (bytes_sent != sizeof(header)) // we've probably screwed framing at this point return false; if (length) { unsigned int bytes_sent = m_socket->Send(data, length); if (bytes_sent != length) // we've probably screwed framing at this point return false; } uint8_t eom = EOM; bytes_sent = m_socket->Send(&eom, sizeof(EOM)); if (bytes_sent != sizeof(EOM)) return false; return true; } /** * Open a path and apply the settings required for talking to widgets. */ ola::network::ConnectedSocket *UsbWidget::OpenDevice( const string &path) { struct termios newtio; int fd = open(path.data(), O_RDWR | O_NONBLOCK | O_NOCTTY); if (fd == -1) { OLA_WARN << "Failed to open " << path << " " << strerror(errno); return NULL; } bzero(&newtio, sizeof(newtio)); // clear struct for new port settings cfsetispeed(&newtio, B115200); cfsetospeed(&newtio, B115200); tcsetattr(fd, TCSANOW, &newtio); return new ola::network::DeviceSocket(fd); } /* * Read the data and handle the messages. */ void UsbWidget::ReceiveMessage() { unsigned int cnt, packet_length; switch (m_state) { case PRE_SOM: do { m_socket->Receive(&m_header.som, 1, cnt); if (cnt != 1) return; } while (m_header.som != SOM); m_state = RECV_LABEL; case RECV_LABEL: m_socket->Receive(&m_header.label, 1, cnt); if (cnt != 1) return; m_state = RECV_SIZE_LO; case RECV_SIZE_LO: m_socket->Receive(&m_header.len, 1, cnt); if (cnt != 1) return; m_state = RECV_SIZE_HI; case RECV_SIZE_HI: m_socket->Receive(&m_header.len_hi, 1, cnt); if (cnt != 1) return; packet_length = (m_header.len_hi << 8) + m_header.len; if (packet_length == 0) { m_state = RECV_EOM; return; } else if (packet_length > MAX_DATA_SIZE) { m_state = PRE_SOM; return; } m_bytes_received = 0; m_state = RECV_BODY; case RECV_BODY: packet_length = (m_header.len_hi << 8) + m_header.len; m_socket->Receive( reinterpret_cast<uint8_t*>(&m_recv_buffer) + m_bytes_received, packet_length - m_bytes_received, cnt); if (!cnt) return; m_bytes_received += cnt; if (m_bytes_received != packet_length) return; m_state = RECV_EOM; case RECV_EOM: // check this is a valid frame with an end byte uint8_t eom; m_socket->Receive(&eom, 1, cnt); if (cnt != 1) return; packet_length = (m_header.len_hi << 8) + m_header.len; if (eom == EOM && m_callback) m_callback->Run(m_header.label, packet_length ? m_recv_buffer : NULL, packet_length); m_state = PRE_SOM; } return; } } // usbpro } // plugin } // ola <commit_msg> * fix a variable name<commit_after>/* * 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 Library 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. * * UsbWidget.cpp * Read and Write to a USB Widget. * Copyright (C) 2010 Simon Newton */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/stat.h> #include <sys/types.h> #include <termios.h> #include <unistd.h> #include <string> #include "ola/Logging.h" #include "plugins/usbpro/UsbWidget.h" namespace ola { namespace plugin { namespace usbpro { UsbWidget::UsbWidget(ola::network::ConnectedSocket *socket) : m_callback(NULL), m_socket(socket), m_state(PRE_SOM), m_bytes_received(0) { m_socket->SetOnData(NewCallback(this, &UsbWidget::SocketReady)); } UsbWidget::~UsbWidget() { if (m_callback) delete m_callback; // don't delete because ownership is transferred to the ss so that device // removal works correctly. If you delete the socket the OnClose closure will // be deleted, which breaks if it's already running. m_socket->Close(); m_socket = NULL; } /** * Set the closure to be called when we receive a message from the widget * @param callback the closure to run, ownership is transferred. */ void UsbWidget::SetMessageHandler( ola::Callback3<void, uint8_t, const uint8_t*, unsigned int> *callback) { if (m_callback) delete m_callback; m_callback = callback; } /* * Set the onRemove handler */ void UsbWidget::SetOnRemove(ola::SingleUseCallback0<void> *on_close) { m_socket->SetOnClose(on_close); } /* * Read data from the widget */ void UsbWidget::SocketReady() { while (m_socket->DataRemaining() > 0) { ReceiveMessage(); } } /* * Send the msg * @return true if successful, false otherwise */ bool UsbWidget::SendMessage(uint8_t label, const uint8_t *data, unsigned int length) const { if (length && !data) return false; message_header header; header.som = SOM; header.label = label; header.len = length & 0xFF; header.len_hi = (length & 0xFF00) >> 8; // should really use writev here instead ssize_t bytes_sent = m_socket->Send(reinterpret_cast<uint8_t*>(&header), sizeof(header)); if (bytes_sent != sizeof(header)) // we've probably screwed framing at this point return false; if (length) { unsigned int bytes_sent = m_socket->Send(data, length); if (bytes_sent != length) // we've probably screwed framing at this point return false; } uint8_t eom = EOM; bytes_sent = m_socket->Send(&eom, sizeof(EOM)); if (bytes_sent != sizeof(EOM)) return false; return true; } /** * Open a path and apply the settings required for talking to widgets. */ ola::network::ConnectedSocket *UsbWidget::OpenDevice( const string &path) { struct termios newtio; int fd = open(path.data(), O_RDWR | O_NONBLOCK | O_NOCTTY); if (fd == -1) { OLA_WARN << "Failed to open " << path << " " << strerror(errno); return NULL; } bzero(&newtio, sizeof(newtio)); // clear struct for new port settings cfsetispeed(&newtio, B115200); cfsetospeed(&newtio, B115200); tcsetattr(fd, TCSANOW, &newtio); return new ola::network::DeviceSocket(fd); } /* * Read the data and handle the messages. */ void UsbWidget::ReceiveMessage() { unsigned int count, packet_length; switch (m_state) { case PRE_SOM: do { m_socket->Receive(&m_header.som, 1, count); if (count != 1) return; } while (m_header.som != SOM); m_state = RECV_LABEL; case RECV_LABEL: m_socket->Receive(&m_header.label, 1, count); if (count != 1) return; m_state = RECV_SIZE_LO; case RECV_SIZE_LO: m_socket->Receive(&m_header.len, 1, count); if (count != 1) return; m_state = RECV_SIZE_HI; case RECV_SIZE_HI: m_socket->Receive(&m_header.len_hi, 1, count); if (count != 1) return; packet_length = (m_header.len_hi << 8) + m_header.len; if (packet_length == 0) { m_state = RECV_EOM; return; } else if (packet_length > MAX_DATA_SIZE) { m_state = PRE_SOM; return; } m_bytes_received = 0; m_state = RECV_BODY; case RECV_BODY: packet_length = (m_header.len_hi << 8) + m_header.len; m_socket->Receive( reinterpret_cast<uint8_t*>(&m_recv_buffer) + m_bytes_received, packet_length - m_bytes_received, count); if (!count) return; m_bytes_received += count; if (m_bytes_received != packet_length) return; m_state = RECV_EOM; case RECV_EOM: // check this is a valid frame with an end byte uint8_t eom; m_socket->Receive(&eom, 1, count); if (count != 1) return; packet_length = (m_header.len_hi << 8) + m_header.len; if (eom == EOM && m_callback) m_callback->Run(m_header.label, packet_length ? m_recv_buffer : NULL, packet_length); m_state = PRE_SOM; } return; } } // usbpro } // plugin } // ola <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <[email protected]> * Copyright (C) 2018 David Shah <[email protected]> * * 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 "cells.h" #include "design_utils.h" #include "log.h" NEXTPNR_NAMESPACE_BEGIN void add_port(const Context *ctx, CellInfo *cell, std::string name, PortType dir) { IdString id = ctx->id(name); cell->ports[id] = PortInfo{id, nullptr, dir}; } std::unique_ptr<CellInfo> create_ice_cell(Context *ctx, IdString type, std::string name) { static int auto_idx = 0; std::unique_ptr<CellInfo> new_cell = std::unique_ptr<CellInfo>(new CellInfo()); if (name.empty()) { new_cell->name = ctx->id("$nextpnr_" + type.str(ctx) + "_" + std::to_string(auto_idx++)); } else { new_cell->name = ctx->id(name); } new_cell->type = type; if (type == ctx->id("ICESTORM_LC")) { new_cell->params[ctx->id("LUT_INIT")] = "0"; new_cell->params[ctx->id("NEG_CLK")] = "0"; new_cell->params[ctx->id("CARRY_ENABLE")] = "0"; new_cell->params[ctx->id("DFF_ENABLE")] = "0"; new_cell->params[ctx->id("SET_NORESET")] = "0"; new_cell->params[ctx->id("ASYNC_SR")] = "0"; new_cell->params[ctx->id("CIN_CONST")] = "0"; new_cell->params[ctx->id("CIN_SET")] = "0"; add_port(ctx, new_cell.get(), "I0", PORT_IN); add_port(ctx, new_cell.get(), "I1", PORT_IN); add_port(ctx, new_cell.get(), "I2", PORT_IN); add_port(ctx, new_cell.get(), "I3", PORT_IN); add_port(ctx, new_cell.get(), "CIN", PORT_IN); add_port(ctx, new_cell.get(), "CLK", PORT_IN); add_port(ctx, new_cell.get(), "CEN", PORT_IN); add_port(ctx, new_cell.get(), "SR", PORT_IN); add_port(ctx, new_cell.get(), "LO", PORT_OUT); add_port(ctx, new_cell.get(), "O", PORT_OUT); add_port(ctx, new_cell.get(), "OUT", PORT_OUT); } else if (type == ctx->id("SB_IO")) { new_cell->params[ctx->id("PIN_TYPE")] = "0"; new_cell->params[ctx->id("PULLUP")] = "0"; new_cell->params[ctx->id("NEG_TRIGGER")] = "0"; new_cell->params[ctx->id("IOSTANDARD")] = "SB_LVCMOS"; add_port(ctx, new_cell.get(), "PACKAGE_PIN", PORT_INOUT); add_port(ctx, new_cell.get(), "LATCH_INPUT_VALUE", PORT_IN); add_port(ctx, new_cell.get(), "CLOCK_ENABLE", PORT_IN); add_port(ctx, new_cell.get(), "INPUT_CLK", PORT_IN); add_port(ctx, new_cell.get(), "OUTPUT_CLK", PORT_IN); add_port(ctx, new_cell.get(), "OUTPUT_ENABLE", PORT_IN); add_port(ctx, new_cell.get(), "D_OUT_0", PORT_IN); add_port(ctx, new_cell.get(), "D_OUT_1", PORT_IN); add_port(ctx, new_cell.get(), "D_IN_0", PORT_OUT); add_port(ctx, new_cell.get(), "D_IN_1", PORT_OUT); } else if (type == ctx->id("ICESTORM_RAM")) { new_cell->params[ctx->id("NEG_CLK_W")] = "0"; new_cell->params[ctx->id("NEG_CLK_R")] = "0"; new_cell->params[ctx->id("WRITE_MODE")] = "0"; new_cell->params[ctx->id("READ_MODE")] = "0"; add_port(ctx, new_cell.get(), "RCLK", PORT_IN); add_port(ctx, new_cell.get(), "RCLKE", PORT_IN); add_port(ctx, new_cell.get(), "RE", PORT_IN); add_port(ctx, new_cell.get(), "WCLK", PORT_IN); add_port(ctx, new_cell.get(), "WCLKE", PORT_IN); add_port(ctx, new_cell.get(), "WE", PORT_IN); for (int i = 0; i < 16; i++) { add_port(ctx, new_cell.get(), "WDATA_" + std::to_string(i), PORT_IN); add_port(ctx, new_cell.get(), "MASK_" + std::to_string(i), PORT_IN); add_port(ctx, new_cell.get(), "RDATA_" + std::to_string(i), PORT_OUT); } for (int i = 0; i < 11; i++) { add_port(ctx, new_cell.get(), "RADDR_" + std::to_string(i), PORT_IN); add_port(ctx, new_cell.get(), "WADDR_" + std::to_string(i), PORT_IN); } } else if (type == ctx->id("ICESTORM_LFOSC")) { add_port(ctx, new_cell.get(), "CLKLFEN", PORT_IN); add_port(ctx, new_cell.get(), "CLKLFPU", PORT_IN); add_port(ctx, new_cell.get(), "CLKLF", PORT_OUT); add_port(ctx, new_cell.get(), "CLKLF_FABRIC", PORT_OUT); } else if (type == ctx->id("ICESTORM_HFOSC")) { new_cell->params[ctx->id("CLKHF_DIV")] = "0"; new_cell->params[ctx->id("TRIM_EN")] = "0"; add_port(ctx, new_cell.get(), "CLKHFEN", PORT_IN); add_port(ctx, new_cell.get(), "CLKHFPU", PORT_IN); add_port(ctx, new_cell.get(), "CLKHF", PORT_OUT); add_port(ctx, new_cell.get(), "CLKHF_FABRIC", PORT_OUT); for (int i = 0; i < 10; i++) add_port(ctx, new_cell.get(), "TRIM" + std::to_string(i), PORT_IN); } else if (type == ctx->id("SB_GB")) { add_port(ctx, new_cell.get(), "USER_SIGNAL_TO_GLOBAL_BUFFER", PORT_IN); add_port(ctx, new_cell.get(), "GLOBAL_BUFFER_OUTPUT", PORT_OUT); } else { log_error("unable to create iCE40 cell of type %s", type.c_str(ctx)); } return std::move(new_cell); } void lut_to_lc(const Context *ctx, CellInfo *lut, CellInfo *lc, bool no_dff) { lc->params[ctx->id("LUT_INIT")] = lut->params[ctx->id("LUT_INIT")]; replace_port(lut, ctx->id("I0"), lc, ctx->id("I0")); replace_port(lut, ctx->id("I1"), lc, ctx->id("I1")); replace_port(lut, ctx->id("I2"), lc, ctx->id("I2")); replace_port(lut, ctx->id("I3"), lc, ctx->id("I3")); if (no_dff) { replace_port(lut, ctx->id("O"), lc, ctx->id("O")); lc->params[ctx->id("DFF_ENABLE")] = "0"; } } void dff_to_lc(const Context *ctx, CellInfo *dff, CellInfo *lc, bool pass_thru_lut) { lc->params[ctx->id("DFF_ENABLE")] = "1"; std::string config = dff->type.str(ctx).substr(6); auto citer = config.begin(); replace_port(dff, ctx->id("C"), lc, ctx->id("CLK")); if (citer != config.end() && *citer == 'N') { lc->params[ctx->id("NEG_CLK")] = "1"; ++citer; } else { lc->params[ctx->id("NEG_CLK")] = "0"; } if (citer != config.end() && *citer == 'E') { replace_port(dff, ctx->id("E"), lc, ctx->id("CEN")); ++citer; } if (citer != config.end()) { if ((config.end() - citer) >= 2) { char c = *(citer++); assert(c == 'S'); lc->params[ctx->id("ASYNC_SR")] = "0"; } else { lc->params[ctx->id("ASYNC_SR")] = "1"; } if (*citer == 'S') { citer++; replace_port(dff, ctx->id("S"), lc, ctx->id("SR")); lc->params[ctx->id("SET_NORESET")] = "1"; } else { assert(*citer == 'R'); citer++; replace_port(dff, ctx->id("R"), lc, ctx->id("SR")); lc->params[ctx->id("SET_NORESET")] = "0"; } } assert(citer == config.end()); if (pass_thru_lut) { lc->params[ctx->id("LUT_INIT")] = "2"; replace_port(dff, ctx->id("D"), lc, ctx->id("I0")); } replace_port(dff, ctx->id("Q"), lc, ctx->id("O")); } void nxio_to_sb(Context *ctx, CellInfo *nxio, CellInfo *sbio) { if (nxio->type == ctx->id("$nextpnr_ibuf")) { sbio->params[ctx->id("PIN_TYPE")] = "1"; auto pu_attr = nxio->attrs.find(ctx->id("PULLUP")); if (pu_attr != nxio->attrs.end()) sbio->params[ctx->id("PULLUP")] = pu_attr->second; replace_port(nxio, ctx->id("O"), sbio, ctx->id("D_IN_0")); } else if (nxio->type == ctx->id("$nextpnr_obuf")) { sbio->params[ctx->id("PIN_TYPE")] = "25"; replace_port(nxio, ctx->id("I"), sbio, ctx->id("D_OUT_0")); } else if (nxio->type == ctx->id("$nextpnr_iobuf")) { // N.B. tristate will be dealt with below sbio->params[ctx->id("PIN_TYPE")] = "25"; replace_port(nxio, ctx->id("I"), sbio, ctx->id("D_OUT_0")); replace_port(nxio, ctx->id("O"), sbio, ctx->id("D_IN_0")); } else { assert(false); } NetInfo *donet = sbio->ports.at(ctx->id("D_OUT_0")).net; CellInfo *tbuf = net_driven_by( ctx, donet, [](const Context *ctx, const CellInfo *cell) { return cell->type == ctx->id("$_TBUF_"); }, ctx->id("Y")); if (tbuf) { sbio->params[ctx->id("PIN_TYPE")] = "41"; replace_port(tbuf, ctx->id("A"), sbio, ctx->id("D_OUT_0")); replace_port(tbuf, ctx->id("E"), sbio, ctx->id("OUTPUT_ENABLE")); ctx->nets.erase(donet->name); if (!donet->users.empty()) log_error("unsupported tristate IO pattern for IO buffer '%s', " "instantiate SB_IO manually to ensure correct behaviour\n", nxio->name.c_str(ctx)); ctx->cells.erase(tbuf->name); } } bool is_clock_port(const BaseCtx *ctx, const PortRef &port) { if (port.cell == nullptr) return false; if (is_ff(ctx, port.cell)) return port.port == ctx->id("C"); if (port.cell->type == ctx->id("ICESTORM_LC")) return port.port == ctx->id("CLK"); if (is_ram(ctx, port.cell) || port.cell->type == ctx->id("ICESTORM_RAM")) return port.port == ctx->id("RCLK") || port.port == ctx->id("WCLK"); return false; } bool is_reset_port(const BaseCtx *ctx, const PortRef &port) { if (port.cell == nullptr) return false; if (is_ff(ctx, port.cell)) return port.port == ctx->id("R") || port.port == ctx->id("S"); if (port.cell->type == ctx->id("ICESTORM_LC")) return port.port == ctx->id("SR"); return false; } bool is_enable_port(const BaseCtx *ctx, const PortRef &port) { if (port.cell == nullptr) return false; if (is_ff(ctx, port.cell)) return port.port == ctx->id("E"); if (port.cell->type == ctx->id("ICESTORM_LC")) return port.port == ctx->id("CEN"); return false; } NEXTPNR_NAMESPACE_END <commit_msg>clang fix<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <[email protected]> * Copyright (C) 2018 David Shah <[email protected]> * * 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 "cells.h" #include "design_utils.h" #include "log.h" NEXTPNR_NAMESPACE_BEGIN void add_port(const Context *ctx, CellInfo *cell, std::string name, PortType dir) { IdString id = ctx->id(name); cell->ports[id] = PortInfo{id, nullptr, dir}; } std::unique_ptr<CellInfo> create_ice_cell(Context *ctx, IdString type, std::string name) { static int auto_idx = 0; std::unique_ptr<CellInfo> new_cell = std::unique_ptr<CellInfo>(new CellInfo()); if (name.empty()) { new_cell->name = ctx->id("$nextpnr_" + type.str(ctx) + "_" + std::to_string(auto_idx++)); } else { new_cell->name = ctx->id(name); } new_cell->type = type; if (type == ctx->id("ICESTORM_LC")) { new_cell->params[ctx->id("LUT_INIT")] = "0"; new_cell->params[ctx->id("NEG_CLK")] = "0"; new_cell->params[ctx->id("CARRY_ENABLE")] = "0"; new_cell->params[ctx->id("DFF_ENABLE")] = "0"; new_cell->params[ctx->id("SET_NORESET")] = "0"; new_cell->params[ctx->id("ASYNC_SR")] = "0"; new_cell->params[ctx->id("CIN_CONST")] = "0"; new_cell->params[ctx->id("CIN_SET")] = "0"; add_port(ctx, new_cell.get(), "I0", PORT_IN); add_port(ctx, new_cell.get(), "I1", PORT_IN); add_port(ctx, new_cell.get(), "I2", PORT_IN); add_port(ctx, new_cell.get(), "I3", PORT_IN); add_port(ctx, new_cell.get(), "CIN", PORT_IN); add_port(ctx, new_cell.get(), "CLK", PORT_IN); add_port(ctx, new_cell.get(), "CEN", PORT_IN); add_port(ctx, new_cell.get(), "SR", PORT_IN); add_port(ctx, new_cell.get(), "LO", PORT_OUT); add_port(ctx, new_cell.get(), "O", PORT_OUT); add_port(ctx, new_cell.get(), "OUT", PORT_OUT); } else if (type == ctx->id("SB_IO")) { new_cell->params[ctx->id("PIN_TYPE")] = "0"; new_cell->params[ctx->id("PULLUP")] = "0"; new_cell->params[ctx->id("NEG_TRIGGER")] = "0"; new_cell->params[ctx->id("IOSTANDARD")] = "SB_LVCMOS"; add_port(ctx, new_cell.get(), "PACKAGE_PIN", PORT_INOUT); add_port(ctx, new_cell.get(), "LATCH_INPUT_VALUE", PORT_IN); add_port(ctx, new_cell.get(), "CLOCK_ENABLE", PORT_IN); add_port(ctx, new_cell.get(), "INPUT_CLK", PORT_IN); add_port(ctx, new_cell.get(), "OUTPUT_CLK", PORT_IN); add_port(ctx, new_cell.get(), "OUTPUT_ENABLE", PORT_IN); add_port(ctx, new_cell.get(), "D_OUT_0", PORT_IN); add_port(ctx, new_cell.get(), "D_OUT_1", PORT_IN); add_port(ctx, new_cell.get(), "D_IN_0", PORT_OUT); add_port(ctx, new_cell.get(), "D_IN_1", PORT_OUT); } else if (type == ctx->id("ICESTORM_RAM")) { new_cell->params[ctx->id("NEG_CLK_W")] = "0"; new_cell->params[ctx->id("NEG_CLK_R")] = "0"; new_cell->params[ctx->id("WRITE_MODE")] = "0"; new_cell->params[ctx->id("READ_MODE")] = "0"; add_port(ctx, new_cell.get(), "RCLK", PORT_IN); add_port(ctx, new_cell.get(), "RCLKE", PORT_IN); add_port(ctx, new_cell.get(), "RE", PORT_IN); add_port(ctx, new_cell.get(), "WCLK", PORT_IN); add_port(ctx, new_cell.get(), "WCLKE", PORT_IN); add_port(ctx, new_cell.get(), "WE", PORT_IN); for (int i = 0; i < 16; i++) { add_port(ctx, new_cell.get(), "WDATA_" + std::to_string(i), PORT_IN); add_port(ctx, new_cell.get(), "MASK_" + std::to_string(i), PORT_IN); add_port(ctx, new_cell.get(), "RDATA_" + std::to_string(i), PORT_OUT); } for (int i = 0; i < 11; i++) { add_port(ctx, new_cell.get(), "RADDR_" + std::to_string(i), PORT_IN); add_port(ctx, new_cell.get(), "WADDR_" + std::to_string(i), PORT_IN); } } else if (type == ctx->id("ICESTORM_LFOSC")) { add_port(ctx, new_cell.get(), "CLKLFEN", PORT_IN); add_port(ctx, new_cell.get(), "CLKLFPU", PORT_IN); add_port(ctx, new_cell.get(), "CLKLF", PORT_OUT); add_port(ctx, new_cell.get(), "CLKLF_FABRIC", PORT_OUT); } else if (type == ctx->id("ICESTORM_HFOSC")) { new_cell->params[ctx->id("CLKHF_DIV")] = "0"; new_cell->params[ctx->id("TRIM_EN")] = "0"; add_port(ctx, new_cell.get(), "CLKHFEN", PORT_IN); add_port(ctx, new_cell.get(), "CLKHFPU", PORT_IN); add_port(ctx, new_cell.get(), "CLKHF", PORT_OUT); add_port(ctx, new_cell.get(), "CLKHF_FABRIC", PORT_OUT); for (int i = 0; i < 10; i++) add_port(ctx, new_cell.get(), "TRIM" + std::to_string(i), PORT_IN); } else if (type == ctx->id("SB_GB")) { add_port(ctx, new_cell.get(), "USER_SIGNAL_TO_GLOBAL_BUFFER", PORT_IN); add_port(ctx, new_cell.get(), "GLOBAL_BUFFER_OUTPUT", PORT_OUT); } else { log_error("unable to create iCE40 cell of type %s", type.c_str(ctx)); } return new_cell; } void lut_to_lc(const Context *ctx, CellInfo *lut, CellInfo *lc, bool no_dff) { lc->params[ctx->id("LUT_INIT")] = lut->params[ctx->id("LUT_INIT")]; replace_port(lut, ctx->id("I0"), lc, ctx->id("I0")); replace_port(lut, ctx->id("I1"), lc, ctx->id("I1")); replace_port(lut, ctx->id("I2"), lc, ctx->id("I2")); replace_port(lut, ctx->id("I3"), lc, ctx->id("I3")); if (no_dff) { replace_port(lut, ctx->id("O"), lc, ctx->id("O")); lc->params[ctx->id("DFF_ENABLE")] = "0"; } } void dff_to_lc(const Context *ctx, CellInfo *dff, CellInfo *lc, bool pass_thru_lut) { lc->params[ctx->id("DFF_ENABLE")] = "1"; std::string config = dff->type.str(ctx).substr(6); auto citer = config.begin(); replace_port(dff, ctx->id("C"), lc, ctx->id("CLK")); if (citer != config.end() && *citer == 'N') { lc->params[ctx->id("NEG_CLK")] = "1"; ++citer; } else { lc->params[ctx->id("NEG_CLK")] = "0"; } if (citer != config.end() && *citer == 'E') { replace_port(dff, ctx->id("E"), lc, ctx->id("CEN")); ++citer; } if (citer != config.end()) { if ((config.end() - citer) >= 2) { char c = *(citer++); assert(c == 'S'); lc->params[ctx->id("ASYNC_SR")] = "0"; } else { lc->params[ctx->id("ASYNC_SR")] = "1"; } if (*citer == 'S') { citer++; replace_port(dff, ctx->id("S"), lc, ctx->id("SR")); lc->params[ctx->id("SET_NORESET")] = "1"; } else { assert(*citer == 'R'); citer++; replace_port(dff, ctx->id("R"), lc, ctx->id("SR")); lc->params[ctx->id("SET_NORESET")] = "0"; } } assert(citer == config.end()); if (pass_thru_lut) { lc->params[ctx->id("LUT_INIT")] = "2"; replace_port(dff, ctx->id("D"), lc, ctx->id("I0")); } replace_port(dff, ctx->id("Q"), lc, ctx->id("O")); } void nxio_to_sb(Context *ctx, CellInfo *nxio, CellInfo *sbio) { if (nxio->type == ctx->id("$nextpnr_ibuf")) { sbio->params[ctx->id("PIN_TYPE")] = "1"; auto pu_attr = nxio->attrs.find(ctx->id("PULLUP")); if (pu_attr != nxio->attrs.end()) sbio->params[ctx->id("PULLUP")] = pu_attr->second; replace_port(nxio, ctx->id("O"), sbio, ctx->id("D_IN_0")); } else if (nxio->type == ctx->id("$nextpnr_obuf")) { sbio->params[ctx->id("PIN_TYPE")] = "25"; replace_port(nxio, ctx->id("I"), sbio, ctx->id("D_OUT_0")); } else if (nxio->type == ctx->id("$nextpnr_iobuf")) { // N.B. tristate will be dealt with below sbio->params[ctx->id("PIN_TYPE")] = "25"; replace_port(nxio, ctx->id("I"), sbio, ctx->id("D_OUT_0")); replace_port(nxio, ctx->id("O"), sbio, ctx->id("D_IN_0")); } else { assert(false); } NetInfo *donet = sbio->ports.at(ctx->id("D_OUT_0")).net; CellInfo *tbuf = net_driven_by( ctx, donet, [](const Context *ctx, const CellInfo *cell) { return cell->type == ctx->id("$_TBUF_"); }, ctx->id("Y")); if (tbuf) { sbio->params[ctx->id("PIN_TYPE")] = "41"; replace_port(tbuf, ctx->id("A"), sbio, ctx->id("D_OUT_0")); replace_port(tbuf, ctx->id("E"), sbio, ctx->id("OUTPUT_ENABLE")); ctx->nets.erase(donet->name); if (!donet->users.empty()) log_error("unsupported tristate IO pattern for IO buffer '%s', " "instantiate SB_IO manually to ensure correct behaviour\n", nxio->name.c_str(ctx)); ctx->cells.erase(tbuf->name); } } bool is_clock_port(const BaseCtx *ctx, const PortRef &port) { if (port.cell == nullptr) return false; if (is_ff(ctx, port.cell)) return port.port == ctx->id("C"); if (port.cell->type == ctx->id("ICESTORM_LC")) return port.port == ctx->id("CLK"); if (is_ram(ctx, port.cell) || port.cell->type == ctx->id("ICESTORM_RAM")) return port.port == ctx->id("RCLK") || port.port == ctx->id("WCLK"); return false; } bool is_reset_port(const BaseCtx *ctx, const PortRef &port) { if (port.cell == nullptr) return false; if (is_ff(ctx, port.cell)) return port.port == ctx->id("R") || port.port == ctx->id("S"); if (port.cell->type == ctx->id("ICESTORM_LC")) return port.port == ctx->id("SR"); return false; } bool is_enable_port(const BaseCtx *ctx, const PortRef &port) { if (port.cell == nullptr) return false; if (is_ff(ctx, port.cell)) return port.port == ctx->id("E"); if (port.cell->type == ctx->id("ICESTORM_LC")) return port.port == ctx->id("CEN"); return false; } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkContourFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS 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 <math.h> #include "vtkContourFilter.h" #include "vtkScalars.h" #include "vtkCell.h" #include "vtkMergePoints.h" #include "vtkContourValues.h" #include "vtkScalarTree.h" #include "vtkObjectFactory.h" #include "vtkTimerLog.h" #include "vtkUnstructuredGrid.h" #include "vtkContourGrid.h" //------------------------------------------------------------------------------ vtkContourFilter* vtkContourFilter::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkContourFilter"); if(ret) { return (vtkContourFilter*)ret; } // If the factory was unable to create the object, then create it here. return new vtkContourFilter; } // Construct object with initial range (0,1) and single contour value // of 0.0. vtkContourFilter::vtkContourFilter() { this->ContourValues = vtkContourValues::New(); this->ComputeNormals = 1; this->ComputeGradients = 0; this->ComputeScalars = 1; this->Locator = NULL; this->UseScalarTree = 0; this->ScalarTree = NULL; } vtkContourFilter::~vtkContourFilter() { this->ContourValues->Delete(); if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } if ( this->ScalarTree ) { this->ScalarTree->Delete(); } } // Overload standard modified time function. If contour values are modified, // then this object is modified as well. unsigned long vtkContourFilter::GetMTime() { unsigned long mTime=this->vtkDataSetToPolyDataFilter::GetMTime(); unsigned long time; if (this->ContourValues) { time = this->ContourValues->GetMTime(); mTime = ( time > mTime ? time : mTime ); } if (this->Locator) { time = this->Locator->GetMTime(); mTime = ( time > mTime ? time : mTime ); } return mTime; } // // General contouring filter. Handles arbitrary input. // void vtkContourFilter::Execute() { int cellId, i, abortExecute=0; vtkIdList *cellPts; vtkScalars *inScalars; vtkCell *cell; float range[2]; vtkCellArray *newVerts, *newLines, *newPolys; vtkPoints *newPts; vtkDataSet *input=this->GetInput(); vtkPolyData *output=this->GetOutput(); int numCells, estimatedSize; vtkPointData *inPd=input->GetPointData(), *outPd=output->GetPointData(); vtkCellData *inCd=input->GetCellData(), *outCd=output->GetCellData(); int numContours=this->ContourValues->GetNumberOfContours(); float *values=this->ContourValues->GetValues(); vtkScalars *cellScalars; vtkTimerLog *timer = vtkTimerLog::New(); timer->StartTimer(); vtkDebugMacro(<< "Executing contour filter"); if (input->GetDataObjectType() == VTK_UNSTRUCTURED_GRID) { vtkContourGrid *cgrid; cgrid = vtkContourGrid::New(); cgrid->SetInput(input); cgrid->Update(); output = cgrid->GetOutput(); } //if type VTK_UNSTRUCTURED_GRID else { numCells = input->GetNumberOfCells(); inScalars = input->GetPointData()->GetScalars(); if ( ! inScalars || numCells < 1 ) { vtkErrorMacro(<<"No data to contour"); return; } inScalars->GetRange(range); // // Create objects to hold output of contour operation. First estimate allocation size. // estimatedSize = (int) pow ((double) numCells, .75); estimatedSize *= numContours; estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024 if (estimatedSize < 1024) { estimatedSize = 1024; } newPts = vtkPoints::New(); newPts->Allocate(estimatedSize,estimatedSize); newVerts = vtkCellArray::New(); newVerts->Allocate(estimatedSize,estimatedSize); newLines = vtkCellArray::New(); newLines->Allocate(estimatedSize,estimatedSize); newPolys = vtkCellArray::New(); newPolys->Allocate(estimatedSize,estimatedSize); cellScalars = vtkScalars::New(); cellScalars->Allocate(VTK_CELL_SIZE); // locator used to merge potentially duplicate points if ( this->Locator == NULL ) { this->CreateDefaultLocator(); } this->Locator->InitPointInsertion (newPts, input->GetBounds(),estimatedSize); // interpolate data along edge // if we did not ask for scalars to be computed, don't copy them if (!this->ComputeScalars) { outPd->CopyScalarsOff(); } outPd->InterpolateAllocate(inPd,estimatedSize,estimatedSize); outCd->CopyAllocate(inCd,estimatedSize,estimatedSize); // If enabled, build a scalar tree to accelerate search // if ( !this->UseScalarTree ) { for (cellId=0; cellId < numCells && !abortExecute; cellId++) { cell = input->GetCell(cellId); cellPts = cell->GetPointIds(); inScalars->GetScalars(cellPts,cellScalars); if ( ! (cellId % 5000) ) { vtkDebugMacro(<<"Contouring #" << cellId); this->UpdateProgress ((float)cellId/numCells); if (this->GetAbortExecute()) { abortExecute = 1; break; } } for (i=0; i < numContours; i++) { cell->Contour(values[i], cellScalars, this->Locator, newVerts, newLines, newPolys, inPd, outPd, inCd, cellId, outCd); } // for all contour values } // for all cells } //if using scalar tree else { if ( this->ScalarTree == NULL ) { this->ScalarTree = vtkScalarTree::New(); } this->ScalarTree->SetDataSet(input); // // Loop over all contour values. Then for each contour value, // loop over all cells. // for (i=0; i < numContours; i++) { for ( this->ScalarTree->InitTraversal(values[i]); (cell=this->ScalarTree->GetNextCell(cellId,cellPts,cellScalars)) != NULL; ) { cell->Contour(values[i], cellScalars, this->Locator, newVerts, newLines, newPolys, inPd, outPd, inCd, cellId, outCd); } //for all cells } //for all contour values } //using scalar tree } //else (for if vtkUnstructuredGrid) vtkDebugMacro(<<"Created: " << newPts->GetNumberOfPoints() << " points, " << newVerts->GetNumberOfCells() << " verts, " << newLines->GetNumberOfCells() << " lines, " << newPolys->GetNumberOfCells() << " triangles"); // // Update ourselves. Because we don't know up front how many verts, lines, // polys we've created, take care to reclaim memory. // output->SetPoints(newPts); newPts->Delete(); cellScalars->Delete(); if (newVerts->GetNumberOfCells()) { output->SetVerts(newVerts); } newVerts->Delete(); if (newLines->GetNumberOfCells()) { output->SetLines(newLines); } newLines->Delete(); if (newPolys->GetNumberOfCells()) { output->SetPolys(newPolys); } newPolys->Delete(); this->Locator->Initialize();//releases leftover memory output->Squeeze(); timer->StopTimer(); vtkErrorMacro(<<"elapsed time: " << timer->GetElapsedTime()); timer->Delete(); } // Specify a spatial locator for merging points. By default, // an instance of vtkMergePoints is used. void vtkContourFilter::SetLocator(vtkPointLocator *locator) { if ( this->Locator == locator ) { return; } if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } if ( locator ) { locator->Register(this); } this->Locator = locator; this->Modified(); } void vtkContourFilter::CreateDefaultLocator() { if ( this->Locator == NULL ) { this->Locator = vtkMergePoints::New(); } } void vtkContourFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetToPolyDataFilter::PrintSelf(os,indent); os << indent << "Compute Gradients: " << (this->ComputeGradients ? "On\n" : "Off\n"); os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n"); os << indent << "Compute Scalars: " << (this->ComputeScalars ? "On\n" : "Off\n"); os << indent << "Use Scalar Tree: " << (this->UseScalarTree ? "On\n" : "Off\n"); this->ContourValues->PrintSelf(os,indent); if ( this->Locator ) { os << indent << "Locator: " << this->Locator << "\n"; } else { os << indent << "Locator: (none)\n"; } } <commit_msg>This moves the calls to Delete for objects being created only if we do not have an unstructured grid inside the appropriate if statement.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkContourFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS 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 <math.h> #include "vtkContourFilter.h" #include "vtkScalars.h" #include "vtkCell.h" #include "vtkMergePoints.h" #include "vtkContourValues.h" #include "vtkScalarTree.h" #include "vtkObjectFactory.h" #include "vtkTimerLog.h" #include "vtkUnstructuredGrid.h" #include "vtkContourGrid.h" //------------------------------------------------------------------------------ vtkContourFilter* vtkContourFilter::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkContourFilter"); if(ret) { return (vtkContourFilter*)ret; } // If the factory was unable to create the object, then create it here. return new vtkContourFilter; } // Construct object with initial range (0,1) and single contour value // of 0.0. vtkContourFilter::vtkContourFilter() { this->ContourValues = vtkContourValues::New(); this->ComputeNormals = 1; this->ComputeGradients = 0; this->ComputeScalars = 1; this->Locator = NULL; this->UseScalarTree = 0; this->ScalarTree = NULL; } vtkContourFilter::~vtkContourFilter() { this->ContourValues->Delete(); if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } if ( this->ScalarTree ) { this->ScalarTree->Delete(); } } // Overload standard modified time function. If contour values are modified, // then this object is modified as well. unsigned long vtkContourFilter::GetMTime() { unsigned long mTime=this->vtkDataSetToPolyDataFilter::GetMTime(); unsigned long time; if (this->ContourValues) { time = this->ContourValues->GetMTime(); mTime = ( time > mTime ? time : mTime ); } if (this->Locator) { time = this->Locator->GetMTime(); mTime = ( time > mTime ? time : mTime ); } return mTime; } // // General contouring filter. Handles arbitrary input. // void vtkContourFilter::Execute() { int cellId, i, abortExecute=0; vtkIdList *cellPts; vtkScalars *inScalars; vtkCell *cell; float range[2]; vtkCellArray *newVerts, *newLines, *newPolys; vtkPoints *newPts; vtkDataSet *input=this->GetInput(); vtkPolyData *output=this->GetOutput(); int numCells, estimatedSize; vtkPointData *inPd=input->GetPointData(), *outPd=output->GetPointData(); vtkCellData *inCd=input->GetCellData(), *outCd=output->GetCellData(); int numContours=this->ContourValues->GetNumberOfContours(); float *values=this->ContourValues->GetValues(); vtkScalars *cellScalars; vtkDebugMacro(<< "Executing contour filter"); if (input->GetDataObjectType() == VTK_UNSTRUCTURED_GRID) { vtkContourGrid *cgrid; cgrid = vtkContourGrid::New(); cgrid->SetInput(input); cgrid->Update(); output = cgrid->GetOutput(); } //if type VTK_UNSTRUCTURED_GRID else { numCells = input->GetNumberOfCells(); inScalars = input->GetPointData()->GetScalars(); if ( ! inScalars || numCells < 1 ) { vtkErrorMacro(<<"No data to contour"); return; } inScalars->GetRange(range); // // Create objects to hold output of contour operation. First estimate allocation size. // estimatedSize = (int) pow ((double) numCells, .75); estimatedSize *= numContours; estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024 if (estimatedSize < 1024) { estimatedSize = 1024; } newPts = vtkPoints::New(); newPts->Allocate(estimatedSize,estimatedSize); newVerts = vtkCellArray::New(); newVerts->Allocate(estimatedSize,estimatedSize); newLines = vtkCellArray::New(); newLines->Allocate(estimatedSize,estimatedSize); newPolys = vtkCellArray::New(); newPolys->Allocate(estimatedSize,estimatedSize); cellScalars = vtkScalars::New(); cellScalars->Allocate(VTK_CELL_SIZE); // locator used to merge potentially duplicate points if ( this->Locator == NULL ) { this->CreateDefaultLocator(); } this->Locator->InitPointInsertion (newPts, input->GetBounds(),estimatedSize); // interpolate data along edge // if we did not ask for scalars to be computed, don't copy them if (!this->ComputeScalars) { outPd->CopyScalarsOff(); } outPd->InterpolateAllocate(inPd,estimatedSize,estimatedSize); outCd->CopyAllocate(inCd,estimatedSize,estimatedSize); // If enabled, build a scalar tree to accelerate search // if ( !this->UseScalarTree ) { for (cellId=0; cellId < numCells && !abortExecute; cellId++) { cell = input->GetCell(cellId); cellPts = cell->GetPointIds(); inScalars->GetScalars(cellPts,cellScalars); if ( ! (cellId % 5000) ) { vtkDebugMacro(<<"Contouring #" << cellId); this->UpdateProgress ((float)cellId/numCells); if (this->GetAbortExecute()) { abortExecute = 1; break; } } for (i=0; i < numContours; i++) { cell->Contour(values[i], cellScalars, this->Locator, newVerts, newLines, newPolys, inPd, outPd, inCd, cellId, outCd); } // for all contour values } // for all cells } //if using scalar tree else { if ( this->ScalarTree == NULL ) { this->ScalarTree = vtkScalarTree::New(); } this->ScalarTree->SetDataSet(input); // // Loop over all contour values. Then for each contour value, // loop over all cells. // for (i=0; i < numContours; i++) { for ( this->ScalarTree->InitTraversal(values[i]); (cell=this->ScalarTree->GetNextCell(cellId,cellPts,cellScalars)) != NULL; ) { cell->Contour(values[i], cellScalars, this->Locator, newVerts, newLines, newPolys, inPd, outPd, inCd, cellId, outCd); } //for all cells } //for all contour values } //using scalar tree vtkDebugMacro(<<"Created: " << newPts->GetNumberOfPoints() << " points, " << newVerts->GetNumberOfCells() << " verts, " << newLines->GetNumberOfCells() << " lines, " << newPolys->GetNumberOfCells() << " triangles"); // // Update ourselves. Because we don't know up front how many verts, lines, // polys we've created, take care to reclaim memory. // output->SetPoints(newPts); newPts->Delete(); cellScalars->Delete(); if (newVerts->GetNumberOfCells()) { output->SetVerts(newVerts); } newVerts->Delete(); if (newLines->GetNumberOfCells()) { output->SetLines(newLines); } newLines->Delete(); if (newPolys->GetNumberOfCells()) { output->SetPolys(newPolys); } newPolys->Delete(); this->Locator->Initialize();//releases leftover memory output->Squeeze(); } //else (for if vtkUnstructuredGrid) } // Specify a spatial locator for merging points. By default, // an instance of vtkMergePoints is used. void vtkContourFilter::SetLocator(vtkPointLocator *locator) { if ( this->Locator == locator ) { return; } if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } if ( locator ) { locator->Register(this); } this->Locator = locator; this->Modified(); } void vtkContourFilter::CreateDefaultLocator() { if ( this->Locator == NULL ) { this->Locator = vtkMergePoints::New(); } } void vtkContourFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetToPolyDataFilter::PrintSelf(os,indent); os << indent << "Compute Gradients: " << (this->ComputeGradients ? "On\n" : "Off\n"); os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n"); os << indent << "Compute Scalars: " << (this->ComputeScalars ? "On\n" : "Off\n"); os << indent << "Use Scalar Tree: " << (this->UseScalarTree ? "On\n" : "Off\n"); this->ContourValues->PrintSelf(os,indent); if ( this->Locator ) { os << indent << "Locator: " << this->Locator << "\n"; } else { os << indent << "Locator: (none)\n"; } } <|endoftext|>
<commit_before>#include "script_system.h" #include <Windows.h> #include <cstdio> #include "core/crc32.h" #include "core/file_system.h" #include "core/ifile.h" #include "core/json_serializer.h" #include "core/log.h" #include "core/pod_array.h" #include "engine/engine.h" #include "universe/universe.h" #include "universe/component_event.h" #include "base_script.h" #include "save_script_visitor.h" static const uint32_t script_type = crc32("script"); namespace Lux { struct ScriptSystemImpl { void postDeserialize(); void compile(); void getDll(const char* script_path, char* dll_path, int max_length); void getScriptDefaultPath(Entity e, char* path, char* full_path, int max_path, const char* ext); PODArray<int> m_scripts; PODArray<BaseScript*> m_script_objs; PODArray<HMODULE> m_libs; Array<string> m_paths; Universe* m_universe; Engine* m_engine; bool m_is_running; ScriptSystem* m_owner; }; typedef BaseScript* (*CreateScriptFunction)(); typedef void (*DestroyScriptFunction)(BaseScript* script); ScriptSystem::ScriptSystem() { m_impl = LUX_NEW(ScriptSystemImpl); m_impl->m_owner = this; m_impl->m_is_running = false; } ScriptSystem::~ScriptSystem() { LUX_DELETE(m_impl); } void ScriptSystem::setEngine(Engine& engine) { m_impl->m_engine = &engine; } Universe* ScriptSystem::getUniverse() const { return m_impl->m_universe; } Engine* ScriptSystem::getEngine() const { return m_impl->m_engine; } void ScriptSystem::setUniverse(Universe* universe) { m_impl->m_universe = universe; } void ScriptSystem::start() { char path[MAX_PATH]; for(int i = 0; i < m_impl->m_scripts.size(); ++i) { Entity e(m_impl->m_universe, m_impl->m_scripts[i]); m_impl->getDll(m_impl->m_paths[i].c_str(), path, MAX_PATH); HMODULE h = LoadLibrary(path); m_impl->m_libs.push(h); if(h) { CreateScriptFunction f = (CreateScriptFunction)GetProcAddress(h, TEXT("createScript")); BaseScript* script = f(); if(!f) { g_log_warning.log("script", "failed to create script %s", m_impl->m_paths[i].c_str()); m_impl->m_script_objs.push(0); } else { m_impl->m_script_objs.push(script); script->create(*this, e); } } else { g_log_warning.log("script", "failed to load script %s", m_impl->m_paths[i].c_str()); m_impl->m_script_objs.push(0); } } m_impl->m_is_running = true; } void ScriptSystem::deserialize(ISerializer& serializer) { int count; serializer.deserialize("count", count); m_impl->m_scripts.resize(count); m_impl->m_paths.resize(count); serializer.deserializeArrayBegin("scripts"); for(int i = 0; i < m_impl->m_scripts.size(); ++i) { serializer.deserializeArrayItem(m_impl->m_scripts[i]); serializer.deserializeArrayItem(m_impl->m_paths[i]); } serializer.deserializeArrayEnd(); m_impl->postDeserialize(); } void ScriptSystem::serialize(ISerializer& serializer) { serializer.serialize("count", m_impl->m_scripts.size()); serializer.beginArray("scripts"); for(int i = 0; i < m_impl->m_scripts.size(); ++i) { serializer.serializeArrayItem(m_impl->m_scripts[i]); serializer.serializeArrayItem(m_impl->m_paths[i]); } serializer.endArray(); } void ScriptSystem::stop() { m_impl->m_is_running = false; for(int i = 0; i < m_impl->m_scripts.size(); ++i) { DestroyScriptFunction f = (DestroyScriptFunction)GetProcAddress(m_impl->m_libs[i], "destroyScript"); f(m_impl->m_script_objs[i]); FreeLibrary(m_impl->m_libs[i]); } m_impl->m_libs.clear(); m_impl->m_script_objs.clear(); } void ScriptSystem::update(float dt) { if(m_impl->m_is_running) { for(int i = 0; i < m_impl->m_scripts.size(); ++i) { m_impl->m_script_objs[i]->update(dt); } } } void ScriptSystem::getScriptPath(Component cmp, string& str) { str = m_impl->m_paths[cmp.index]; } void ScriptSystem::setScriptPath(Component cmp, const string& str) { m_impl->m_paths[cmp.index] = str; } void ScriptSystemImpl::getDll(const char* script_path, char* dll_path, int max_length) { strcpy_s(dll_path, max_length, script_path); int len = strlen(script_path); if(len > 4) { strcpy_s(dll_path + len - 4, 5, ".dll"); } } void ScriptSystemImpl::getScriptDefaultPath(Entity e, char* path, char* full_path, int max_path, const char* ext) { sprintf_s(full_path, max_path, "%s\\scripts\\e%d.%s", m_engine->getBasePath(), e.index, ext); sprintf_s(path, max_path, "scripts\\e%d.%s", e.index, ext); } void ScriptSystemImpl::postDeserialize() { for(int i = 0; i < m_scripts.size(); ++i) { Entity e(m_universe, m_scripts[i]); m_universe->getEventManager()->emitEvent(ComponentEvent(Component(e, script_type, m_owner, i))); } } Component ScriptSystem::createScript(Entity entity) { char path[MAX_PATH]; char full_path[MAX_PATH]; m_impl->getScriptDefaultPath(entity, path, full_path, MAX_PATH, "cpp"); FS::FileSystem& fs = m_impl->m_engine->getFileSystem(); FS::IFile* file = fs.open(fs.getDefaultDevice(), full_path, FS::Mode::OPEN_OR_CREATE | FS::Mode::WRITE); fs.close(file); m_impl->m_scripts.push(entity.index); m_impl->m_paths.push(string(path)); Component cmp(entity, script_type, this, m_impl->m_scripts.size() - 1); m_impl->m_universe->getEventManager()->emitEvent(ComponentEvent(cmp)); return cmp; } } // ~namespace Lux<commit_msg>load script libraries using right path after open dialog is shown<commit_after>#include "script_system.h" #include <Windows.h> #include <cstdio> #include "core/crc32.h" #include "core/file_system.h" #include "core/ifile.h" #include "core/json_serializer.h" #include "core/log.h" #include "core/pod_array.h" #include "engine/engine.h" #include "universe/universe.h" #include "universe/component_event.h" #include "base_script.h" #include "save_script_visitor.h" static const uint32_t script_type = crc32("script"); namespace Lux { struct ScriptSystemImpl { void postDeserialize(); void compile(); void getDll(const char* script_path, char* dll_path, char* full_path, int max_length); void getScriptDefaultPath(Entity e, char* path, char* full_path, int max_path, const char* ext); PODArray<int> m_scripts; PODArray<BaseScript*> m_script_objs; PODArray<HMODULE> m_libs; Array<string> m_paths; Universe* m_universe; Engine* m_engine; bool m_is_running; ScriptSystem* m_owner; }; typedef BaseScript* (*CreateScriptFunction)(); typedef void (*DestroyScriptFunction)(BaseScript* script); ScriptSystem::ScriptSystem() { m_impl = LUX_NEW(ScriptSystemImpl); m_impl->m_owner = this; m_impl->m_is_running = false; } ScriptSystem::~ScriptSystem() { LUX_DELETE(m_impl); } void ScriptSystem::setEngine(Engine& engine) { m_impl->m_engine = &engine; } Universe* ScriptSystem::getUniverse() const { return m_impl->m_universe; } Engine* ScriptSystem::getEngine() const { return m_impl->m_engine; } void ScriptSystem::setUniverse(Universe* universe) { m_impl->m_universe = universe; } void ScriptSystem::start() { char path[MAX_PATH]; char full_path[MAX_PATH]; for(int i = 0; i < m_impl->m_scripts.size(); ++i) { Entity e(m_impl->m_universe, m_impl->m_scripts[i]); m_impl->getDll(m_impl->m_paths[i].c_str(), path, full_path, MAX_PATH); HMODULE h = LoadLibrary(full_path); m_impl->m_libs.push(h); if(h) { CreateScriptFunction f = (CreateScriptFunction)GetProcAddress(h, TEXT("createScript")); BaseScript* script = f(); if(!f) { g_log_warning.log("script", "failed to create script %s", m_impl->m_paths[i].c_str()); m_impl->m_script_objs.push(0); } else { m_impl->m_script_objs.push(script); script->create(*this, e); } } else { g_log_warning.log("script", "failed to load script %s", m_impl->m_paths[i].c_str()); m_impl->m_script_objs.push(0); } } m_impl->m_is_running = true; } void ScriptSystem::deserialize(ISerializer& serializer) { int count; serializer.deserialize("count", count); m_impl->m_scripts.resize(count); m_impl->m_paths.resize(count); serializer.deserializeArrayBegin("scripts"); for(int i = 0; i < m_impl->m_scripts.size(); ++i) { serializer.deserializeArrayItem(m_impl->m_scripts[i]); serializer.deserializeArrayItem(m_impl->m_paths[i]); } serializer.deserializeArrayEnd(); m_impl->postDeserialize(); } void ScriptSystem::serialize(ISerializer& serializer) { serializer.serialize("count", m_impl->m_scripts.size()); serializer.beginArray("scripts"); for(int i = 0; i < m_impl->m_scripts.size(); ++i) { serializer.serializeArrayItem(m_impl->m_scripts[i]); serializer.serializeArrayItem(m_impl->m_paths[i]); } serializer.endArray(); } void ScriptSystem::stop() { m_impl->m_is_running = false; for(int i = 0; i < m_impl->m_scripts.size(); ++i) { DestroyScriptFunction f = (DestroyScriptFunction)GetProcAddress(m_impl->m_libs[i], "destroyScript"); f(m_impl->m_script_objs[i]); FreeLibrary(m_impl->m_libs[i]); } m_impl->m_libs.clear(); m_impl->m_script_objs.clear(); } void ScriptSystem::update(float dt) { if(m_impl->m_is_running) { for(int i = 0; i < m_impl->m_scripts.size(); ++i) { m_impl->m_script_objs[i]->update(dt); } } } void ScriptSystem::getScriptPath(Component cmp, string& str) { str = m_impl->m_paths[cmp.index]; } void ScriptSystem::setScriptPath(Component cmp, const string& str) { m_impl->m_paths[cmp.index] = str; } void ScriptSystemImpl::getDll(const char* script_path, char* dll_path, char* full_path, int max_length) { strcpy_s(dll_path, max_length, script_path); int len = strlen(script_path); if(len > 4) { strcpy_s(dll_path + len - 4, 5, ".dll"); } strcpy(full_path, m_engine->getBasePath()); strcat(full_path, "\\"); strcat(full_path, dll_path); } void ScriptSystemImpl::getScriptDefaultPath(Entity e, char* path, char* full_path, int max_path, const char* ext) { sprintf_s(full_path, max_path, "%s\\scripts\\e%d.%s", m_engine->getBasePath(), e.index, ext); sprintf_s(path, max_path, "scripts\\e%d.%s", e.index, ext); } void ScriptSystemImpl::postDeserialize() { for(int i = 0; i < m_scripts.size(); ++i) { Entity e(m_universe, m_scripts[i]); m_universe->getEventManager()->emitEvent(ComponentEvent(Component(e, script_type, m_owner, i))); } } Component ScriptSystem::createScript(Entity entity) { char path[MAX_PATH]; char full_path[MAX_PATH]; m_impl->getScriptDefaultPath(entity, path, full_path, MAX_PATH, "cpp"); FS::FileSystem& fs = m_impl->m_engine->getFileSystem(); FS::IFile* file = fs.open(fs.getDefaultDevice(), full_path, FS::Mode::OPEN_OR_CREATE | FS::Mode::WRITE); fs.close(file); m_impl->m_scripts.push(entity.index); m_impl->m_paths.push(string(path)); Component cmp(entity, script_type, this, m_impl->m_scripts.size() - 1); m_impl->m_universe->getEventManager()->emitEvent(ComponentEvent(cmp)); return cmp; } } // ~namespace Lux<|endoftext|>
<commit_before>AliAnalysisTaskNewJetSubstructure* AddTaskNewJetSubstructure(const char * njetsBase, const char * njetsUS, const char * njetsTrue, const char * njetsPartLevel, const Double_t R, const char * nrhoBase, const char * ntracks, const char * ntracksUS, const char *ntracksPartLevel, const char * nclusters, const char * ntracksTrue, const char *type, const char *CentEst, Int_t pSel, TString trigClass = "", TString kEmcalTriggers = "", TString tag = "", AliAnalysisTaskNewJetSubstructure::JetShapeType jetShapeType = AliAnalysisTaskNewJetSubstructure::kMCTrue, AliAnalysisTaskNewJetSubstructure::JetShapeSub jetShapeSub = AliAnalysisTaskNewJetSubstructure::kNoSub, AliAnalysisTaskNewJetSubstructure::JetSelectionType jetSelection = AliAnalysisTaskNewJetSubstructure::kInclusive, Float_t minpTHTrigger =0., Float_t maxpTHTrigger =0., Float_t acut =0.6, AliAnalysisTaskNewJetSubstructure::DerivSubtrOrder derivSubtrOrder = AliAnalysisTaskNewJetSubstructure::kSecondOrder ) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskNewJetSubstructure","No analysis manager found."); return 0; } Bool_t ismc=kFALSE; ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE; // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskNewJetSubstructure", "This task requires an input event handler"); return NULL; } TString wagonName1 = Form("JetSubstructure_%s_TC%s%s",njetsBase,trigClass.Data(),tag.Data()); TString wagonName2 = Form("JetSubstructure_%s_TC%s%sTree",njetsBase,trigClass.Data(),tag.Data()); //Configure jet tagger task AliAnalysisTaskNewJetSubstructure *task = new AliAnalysisTaskNewJetSubstructure(wagonName1.Data()); //task->SetNCentBins(4); task->SetJetShapeType(jetShapeType); task->SetJetShapeSub(jetShapeSub); task->SetJetSelection(jetSelection); task->SetDerivativeSubtractionOrder(derivSubtrOrder); TString thename(njetsBase); //if(thename.Contains("Sub")) task->SetIsConstSub(kTRUE); //task->SetVzRange(-10.,10.); AliParticleContainer *trackCont;// = task->AddTrackContainer(ntracks); if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kData) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){ trackCont = task->AddParticleContainer(ntracks);} else trackCont = task->AddTrackContainer(ntracks); //Printf("tracks() = %s, trackCont =%p", ntracks, trackCont); AliParticleContainer *trackContUS = task->AddTrackContainer(ntracksUS); //Printf("tracksUS() = %s", ntracksUS); AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue); //Printf("ntracksTrue() = %s, trackContTrue=%p ", ntracksTrue, trackContTrue); if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContTrue->SetIsEmbedding(true); AliParticleContainer *trackContPartLevel=0; if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){ trackContPartLevel = task->AddParticleContainer(ntracksPartLevel); } else trackContPartLevel = task->AddMCParticleContainer(ntracksPartLevel); if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContPartLevel->SetIsEmbedding(true); //Printf("ntracksPartLevel() = %s, trackContPartLevel=%p ", ntracksPartLevel, trackContPartLevel); AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters); AliJetContainer *jetContBase=0x0; AliJetContainer *jetContUS=0x0; AliJetContainer *jetContTrue=0x0; AliJetContainer *jetContPart=0x0; TString strType(type); if ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kGenOnTheFly))) { jetContBase = task->AddJetContainer(njetsBase,strType,R); if(jetContBase) { jetContBase->SetRhoName(nrhoBase); jetContBase->ConnectParticleContainer(trackContPartLevel); jetContBase->ConnectClusterContainer(clusterCont); jetContBase->SetPercAreaCut(acut); } } if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kData){ jetContBase = task->AddJetContainer(njetsBase,strType,R); if(jetContBase) { jetContBase->SetRhoName(nrhoBase); jetContBase->ConnectParticleContainer(trackCont); jetContBase->ConnectClusterContainer(clusterCont); jetContBase->SetPercAreaCut(acut); if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2); } } if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia){ jetContBase = task->AddJetContainer(njetsBase,strType,R); if(jetContBase) { jetContBase->SetRhoName(nrhoBase); jetContBase->ConnectParticleContainer(trackCont); jetContBase->ConnectClusterContainer(clusterCont); jetContBase->SetPercAreaCut(acut); if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2); } jetContTrue = task->AddJetContainer(njetsTrue,strType,R); if(jetContTrue) { jetContTrue->SetRhoName(nrhoBase); jetContTrue->ConnectParticleContainer(trackContTrue); jetContTrue->SetPercAreaCut(acut); } if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub){ jetContUS=task->AddJetContainer(njetsUS,strType,R); if(jetContUS) { jetContUS->SetRhoName(nrhoBase); jetContUS->ConnectParticleContainer(trackContUS); jetContUS->SetPercAreaCut(acut); } } jetContPart = task->AddJetContainer(njetsPartLevel,strType,R); if(jetContPart) { jetContPart->SetRhoName(nrhoBase); jetContPart->ConnectParticleContainer(trackContPartLevel); jetContPart->SetPercAreaCut(acut); } } if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef){ jetContBase = task->AddJetContainer(njetsBase,strType,R); if(jetContBase) { jetContBase->ConnectParticleContainer(trackCont); jetContBase->ConnectClusterContainer(clusterCont); jetContBase->SetPercAreaCut(acut); } jetContTrue = task->AddJetContainer(njetsTrue,strType,R); if(jetContTrue) { jetContTrue->SetRhoName(nrhoBase); jetContTrue->ConnectParticleContainer(trackContTrue); jetContTrue->SetPercAreaCut(acut); } if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub){ jetContUS=task->AddJetContainer(njetsUS,strType,R); if(jetContUS) { jetContUS->SetRhoName(nrhoBase); jetContUS->ConnectParticleContainer(trackContUS); jetContUS->SetPercAreaCut(acut); } } jetContPart = task->AddJetContainer(njetsPartLevel,strType,R); if(jetContPart) { jetContPart->SetRhoName(nrhoBase); jetContPart->ConnectParticleContainer(trackContPartLevel); jetContPart->SetPercAreaCut(acut); } } task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data()); task->SetCentralityEstimator(CentEst); task->SelectCollisionCandidates(pSel); task->SetUseAliAnaUtils(kFALSE); mgr->AddTask(task); //Connnect input mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() ); //Connect output TString contName1(wagonName1); TString contName2(wagonName2); if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName1 += "_MCTrue"; if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName1 += "_Data"; if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName1 +="_PythiaDef"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName1 += "_NoSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName1 += "_ConstSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName1 += "_EventSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName1 += "_DerivSub"; if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName1 += "_Incl"; if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName2 += "_MCTrue"; if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName2 += "_Data"; if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName2 +="_PythiaDef"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName2 += "_NoSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName2 += "_ConstSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName2 += "_EventSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName2 += "_DerivSub"; if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName2 += "_Incl"; TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName()); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectOutput(task,1,coutput1); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(contName2.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectOutput(task,2,coutput2); return task; } <commit_msg>i also forgot to add the unsub container<commit_after>AliAnalysisTaskNewJetSubstructure* AddTaskNewJetSubstructure(const char * njetsBase, const char * njetsUS, const char * njetsTrue, const char * njetsPartLevel, const Double_t R, const char * nrhoBase, const char * ntracks, const char * ntracksUS, const char *ntracksPartLevel, const char * nclusters, const char * ntracksTrue, const char *type, const char *CentEst, Int_t pSel, TString trigClass = "", TString kEmcalTriggers = "", TString tag = "", AliAnalysisTaskNewJetSubstructure::JetShapeType jetShapeType = AliAnalysisTaskNewJetSubstructure::kMCTrue, AliAnalysisTaskNewJetSubstructure::JetShapeSub jetShapeSub = AliAnalysisTaskNewJetSubstructure::kNoSub, AliAnalysisTaskNewJetSubstructure::JetSelectionType jetSelection = AliAnalysisTaskNewJetSubstructure::kInclusive, Float_t minpTHTrigger =0., Float_t maxpTHTrigger =0., Float_t acut =0.6, AliAnalysisTaskNewJetSubstructure::DerivSubtrOrder derivSubtrOrder = AliAnalysisTaskNewJetSubstructure::kSecondOrder ) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskNewJetSubstructure","No analysis manager found."); return 0; } Bool_t ismc=kFALSE; ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE; // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskNewJetSubstructure", "This task requires an input event handler"); return NULL; } TString wagonName1 = Form("JetSubstructure_%s_TC%s%s",njetsBase,trigClass.Data(),tag.Data()); TString wagonName2 = Form("JetSubstructure_%s_TC%s%sTree",njetsBase,trigClass.Data(),tag.Data()); //Configure jet tagger task AliAnalysisTaskNewJetSubstructure *task = new AliAnalysisTaskNewJetSubstructure(wagonName1.Data()); //task->SetNCentBins(4); task->SetJetShapeType(jetShapeType); task->SetJetShapeSub(jetShapeSub); task->SetJetSelection(jetSelection); task->SetDerivativeSubtractionOrder(derivSubtrOrder); TString thename(njetsBase); //if(thename.Contains("Sub")) task->SetIsConstSub(kTRUE); //task->SetVzRange(-10.,10.); AliParticleContainer *trackCont;// = task->AddTrackContainer(ntracks); if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kData) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){ trackCont = task->AddParticleContainer(ntracks);} else trackCont = task->AddTrackContainer(ntracks); //Printf("tracks() = %s, trackCont =%p", ntracks, trackCont); AliParticleContainer *trackContUS = task->AddTrackContainer(ntracksUS); //Printf("tracksUS() = %s", ntracksUS); AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue); //Printf("ntracksTrue() = %s, trackContTrue=%p ", ntracksTrue, trackContTrue); if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContTrue->SetIsEmbedding(true); AliParticleContainer *trackContPartLevel=0; if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){ trackContPartLevel = task->AddParticleContainer(ntracksPartLevel); } else trackContPartLevel = task->AddMCParticleContainer(ntracksPartLevel); if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContPartLevel->SetIsEmbedding(true); //Printf("ntracksPartLevel() = %s, trackContPartLevel=%p ", ntracksPartLevel, trackContPartLevel); AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters); AliJetContainer *jetContBase=0x0; AliJetContainer *jetContUS=0x0; AliJetContainer *jetContTrue=0x0; AliJetContainer *jetContPart=0x0; TString strType(type); if ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kGenOnTheFly))) { jetContBase = task->AddJetContainer(njetsBase,strType,R); if(jetContBase) { jetContBase->SetRhoName(nrhoBase); jetContBase->ConnectParticleContainer(trackContPartLevel); jetContBase->ConnectClusterContainer(clusterCont); jetContBase->SetPercAreaCut(acut); } } if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kData){ jetContBase = task->AddJetContainer(njetsBase,strType,R); if(jetContBase) { jetContBase->SetRhoName(nrhoBase); jetContBase->ConnectParticleContainer(trackCont); jetContBase->ConnectClusterContainer(clusterCont); jetContBase->SetPercAreaCut(acut); if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2); } } if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia){ jetContBase = task->AddJetContainer(njetsBase,strType,R); if(jetContBase) { jetContBase->SetRhoName(nrhoBase); jetContBase->ConnectParticleContainer(trackCont); jetContBase->ConnectClusterContainer(clusterCont); jetContBase->SetPercAreaCut(acut); if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2); } jetContTrue = task->AddJetContainer(njetsTrue,strType,R); if(jetContTrue) { jetContTrue->SetRhoName(nrhoBase); jetContTrue->ConnectParticleContainer(trackContTrue); jetContTrue->SetPercAreaCut(acut); } if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub || jetShapeSub==AliAnalysisTaskNewJetSubstructure::kEventSub){ jetContUS=task->AddJetContainer(njetsUS,strType,R); if(jetContUS) { jetContUS->SetRhoName(nrhoBase); jetContUS->ConnectParticleContainer(trackContUS); jetContUS->SetPercAreaCut(acut); } } jetContPart = task->AddJetContainer(njetsPartLevel,strType,R); if(jetContPart) { jetContPart->SetRhoName(nrhoBase); jetContPart->ConnectParticleContainer(trackContPartLevel); jetContPart->SetPercAreaCut(acut); } } if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef){ jetContBase = task->AddJetContainer(njetsBase,strType,R); if(jetContBase) { jetContBase->ConnectParticleContainer(trackCont); jetContBase->ConnectClusterContainer(clusterCont); jetContBase->SetPercAreaCut(acut); } jetContTrue = task->AddJetContainer(njetsTrue,strType,R); if(jetContTrue) { jetContTrue->SetRhoName(nrhoBase); jetContTrue->ConnectParticleContainer(trackContTrue); jetContTrue->SetPercAreaCut(acut); } if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub){ jetContUS=task->AddJetContainer(njetsUS,strType,R); if(jetContUS) { jetContUS->SetRhoName(nrhoBase); jetContUS->ConnectParticleContainer(trackContUS); jetContUS->SetPercAreaCut(acut); } } jetContPart = task->AddJetContainer(njetsPartLevel,strType,R); if(jetContPart) { jetContPart->SetRhoName(nrhoBase); jetContPart->ConnectParticleContainer(trackContPartLevel); jetContPart->SetPercAreaCut(acut); } } task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data()); task->SetCentralityEstimator(CentEst); task->SelectCollisionCandidates(pSel); task->SetUseAliAnaUtils(kFALSE); mgr->AddTask(task); //Connnect input mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() ); //Connect output TString contName1(wagonName1); TString contName2(wagonName2); if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName1 += "_MCTrue"; if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName1 += "_Data"; if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName1 +="_PythiaDef"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName1 += "_NoSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName1 += "_ConstSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName1 += "_EventSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName1 += "_DerivSub"; if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName1 += "_Incl"; if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName2 += "_MCTrue"; if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName2 += "_Data"; if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName2 +="_PythiaDef"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName2 += "_NoSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName2 += "_ConstSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName2 += "_EventSub"; if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName2 += "_DerivSub"; if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName2 += "_Incl"; TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName()); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectOutput(task,1,coutput1); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(contName2.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectOutput(task,2,coutput2); return task; } <|endoftext|>
<commit_before>/* * 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 Library 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. * * BaseUsbProWidget.cpp * Read and Write to a USB Widget. * Copyright (C) 2010 Simon Newton */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/stat.h> #include <sys/types.h> #include <termios.h> #include <unistd.h> #include <string> #include "ola/BaseTypes.h" #include "ola/Logging.h" #include "plugins/usbpro/BaseUsbProWidget.h" namespace ola { namespace plugin { namespace usbpro { const unsigned int BaseUsbProWidget::HEADER_SIZE = sizeof(BaseUsbProWidget::message_header); BaseUsbProWidget::BaseUsbProWidget( ola::io::ConnectedDescriptor *descriptor) : m_descriptor(descriptor), m_state(PRE_SOM), m_bytes_received(0) { m_descriptor->SetOnData( NewCallback(this, &BaseUsbProWidget::DescriptorReady)); } BaseUsbProWidget::~BaseUsbProWidget() { m_descriptor->SetOnData(NULL); } /* * Read data from the widget */ void BaseUsbProWidget::DescriptorReady() { while (m_descriptor->DataRemaining() > 0) { ReceiveMessage(); } } /* * Send a DMX frame. * @returns true if we sent ok, false otherwise */ bool BaseUsbProWidget::SendDMX(const DmxBuffer &buffer) { struct { uint8_t start_code; uint8_t dmx[DMX_UNIVERSE_SIZE]; } widget_dmx; widget_dmx.start_code = DMX512_START_CODE; unsigned int length = DMX_UNIVERSE_SIZE; buffer.Get(widget_dmx.dmx, &length); return SendMessage(DMX_LABEL, reinterpret_cast<uint8_t*>(&widget_dmx), length + 1); } /* * Send the msg * @return true if successful, false otherwise */ bool BaseUsbProWidget::SendMessage(uint8_t label, const uint8_t *data, unsigned int length) const { if (length && !data) return false; ssize_t frame_size = HEADER_SIZE + length + 1; uint8_t frame[frame_size]; message_header *header = reinterpret_cast<message_header*>(frame); header->som = SOM; header->label = label; header->len = length & 0xFF; header->len_hi = (length & 0xFF00) >> 8; memcpy(frame + sizeof(message_header), data, length); frame[frame_size - 1] = EOM; ssize_t bytes_sent = m_descriptor->Send(frame, frame_size); if (bytes_sent != frame_size) // we've probably screwed framing at this point return false; return true; } /** * Open a path and apply the settings required for talking to widgets. */ ola::io::ConnectedDescriptor *BaseUsbProWidget::OpenDevice( const string &path) { struct termios newtio; int fd = open(path.data(), O_RDWR | O_NONBLOCK | O_NOCTTY); if (fd == -1) { OLA_WARN << "Failed to open " << path << " " << strerror(errno); return NULL; } bzero(&newtio, sizeof(newtio)); // clear struct for new port settings newtio.c_cflag |= CREAD; cfsetispeed(&newtio, B115200); cfsetospeed(&newtio, B115200); tcsetattr(fd, TCSANOW, &newtio); return new ola::io::DeviceDescriptor(fd); } /* * Read the data and handle the messages. */ void BaseUsbProWidget::ReceiveMessage() { unsigned int count, packet_length; switch (m_state) { case PRE_SOM: do { m_descriptor->Receive(&m_header.som, 1, count); if (count != 1) return; } while (m_header.som != SOM); m_state = RECV_LABEL; case RECV_LABEL: m_descriptor->Receive(&m_header.label, 1, count); if (count != 1) return; m_state = RECV_SIZE_LO; case RECV_SIZE_LO: m_descriptor->Receive(&m_header.len, 1, count); if (count != 1) return; m_state = RECV_SIZE_HI; case RECV_SIZE_HI: m_descriptor->Receive(&m_header.len_hi, 1, count); if (count != 1) return; packet_length = (m_header.len_hi << 8) + m_header.len; if (packet_length == 0) { m_state = RECV_EOM; return; } else if (packet_length > MAX_DATA_SIZE) { m_state = PRE_SOM; return; } m_bytes_received = 0; m_state = RECV_BODY; case RECV_BODY: packet_length = (m_header.len_hi << 8) + m_header.len; m_descriptor->Receive( reinterpret_cast<uint8_t*>(&m_recv_buffer) + m_bytes_received, packet_length - m_bytes_received, count); if (!count) return; m_bytes_received += count; if (m_bytes_received != packet_length) return; m_state = RECV_EOM; case RECV_EOM: // check this is a valid frame with an end byte uint8_t eom; m_descriptor->Receive(&eom, 1, count); if (count != 1) return; packet_length = (m_header.len_hi << 8) + m_header.len; if (eom == EOM) HandleMessage(m_header.label, packet_length ? m_recv_buffer : NULL, packet_length); m_state = PRE_SOM; } return; } } // usbpro } // plugin } // ola <commit_msg>Set the char size to 8 bits for the usb serial devices. As suggested by Michael Markstaller<commit_after>/* * 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 Library 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. * * BaseUsbProWidget.cpp * Read and Write to a USB Widget. * Copyright (C) 2010 Simon Newton */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/stat.h> #include <sys/types.h> #include <termios.h> #include <unistd.h> #include <string> #include "ola/BaseTypes.h" #include "ola/Logging.h" #include "plugins/usbpro/BaseUsbProWidget.h" namespace ola { namespace plugin { namespace usbpro { const unsigned int BaseUsbProWidget::HEADER_SIZE = sizeof(BaseUsbProWidget::message_header); BaseUsbProWidget::BaseUsbProWidget( ola::io::ConnectedDescriptor *descriptor) : m_descriptor(descriptor), m_state(PRE_SOM), m_bytes_received(0) { m_descriptor->SetOnData( NewCallback(this, &BaseUsbProWidget::DescriptorReady)); } BaseUsbProWidget::~BaseUsbProWidget() { m_descriptor->SetOnData(NULL); } /* * Read data from the widget */ void BaseUsbProWidget::DescriptorReady() { while (m_descriptor->DataRemaining() > 0) { ReceiveMessage(); } } /* * Send a DMX frame. * @returns true if we sent ok, false otherwise */ bool BaseUsbProWidget::SendDMX(const DmxBuffer &buffer) { struct { uint8_t start_code; uint8_t dmx[DMX_UNIVERSE_SIZE]; } widget_dmx; widget_dmx.start_code = DMX512_START_CODE; unsigned int length = DMX_UNIVERSE_SIZE; buffer.Get(widget_dmx.dmx, &length); return SendMessage(DMX_LABEL, reinterpret_cast<uint8_t*>(&widget_dmx), length + 1); } /* * Send the msg * @return true if successful, false otherwise */ bool BaseUsbProWidget::SendMessage(uint8_t label, const uint8_t *data, unsigned int length) const { if (length && !data) return false; ssize_t frame_size = HEADER_SIZE + length + 1; uint8_t frame[frame_size]; message_header *header = reinterpret_cast<message_header*>(frame); header->som = SOM; header->label = label; header->len = length & 0xFF; header->len_hi = (length & 0xFF00) >> 8; memcpy(frame + sizeof(message_header), data, length); frame[frame_size - 1] = EOM; ssize_t bytes_sent = m_descriptor->Send(frame, frame_size); if (bytes_sent != frame_size) // we've probably screwed framing at this point return false; return true; } /** * Open a path and apply the settings required for talking to widgets. */ ola::io::ConnectedDescriptor *BaseUsbProWidget::OpenDevice( const string &path) { struct termios newtio; int fd = open(path.data(), O_RDWR | O_NONBLOCK | O_NOCTTY); if (fd == -1) { OLA_WARN << "Failed to open " << path << " " << strerror(errno); return NULL; } bzero(&newtio, sizeof(newtio)); // clear struct for new port settings newtio.c_cflag |= CREAD; newtio.c_cflag |= CS8; cfsetispeed(&newtio, B115200); cfsetospeed(&newtio, B115200); tcsetattr(fd, TCSANOW, &newtio); return new ola::io::DeviceDescriptor(fd); } /* * Read the data and handle the messages. */ void BaseUsbProWidget::ReceiveMessage() { unsigned int count, packet_length; switch (m_state) { case PRE_SOM: do { m_descriptor->Receive(&m_header.som, 1, count); if (count != 1) return; } while (m_header.som != SOM); m_state = RECV_LABEL; case RECV_LABEL: m_descriptor->Receive(&m_header.label, 1, count); if (count != 1) return; m_state = RECV_SIZE_LO; case RECV_SIZE_LO: m_descriptor->Receive(&m_header.len, 1, count); if (count != 1) return; m_state = RECV_SIZE_HI; case RECV_SIZE_HI: m_descriptor->Receive(&m_header.len_hi, 1, count); if (count != 1) return; packet_length = (m_header.len_hi << 8) + m_header.len; if (packet_length == 0) { m_state = RECV_EOM; return; } else if (packet_length > MAX_DATA_SIZE) { m_state = PRE_SOM; return; } m_bytes_received = 0; m_state = RECV_BODY; case RECV_BODY: packet_length = (m_header.len_hi << 8) + m_header.len; m_descriptor->Receive( reinterpret_cast<uint8_t*>(&m_recv_buffer) + m_bytes_received, packet_length - m_bytes_received, count); if (!count) return; m_bytes_received += count; if (m_bytes_received != packet_length) return; m_state = RECV_EOM; case RECV_EOM: // check this is a valid frame with an end byte uint8_t eom; m_descriptor->Receive(&eom, 1, count); if (count != 1) return; packet_length = (m_header.len_hi << 8) + m_header.len; if (eom == EOM) HandleMessage(m_header.label, packet_length ? m_recv_buffer : NULL, packet_length); m_state = PRE_SOM; } return; } } // usbpro } // plugin } // ola <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_GSLIB #define MFEM_GSLIB #include "../config/config.hpp" #include "gridfunc.hpp" #ifdef MFEM_USE_GSLIB struct comm; struct findpts_data_2; struct findpts_data_3; struct array; struct crystal; namespace mfem { /** \brief FindPointsGSLIB can robustly evaluate a GridFunction on an arbitrary * collection of points. There are three key functions in FindPointsGSLIB: * * 1. Setup - constructs the internal data structures of gslib. * * 2. FindPoints - for any given arbitrary set of points in physical space, * gslib finds the element number, MPI rank, and the reference space * coordinates inside the element that each point is located in. gslib also * returns a code that indicates wether the point was found inside an * element, on element border, or not found in the domain. * * 3. Interpolate - Interpolates any gridfunction at the points found using 2. * * FindPointsGSLIB provides interface to use these functions individually or using * a single call. */ class FindPointsGSLIB { protected: Mesh *mesh, *meshsplit; IntegrationRule *ir_simplex; // IntegrationRule to split quads/hex -> simplex struct findpts_data_2 *fdata2D; // pointer to gslib's struct findpts_data_3 *fdata3D; // internal data int dim, points_cnt; Array<unsigned int> gsl_code, gsl_proc, gsl_elem, gsl_mfem_elem; Vector gsl_mesh, gsl_ref, gsl_dist, gsl_mfem_ref; bool setupflag; struct crystal *cr; struct comm *gsl_comm; double default_interp_value; GridFunction::AvgType avgtype; /// Get GridFunction from MFEM format to GSLIB format void GetNodeValues(const GridFunction &gf_in, Vector &node_vals); /// Get nodal coordinates from mesh to the format expected by GSLIB for quads /// and hexes void GetQuadHexNodalCoordinates(); /// Convert simplices to quad/hexes and then get nodal coordinates for each /// split element into format expected by GSLIB void GetSimplexNodalCoordinates(); /// Use GSLIB for communication and interpolation void InterpolateH1(const GridFunction &field_in, Vector &field_out); /// Uses GSLIB Crystal Router for communication followed by MFEM's /// interpolation functions void InterpolateGeneral(const GridFunction &field_in, Vector &field_out); /// Map {r,s,t} coordinates from [-1,1] to [0,1] for MFEM. For simplices mesh /// find the original element number (that was split into micro quads/hexes /// by GetSimplexNodalCoordinates()) void MapRefPosAndElemIndices(); public: FindPointsGSLIB(); #ifdef MFEM_USE_MPI FindPointsGSLIB(MPI_Comm _comm); #endif ~FindPointsGSLIB(); /** Initializes the internal mesh in gslib, by sending the positions of the Gauss-Lobatto nodes of the input Mesh object @a m. Note: not tested with periodic (DG meshes). Note: the input mesh @a m must have Nodes set. @param[in] m Input mesh. @param[in] bb_t Relative size of bounding box around each element. @param[in] newt_tol Newton tolerance for the gslib search methods. @param[in] npt_max Number of points for simultaneous iteration. This alters performance and memory footprint. */ void Setup(Mesh &m, const double bb_t = 0.1, const double newt_tol = 1.0e-12, const int npt_max = 256); /** Searches positions given in physical space by @a point_pos. This function populates the following Class variables: #point_pos Positions to be found. Must by ordered by nodes: (XXX...,YYY...,ZZZ). #gsl_code Return codes for each point: inside element (0), element boundary (1), not found (2). #gsl_proc MPI proc ids where the points were found. #gsl_elem Element ids where the points were found. Defaults to 0 for points that were not found. #gsl_mfem_elem Element ids corresponding to MFEM-mesh where the points were found. #gsl_mfem_elem != #gsl_elem for simplices Defaults to 0 for points that were not found. #gsl_ref Reference coordinates of the found point. Ordered by vdim (XYZ,XYZ,XYZ...). Defaults to -1 for points that were not found. Note: the gslib reference frame is [-1,1]. #gsl_mfem_ref Reference coordinates #gsl_ref mapped to [0,1]. Defaults to 0 for points that were not found. #gsl_dist Distance between the sought and the found point in physical space. */ void FindPoints(const Vector &point_pos); /// Setup FindPoints and search positions void FindPoints(Mesh &m, const Vector &point_pos, const double bb_t = 0.1, const double newt_tol = 1.0e-12, const int npt_max = 256); /** Interpolation of field values at prescribed reference space positions. @param[in] field_in Function values that will be interpolated on the reference positions. Note: it is assumed that @a field_in is in H1 and in the same space as the mesh that was given to Setup(). @param[out] field_out Interpolated values. For points that are not found the value is set to #default_interp_value. */ void Interpolate(const GridFunction &field_in, Vector &field_out); /** Search positions and interpolate */ void Interpolate(const Vector &point_pos, const GridFunction &field_in, Vector &field_out); /** Setup FindPoints, search positions and interpolate */ void Interpolate(Mesh &m, const Vector &point_pos, const GridFunction &field_in, Vector &field_out); /// Average type to be used for L2 functions in-case a point is located at /// an element boundary where the function might not have a unique value. void SetL2AvgType(GridFunction::AvgType avgtype_) { avgtype = avgtype_; } /// Set the default interpolation value for points that are not found in the /// mesh. void SetDefaultInterpolationValue(double interp_value_) { default_interp_value = interp_value_; } /** Cleans up memory allocated internally by gslib. Note that in parallel, this must be called before MPI_Finalize(), as it calls MPI_Comm_free() for internal gslib communicators. */ void FreeData(); /// Return code for each point searched by FindPoints: inside element (0), on /// element boundary (1), or not found (2). const Array<unsigned int> &GetCode() const { return gsl_code; } /// Return element number for each point found by FindPoints. const Array<unsigned int> &GetElem() const { return gsl_mfem_elem; } /// Return MPI rank on which each point was found by FindPoints. const Array<unsigned int> &GetProc() const { return gsl_proc; } /// Return reference coordinates for each point found by FindPoints. const Vector &GetReferencePosition() const { return gsl_mfem_ref; } /// Return distance Distance between the sought and the found point /// in physical space, for each point found by FindPoints. const Vector &GetDist() const { return gsl_dist; } /// Return element number for each point found by FindPoints corresponding to /// GSLIB mesh. gsl_mfem_elem != gsl_elem for mesh with simplices. const Array<unsigned int> &GetGSLIBElem() const { return gsl_elem; } /// Return reference coordinates in [-1,1] (internal range in GSLIB) for each /// point found by FindPoints. const Vector &GetGSLIBReferencePosition() const { return gsl_ref; } }; } // namespace mfem #endif //MFEM_USE_GSLIB #endif //MFEM_GSLIB guard <commit_msg>minor<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_GSLIB #define MFEM_GSLIB #include "../config/config.hpp" #include "gridfunc.hpp" #ifdef MFEM_USE_GSLIB struct comm; struct findpts_data_2; struct findpts_data_3; struct array; struct crystal; namespace mfem { /** \brief FindPointsGSLIB can robustly evaluate a GridFunction on an arbitrary * collection of points. There are three key functions in FindPointsGSLIB: * * 1. Setup - constructs the internal data structures of gslib. * * 2. FindPoints - for any given arbitrary set of points in physical space, * gslib finds the element number, MPI rank, and the reference space * coordinates inside the element that each point is located in. gslib also * returns a code that indicates wether the point was found inside an * element, on element border, or not found in the domain. * * 3. Interpolate - Interpolates any gridfunction at the points found using 2. * * FindPointsGSLIB provides interface to use these functions individually or using * a single call. */ class FindPointsGSLIB { protected: Mesh *mesh, *meshsplit; IntegrationRule *ir_simplex; // IntegrationRule to split quads/hex -> simplex struct findpts_data_2 *fdata2D; // pointer to gslib's struct findpts_data_3 *fdata3D; // internal data int dim, points_cnt; Array<unsigned int> gsl_code, gsl_proc, gsl_elem, gsl_mfem_elem; Vector gsl_mesh, gsl_ref, gsl_dist, gsl_mfem_ref; bool setupflag; struct crystal *cr; struct comm *gsl_comm; double default_interp_value; GridFunction::AvgType avgtype; /// Get GridFunction from MFEM format to GSLIB format void GetNodeValues(const GridFunction &gf_in, Vector &node_vals); /// Get nodal coordinates from mesh to the format expected by GSLIB for quads /// and hexes void GetQuadHexNodalCoordinates(); /// Convert simplices to quad/hexes and then get nodal coordinates for each /// split element into format expected by GSLIB void GetSimplexNodalCoordinates(); /// Use GSLIB for communication and interpolation void InterpolateH1(const GridFunction &field_in, Vector &field_out); /// Uses GSLIB Crystal Router for communication followed by MFEM's /// interpolation functions void InterpolateGeneral(const GridFunction &field_in, Vector &field_out); /// Map {r,s,t} coordinates from [-1,1] to [0,1] for MFEM. For simplices mesh /// find the original element number (that was split into micro quads/hexes /// by GetSimplexNodalCoordinates()) void MapRefPosAndElemIndices(); public: FindPointsGSLIB(); #ifdef MFEM_USE_MPI FindPointsGSLIB(MPI_Comm _comm); #endif ~FindPointsGSLIB(); /** Initializes the internal mesh in gslib, by sending the positions of the Gauss-Lobatto nodes of the input Mesh object @a m. Note: not tested with periodic (DG meshes). Note: the input mesh @a m must have Nodes set. @param[in] m Input mesh. @param[in] bb_t Relative size of bounding box around each element. @param[in] newt_tol Newton tolerance for the gslib search methods. @param[in] npt_max Number of points for simultaneous iteration. This alters performance and memory footprint. */ void Setup(Mesh &m, const double bb_t = 0.1, const double newt_tol = 1.0e-12, const int npt_max = 256); /** Searches positions given in physical space by @a point_pos. These positions must by ordered by nodes: (XXX...,YYY...,ZZZ). This function populates the following member variables: #gsl_code Return codes for each point: inside element (0), element boundary (1), not found (2). #gsl_proc MPI proc ids where the points were found. #gsl_elem Element ids where the points were found. Defaults to 0 for points that were not found. #gsl_mfem_elem Element ids corresponding to MFEM-mesh where the points were found. #gsl_mfem_elem != #gsl_elem for simplices Defaults to 0 for points that were not found. #gsl_ref Reference coordinates of the found point. Ordered by vdim (XYZ,XYZ,XYZ...). Defaults to -1 for points that were not found. Note: the gslib reference frame is [-1,1]. #gsl_mfem_ref Reference coordinates #gsl_ref mapped to [0,1]. Defaults to 0 for points that were not found. #gsl_dist Distance between the sought and the found point in physical space. */ void FindPoints(const Vector &point_pos); /// Setup FindPoints and search positions void FindPoints(Mesh &m, const Vector &point_pos, const double bb_t = 0.1, const double newt_tol = 1.0e-12, const int npt_max = 256); /** Interpolation of field values at prescribed reference space positions. @param[in] field_in Function values that will be interpolated on the reference positions. Note: it is assumed that @a field_in is in H1 and in the same space as the mesh that was given to Setup(). @param[out] field_out Interpolated values. For points that are not found the value is set to #default_interp_value. */ void Interpolate(const GridFunction &field_in, Vector &field_out); /** Search positions and interpolate */ void Interpolate(const Vector &point_pos, const GridFunction &field_in, Vector &field_out); /** Setup FindPoints, search positions and interpolate */ void Interpolate(Mesh &m, const Vector &point_pos, const GridFunction &field_in, Vector &field_out); /// Average type to be used for L2 functions in-case a point is located at /// an element boundary where the function might not have a unique value. void SetL2AvgType(GridFunction::AvgType avgtype_) { avgtype = avgtype_; } /// Set the default interpolation value for points that are not found in the /// mesh. void SetDefaultInterpolationValue(double interp_value_) { default_interp_value = interp_value_; } /** Cleans up memory allocated internally by gslib. Note that in parallel, this must be called before MPI_Finalize(), as it calls MPI_Comm_free() for internal gslib communicators. */ void FreeData(); /// Return code for each point searched by FindPoints: inside element (0), on /// element boundary (1), or not found (2). const Array<unsigned int> &GetCode() const { return gsl_code; } /// Return element number for each point found by FindPoints. const Array<unsigned int> &GetElem() const { return gsl_mfem_elem; } /// Return MPI rank on which each point was found by FindPoints. const Array<unsigned int> &GetProc() const { return gsl_proc; } /// Return reference coordinates for each point found by FindPoints. const Vector &GetReferencePosition() const { return gsl_mfem_ref; } /// Return distance Distance between the sought and the found point /// in physical space, for each point found by FindPoints. const Vector &GetDist() const { return gsl_dist; } /// Return element number for each point found by FindPoints corresponding to /// GSLIB mesh. gsl_mfem_elem != gsl_elem for mesh with simplices. const Array<unsigned int> &GetGSLIBElem() const { return gsl_elem; } /// Return reference coordinates in [-1,1] (internal range in GSLIB) for each /// point found by FindPoints. const Vector &GetGSLIBReferencePosition() const { return gsl_ref; } }; } // namespace mfem #endif //MFEM_USE_GSLIB #endif //MFEM_GSLIB guard <|endoftext|>
<commit_before>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBenchmark.h" #include "SkBlurMask.h" #include "SkBlurMaskFilter.h" #include "SkCanvas.h" #include "SkColorFilter.h" #include "SkLayerDrawLooper.h" #include "SkPaint.h" #include "SkPath.h" #include "SkPoint.h" #include "SkRect.h" #include "SkRRect.h" #include "SkString.h" #include "SkXfermode.h" class BlurRoundRectBench : public SkBenchmark { public: BlurRoundRectBench(int width, int height, // X and Y radii for the upper left corner int ulX, int ulY, // X and Y radii for the upper right corner int urX, int urY, // X and Y radii for the lower right corner int lrX, int lrY, // X and Y radii for the lower left corner int llX, int llY) : fName("blurroundrect") , fWidth(width) , fHeight(height) { fName.appendf("_WH[%ix%i]_UL[%ix%i]_UR[%ix%i]_LR[%ix%i]_LL[%ix%i]", width, height, ulX, ulY, urX, urY, lrX, lrY, llX, llY); fRadii[0].set(SkIntToScalar(ulX), SkIntToScalar(ulY)); fRadii[1].set(SkIntToScalar(urX), SkIntToScalar(urY)); fRadii[2].set(SkIntToScalar(lrX), SkIntToScalar(lrY)); fRadii[3].set(SkIntToScalar(llX), SkIntToScalar(llY)); } virtual const char* onGetName() SK_OVERRIDE { return fName.c_str(); } virtual SkIPoint onGetSize() SK_OVERRIDE { return SkIPoint::Make(fWidth, fHeight); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { for (int i = 0; i < this->getLoops(); i++) { SkLayerDrawLooper* looper = new SkLayerDrawLooper; { SkLayerDrawLooper::LayerInfo info; info.fFlagsMask = 0; info.fPaintBits = 40; info.fColorMode = SkXfermode::kSrc_Mode; info.fOffset = SkPoint::Make(SkIntToScalar(-1), SkIntToScalar(0)); info.fPostTranslate = false; SkPaint* paint = looper->addLayerOnTop(info); SkMaskFilter* maskFilter = SkBlurMaskFilter::Create(SK_ScalarHalf, SkBlurMaskFilter::kNormal_BlurStyle, SkBlurMaskFilter::kHighQuality_BlurFlag); paint->setMaskFilter(maskFilter)->unref(); SkColorFilter* colorFilter = SkColorFilter::CreateModeFilter(SK_ColorLTGRAY, SkXfermode::kSrcIn_Mode); paint->setColorFilter(colorFilter)->unref(); paint->setColor(SK_ColorGRAY); } { SkLayerDrawLooper::LayerInfo info; looper->addLayerOnTop(info); } SkPaint paint; SkRect rect = SkRect::MakeWH(fWidth, fHeight); canvas->drawRect(rect, paint); paint.setLooper(looper)->unref(); paint.setAntiAlias(true); paint.setColor(SK_ColorCYAN); SkRRect rrect; rrect.setRectRadii(rect, fRadii); canvas->drawRRect(rrect, paint); } } private: SkString fName; const int fWidth; const int fHeight; SkVector fRadii[4]; typedef SkBenchmark INHERITED; }; // Create one with dimensions/rounded corners based on the skp DEF_BENCH(return new BlurRoundRectBench(600, 5514, 6, 6, 6, 6, 6, 6, 6, 6);) // Same radii, much smaller rectangle DEF_BENCH(return new BlurRoundRectBench(100, 100, 6, 6, 6, 6, 6, 6, 6, 6);) // Rounded rect with two opposite corners with large radii, the other two // small. DEF_BENCH(return new BlurRoundRectBench(100, 100, 30, 30, 10, 10, 30, 30, 10, 10);) DEF_BENCH(return new BlurRoundRectBench(100, 100, 90, 90, 90, 90, 90, 90, 90, 90);) <commit_msg>Another int to scalar fix.<commit_after>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBenchmark.h" #include "SkBlurMask.h" #include "SkBlurMaskFilter.h" #include "SkCanvas.h" #include "SkColorFilter.h" #include "SkLayerDrawLooper.h" #include "SkPaint.h" #include "SkPath.h" #include "SkPoint.h" #include "SkRect.h" #include "SkRRect.h" #include "SkString.h" #include "SkXfermode.h" class BlurRoundRectBench : public SkBenchmark { public: BlurRoundRectBench(int width, int height, // X and Y radii for the upper left corner int ulX, int ulY, // X and Y radii for the upper right corner int urX, int urY, // X and Y radii for the lower right corner int lrX, int lrY, // X and Y radii for the lower left corner int llX, int llY) : fName("blurroundrect") , fWidth(width) , fHeight(height) { fName.appendf("_WH[%ix%i]_UL[%ix%i]_UR[%ix%i]_LR[%ix%i]_LL[%ix%i]", width, height, ulX, ulY, urX, urY, lrX, lrY, llX, llY); fRadii[0].set(SkIntToScalar(ulX), SkIntToScalar(ulY)); fRadii[1].set(SkIntToScalar(urX), SkIntToScalar(urY)); fRadii[2].set(SkIntToScalar(lrX), SkIntToScalar(lrY)); fRadii[3].set(SkIntToScalar(llX), SkIntToScalar(llY)); } virtual const char* onGetName() SK_OVERRIDE { return fName.c_str(); } virtual SkIPoint onGetSize() SK_OVERRIDE { return SkIPoint::Make(fWidth, fHeight); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { for (int i = 0; i < this->getLoops(); i++) { SkLayerDrawLooper* looper = new SkLayerDrawLooper; { SkLayerDrawLooper::LayerInfo info; info.fFlagsMask = 0; info.fPaintBits = 40; info.fColorMode = SkXfermode::kSrc_Mode; info.fOffset = SkPoint::Make(SkIntToScalar(-1), SkIntToScalar(0)); info.fPostTranslate = false; SkPaint* paint = looper->addLayerOnTop(info); SkMaskFilter* maskFilter = SkBlurMaskFilter::Create(SK_ScalarHalf, SkBlurMaskFilter::kNormal_BlurStyle, SkBlurMaskFilter::kHighQuality_BlurFlag); paint->setMaskFilter(maskFilter)->unref(); SkColorFilter* colorFilter = SkColorFilter::CreateModeFilter(SK_ColorLTGRAY, SkXfermode::kSrcIn_Mode); paint->setColorFilter(colorFilter)->unref(); paint->setColor(SK_ColorGRAY); } { SkLayerDrawLooper::LayerInfo info; looper->addLayerOnTop(info); } SkPaint paint; SkRect rect = SkRect::MakeWH(SkIntToScalar(fWidth), SkIntToScalar(fHeight)); canvas->drawRect(rect, paint); paint.setLooper(looper)->unref(); paint.setAntiAlias(true); paint.setColor(SK_ColorCYAN); SkRRect rrect; rrect.setRectRadii(rect, fRadii); canvas->drawRRect(rrect, paint); } } private: SkString fName; const int fWidth; const int fHeight; SkVector fRadii[4]; typedef SkBenchmark INHERITED; }; // Create one with dimensions/rounded corners based on the skp DEF_BENCH(return new BlurRoundRectBench(600, 5514, 6, 6, 6, 6, 6, 6, 6, 6);) // Same radii, much smaller rectangle DEF_BENCH(return new BlurRoundRectBench(100, 100, 6, 6, 6, 6, 6, 6, 6, 6);) // Rounded rect with two opposite corners with large radii, the other two // small. DEF_BENCH(return new BlurRoundRectBench(100, 100, 30, 30, 10, 10, 30, 30, 10, 10);) DEF_BENCH(return new BlurRoundRectBench(100, 100, 90, 90, 90, 90, 90, 90, 90, 90);) <|endoftext|>
<commit_before>/** * File : D.cpp * Author : Kazune Takahashi * Created : 2018-4-7 21:10:12 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 1 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; ll A, B; int solve() { ll S = A * B; if (A > B) swap(A, B); if (S <= 2) return 0; ll ub = S; ll lb = 1; while (ub - lb > 1) { ll t = (ub + lb) / 2; if ((S+t)/(t+1) + 1 >= (S+t-1)/t) { ub = t; } else { lb = t; } } #if DEBUG == 1 cerr << "S = " << S << ", ub = " << ub << endl; #endif ll ans = (ub - 1) + ((S+ub-1) / ub - 1); ll X = ub - 1; ll Y = (S + ub - 1) / ub - 1; if (X > Y) swap(X, Y); if (B <= X) { ans -= 2; } else if (A > Y) { // } else { ans -= 1; } return ans; } int main() { int Q; cin >> Q; for (auto i = 0; i < Q; i++) { cin >> A >> B; cout << solve() << endl; } }<commit_msg>tried D.cpp to 'D'<commit_after>/** * File : D.cpp * Author : Kazune Takahashi * Created : 2018-4-7 21:10:12 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 1 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; ll A, B; int solve() { ll S = A * B; if (A > B) swap(A, B); if (S <= 2) return 0; ll ub = S; ll lb = 1; while (ub - lb > 1) { ll t = (ub + lb) / 2; if ((S+t)/(t+1) >= (S+t-1)/t) { ub = t; } else { lb = t; } } #if DEBUG == 1 cerr << "S = " << S << ", ub = " << ub << endl; #endif ll ans = (ub - 1) + ((S+ub-1) / ub - 1); ll X = ub - 1; ll Y = (S + ub - 1) / ub - 1; if (X > Y) swap(X, Y); if (B <= X) { ans -= 2; } else if (A > Y) { // } else { ans -= 1; } return ans; } int main() { int Q; cin >> Q; for (auto i = 0; i < Q; i++) { cin >> A >> B; cout << solve() << endl; } }<|endoftext|>
<commit_before>/** * File : F.cpp * Author : Kazune Takahashi * Created : 2018-4-15 23:25:04 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, M, Q; int a[50]; int l[50]; int r[50]; bool used[50]; ll solve() { ll ans = 0; for (auto i = 0; i < Q; i++) { int maxi = 0; for (auto j = l[i]; j <= r[i]; j++) { if (!used[j] && a[j] > maxi) { maxi = a[j]; } } // cerr << maxi << " "; ans += maxi; } // cerr << ", ans = " << ans << endl; return ans; } void solveA() { ll ans = 100000000; for (auto i = 0; i < (1 << N); i++) { int cnt = 0; for (auto j = 0; j < N; j++) { if ((i >> j) & 1) { cnt++; } } if (cnt == M) { for (auto j = 0; j < N; j++) { used[j] = (i >> j) & 1; } ans = min(ans, solve()); } } cout << ans << endl; } void solveB() { fill(used, used + N, false); int c[50]; fill(c, c + 50, 0); for (auto i = 0; i < Q; i++) { for (auto j = l[i]; j <= r[i]; j++) { c[j]++; } } vector< tuple<int, int> > V; for (auto i = 0; i < N; i++) { V.push_back(make_tuple(c[i], i)); } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); for (auto i = 0; i < M; i++) { used[get<1>(V[i])] = true; } cout << solve() << endl; } int main() { cin >> N >> M >> Q; for (auto i = 0; i < N; i++) { cin >> a[i]; } for (auto i = 0; i < Q; i++) { cin >> l[i] >> r[i]; l[i]--; r[i]--; } if (N <= 15) { solveA(); } else { solveB(); } }<commit_msg>submit F.cpp to 'F - Lunch Menu' (s8pc-5) [C++14 (GCC 5.4.1)]<commit_after>/** * File : F.cpp * Author : Kazune Takahashi * Created : 2018-4-15 23:25:04 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, M, Q; int a[50]; int l[50]; int r[50]; bool used[50]; ll solve() { ll ans = 0; for (auto i = 0; i < Q; i++) { int maxi = 0; for (auto j = l[i]; j <= r[i]; j++) { if (!used[j] && a[j] > maxi) { maxi = a[j]; } } // cerr << maxi << " "; ans += maxi; } // cerr << ", ans = " << ans << endl; return ans; } void solveA() { ll ans = 10000000000000; for (auto i = 0; i < (1 << N); i++) { int cnt = 0; for (auto j = 0; j < N; j++) { if ((i >> j) & 1) { cnt++; } } if (cnt == M) { for (auto j = 0; j < N; j++) { used[j] = (i >> j) & 1; } ans = min(ans, solve()); } } cout << ans << endl; } void solveB() { fill(used, used + N, false); int c[50]; fill(c, c + 50, 0); for (auto i = 0; i < Q; i++) { for (auto j = l[i]; j <= r[i]; j++) { c[j]++; } } vector< tuple<int, int> > V; for (auto i = 0; i < N; i++) { V.push_back(make_tuple(c[i], i)); } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); for (auto i = 0; i < M; i++) { used[get<1>(V[i])] = true; } cout << solve() << endl; } int main() { cin >> N >> M >> Q; for (auto i = 0; i < N; i++) { cin >> a[i]; } for (auto i = 0; i < Q; i++) { cin >> l[i] >> r[i]; l[i]--; r[i]--; } if (N <= 15) { solveA(); } else { solveB(); } }<|endoftext|>
<commit_before>/** * File : B.cpp * Author : Kazune Takahashi * Created : 2018-6-3 21:04:40 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. const int MAX_SIZE = 1000010; const long long MOD = 998244353; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; typedef long long ll; void init() { inv[1] = 1; for (int i = 2; i < MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD; } fact[0] = factinv[0] = 1; for (int i = 1; i < MAX_SIZE; i++) { fact[i] = (i * fact[i - 1]) % MOD; factinv[i] = (inv[i] * factinv[i - 1]) % MOD; } } long long C(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n % 2 == 1) { return (x * power(x, n - 1)) % MOD; } else { long long half = power(x, n / 2); return (half * half) % MOD; } } long long gcm(long long a, long long b) { if (a < b) { return gcm(b, a); } if (b == 0) return a; return gcm(b, a % b); } ll N, A, B, K; ll calc(ll k, ll l) { return (C(N, k) * C(N, l)) % MOD; } int main() { cin >> N >> A >> B >> K; ll g = gcm(A, B); if (K % g != 0) { cout << 0 << endl; return 0; } A /= g; B /= g; K /= g; ll ans = 0; for (ll k = 0; k <= N; k++) { ll BL = K - A * k; if (BL % B == 0) { ll l = BL / B; if (0 <= l && l <= N) { ans += calc(k, l); ans %= MOD; } } } cout << ans << endl; }<commit_msg>submit B.cpp to 'B - RGB Coloring' (agc025) [C++14 (GCC 5.4.1)]<commit_after>/** * File : B.cpp * Author : Kazune Takahashi * Created : 2018-6-3 21:04:40 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. const int MAX_SIZE = 1000010; const long long MOD = 998244353; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; typedef long long ll; void init() { inv[1] = 1; for (int i = 2; i < MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD; } fact[0] = factinv[0] = 1; for (int i = 1; i < MAX_SIZE; i++) { fact[i] = (i * fact[i - 1]) % MOD; factinv[i] = (inv[i] * factinv[i - 1]) % MOD; } } long long C(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n % 2 == 1) { return (x * power(x, n - 1)) % MOD; } else { long long half = power(x, n / 2); return (half * half) % MOD; } } long long gcm(long long a, long long b) { if (a < b) { return gcm(b, a); } if (b == 0) return a; return gcm(b, a % b); } ll N, A, B, K; ll calc(ll k, ll l) { return (C(N, k) * C(N, l)) % MOD; } int main() { init(); cin >> N >> A >> B >> K; ll g = gcm(A, B); if (K % g != 0) { cout << 0 << endl; return 0; } A /= g; B /= g; K /= g; ll ans = 0; for (ll k = 0; k <= N; k++) { ll BL = K - A * k; if (BL % B == 0) { ll l = BL / B; if (0 <= l && l <= N) { ans += calc(k, l); ans %= MOD; } } } cout << ans << endl; }<|endoftext|>
<commit_before>/** * File : C.cpp * Author : Kazune Takahashi * Created : 2018-8-25 20:45:21 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, K; ll x[100010]; vector<ll> V[2]; int main() { cin >> N >> K; for (auto i = 0; i < N; i++) { cin >> x[i]; } for (auto i = 0; i < N; i++) { if (x[i] > 0) { V[0].push_back(x[i]); } else { V[1].push_back(-x[i]); } } sort(V[1].begin(), V[1].end()); ll ans = 100000000000000; for (auto i = 0; i < 2; i++) { if ((int)V[i].size() >= K) { ans = min(ans, V[i][K - 1]); } } for (auto k = 0; k <= K; k++) { int l = K - k; if ((int)V[0].size() >= k && l >= 0 && (int)V[1].size() >= l) { ans = min(ans, V[0][k - 1] + 2 * V[1][l - 1]); ans = min(ans, 2 * V[0][k - 1] + V[1][l - 1]); } } cout << ans << endl; }<commit_msg>tried C.cpp to 'C'<commit_after>/** * File : C.cpp * Author : Kazune Takahashi * Created : 2018-8-25 20:45:21 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, K; ll x[100010]; vector<ll> V[2]; int main() { cin >> N >> K; for (auto i = 0; i < N; i++) { cin >> x[i]; } for (auto i = 0; i < N; i++) { if (x[i] > 0) { V[0].push_back(x[i]); } else { V[1].push_back(-1 * x[i]); } } sort(V[1].begin(), V[1].end()); for (auto x : V[0]) { cerr << x << endl; } cerr << " " << endl; for (auto x : V[1]) { cerr << x << endl; } ll ans = 100000000000000; for (auto i = 0; i < 2; i++) { if ((int)V[i].size() >= K) { ans = min(ans, V[i][K - 1]); } } for (auto k = 0; k <= K; k++) { int l = K - k; if ((int)V[0].size() >= k && (int)V[1].size() >= l) { ans = min(ans, V[0][k - 1] + 2 * V[1][l - 1]); ans = min(ans, 2 * V[0][k - 1] + V[1][l - 1]); } } cout << ans << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 3/9/2019, 9:11:28 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; ll A, B; ll X(ll L) { ll ans = 0; for (auto i = 0; i < 60; i++) { ll M = (1LL << (i + 1)); ll cnt = L % M; #if DEBUG == 1 cerr << "M = " << M << ", cnt = " << cnt << endl; #endif if (cnt >= M / 2) { cnt -= M / 2; if (cnt % 2 == 1) { ans += (1LL << i); } } } return ans; } int main() { cin >> A >> B; cout << (X(A) ^ X(B)) << endl; }<commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 3/9/2019, 9:11:28 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; ll A, B; ll X(ll L) { ll ans = 0; for (auto i = 0; i < 60; i++) { ll M = (1LL << (i + 1)); ll cnt = L % M; #if DEBUG == 1 cerr << "M = " << M << ", cnt = " << cnt << endl; #endif if (cnt >= M / 2) { cnt -= M / 2; if (cnt % 2 == 1) { ans += (1LL << i); } } #if DEBUG == 1 cerr << "ans = " << ans << endl; #endif } return ans; } int main() { cin >> A >> B; cout << (X(A) ^ X(B)) << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 11/18/2019, 8:58:07 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{3000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator==(const Mint &a) const { return x == a.x; } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- void add_edge(map<int, int> &m, int h, int d) { if (m.find(h) == m.end()) { m[h] = d; } else { ch_max(m[h], d); } } void calc_high(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d) { add_edge(M[i + 1], A[i + 1] - (A[i] - h), d); add_edge(M[i + 1], h, d + 1); add_edge(M[i + 1], 0, d + 2); } void calc_low(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d) { if (h <= A[i + 1]) { add_edge(M[i + 1], h, d); } add_edge(M[i + 1], max(0, A[i + 1] - (A[i] - h)), d + 1); add_edge(M[i + 1], 0, d + 2); } void eliminate(map<int, int> &m) { int now{m[0]}; map<int, int> k; for (auto const &x : m) { if (x.second == now) { k.insert(x); --now; } } swap(m, k); } void calc(vector<int> const &A, vector<map<int, int>> &M, int i, pair<int, int> const &x) { int h{x.first}; int d{x.second}; if (A[i] <= A[i + 1]) { calc_high(A, M, i, h, d); } else { calc_low(A, M, i, h, d); } #if DEBUG == 1 for (auto const &x : M[i + 1]) { cerr << "M[" << i + 1 << "][" << x.first << "] = " << x.second << endl; } #endif eliminate(M[i + 1]); } int main() { int N; cin >> N; vector<int> A(N + 1, 0); for (auto i = 1; i <= N; i++) { cin >> A[i]; } vector<map<int, int>> M(N + 1); M[0][0] = 0; for (auto i = 0; i < N; i++) { for (auto const &x : M[i]) { calc(A, M, i, x); } } cout << M[N].end()->second << endl; } <commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 11/18/2019, 8:58:07 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{3000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator==(const Mint &a) const { return x == a.x; } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- void add_edge(map<int, int> &m, int h, int d) { if (m.find(h) == m.end()) { m[h] = d; } else { ch_min(m[h], d); } } void calc_high(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d) { add_edge(M[i + 1], A[i + 1] - (A[i] - h), d); add_edge(M[i + 1], h, d + 1); add_edge(M[i + 1], 0, d + 2); } void calc_low(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d) { if (h <= A[i + 1]) { add_edge(M[i + 1], h, d); } add_edge(M[i + 1], max(0, A[i + 1] - (A[i] - h)), d + 1); add_edge(M[i + 1], 0, d + 2); } void eliminate(map<int, int> &m) { int now{m[0]}; map<int, int> k; for (auto const &x : m) { if (x.second == now) { k.insert(x); --now; } } swap(m, k); } void calc(vector<int> const &A, vector<map<int, int>> &M, int i, pair<int, int> const &x) { int h{x.first}; int d{x.second}; if (A[i] <= A[i + 1]) { calc_high(A, M, i, h, d); } else { calc_low(A, M, i, h, d); } #if DEBUG == 1 for (auto const &x : M[i + 1]) { cerr << "M[" << i + 1 << "][" << x.first << "] = " << x.second << endl; } #endif eliminate(M[i + 1]); } int main() { int N; cin >> N; vector<int> A(N + 1, 0); for (auto i = 1; i <= N; i++) { cin >> A[i]; } vector<map<int, int>> M(N + 1); M[0][0] = 0; for (auto i = 0; i < N; i++) { for (auto const &x : M[i]) { calc(A, M, i, x); } } cout << M[N].end()->second << endl; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 4/23/2020, 7:08:47 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Point ----- using Point = tuple<int, int>; ostream &operator<<(ostream &os, Point const &pt) { return os << get<0>(pt) << " " << get<1>(pt); } // ----- Cycle ----- class Cycle { int num; bool pos; public: Cycle(int num, bool pos) : num{num}, pos{pos} {} vector<Point> path() const { vector<Point> ans; for (auto i = 0; i <= num; ++i) { ans.push_back(Point(i, 0)); } if (pos) { ans.push_back(Point(num + 1, 0)); ans.push_back(Point(num + 1, 1)); ans.push_back(Point(num, 1)); } else { ans.push_back(Point(num, 1)); ans.push_back(Point(num + 1, 1)); ans.push_back(Point(num + 1, 0)); } for (auto i = num; i >= 1; --i) { ans.push_back(Point(i, 0)); } return ans; } Cycle inv() const { return Cycle(num, !pos); } }; class Chain { vector<Cycle> V; public: Chain() {} Chain(Cycle c) : V{c} {} Chain(vector<Cycle> V) : V(V) {} Chain(int mask) { #if DEBUG == 1 cerr << "mask = " << mask << endl; #endif int cnt{0}; while ((mask >> cnt) != 0) { if ((mask >> cnt) & 1) { merge(cnt); } ++cnt; } } vector<Point> path() const { vector<Point> ans; for (auto const &e : V) { auto tmp{e.path()}; copy(tmp.begin(), tmp.end(), back_inserter(ans)); } return ans; } vector<Cycle> const &seq() const { return V; } void operator+=(Chain const &other) { copy(other.seq().begin(), other.seq().end(), back_inserter(V)); } private: void merge(int n) { if (V.empty()) { V.push_back(Cycle{n, true}); } else { auto inverse{inv()}; *this += Chain{Cycle{n, true}}; *this += inverse; *this += Chain{Cycle{n, false}}; } } Chain inv() const { vector<Cycle> W; for (auto it = V.rbegin(); it != V.rend(); ++it) { W.push_back(it->inv()); } return Chain(W); } }; // ----- Solve ----- class Solve { int N; vector<bool> V; Chain C; bool possible; public: Solve(int N, string A) : N{N}, V(1 << N), possible{true} { for (auto i = 0; i < 1 << N; ++i) { V[i] = (A[i] == '1'); } } void answer() { if (check()) { construct(); } else { possible = false; } flush(); } private: bool check() const { for (auto i = 0; i < 1 << N; ++i) { for (auto j = 0; j < 1 << N; ++j) { if ((i & j) == j) { if (!V[j] && V[i]) { return false; } } } } return true; } void construct() { for (auto i = 0; i < 1 << N; ++i) { if (V[i]) { continue; } #if DEBUG == 1 cerr << "i = " << i << endl; #endif bool create{true}; for (auto j = 0; j < 1 << N; ++j) { if ((i & j) == j && !V[j]) { create = false; break; } } if (create) { C += Chain{i}; } } } void flush() const { if (possible) { cout << "Possible" << endl; } else { cout << "Impossible" << endl; return; } auto tmp{C.path()}; cout << tmp.size() << endl; for (auto const &e : tmp) { cout << e << endl; } } }; // ----- main() ----- int main() { int N; cin >> N; string A; cin >> A; Solve solve(N, A); solve.answer(); } <commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 4/23/2020, 7:08:47 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Point ----- using Point = tuple<int, int>; ostream &operator<<(ostream &os, Point const &pt) { return os << get<0>(pt) << " " << get<1>(pt); } // ----- Cycle ----- class Cycle { int num; bool pos; public: Cycle(int num, bool pos) : num{num}, pos{pos} {} vector<Point> path() const { vector<Point> ans; for (auto i = 0; i <= num; ++i) { ans.push_back(Point(i, 0)); } if (pos) { ans.push_back(Point(num + 1, 0)); ans.push_back(Point(num + 1, 1)); ans.push_back(Point(num, 1)); } else { ans.push_back(Point(num, 1)); ans.push_back(Point(num + 1, 1)); ans.push_back(Point(num + 1, 0)); } for (auto i = num; i >= 1; --i) { ans.push_back(Point(i, 0)); } return ans; } Cycle inv() const { return Cycle(num, !pos); } }; class Chain { vector<Cycle> V; public: Chain() {} Chain(Cycle c) : V{c} {} Chain(vector<Cycle> V) : V(V) {} Chain(int mask) { #if DEBUG == 1 cerr << "mask = " << mask << endl; #endif int cnt{0}; while ((mask >> cnt) != 0) { if ((mask >> cnt) & 1) { merge(cnt); } ++cnt; } } vector<Point> path() const { vector<Point> ans; for (auto const &e : V) { auto tmp{e.path()}; copy(tmp.begin(), tmp.end(), back_inserter(ans)); } return ans; } vector<Cycle> const &seq() const { return V; } void operator+=(Chain const &other) { copy(other.seq().begin(), other.seq().end(), back_inserter(V)); } private: void merge(int n) { if (V.empty()) { V.push_back(Cycle{n, true}); } else { auto inverse{inv()}; *this += Chain{Cycle{n, true}}; *this += inverse; *this += Chain{Cycle{n, false}}; } } Chain inv() const { vector<Cycle> W; for (auto it = V.rbegin(); it != V.rend(); ++it) { W.push_back(it->inv()); } return Chain(W); } }; // ----- Solve ----- class Solve { int N; vector<bool> V; Chain C; bool possible; public: Solve(int N, string A) : N{N}, V(1 << N), possible{true} { for (auto i = 0; i < 1 << N; ++i) { V[i] = (A[i] == '1'); } } void answer() { if (check()) { construct(); } else { possible = false; } flush(); } private: bool check() const { if (!V[0]) { return false; } for (auto i = 0; i < 1 << N; ++i) { for (auto j = 0; j < 1 << N; ++j) { if ((i & j) == j) { if (!V[j] && V[i]) { return false; } } } } return true; } void construct() { for (auto i = 0; i < 1 << N; ++i) { if (V[i]) { continue; } #if DEBUG == 1 cerr << "i = " << i << endl; #endif bool create{true}; for (auto j = 0; j < 1 << N; ++j) { if ((i & j) == j && !V[j]) { create = false; break; } } if (create) { C += Chain{i}; } } } void flush() const { if (possible) { cout << "Possible" << endl; } else { cout << "Impossible" << endl; return; } auto tmp{C.path()}; cout << tmp.size() << endl; tmp.push_back(Point(0, 0)); for (auto const &e : tmp) { cout << e << endl; } } }; // ----- main() ----- int main() { int N; cin >> N; string A; cin >> A; Solve solve(N, A); solve.answer(); } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2020/6/23 1:01:43 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/integer/common_factor_rt.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::integer::gcd; // for C++14 or for cpp_int using boost::integer::lcm; // for C++14 or for cpp_int using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; // ----- for C++17 ----- template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr> size_t popcount(T x) { return bitset<64>(x).count(); } size_t popcount(string const &S) { return bitset<200010>{S}.count(); } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- class Solve { ll N, K; map<ll, mint> M; public: Solve(ll N, ll K) : N{N}, K{K} { #if DEBUG == 1 cerr << "N = " << N << ", K = " << K << endl; #endif } void flush() { mint ans{0}; auto V{table()}; for (auto i{1LL}; i <= K; ++i) { ans += V[i] * i; #if DEBUG == 1 if (K == 2) { cerr << "V[" << i << "] = " << V[i] << endl; } #endif } cout << ans << endl; } private: vector<mint> table() { vector<mint> V(K + 1, 0); for (auto X{K}; X >= 1; --X) { V[X] = count(K); for (auto i{2LL};; ++i) { if (auto t{X * i}; t <= K) { V[X] -= V[t]; } else { break; } } } return V; } mint count(ll X) { return mint{K / X}.power(N); } }; // ----- main() ----- int main() { ll N, K; cin >> N >> K; Solve solve(N, K); solve.flush(); } <commit_msg>submit E.cpp to 'E - Sum of gcd of Tuples (Hard)' (abc162) [C++ (GCC 9.2.1)]<commit_after>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2020/6/23 1:01:43 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/integer/common_factor_rt.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::integer::gcd; // for C++14 or for cpp_int using boost::integer::lcm; // for C++14 or for cpp_int using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; // ----- for C++17 ----- template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr> size_t popcount(T x) { return bitset<64>(x).count(); } size_t popcount(string const &S) { return bitset<200010>{S}.count(); } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- class Solve { ll N, K; map<ll, mint> M; public: Solve(ll N, ll K) : N{N}, K{K} { #if DEBUG == 1 cerr << "N = " << N << ", K = " << K << endl; #endif } void flush() { mint ans{0}; auto V{table()}; for (auto i{1LL}; i <= K; ++i) { ans += V[i] * i; #if DEBUG == 1 if (K == 2) { cerr << "V[" << i << "] = " << V[i] << endl; } #endif } cout << ans << endl; } private: vector<mint> table() { vector<mint> V(K + 1, 0); for (auto X{K}; X >= 1; --X) { V[X] = count(X); for (auto i{2LL};; ++i) { if (auto t{X * i}; t <= K) { V[X] -= V[t]; } else { break; } } } return V; } mint count(ll X) { return mint{K / X}.power(N); } }; // ----- main() ----- int main() { ll N, K; cin >> N >> K; Solve solve(N, K); solve.flush(); } <|endoftext|>
<commit_before>//===--- Action.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open // Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Action class - implementation and auxiliary functions. // //===----------------------------------------------------------------------===// #include "llvm/CompilerDriver/Action.h" #include "llvm/CompilerDriver/BuiltinOptions.h" #include "llvm/CompilerDriver/Error.h" #include "llvm/CompilerDriver/Main.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/SystemUtils.h" #include "llvm/System/Program.h" #include "llvm/System/TimeValue.h" #include <stdexcept> #include <string> using namespace llvm; using namespace llvmc; namespace llvmc { extern const char* ProgramName; } namespace { void PrintString (const std::string& str) { errs() << str << ' '; } void PrintCommand (const std::string& Cmd, const StrVector& Args) { errs() << Cmd << ' '; std::for_each(Args.begin(), Args.end(), &PrintString); errs() << '\n'; } bool IsSegmentationFault (int returnCode) { #ifdef LLVM_ON_WIN32 return (returnCode >= 0xc0000000UL) #else return (returnCode < 0); #endif } int ExecuteProgram (const std::string& name, const StrVector& args) { sys::Path prog(name); if (!prog.isAbsolute()) prog = FindExecutable(name, ProgramName, (void *)(intptr_t)&Main); if (prog.isEmpty()) { prog = sys::Program::FindProgramByName(name); if (prog.isEmpty()) { PrintError("Can't find program '" + name + "'"); return -1; } } if (!prog.canExecute()) { PrintError("Program '" + name + "' is not executable."); return -1; } // Build the command line vector and the redirects array. const sys::Path* redirects[3] = {0,0,0}; sys::Path stdout_redirect; std::vector<const char*> argv; argv.reserve((args.size()+2)); argv.push_back(name.c_str()); for (StrVector::const_iterator B = args.begin(), E = args.end(); B!=E; ++B) { if (*B == ">") { ++B; stdout_redirect.set(*B); redirects[1] = &stdout_redirect; } else { argv.push_back((*B).c_str()); } } argv.push_back(0); // null terminate list. // Invoke the program. int ret = sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]); if (IsSegmentationFault(ret)) { errs() << "Segmentation fault: "; PrintCommand(name, args); } return ret; } } namespace llvmc { void AppendToGlobalTimeLog (const std::string& cmd, double time); } int llvmc::Action::Execute () const { if (DryRun || VerboseMode) PrintCommand(Command_, Args_); if (!DryRun) { if (Time) { sys::TimeValue now = sys::TimeValue::now(); int ret = ExecuteProgram(Command_, Args_); sys::TimeValue now2 = sys::TimeValue::now(); now2 -= now; double elapsed = now2.seconds() + now2.microseconds() / 1000000.0; AppendToGlobalTimeLog(Command_, elapsed); return ret; } else { return ExecuteProgram(Command_, Args_); } } return 0; } <commit_msg>llvmc: Fix tool finding logic.<commit_after>//===--- Action.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open // Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Action class - implementation and auxiliary functions. // //===----------------------------------------------------------------------===// #include "llvm/CompilerDriver/Action.h" #include "llvm/CompilerDriver/BuiltinOptions.h" #include "llvm/CompilerDriver/Error.h" #include "llvm/CompilerDriver/Main.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/SystemUtils.h" #include "llvm/System/Program.h" #include "llvm/System/TimeValue.h" #include <stdexcept> #include <string> using namespace llvm; using namespace llvmc; namespace llvmc { extern const char* ProgramName; } namespace { void PrintString (const std::string& str) { errs() << str << ' '; } void PrintCommand (const std::string& Cmd, const StrVector& Args) { errs() << Cmd << ' '; std::for_each(Args.begin(), Args.end(), &PrintString); errs() << '\n'; } bool IsSegmentationFault (int returnCode) { #ifdef LLVM_ON_WIN32 return (returnCode >= 0xc0000000UL) #else return (returnCode < 0); #endif } int ExecuteProgram (const std::string& name, const StrVector& args) { sys::Path prog(name); if (!prog.isAbsolute()) { prog = FindExecutable(name, ProgramName, (void *)(intptr_t)&Main); if (!prog.canExecute()) { prog = sys::Program::FindProgramByName(name); if (prog.isEmpty()) { PrintError("Can't find program '" + name + "'"); return -1; } } } if (!prog.canExecute()) { PrintError("Program '" + name + "' is not executable."); return -1; } // Build the command line vector and the redirects array. const sys::Path* redirects[3] = {0,0,0}; sys::Path stdout_redirect; std::vector<const char*> argv; argv.reserve((args.size()+2)); argv.push_back(name.c_str()); for (StrVector::const_iterator B = args.begin(), E = args.end(); B!=E; ++B) { if (*B == ">") { ++B; stdout_redirect.set(*B); redirects[1] = &stdout_redirect; } else { argv.push_back((*B).c_str()); } } argv.push_back(0); // null terminate list. // Invoke the program. int ret = sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]); if (IsSegmentationFault(ret)) { errs() << "Segmentation fault: "; PrintCommand(name, args); } return ret; } } namespace llvmc { void AppendToGlobalTimeLog (const std::string& cmd, double time); } int llvmc::Action::Execute () const { if (DryRun || VerboseMode) PrintCommand(Command_, Args_); if (!DryRun) { if (Time) { sys::TimeValue now = sys::TimeValue::now(); int ret = ExecuteProgram(Command_, Args_); sys::TimeValue now2 = sys::TimeValue::now(); now2 -= now; double elapsed = now2.seconds() + now2.microseconds() / 1000000.0; AppendToGlobalTimeLog(Command_, elapsed); return ret; } else { return ExecuteProgram(Command_, Args_); } } return 0; } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Sven Kaulmann #ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #include <dune/common/fvector.hh> #include <dune/grid/common/backuprestore.hh> #include <dune/grid/common/grid.hh> #include <dune/grid/common/entity.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/fem/namespace.hh> #if HAVE_DUNE_FEM #include <dune/fem/function/common/discretefunction.hh> #include <dune/fem/quadrature/cachingquadrature.hh> #include <dune/fem/space/finitevolume.hh> #include <dune/fem/space/lagrange.hh> #endif #include <dune/grid/io/file/vtk/function.hh> #include <dune/stuff/grid/search.hh> namespace Dune { namespace Stuff { #if HAVE_DUNE_FEM template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>& space, const typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::EntityType& target_entity) { const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity); const auto& target_geometry = target_entity.geometry(); const auto quadNop = target_lagrangepoint_set.nop(); std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> points(quadNop); for(size_t qP = 0; qP < quadNop ; ++qP) { points[qP] = target_geometry.global(target_lagrangepoint_set.point(qP)); } return points; } template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::FiniteVolumeSpace<F,G,p,S>& /*space*/, const typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::EntityType& target_entity) { assert(false); typedef std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> Ret; return Ret(1, target_entity.geometry().center()); } template< template< class > class SearchStrategy = Grid::EntityInlevelSearch > class HeterogenousProjection { public: /** If your SearchStrategy only takes a leafview of the source grid, you may use this signature. * Otherwise you'll have to provide an instance of the SearchStrategy to the method below **/ template < class SourceDFImp, class TargetDFImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target) { SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView()); project(source, target, search); } //! signature for non-default SearchStrategy constructions template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target, SearchStrategyImp& search) { typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType; static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange; const auto& space = target.space(); // set all DoFs to infinity preprocess(target); const auto endit = space.end(); for(auto it = space.begin(); it != endit ; ++it) { const auto& target_entity = *it; auto target_local_function = target.localFunction(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); int k = 0; typename TargetDiscreteFunctionSpaceType::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { if(std::isinf(target_local_function[ k ])) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& source_local_function = source.localFunction(*source_entity_ptr); source_local_function.evaluate(source_local_point, source_value); for(int i = 0; i < target_dimRange; ++i, ++k) setDofValue(target_local_function[k], source_value[i]); } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } else k += target_dimRange; } } postprocess(target); } // ... project(...) protected: template<class TargetDFImp> static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) { typedef typename TargetDFImp::DofType TargetDofType; const auto infinity = DSC::numeric_limits< TargetDofType >::infinity(); // set all DoFs to infinity const auto dend = func.dend(); for( auto dit = func.dbegin(); dit != dend; ++dit ) *dit = infinity; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof = value; } template<class TargetDFImp> static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& /*func*/) { return; } }; // class HeterogenousProjection template< template< class > class SearchStrategy = Grid::EntityInlevelSearch > class MsFEMProjection { public: //! signature for non-default SearchStrategy constructions template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target, SearchStrategyImp& search) { typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType; static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange; const auto& space = target.space(); // set all DoFs to infinity preprocess(target); const auto endit = space.end(); for(auto it = space.begin(); it != endit ; ++it) { const auto& target_entity = *it; auto target_local_function = target.localFunction(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); int k = 0; typename TargetDiscreteFunctionSpaceType::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& source_local_function = source.localFunction(*source_entity_ptr); source_local_function.evaluate(source_local_point, source_value); for(int i = 0; i < target_dimRange; ++i, ++k) setDofValue(target_local_function[k], source_value[i]); } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } } postprocess(target); } // ... project(...) protected: template<class TargetDFImp> static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) { // set all DoFs to zero const auto dend = func.dend(); for( auto dit = func.dbegin(); dit != dend; ++dit ) *dit = 0.0; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof += value; } template<class TargetDFImp> static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) { // compute node to entity relations typedef Dune::Fem::DiscreteFunctionInterface<TargetDFImp> DiscFuncType; const static int dimension = DiscFuncType::DiscreteFunctionSpaceType::GridPartType::GridType::dimension; std::vector<int> nodeToEntity(func.space().gridPart().grid().size(dimension), 0); identifySharedNodes(func.space().gridPart(), nodeToEntity); const auto dend = func.dend(); auto factorsIt = nodeToEntity.begin(); for (auto dit = func.dbegin(); dit!=dend; ++dit) { assert(factorsIt!=nodeToEntity.end()); assert(*factorsIt>0); *dit /= *factorsIt; ++factorsIt; } return; } template<class GridPartType, class MapType> static void identifySharedNodes(const GridPartType& gridPart, MapType& map) { typedef typename GridPartType::GridType GridType; const auto& indexSet = gridPart.indexSet(); for (auto& entity : DSC::viewRange(gridPart.grid().leafGridView())) { int number_of_nodes_in_entity = entity.template count<GridType::dimension>(); for (int i = 0; i < number_of_nodes_in_entity; ++i) { const auto node = entity.template subEntity<GridType::dimension>(i); const auto global_index_node = indexSet.index(*node); // make sure we don't access non-existing elements assert(map.size() > global_index_node); ++map[global_index_node]; } } } }; #endif // HAVE_DUNE_FEM } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH <commit_msg>doc and whitespace<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Sven Kaulmann #ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #include <dune/common/fvector.hh> #include <dune/grid/common/backuprestore.hh> #include <dune/grid/common/grid.hh> #include <dune/grid/common/entity.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/fem/namespace.hh> #if HAVE_DUNE_FEM #include <dune/fem/function/common/discretefunction.hh> #include <dune/fem/quadrature/cachingquadrature.hh> #include <dune/fem/space/finitevolume.hh> #include <dune/fem/space/lagrange.hh> #endif #include <dune/grid/io/file/vtk/function.hh> #include <dune/stuff/grid/search.hh> namespace Dune { namespace Stuff { #if HAVE_DUNE_FEM template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>& space, const typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::EntityType& target_entity) { const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity); const auto& target_geometry = target_entity.geometry(); const auto quadNop = target_lagrangepoint_set.nop(); std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> points(quadNop); for(size_t qP = 0; qP < quadNop ; ++qP) { points[qP] = target_geometry.global(target_lagrangepoint_set.point(qP)); } return points; } template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::FiniteVolumeSpace<F,G,p,S>& /*space*/, const typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::EntityType& target_entity) { assert(false); typedef std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> Ret; return Ret(1, target_entity.geometry().center()); } template< template< class > class SearchStrategy = Grid::EntityInlevelSearch > class HeterogenousProjection { public: /** If your SearchStrategy only takes a leafview of the source grid, you may use this signature. * Otherwise you'll have to provide an instance of the SearchStrategy to the method below **/ template < class SourceDFImp, class TargetDFImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target) { SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView()); project(source, target, search); } //! signature for non-default SearchStrategy constructions template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target, SearchStrategyImp& search) { typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType; static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange; const auto& space = target.space(); // set all DoFs to infinity preprocess(target); const auto endit = space.end(); for(auto it = space.begin(); it != endit ; ++it) { const auto& target_entity = *it; auto target_local_function = target.localFunction(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); int k = 0; typename TargetDiscreteFunctionSpaceType::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { if(std::isinf(target_local_function[ k ])) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& source_local_function = source.localFunction(*source_entity_ptr); source_local_function.evaluate(source_local_point, source_value); for(int i = 0; i < target_dimRange; ++i, ++k) setDofValue(target_local_function[k], source_value[i]); } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } else k += target_dimRange; } } postprocess(target); } // ... project(...) protected: template<class TargetDFImp> static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) { typedef typename TargetDFImp::DofType TargetDofType; const auto infinity = DSC::numeric_limits< TargetDofType >::infinity(); // set all DoFs to infinity const auto dend = func.dend(); for( auto dit = func.dbegin(); dit != dend; ++dit ) *dit = infinity; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof = value; } template<class TargetDFImp> static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& /*func*/) { return; } }; // class HeterogenousProjection template< template< class > class SearchStrategy = Grid::EntityInlevelSearch > class MsFEMProjection { public: //! signature for non-default SearchStrategy constructions template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target, SearchStrategyImp& search) { typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType; static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange; const auto& space = target.space(); preprocess(target); const auto endit = space.end(); for(auto it = space.begin(); it != endit ; ++it) { const auto& target_entity = *it; auto target_local_function = target.localFunction(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); int k = 0; typename TargetDiscreteFunctionSpaceType::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& source_local_function = source.localFunction(*source_entity_ptr); source_local_function.evaluate(source_local_point, source_value); for(int i = 0; i < target_dimRange; ++i, ++k) setDofValue(target_local_function[k], source_value[i]); } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } } postprocess(target); } // ... project(...) protected: template<class TargetDFImp> static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) { // set all DoFs to zero const auto dend = func.dend(); for( auto dit = func.dbegin(); dit != dend; ++dit ) *dit = 0.0; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof += value; } template<class TargetDFImp> static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) { // compute node to entity relations typedef Dune::Fem::DiscreteFunctionInterface<TargetDFImp> DiscFuncType; const static int dimension = DiscFuncType::DiscreteFunctionSpaceType::GridPartType::GridType::dimension; std::vector<int> nodeToEntity(func.space().gridPart().grid().size(dimension), 0); identifySharedNodes(func.space().gridPart(), nodeToEntity); const auto dend = func.dend(); auto factorsIt = nodeToEntity.begin(); for (auto dit = func.dbegin(); dit!=dend; ++dit) { assert(factorsIt!=nodeToEntity.end()); assert(*factorsIt>0); *dit /= *factorsIt; ++factorsIt; } return; } template<class GridPartType, class MapType> static void identifySharedNodes(const GridPartType& gridPart, MapType& map) { typedef typename GridPartType::GridType GridType; const auto& indexSet = gridPart.indexSet(); for (auto& entity : DSC::viewRange(gridPart.grid().leafGridView())) { int number_of_nodes_in_entity = entity.template count<GridType::dimension>(); for (int i = 0; i < number_of_nodes_in_entity; ++i) { const auto node = entity.template subEntity<GridType::dimension>(i); const auto global_index_node = indexSet.index(*node); // make sure we don't access non-existing elements assert(map.size() > global_index_node); ++map[global_index_node]; } } } }; #endif // HAVE_DUNE_FEM } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH <|endoftext|>
<commit_before>#include "souper/Infer/DataflowPruning.h" namespace souper { namespace { using souper::dataflow::EvalValue; using souper::dataflow::ValueCache; EvalValue evaluateInstRecursive(souper::Inst* Inst, std::vector<EvalValue> args) { switch (Inst->K) { case souper::Inst::Const: return {Inst->Val}; case souper::Inst::UntypedConst: return {Inst->Val}; case souper::Inst::Var: llvm_unreachable("Should get value from cache without reaching here"); case souper::Inst::Add: return {args[0].getValue() + args[1].getValue()}; case souper::Inst::Sub: return {args[0].getValue() - args[1].getValue()}; case souper::Inst::Mul: return {args[0].getValue() * args[1].getValue()}; case souper::Inst::UDiv: return {args[0].getValue().udiv(args[1].getValue())}; case souper::Inst::SDiv: return {args[0].getValue().sdiv(args[1].getValue())}; case souper::Inst::URem: return {args[0].getValue().urem(args[1].getValue())}; case souper::Inst::SRem: return {args[0].getValue().srem(args[1].getValue())}; case souper::Inst::And: return {args[0].getValue() & args[1].getValue()}; case souper::Inst::Or: return {args[0].getValue() | args[1].getValue()}; case souper::Inst::Xor: return {args[0].getValue() ^ args[1].getValue()}; case souper::Inst::Shl: return {args[0].getValue() << args[1].getValue()}; case souper::Inst::LShr: return {args[0].getValue().lshr(args[1].getValue())}; case souper::Inst::AShr: return {args[0].getValue().ashr(args[1].getValue())}; // TODO: Handle NSW/NUW/NW variants of instructions case souper::Inst::Select: { if (!args[0].hasValue()) { return args[0]; } else { bool cond = args[0].getValue().getBoolValue(); return cond ? args[1] : args[2]; } } case souper::Inst::ZExt: return {args[0].getValue().zext(Inst->Width)}; case souper::Inst::SExt: return {args[0].getValue().sext(Inst->Width)}; case souper::Inst::Trunc: return {args[0].getValue().trunc(Inst->Width)}; case souper::Inst::Eq: return {{1, args[0].getValue() == args[1].getValue()}}; case souper::Inst::Ne: return {{1, args[0].getValue() != args[1].getValue()}}; case souper::Inst::Ult: return {{1, args[0].getValue().ult(args[1].getValue())}}; case souper::Inst::Slt: return {{1, args[0].getValue().slt(args[1].getValue())}}; case souper::Inst::Ule: return {{1, args[0].getValue().ule(args[1].getValue())}}; case souper::Inst::Sle: return {{1, args[0].getValue().sle(args[1].getValue())}}; case souper::Inst::CtPop: return {llvm::APInt(Inst->Width, args[0].getValue().countPopulation())}; case souper::Inst::Ctlz: return {llvm::APInt(Inst->Width, args[0].getValue().countLeadingZeros())}; case souper::Inst::Cttz: return {llvm::APInt(Inst->Width, args[0].getValue().countTrailingZeros())}; case souper::Inst::BSwap: return {args[0].getValue().byteSwap()}; default: return EvalValue(); // Indicates an 'unavailable' value } } } // Errs on the side of an 'unavailable' result // TODO: Some instructions unimplemented EvalValue souper::dataflow::evaluateInst(souper::Inst* Root, ValueCache &Cache) { std::vector<EvalValue> EvaluatedArgs; EvalValue Result; if (Root->K == souper::Inst::Var) { Result = Cache[Root]; } else { for (auto &&I : Root->Ops) { auto eval = evaluateInst(I, Cache); if (!eval.hasValue() && Root->K != souper::Inst::Select) { return Result; // result is `Unavailable` if args fail to evaluate } EvaluatedArgs.push_back(eval); } Result = evaluateInstRecursive(Root, EvaluatedArgs); } return Result; } EvalValue getValue(Inst *I, ValueCache &C) { if (I->K == souper::Inst::Const) { return {I->Val}; } else if (I->K == souper::Inst::Var || I->K == souper::Inst::ReservedConst || I->K == souper::Inst::ReservedInst) { if (I->Name != "" && C.find(I) != C.end()) { return C[I]; } else { return EvalValue(); // unavailable } } return EvalValue(); } llvm::KnownBits dataflow::findKnownBits(Inst* I, ValueCache& C) { llvm::KnownBits Result(I->Width); switch(I->K) { case souper::Inst::Const: case souper::Inst::Var : { EvalValue V = getValue(I, C); if (V.hasValue()) { Result.One = V.getValue(); Result.Zero = ~V.getValue(); return Result; } else { return Result; } } case souper::Inst::Shl : { auto Op0KB = findKnownBits(I->Ops[0], C); auto Op1V = getValue(I->Ops[1], C); if (Op1V.hasValue()) { Op0KB.One <<= Op1V.getValue(); Op0KB.Zero <<= Op1V.getValue(); Op0KB.Zero.setLowBits(Op1V.getValue().getLimitedValue()); // setLowBits takes an unsiged int, so getLimitedValue is harmless return Op0KB; } else { return Result; } } case souper::Inst::And : { auto Op0KB = findKnownBits(I->Ops[0], C); auto Op1KB = findKnownBits(I->Ops[1], C); Op0KB.One &= Op1KB.One; Op0KB.Zero |= Op1KB.Zero; return Op0KB; } case souper::Inst::Or : { auto Op0KB = findKnownBits(I->Ops[0], C); auto Op1KB = findKnownBits(I->Ops[1], C); Op0KB.One |= Op1KB.One; Op0KB.Zero &= Op1KB.Zero; return Op0KB; } case souper::Inst::Xor : { auto Op0KB = findKnownBits(I->Ops[0], C); auto Op1KB = findKnownBits(I->Ops[1], C); llvm::APInt KnownZeroOut = (Op0KB.Zero & Op1KB.Zero) | (Op0KB.One & Op1KB.One); Op0KB.One = (Op0KB.Zero & Op1KB.One) | (Op0KB.One & Op1KB.Zero); Op0KB.Zero = std::move(KnownZeroOut); // ^ logic copied from LLVM ValueTracking.cpp return Op0KB; } default : return Result; } } llvm::ConstantRange dataflow::findConstantRange(souper::Inst* I, souper::ValueCache& C) { llvm::ConstantRange result(I->Width); switch (I->K) { case souper::Inst::Const: case souper::Inst::Var : { EvalValue V = getValue(I, C); if (V.hasValue()) { return llvm::ConstantRange(V.getValue()); } else { return result; // Whole range } } case souper::Inst::Add: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.add(R1); } case souper::Inst::AddNSW: { auto R0 = findConstantRange(I->Ops[0], C); auto V1 = getValue(I->Ops[1], C); if (V1.hasValue()) { return R0.addWithNoSignedWrap(V1.getValue()); } else { return result; // full range, can we do better? } } case souper::Inst::Sub: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.sub(R1); } case souper::Inst::Mul: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.multiply(R1); } case souper::Inst::And: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.binaryAnd(R1); } case souper::Inst::Or: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.binaryOr(R1); } case souper::Inst::Shl: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.shl(R1); } case souper::Inst::AShr: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.ashr(R1); } case souper::Inst::LShr: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.lshr(R1); } case souper::Inst::UDiv: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.udiv(R1); } // case souper::Inst::SDiv: { // auto R0 = FindConstantRange(I->Ops[0], C); // auto R1 = FindConstantRange(I->Ops[1], C); // return R0.sdiv(R1); // unimplemented // } // TODO: Xor pattern for not, truncs and extends, etc default: return result; } } bool dataflow::ValueAnalysis::isInfeasible(souper::Inst* RHS) { for (int I = 0; I < Inputs.size(); ++I) { auto C = LHSValues[I]; if (C.hasValue()) { auto CR = findConstantRange(RHS, Inputs[I]); if (!CR.contains(C.getValue())) { return true; } auto KB = findKnownBits(RHS, Inputs[I]); if ((KB.Zero & C.getValue()) != 0 || (KB.One & ~C.getValue()) != 0) { return true; } auto RHSV = evaluateInst(RHS, Inputs[I]); if (RHSV.hasValue()) { if (C.getValue() != RHSV.getValue()) { return true; } } } } return false; } dataflow::DataflowPruningManager::DataflowPruningManager( souper::Inst* LHS, std::vector<Inst *> &Inputs, unsigned StatsLevel) : VA(LHS, generateInputSets(Inputs)), NumPruned(0), TotalGuesses(0) { if (StatsLevel > 1) { DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) { TotalGuesses++; if (VA.isInfeasible(I)) { NumPruned++; llvm::outs() << "Dataflow Pruned " << NumPruned << "/" << TotalGuesses << "\n"; ReplacementContext RC; RC.printInst(I, llvm::outs(), true); return false; } return true; }; } else if (StatsLevel == 1) { DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) { TotalGuesses++; if (VA.isInfeasible(I)) { NumPruned++; return false; } return true; }; } else { DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) { return !VA.isInfeasible(I); }; } } std::vector<ValueCache> dataflow::DataflowPruningManager::generateInputSets( std::vector<Inst *> &Inputs) { std::vector<dataflow::ValueCache> InputSets; dataflow::ValueCache Cache; int64_t Current = 0; for (auto &&I : Inputs) { if (I->K == souper::Inst::Var) Cache[I] = {llvm::APInt(I->Width, Current++)}; } InputSets.push_back(Cache); Current = 2*Current + 1; for (auto &&I : Inputs) { if (I->K == souper::Inst::Var) Cache[I] = {llvm::APInt(I->Width, Current++)}; } InputSets.push_back(Cache); return InputSets; } } <commit_msg>Support trunc, sext, zext in findConstantRange<commit_after>#include "souper/Infer/DataflowPruning.h" namespace souper { namespace { using souper::dataflow::EvalValue; using souper::dataflow::ValueCache; EvalValue evaluateInstRecursive(souper::Inst* Inst, std::vector<EvalValue> args) { switch (Inst->K) { case souper::Inst::Const: return {Inst->Val}; case souper::Inst::UntypedConst: return {Inst->Val}; case souper::Inst::Var: llvm_unreachable("Should get value from cache without reaching here"); case souper::Inst::Add: return {args[0].getValue() + args[1].getValue()}; case souper::Inst::Sub: return {args[0].getValue() - args[1].getValue()}; case souper::Inst::Mul: return {args[0].getValue() * args[1].getValue()}; case souper::Inst::UDiv: return {args[0].getValue().udiv(args[1].getValue())}; case souper::Inst::SDiv: return {args[0].getValue().sdiv(args[1].getValue())}; case souper::Inst::URem: return {args[0].getValue().urem(args[1].getValue())}; case souper::Inst::SRem: return {args[0].getValue().srem(args[1].getValue())}; case souper::Inst::And: return {args[0].getValue() & args[1].getValue()}; case souper::Inst::Or: return {args[0].getValue() | args[1].getValue()}; case souper::Inst::Xor: return {args[0].getValue() ^ args[1].getValue()}; case souper::Inst::Shl: return {args[0].getValue() << args[1].getValue()}; case souper::Inst::LShr: return {args[0].getValue().lshr(args[1].getValue())}; case souper::Inst::AShr: return {args[0].getValue().ashr(args[1].getValue())}; // TODO: Handle NSW/NUW/NW variants of instructions case souper::Inst::Select: { if (!args[0].hasValue()) { return args[0]; } else { bool cond = args[0].getValue().getBoolValue(); return cond ? args[1] : args[2]; } } case souper::Inst::ZExt: return {args[0].getValue().zext(Inst->Width)}; case souper::Inst::SExt: return {args[0].getValue().sext(Inst->Width)}; case souper::Inst::Trunc: return {args[0].getValue().trunc(Inst->Width)}; case souper::Inst::Eq: return {{1, args[0].getValue() == args[1].getValue()}}; case souper::Inst::Ne: return {{1, args[0].getValue() != args[1].getValue()}}; case souper::Inst::Ult: return {{1, args[0].getValue().ult(args[1].getValue())}}; case souper::Inst::Slt: return {{1, args[0].getValue().slt(args[1].getValue())}}; case souper::Inst::Ule: return {{1, args[0].getValue().ule(args[1].getValue())}}; case souper::Inst::Sle: return {{1, args[0].getValue().sle(args[1].getValue())}}; case souper::Inst::CtPop: return {llvm::APInt(Inst->Width, args[0].getValue().countPopulation())}; case souper::Inst::Ctlz: return {llvm::APInt(Inst->Width, args[0].getValue().countLeadingZeros())}; case souper::Inst::Cttz: return {llvm::APInt(Inst->Width, args[0].getValue().countTrailingZeros())}; case souper::Inst::BSwap: return {args[0].getValue().byteSwap()}; default: return EvalValue(); // Indicates an 'unavailable' value } } } // Errs on the side of an 'unavailable' result // TODO: Some instructions unimplemented EvalValue souper::dataflow::evaluateInst(souper::Inst* Root, ValueCache &Cache) { std::vector<EvalValue> EvaluatedArgs; EvalValue Result; if (Root->K == souper::Inst::Var) { Result = Cache[Root]; } else { for (auto &&I : Root->Ops) { auto eval = evaluateInst(I, Cache); if (!eval.hasValue() && Root->K != souper::Inst::Select) { return Result; // result is `Unavailable` if args fail to evaluate } EvaluatedArgs.push_back(eval); } Result = evaluateInstRecursive(Root, EvaluatedArgs); } return Result; } EvalValue getValue(Inst *I, ValueCache &C) { if (I->K == souper::Inst::Const) { return {I->Val}; } else if (I->K == souper::Inst::Var || I->K == souper::Inst::ReservedConst || I->K == souper::Inst::ReservedInst) { if (I->Name != "" && C.find(I) != C.end()) { return C[I]; } else { return EvalValue(); // unavailable } } return EvalValue(); } llvm::KnownBits dataflow::findKnownBits(Inst* I, ValueCache& C) { llvm::KnownBits Result(I->Width); switch(I->K) { case souper::Inst::Const: case souper::Inst::Var : { EvalValue V = getValue(I, C); if (V.hasValue()) { Result.One = V.getValue(); Result.Zero = ~V.getValue(); return Result; } else { return Result; } } case souper::Inst::Shl : { auto Op0KB = findKnownBits(I->Ops[0], C); auto Op1V = getValue(I->Ops[1], C); if (Op1V.hasValue()) { Op0KB.One <<= Op1V.getValue(); Op0KB.Zero <<= Op1V.getValue(); Op0KB.Zero.setLowBits(Op1V.getValue().getLimitedValue()); // setLowBits takes an unsiged int, so getLimitedValue is harmless return Op0KB; } else { return Result; } } case souper::Inst::And : { auto Op0KB = findKnownBits(I->Ops[0], C); auto Op1KB = findKnownBits(I->Ops[1], C); Op0KB.One &= Op1KB.One; Op0KB.Zero |= Op1KB.Zero; return Op0KB; } case souper::Inst::Or : { auto Op0KB = findKnownBits(I->Ops[0], C); auto Op1KB = findKnownBits(I->Ops[1], C); Op0KB.One |= Op1KB.One; Op0KB.Zero &= Op1KB.Zero; return Op0KB; } case souper::Inst::Xor : { auto Op0KB = findKnownBits(I->Ops[0], C); auto Op1KB = findKnownBits(I->Ops[1], C); llvm::APInt KnownZeroOut = (Op0KB.Zero & Op1KB.Zero) | (Op0KB.One & Op1KB.One); Op0KB.One = (Op0KB.Zero & Op1KB.One) | (Op0KB.One & Op1KB.Zero); Op0KB.Zero = std::move(KnownZeroOut); // ^ logic copied from LLVM ValueTracking.cpp return Op0KB; } default : return Result; } } llvm::ConstantRange dataflow::findConstantRange(souper::Inst* I, souper::ValueCache& C) { llvm::ConstantRange result(I->Width); switch (I->K) { case souper::Inst::Const: case souper::Inst::Var : { EvalValue V = getValue(I, C); if (V.hasValue()) { return llvm::ConstantRange(V.getValue()); } else { return result; // Whole range } } case souper::Inst::Trunc: { auto R0 = findConstantRange(I->Ops[0], C); return R0.truncate(I->Width); } case souper::Inst::SExt: { auto R0 = findConstantRange(I->Ops[0], C); return R0.signExtend(I->Width); } case souper::Inst::ZExt: { auto R0 = findConstantRange(I->Ops[0], C); return R0.zeroExtend(I->Width); } case souper::Inst::Add: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.add(R1); } case souper::Inst::AddNSW: { auto R0 = findConstantRange(I->Ops[0], C); auto V1 = getValue(I->Ops[1], C); if (V1.hasValue()) { return R0.addWithNoSignedWrap(V1.getValue()); } else { return result; // full range, can we do better? } } case souper::Inst::Sub: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.sub(R1); } case souper::Inst::Mul: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.multiply(R1); } case souper::Inst::And: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.binaryAnd(R1); } case souper::Inst::Or: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.binaryOr(R1); } case souper::Inst::Shl: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.shl(R1); } case souper::Inst::AShr: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.ashr(R1); } case souper::Inst::LShr: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.lshr(R1); } case souper::Inst::UDiv: { auto R0 = findConstantRange(I->Ops[0], C); auto R1 = findConstantRange(I->Ops[1], C); return R0.udiv(R1); } // case souper::Inst::SDiv: { // auto R0 = FindConstantRange(I->Ops[0], C); // auto R1 = FindConstantRange(I->Ops[1], C); // return R0.sdiv(R1); // unimplemented // } // TODO: Xor pattern for not, truncs and extends, etc default: return result; } } bool dataflow::ValueAnalysis::isInfeasible(souper::Inst* RHS) { for (int I = 0; I < Inputs.size(); ++I) { auto C = LHSValues[I]; if (C.hasValue()) { auto CR = findConstantRange(RHS, Inputs[I]); if (!CR.contains(C.getValue())) { return true; } auto KB = findKnownBits(RHS, Inputs[I]); if ((KB.Zero & C.getValue()) != 0 || (KB.One & ~C.getValue()) != 0) { return true; } auto RHSV = evaluateInst(RHS, Inputs[I]); if (RHSV.hasValue()) { if (C.getValue() != RHSV.getValue()) { return true; } } } } return false; } dataflow::DataflowPruningManager::DataflowPruningManager( souper::Inst* LHS, std::vector<Inst *> &Inputs, unsigned StatsLevel) : VA(LHS, generateInputSets(Inputs)), NumPruned(0), TotalGuesses(0) { if (StatsLevel > 1) { DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) { TotalGuesses++; if (VA.isInfeasible(I)) { NumPruned++; llvm::outs() << "Dataflow Pruned " << NumPruned << "/" << TotalGuesses << "\n"; ReplacementContext RC; RC.printInst(I, llvm::outs(), true); return false; } return true; }; } else if (StatsLevel == 1) { DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) { TotalGuesses++; if (VA.isInfeasible(I)) { NumPruned++; return false; } return true; }; } else { DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) { return !VA.isInfeasible(I); }; } } std::vector<ValueCache> dataflow::DataflowPruningManager::generateInputSets( std::vector<Inst *> &Inputs) { std::vector<dataflow::ValueCache> InputSets; dataflow::ValueCache Cache; int64_t Current = 0; for (auto &&I : Inputs) { if (I->K == souper::Inst::Var) Cache[I] = {llvm::APInt(I->Width, Current++)}; } InputSets.push_back(Cache); Current = 2*Current + 1; for (auto &&I : Inputs) { if (I->K == souper::Inst::Var) Cache[I] = {llvm::APInt(I->Width, Current++)}; } InputSets.push_back(Cache); return InputSets; } } <|endoftext|>
<commit_before>#include "HotkeyManager.h" #include "Logger.h" HotkeyManager *HotkeyManager::instance = NULL; HotkeyManager *HotkeyManager::Instance() { return instance; } HotkeyManager *HotkeyManager::Instance(HWND notifyWnd) { if (instance == NULL) { instance = new HotkeyManager(); instance->Hook(); instance->_notifyWnd = notifyWnd; } return instance; } HotkeyManager::HotkeyManager() : _fixWin(false) { } HotkeyManager::~HotkeyManager() { while (true) { auto i = _keyCombinations.begin(); if (_keyCombinations.size() > 0) { Unregister(*i); } else { break; } } Unhook(); } void HotkeyManager::Shutdown() { delete instance; instance = NULL; } bool HotkeyManager::Hook() { _mouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, NULL, NULL); _keyHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, NULL); return _mouseHook && _keyHook; } bool HotkeyManager::Unhook() { BOOL unMouse = UnhookWindowsHookEx(_mouseHook); BOOL unKey = UnhookWindowsHookEx(_keyHook); return unMouse && unKey; } void HotkeyManager::Register(int keyCombination) { if (_keyCombinations.count(keyCombination) > 0) { CLOG(L"Hotkey combination [%d] already registered", keyCombination); return; } else { _keyCombinations.insert(keyCombination); } /* get VK_* value; includes unused bits */ int vk = 0xFFFF & keyCombination; if ((keyCombination >> 20) > 0 /* uses a HKM_MOUSE_* flag */ || vk == VK_LBUTTON || vk == VK_RBUTTON || vk == VK_MBUTTON) { /* mouse-based hotkeys; we are done */ CLOG(L"Registered new mouse-based hotkey: %d", keyCombination); return; } /* keyboard-only hotkeys; use WinAPI */ int mods = (0xF0000 & keyCombination) >> 16; if (!RegisterHotKey(_notifyWnd, keyCombination, mods, vk)) { CLOG(L"Failed to register hotkey [%d]\n" L"Mods: %d, VK: %d", keyCombination, mods, vk); return; } CLOG(L"Registered new keyboard-based hotkey: %d", keyCombination); } bool HotkeyManager::Unregister(int keyCombination) { CLOG(L"Unregistering hotkey combination: %d", keyCombination); if (_keyCombinations.count(keyCombination) <= 0) { QCLOG(L"Hotkey combination [%d] was not previously registered", keyCombination); return false; } _keyCombinations.erase(keyCombination); if ((keyCombination >> 20) == 0) { /* This hotkey isn't mouse-based; unregister with Windows */ if (!UnregisterHotKey(_notifyWnd, keyCombination)) { CLOG(L"Failed to unregister hotkey: %d", keyCombination); return false; } } return true; } bool HotkeyManager::IsModifier(DWORD vk) { switch (vk) { case VK_MENU: case VK_LMENU: case VK_RMENU: case VK_CONTROL: case VK_LCONTROL: case VK_RCONTROL: case VK_SHIFT: case VK_LSHIFT: case VK_RSHIFT: case VK_LWIN: case VK_RWIN: return true; } return false; } int HotkeyManager::Modifiers() { int mods = 0; mods += (GetKeyState(VK_MENU) & 0x8000) << 1; mods += (GetKeyState(VK_CONTROL) & 0x8000) << 2; mods += (GetKeyState(VK_SHIFT) & 0x8000) << 3; mods += (GetKeyState(VK_LWIN) & 0x8000) << 4; mods += (GetKeyState(VK_RWIN) & 0x8000) << 4; return mods; } int HotkeyManager::ModifiersAsync() { int mods = 0; mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1; mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2; mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3; mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4; mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4; return mods; } std::wstring HotkeyManager::HotkeysToModString(int combination, std::wstring separator) { std::wstring str = L""; if (combination & HKM_MOD_ALT) { str += VKToString(VK_MENU) + separator; } if (combination & HKM_MOD_CTRL) { str += VKToString(VK_CONTROL) + separator; } if (combination & HKM_MOD_SHF) { str += VKToString(VK_SHIFT) + separator; } if (combination & HKM_MOD_WIN) { str += L"Win" + separator; } return str; } std::wstring HotkeyManager::HotkeysToString(int combination, std::wstring separator) { std::wstring mods = HotkeysToModString(combination, separator); int vk = combination & 0xFF; std::wstring str = VKToString(vk); return mods + str; } std::wstring HotkeyManager::VKToString(unsigned int vk, bool extendedKey) { int extended = extendedKey ? 0x1 : 0x0; unsigned int scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC); scanCode = scanCode << 16; scanCode |= extended << 24; wchar_t buf[256] = {}; GetKeyNameText(scanCode, buf, 256); return std::wstring(buf); } LRESULT CALLBACK HotkeyManager::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0) { if (wParam == WM_KEYUP) { KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT*) lParam; if ((kbInfo->vkCode == VK_LWIN || kbInfo->vkCode == VK_RWIN) && _fixWin) { /* WIN+Mouse combination used; we need to prevent the * system from only seeing a WIN keypress (and usually * popping up the start menu). We simulate WIN+VK_NONAME. */ INPUT input = { 0 }; input.type = INPUT_KEYBOARD; input.ki.wVk = VK_NONAME; input.ki.wScan = 0; input.ki.dwFlags = 0; input.ki.time = 1; input.ki.dwExtraInfo = GetMessageExtraInfo(); /* key down: */ SendInput(1, &input, sizeof(INPUT)); input.ki.dwFlags = KEYEVENTF_KEYUP; /* key up: */ SendInput(1, &input, sizeof(INPUT)); _fixWin = false; } } } return CallNextHookEx(NULL, nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0) { int mouseState = 0; MSLLHOOKSTRUCT *msInfo; switch (wParam) { case WM_LBUTTONDOWN: mouseState += VK_LBUTTON; break; case WM_MBUTTONDOWN: mouseState += VK_MBUTTON; break; case WM_RBUTTONDOWN: mouseState += VK_RBUTTON; break; case WM_XBUTTONDOWN: { msInfo = (MSLLHOOKSTRUCT*) lParam; int button = msInfo->mouseData >> 16 & 0xFFFF; if (button == 1) mouseState += HKM_MOUSE_XB1; else if (button == 2) mouseState += HKM_MOUSE_XB2; break; } case WM_MOUSEWHEEL: { msInfo = (MSLLHOOKSTRUCT*) lParam; if ((int) msInfo->mouseData > 0) { mouseState += HKM_MOUSE_WHUP; } else { mouseState += HKM_MOUSE_WHDN; } break; } } if (mouseState > 0) { mouseState += Modifiers(); if (_keyCombinations.count(mouseState) > 0) { PostMessage(_notifyWnd, WM_HOTKEY, mouseState, mouseState & 0xF0000); if (mouseState & HKM_MOD_WIN) { _fixWin = true; /* enable fix right before WIN goes up */ } return 1; /* processed the message; eat it */ } } } return CallNextHookEx(NULL, nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) { return HotkeyManager::instance->MouseProc(nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) { return HotkeyManager::instance->KeyProc(nCode, wParam, lParam); }<commit_msg>Reorder comments/statements to clarify<commit_after>#include "HotkeyManager.h" #include "Logger.h" HotkeyManager *HotkeyManager::instance = NULL; HotkeyManager *HotkeyManager::Instance() { return instance; } HotkeyManager *HotkeyManager::Instance(HWND notifyWnd) { if (instance == NULL) { instance = new HotkeyManager(); instance->Hook(); instance->_notifyWnd = notifyWnd; } return instance; } HotkeyManager::HotkeyManager() : _fixWin(false) { } HotkeyManager::~HotkeyManager() { while (true) { auto i = _keyCombinations.begin(); if (_keyCombinations.size() > 0) { Unregister(*i); } else { break; } } Unhook(); } void HotkeyManager::Shutdown() { delete instance; instance = NULL; } bool HotkeyManager::Hook() { _mouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, NULL, NULL); _keyHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, NULL); return _mouseHook && _keyHook; } bool HotkeyManager::Unhook() { BOOL unMouse = UnhookWindowsHookEx(_mouseHook); BOOL unKey = UnhookWindowsHookEx(_keyHook); return unMouse && unKey; } void HotkeyManager::Register(int keyCombination) { if (_keyCombinations.count(keyCombination) > 0) { CLOG(L"Hotkey combination [%d] already registered", keyCombination); return; } else { _keyCombinations.insert(keyCombination); } /* get VK_* value; includes unused bits */ int vk = 0xFFFF & keyCombination; if ((keyCombination >> 20) > 0 /* uses a HKM_MOUSE_* flag */ || vk == VK_LBUTTON || vk == VK_RBUTTON || vk == VK_MBUTTON) { /* mouse-based hotkeys; we are done */ CLOG(L"Registered new mouse-based hotkey: %d", keyCombination); return; } /* keyboard-only hotkeys; use WinAPI */ int mods = (0xF0000 & keyCombination) >> 16; if (!RegisterHotKey(_notifyWnd, keyCombination, mods, vk)) { CLOG(L"Failed to register hotkey [%d]\n" L"Mods: %d, VK: %d", keyCombination, mods, vk); return; } CLOG(L"Registered new keyboard-based hotkey: %d", keyCombination); } bool HotkeyManager::Unregister(int keyCombination) { CLOG(L"Unregistering hotkey combination: %d", keyCombination); if (_keyCombinations.count(keyCombination) <= 0) { QCLOG(L"Hotkey combination [%d] was not previously registered", keyCombination); return false; } _keyCombinations.erase(keyCombination); if ((keyCombination >> 20) == 0) { /* This hotkey isn't mouse-based; unregister with Windows */ if (!UnregisterHotKey(_notifyWnd, keyCombination)) { CLOG(L"Failed to unregister hotkey: %d", keyCombination); return false; } } return true; } bool HotkeyManager::IsModifier(DWORD vk) { switch (vk) { case VK_MENU: case VK_LMENU: case VK_RMENU: case VK_CONTROL: case VK_LCONTROL: case VK_RCONTROL: case VK_SHIFT: case VK_LSHIFT: case VK_RSHIFT: case VK_LWIN: case VK_RWIN: return true; } return false; } int HotkeyManager::Modifiers() { int mods = 0; mods += (GetKeyState(VK_MENU) & 0x8000) << 1; mods += (GetKeyState(VK_CONTROL) & 0x8000) << 2; mods += (GetKeyState(VK_SHIFT) & 0x8000) << 3; mods += (GetKeyState(VK_LWIN) & 0x8000) << 4; mods += (GetKeyState(VK_RWIN) & 0x8000) << 4; return mods; } int HotkeyManager::ModifiersAsync() { int mods = 0; mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1; mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2; mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3; mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4; mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4; return mods; } std::wstring HotkeyManager::HotkeysToModString(int combination, std::wstring separator) { std::wstring str = L""; if (combination & HKM_MOD_ALT) { str += VKToString(VK_MENU) + separator; } if (combination & HKM_MOD_CTRL) { str += VKToString(VK_CONTROL) + separator; } if (combination & HKM_MOD_SHF) { str += VKToString(VK_SHIFT) + separator; } if (combination & HKM_MOD_WIN) { str += L"Win" + separator; } return str; } std::wstring HotkeyManager::HotkeysToString(int combination, std::wstring separator) { std::wstring mods = HotkeysToModString(combination, separator); int vk = combination & 0xFF; std::wstring str = VKToString(vk); return mods + str; } std::wstring HotkeyManager::VKToString(unsigned int vk, bool extendedKey) { int extended = extendedKey ? 0x1 : 0x0; unsigned int scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC); scanCode = scanCode << 16; scanCode |= extended << 24; wchar_t buf[256] = {}; GetKeyNameText(scanCode, buf, 256); return std::wstring(buf); } LRESULT CALLBACK HotkeyManager::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0) { if (wParam == WM_KEYUP) { KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT*) lParam; if ((kbInfo->vkCode == VK_LWIN || kbInfo->vkCode == VK_RWIN) && _fixWin) { /* WIN+Mouse combination used; we need to prevent the * system from only seeing a WIN keypress (and usually * popping up the start menu). We simulate WIN+VK_NONAME. */ INPUT input = { 0 }; input.type = INPUT_KEYBOARD; input.ki.wVk = VK_NONAME; input.ki.wScan = 0; input.ki.dwFlags = 0; input.ki.time = 1; input.ki.dwExtraInfo = GetMessageExtraInfo(); /* key down: */ SendInput(1, &input, sizeof(INPUT)); /* key up: */ input.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &input, sizeof(INPUT)); _fixWin = false; } } } return CallNextHookEx(NULL, nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0) { int mouseState = 0; MSLLHOOKSTRUCT *msInfo; switch (wParam) { case WM_LBUTTONDOWN: mouseState += VK_LBUTTON; break; case WM_MBUTTONDOWN: mouseState += VK_MBUTTON; break; case WM_RBUTTONDOWN: mouseState += VK_RBUTTON; break; case WM_XBUTTONDOWN: { msInfo = (MSLLHOOKSTRUCT*) lParam; int button = msInfo->mouseData >> 16 & 0xFFFF; if (button == 1) mouseState += HKM_MOUSE_XB1; else if (button == 2) mouseState += HKM_MOUSE_XB2; break; } case WM_MOUSEWHEEL: { msInfo = (MSLLHOOKSTRUCT*) lParam; if ((int) msInfo->mouseData > 0) { mouseState += HKM_MOUSE_WHUP; } else { mouseState += HKM_MOUSE_WHDN; } break; } } if (mouseState > 0) { mouseState += Modifiers(); if (_keyCombinations.count(mouseState) > 0) { PostMessage(_notifyWnd, WM_HOTKEY, mouseState, mouseState & 0xF0000); if (mouseState & HKM_MOD_WIN) { _fixWin = true; /* enable fix right before WIN goes up */ } return 1; /* processed the message; eat it */ } } } return CallNextHookEx(NULL, nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) { return HotkeyManager::instance->MouseProc(nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) { return HotkeyManager::instance->KeyProc(nCode, wParam, lParam); }<|endoftext|>
<commit_before>// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "HotkeyManager.h" #include "Logger.h" #include "SyntheticKeyboard.h" HotkeyManager *HotkeyManager::instance = NULL; std::unordered_map<UINT, std::wstring> HotkeyManager::_vkStringMap = { { VK_SELECT, L"Select" }, { VK_PRINT, L"Print" }, { VK_EXECUTE, L"Execute" }, { VK_SNAPSHOT, L"Print Screen" }, { VK_HELP, L"Help" }, { VK_SLEEP, L"Sleep" }, { VK_BROWSER_BACK, L"Browser Back" }, { VK_BROWSER_FORWARD, L"Browser Forward" }, { VK_BROWSER_REFRESH, L"Browser Refresh" }, { VK_BROWSER_STOP, L"Browser Stop" }, { VK_BROWSER_SEARCH, L"Browser Search" }, { VK_BROWSER_FAVORITES, L"Browser Favorites" }, { VK_BROWSER_HOME, L"Browser Home" }, { VK_VOLUME_MUTE, L"Mute" }, { VK_VOLUME_DOWN, L"Volume Down" }, { VK_VOLUME_UP, L"Volume Up" }, { VK_MEDIA_NEXT_TRACK, L"Next Track" }, { VK_MEDIA_PREV_TRACK, L"Previous Track" }, { VK_MEDIA_STOP, L"Stop" }, { VK_MEDIA_PLAY_PAUSE, L"Play/Pause" }, { VK_LAUNCH_MAIL, L"Mail" }, { VK_LAUNCH_MEDIA_SELECT, L"Select Media" }, { VK_LAUNCH_APP1, L"App 1" }, { VK_LAUNCH_APP2, L"App 2" }, { VK_PLAY, L"Play" }, { VK_ZOOM, L"Zoom" }, { VK_OEM_CLEAR, L"Clear" }, }; HotkeyManager *HotkeyManager::Instance() { return instance; } HotkeyManager *HotkeyManager::Instance(HWND notifyWnd) { if (instance == NULL) { instance = new HotkeyManager(); instance->Hook(); instance->_notifyWnd = notifyWnd; } return instance; } HotkeyManager::HotkeyManager() : _fixWin(false) { } HotkeyManager::~HotkeyManager() { while (true) { auto i = _keyCombinations.begin(); if (_keyCombinations.size() > 0) { Unregister(*i); } else { break; } } _hookCombinations.clear(); Unhook(); } void HotkeyManager::Shutdown() { delete instance; instance = NULL; } bool HotkeyManager::Hook() { _mouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, NULL, NULL); _keyHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, NULL); return _mouseHook && _keyHook; } bool HotkeyManager::Unhook() { BOOL unMouse = UnhookWindowsHookEx(_mouseHook); BOOL unKey = UnhookWindowsHookEx(_keyHook); return unMouse && unKey; } void HotkeyManager::Register(int keyCombination) { if (_keyCombinations.count(keyCombination) > 0) { CLOG(L"Hotkey combination [%d] already registered", keyCombination); return; } else { _keyCombinations.insert(keyCombination); } /* get VK_* value; */ int vk = 0xFF & keyCombination; if ((keyCombination >> 20) > 0 /* uses a HKM_MOUSE_* flag */ || vk == VK_LBUTTON || vk == VK_RBUTTON || vk == VK_MBUTTON) { /* mouse-based hotkeys; we are done */ CLOG(L"Registered new mouse-based hotkey: %d", keyCombination); return; } /* keyboard-only hotkeys; use WinAPI */ int mods = (0xF0000 & keyCombination) >> 16; if (!RegisterHotKey(_notifyWnd, keyCombination, mods, vk)) { CLOG(L"Failed to register hotkey [%d]\n" L"Mods: %d, VK: %d\n" L"Placing in hook list", keyCombination, mods, vk); _hookCombinations.insert(keyCombination); return; } CLOG(L"Registered new keyboard-based hotkey: %d", keyCombination); } bool HotkeyManager::Unregister(int keyCombination) { CLOG(L"Unregistering hotkey combination: %d", keyCombination); if (_keyCombinations.count(keyCombination) <= 0) { QCLOG(L"Hotkey combination [%d] was not previously registered", keyCombination); return false; } _keyCombinations.erase(keyCombination); if ((keyCombination >> 20) == 0) { /* This hotkey isn't mouse-based; unregister with Windows */ if (!UnregisterHotKey(_notifyWnd, keyCombination)) { CLOG(L"Failed to unregister hotkey: %d", keyCombination); return false; } } return true; } LRESULT CALLBACK HotkeyManager::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0) { if (wParam == WM_KEYUP) { KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam; if ((kbInfo->vkCode == VK_LWIN || kbInfo->vkCode == VK_RWIN) && _fixWin) { /* WIN+Mouse combination used; we need to prevent the * system from only seeing a WIN keypress (and usually * popping up the start menu). We simulate WIN+VK_NONAME. */ SyntheticKeyboard::SimulateKeypress(VK_NONAME, false); _fixWin = false; return CallNextHookEx(NULL, nCode, wParam, lParam); } } if (_hookCombinations.size() <= 0) { return CallNextHookEx(NULL, nCode, wParam, lParam); } if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) { KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam; DWORD vk = kbInfo->vkCode; int mods = HotkeyManager::IsModifier(vk); if (mods) { _modifiers |= mods; return CallNextHookEx(NULL, nCode, wParam, lParam); } else { /* Is this an extended key? */ int ext = (kbInfo->flags & 0x1) << EXT_OFFSET; int keys = _modifiers | ext | vk; if (_hookCombinations.count(keys) > 0) { SendMessage(_notifyWnd, WM_HOTKEY, keys, _modifiers >> MOD_OFFSET); return (LRESULT) 1; } } } if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP) { KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam; int m = HotkeyManager::IsModifier(kbInfo->vkCode); if (m) { _modifiers ^= m; } return CallNextHookEx(NULL, nCode, wParam, lParam); } } return CallNextHookEx(NULL, nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0 && wParam != WM_MOUSEMOVE) { int mouseState = 0; MSLLHOOKSTRUCT *msInfo; switch (wParam) { case WM_LBUTTONDOWN: mouseState += VK_LBUTTON; break; case WM_MBUTTONDOWN: mouseState += VK_MBUTTON; break; case WM_RBUTTONDOWN: mouseState += VK_RBUTTON; break; case WM_XBUTTONDOWN: { msInfo = (MSLLHOOKSTRUCT *) lParam; int button = msInfo->mouseData >> 16 & 0xFFFF; if (button == 1) mouseState += HKM_MOUSE_XB1; else if (button == 2) mouseState += HKM_MOUSE_XB2; break; } case WM_MOUSEWHEEL: { /* Note: WM_MOUSEWHEEL on a hook is a little different, so we * need to grab the wheel delta info from the lParam. */ msInfo = (MSLLHOOKSTRUCT *) lParam; if ((int) msInfo->mouseData > 0) { mouseState += HKM_MOUSE_WHUP; } else { mouseState += HKM_MOUSE_WHDN; } break; } } if (mouseState > 0) { mouseState += Modifiers(); if (_keyCombinations.count(mouseState) > 0) { PostMessage(_notifyWnd, WM_HOTKEY, mouseState, mouseState & 0xF0000); if (mouseState & HKM_MOD_WIN) { _fixWin = true; /* enable fix right before WIN goes up */ } return 1; /* processed the message; eat it */ } } } return CallNextHookEx(NULL, nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) { return HotkeyManager::instance->MouseProc(nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) { return HotkeyManager::instance->KeyProc(nCode, wParam, lParam); } int HotkeyManager::IsModifier(int vk) { switch (vk) { case VK_MENU: case VK_LMENU: case VK_RMENU: return HKM_MOD_ALT; case VK_CONTROL: case VK_LCONTROL: case VK_RCONTROL: return HKM_MOD_CTRL; case VK_SHIFT: case VK_LSHIFT: case VK_RSHIFT: return HKM_MOD_SHF; case VK_LWIN: case VK_RWIN: return HKM_MOD_WIN; } return 0; } bool HotkeyManager::IsMouseKey(int vk) { if (vk < 0x07 && vk != VK_CANCEL) { return true; } if (vk & (0xF << MOUSE_OFFSET)) { /* Has wheel or xbutton flags */ return true; } return false; } int HotkeyManager::Modifiers() { int mods = 0; mods += (GetKeyState(VK_MENU) & 0x8000) << 1; mods += (GetKeyState(VK_CONTROL) & 0x8000) << 2; mods += (GetKeyState(VK_SHIFT) & 0x8000) << 3; mods += (GetKeyState(VK_LWIN) & 0x8000) << 4; mods += (GetKeyState(VK_RWIN) & 0x8000) << 4; return mods; } int HotkeyManager::ModifiersAsync() { int mods = 0; mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1; mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2; mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3; mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4; mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4; return mods; } std::wstring HotkeyManager::HotkeysToModString(int combination, std::wstring separator) { std::wstring str = L""; if (combination & HKM_MOD_ALT) { str += VKToString(VK_MENU) + separator; } if (combination & HKM_MOD_CTRL) { str += VKToString(VK_CONTROL) + separator; } if (combination & HKM_MOD_SHF) { str += VKToString(VK_SHIFT) + separator; } if (combination & HKM_MOD_WIN) { str += L"Win" + separator; } return str; } std::wstring HotkeyManager::HotkeysToString(int combination, std::wstring separator) { std::wstring mods = HotkeysToModString(combination, separator); int vk = combination & 0xFF; std::wstring str; if (IsMouseKey(vk)) { str = MouseString(combination); } else { bool ext = (combination & 0x100) > 0; str = VKToString(vk, ext); } return mods + str; } std::wstring HotkeyManager::MouseString(int combination) { int vk = combination & 0xFF; if (vk > 0) { switch (vk) { case VK_LBUTTON: return L"Mouse 1"; case VK_RBUTTON: return L"Mouse 2"; case VK_MBUTTON: return L"Mouse 3"; } } int flags = combination & (0xF << MOUSE_OFFSET); if (flags == HKM_MOUSE_XB1) { return L"Mouse 4"; } else if (flags == HKM_MOUSE_XB2) { return L"Mouse 5"; } else if (flags == HKM_MOUSE_WHUP) { return L"Mouse Wheel Up"; } else if (flags == HKM_MOUSE_WHDN) { return L"Mouse Wheel Down"; } return L""; } std::wstring HotkeyManager::VKToString(unsigned int vk, bool extendedKey) { if (_vkStringMap.find(vk) != _vkStringMap.end()) { return _vkStringMap[vk]; } if ( vk == 0x03 /* break */ || (vk >= 0x21 && vk <= 0x2f) /* arrow keys, home/insert/del, etc */ || (vk >= 0x5b && vk <= 0x5d) /* win, app keys (natural keyboard) */ || (vk == 0x90) /* num lock */ ) { extendedKey = true; } /* GetKeyNameText expects the following: * 16-23: scan code * 24: extended key flag * 25: 'do not care' bit (don't distinguish between L/R keys) */ unsigned int scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC); scanCode = scanCode << 16; if (vk == VK_RSHIFT) { /* For some reason, the right shift key ends up having its extended * key flag set and confuses GetKeyNameText. */ extendedKey = false; } int extended = extendedKey ? 0x1 : 0x0; scanCode |= extended << 24; wchar_t buf[256] = {}; GetKeyNameText(scanCode, buf, 256); return std::wstring(buf); } void HotkeyManager::VKStringTest() { for (unsigned int i = 0; i < 0xFF; ++i) { CLOG(L"%02x - %s", i, VKToString(i).c_str()); } } <commit_msg>Allow using pause as a hotkey (super useful on Logitech G513)<commit_after>// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "HotkeyManager.h" #include "Logger.h" #include "SyntheticKeyboard.h" HotkeyManager *HotkeyManager::instance = NULL; std::unordered_map<UINT, std::wstring> HotkeyManager::_vkStringMap = { { VK_SELECT, L"Select" }, { VK_PRINT, L"Print" }, { VK_EXECUTE, L"Execute" }, { VK_SNAPSHOT, L"Print Screen" }, { VK_HELP, L"Help" }, { VK_SLEEP, L"Sleep" }, { VK_BROWSER_BACK, L"Browser Back" }, { VK_BROWSER_FORWARD, L"Browser Forward" }, { VK_BROWSER_REFRESH, L"Browser Refresh" }, { VK_BROWSER_STOP, L"Browser Stop" }, { VK_BROWSER_SEARCH, L"Browser Search" }, { VK_BROWSER_FAVORITES, L"Browser Favorites" }, { VK_BROWSER_HOME, L"Browser Home" }, { VK_VOLUME_MUTE, L"Mute" }, { VK_VOLUME_DOWN, L"Volume Down" }, { VK_VOLUME_UP, L"Volume Up" }, { VK_MEDIA_NEXT_TRACK, L"Next Track" }, { VK_MEDIA_PREV_TRACK, L"Previous Track" }, { VK_MEDIA_STOP, L"Stop" }, { VK_MEDIA_PLAY_PAUSE, L"Play/Pause" }, { VK_LAUNCH_MAIL, L"Mail" }, { VK_LAUNCH_MEDIA_SELECT, L"Select Media" }, { VK_LAUNCH_APP1, L"App 1" }, { VK_LAUNCH_APP2, L"App 2" }, { VK_PLAY, L"Play" }, { VK_ZOOM, L"Zoom" }, { VK_OEM_CLEAR, L"Clear" }, }; HotkeyManager *HotkeyManager::Instance() { return instance; } HotkeyManager *HotkeyManager::Instance(HWND notifyWnd) { if (instance == NULL) { instance = new HotkeyManager(); instance->Hook(); instance->_notifyWnd = notifyWnd; } return instance; } HotkeyManager::HotkeyManager() : _fixWin(false) { } HotkeyManager::~HotkeyManager() { while (true) { auto i = _keyCombinations.begin(); if (_keyCombinations.size() > 0) { Unregister(*i); } else { break; } } _hookCombinations.clear(); Unhook(); } void HotkeyManager::Shutdown() { delete instance; instance = NULL; } bool HotkeyManager::Hook() { _mouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, NULL, NULL); _keyHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, NULL); return _mouseHook && _keyHook; } bool HotkeyManager::Unhook() { BOOL unMouse = UnhookWindowsHookEx(_mouseHook); BOOL unKey = UnhookWindowsHookEx(_keyHook); return unMouse && unKey; } void HotkeyManager::Register(int keyCombination) { if (_keyCombinations.count(keyCombination) > 0) { CLOG(L"Hotkey combination [%d] already registered", keyCombination); return; } else { _keyCombinations.insert(keyCombination); } /* get VK_* value; */ int vk = 0xFF & keyCombination; if ((keyCombination >> 20) > 0 /* uses a HKM_MOUSE_* flag */ || vk == VK_LBUTTON || vk == VK_RBUTTON || vk == VK_MBUTTON) { /* mouse-based hotkeys; we are done */ CLOG(L"Registered new mouse-based hotkey: %d", keyCombination); return; } /* keyboard-only hotkeys; use WinAPI */ int mods = (0xF0000 & keyCombination) >> 16; if (!RegisterHotKey(_notifyWnd, keyCombination, mods, vk)) { CLOG(L"Failed to register hotkey [%d]\n" L"Mods: %d, VK: %d\n" L"Placing in hook list", keyCombination, mods, vk); _hookCombinations.insert(keyCombination); return; } CLOG(L"Registered new keyboard-based hotkey: %d", keyCombination); } bool HotkeyManager::Unregister(int keyCombination) { CLOG(L"Unregistering hotkey combination: %d", keyCombination); if (_keyCombinations.count(keyCombination) <= 0) { QCLOG(L"Hotkey combination [%d] was not previously registered", keyCombination); return false; } _keyCombinations.erase(keyCombination); if ((keyCombination >> 20) == 0) { /* This hotkey isn't mouse-based; unregister with Windows */ if (!UnregisterHotKey(_notifyWnd, keyCombination)) { CLOG(L"Failed to unregister hotkey: %d", keyCombination); return false; } } return true; } LRESULT CALLBACK HotkeyManager::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0) { if (wParam == WM_KEYUP) { KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam; if ((kbInfo->vkCode == VK_LWIN || kbInfo->vkCode == VK_RWIN) && _fixWin) { /* WIN+Mouse combination used; we need to prevent the * system from only seeing a WIN keypress (and usually * popping up the start menu). We simulate WIN+VK_NONAME. */ SyntheticKeyboard::SimulateKeypress(VK_NONAME, false); _fixWin = false; return CallNextHookEx(NULL, nCode, wParam, lParam); } } if (_hookCombinations.size() <= 0) { return CallNextHookEx(NULL, nCode, wParam, lParam); } if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) { KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam; DWORD vk = kbInfo->vkCode; int mods = HotkeyManager::IsModifier(vk); if (mods) { _modifiers |= mods; return CallNextHookEx(NULL, nCode, wParam, lParam); } else { /* Is this an extended key? */ int ext = (kbInfo->flags & 0x1) << EXT_OFFSET; int keys = _modifiers | ext | vk; if (_hookCombinations.count(keys) > 0) { SendMessage(_notifyWnd, WM_HOTKEY, keys, _modifiers >> MOD_OFFSET); return (LRESULT) 1; } } } if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP) { KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam; int m = HotkeyManager::IsModifier(kbInfo->vkCode); if (m) { _modifiers ^= m; } return CallNextHookEx(NULL, nCode, wParam, lParam); } } return CallNextHookEx(NULL, nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0 && wParam != WM_MOUSEMOVE) { int mouseState = 0; MSLLHOOKSTRUCT *msInfo; switch (wParam) { case WM_LBUTTONDOWN: mouseState += VK_LBUTTON; break; case WM_MBUTTONDOWN: mouseState += VK_MBUTTON; break; case WM_RBUTTONDOWN: mouseState += VK_RBUTTON; break; case WM_XBUTTONDOWN: { msInfo = (MSLLHOOKSTRUCT *) lParam; int button = msInfo->mouseData >> 16 & 0xFFFF; if (button == 1) mouseState += HKM_MOUSE_XB1; else if (button == 2) mouseState += HKM_MOUSE_XB2; break; } case WM_MOUSEWHEEL: { /* Note: WM_MOUSEWHEEL on a hook is a little different, so we * need to grab the wheel delta info from the lParam. */ msInfo = (MSLLHOOKSTRUCT *) lParam; if ((int) msInfo->mouseData > 0) { mouseState += HKM_MOUSE_WHUP; } else { mouseState += HKM_MOUSE_WHDN; } break; } } if (mouseState > 0) { mouseState += Modifiers(); if (_keyCombinations.count(mouseState) > 0) { PostMessage(_notifyWnd, WM_HOTKEY, mouseState, mouseState & 0xF0000); if (mouseState & HKM_MOD_WIN) { _fixWin = true; /* enable fix right before WIN goes up */ } return 1; /* processed the message; eat it */ } } } return CallNextHookEx(NULL, nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) { return HotkeyManager::instance->MouseProc(nCode, wParam, lParam); } LRESULT CALLBACK HotkeyManager::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) { return HotkeyManager::instance->KeyProc(nCode, wParam, lParam); } int HotkeyManager::IsModifier(int vk) { switch (vk) { case VK_MENU: case VK_LMENU: case VK_RMENU: return HKM_MOD_ALT; case VK_CONTROL: case VK_LCONTROL: case VK_RCONTROL: return HKM_MOD_CTRL; case VK_SHIFT: case VK_LSHIFT: case VK_RSHIFT: return HKM_MOD_SHF; case VK_LWIN: case VK_RWIN: return HKM_MOD_WIN; } return 0; } bool HotkeyManager::IsMouseKey(int vk) { if (vk < 0x07 && vk != VK_CANCEL) { return true; } if (vk & (0xF << MOUSE_OFFSET)) { /* Has wheel or xbutton flags */ return true; } return false; } int HotkeyManager::Modifiers() { int mods = 0; mods += (GetKeyState(VK_MENU) & 0x8000) << 1; mods += (GetKeyState(VK_CONTROL) & 0x8000) << 2; mods += (GetKeyState(VK_SHIFT) & 0x8000) << 3; mods += (GetKeyState(VK_LWIN) & 0x8000) << 4; mods += (GetKeyState(VK_RWIN) & 0x8000) << 4; return mods; } int HotkeyManager::ModifiersAsync() { int mods = 0; mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1; mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2; mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3; mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4; mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4; return mods; } std::wstring HotkeyManager::HotkeysToModString(int combination, std::wstring separator) { std::wstring str = L""; if (combination & HKM_MOD_ALT) { str += VKToString(VK_MENU) + separator; } if (combination & HKM_MOD_CTRL) { str += VKToString(VK_CONTROL) + separator; } if (combination & HKM_MOD_SHF) { str += VKToString(VK_SHIFT) + separator; } if (combination & HKM_MOD_WIN) { str += L"Win" + separator; } return str; } std::wstring HotkeyManager::HotkeysToString(int combination, std::wstring separator) { std::wstring mods = HotkeysToModString(combination, separator); int vk = combination & 0xFF; std::wstring str; if (IsMouseKey(vk)) { str = MouseString(combination); } else { bool ext = (combination & 0x100) > 0; str = VKToString(vk, ext); } return mods + str; } std::wstring HotkeyManager::MouseString(int combination) { int vk = combination & 0xFF; if (vk > 0) { switch (vk) { case VK_LBUTTON: return L"Mouse 1"; case VK_RBUTTON: return L"Mouse 2"; case VK_MBUTTON: return L"Mouse 3"; } } int flags = combination & (0xF << MOUSE_OFFSET); if (flags == HKM_MOUSE_XB1) { return L"Mouse 4"; } else if (flags == HKM_MOUSE_XB2) { return L"Mouse 5"; } else if (flags == HKM_MOUSE_WHUP) { return L"Mouse Wheel Up"; } else if (flags == HKM_MOUSE_WHDN) { return L"Mouse Wheel Down"; } return L""; } std::wstring HotkeyManager::VKToString(unsigned int vk, bool extendedKey) { if (_vkStringMap.find(vk) != _vkStringMap.end()) { return _vkStringMap[vk]; } if ( vk == 0x03 /* break */ || (vk >= 0x21 && vk <= 0x2f) /* arrow keys, home/insert/del, etc */ || (vk >= 0x5b && vk <= 0x5d) /* win, app keys (natural keyboard) */ || (vk == 0x90) /* num lock */ ) { extendedKey = true; } /* GetKeyNameText expects the following: * 16-23: scan code * 24: extended key flag * 25: 'do not care' bit (don't distinguish between L/R keys) */ unsigned int scanCode; if (vk == VK_PAUSE) scanCode = 0x45; /* MapVirtualKey is unable to map VK_PAUSE (this is a known bug), hence we map that by hand. */ else scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC); scanCode = scanCode << 16; if (vk == VK_RSHIFT) { /* For some reason, the right shift key ends up having its extended * key flag set and confuses GetKeyNameText. */ extendedKey = false; } int extended = extendedKey ? 0x1 : 0x0; scanCode |= extended << 24; wchar_t buf[256] = {}; GetKeyNameText(scanCode, buf, 256); return std::wstring(buf); } void HotkeyManager::VKStringTest() { for (unsigned int i = 0; i < 0xFF; ++i) { CLOG(L"%02x - %s", i, VKToString(i).c_str()); } } <|endoftext|>
<commit_before>#include "VolumeOSD.h" #include "..\SoundPlayer.h" #include <string> #include "..\HotkeyInfo.h" #include "..\MeterWnd\Meters\CallbackMeter.h" #include "..\Monitor.h" #include "..\Skin.h" #include "..\SkinManager.h" #include "..\Slider\VolumeSlider.h" #include "..\MeterWnd\LayeredWnd.h" #define MENU_SETTINGS 0 #define MENU_MIXER 1 #define MENU_EXIT 2 #define MENU_DEVICE 0xF000 VolumeOSD::VolumeOSD() : OSD(L"3RVX-VolumeDispatcher"), _mWnd(L"3RVX-VolumeOSD", L"3RVX-VolumeOSD"), _muteWnd(L"3RVX-MuteOSD", L"3RVX-MuteOSD") { LoadSkin(); Settings *settings = Settings::Instance(); /* Start the volume controller */ _volumeCtrl = new CoreAudio(_hWnd); std::wstring device = settings->AudioDeviceID(); _volumeCtrl->Init(device); _selectedDesc = _volumeCtrl->DeviceDesc(); /* Set up volume state variables */ _lastVolume = _volumeCtrl->Volume(); _muted = _volumeCtrl->Muted(); if (settings->SoundEffectsEnabled()) { _sounds = true; } /* Create the slider */ _volumeSlider = new VolumeSlider(*_volumeCtrl); /* Set up context menu */ if (settings->NotifyIconEnabled()) { _menu = CreatePopupMenu(); _deviceMenu = CreatePopupMenu(); InsertMenu(_menu, -1, MF_ENABLED, MENU_SETTINGS, L"Settings"); InsertMenu(_menu, -1, MF_POPUP, UINT(_deviceMenu), L"Audio Device"); InsertMenu(_menu, -1, MF_ENABLED, MENU_MIXER, L"Mixer"); InsertMenu(_menu, -1, MF_ENABLED, MENU_EXIT, L"Exit"); _menuFlags = TPM_RIGHTBUTTON; if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) { _menuFlags |= TPM_RIGHTALIGN; } else { _menuFlags |= TPM_LEFTALIGN; } UpdateDeviceMenu(); } _mWnd.AlwaysOnTop(settings->AlwaysOnTop()); _mWnd.HideAnimation(settings->HideAnim(), settings->HideSpeed()); _mWnd.VisibleDuration(settings->HideDelay()); _muteWnd.AlwaysOnTop(settings->AlwaysOnTop()); _muteWnd.HideAnimation(settings->HideAnim(), settings->HideSpeed()); _muteWnd.VisibleDuration(settings->HideDelay()); UpdateIcon(); float v = _volumeCtrl->Volume(); MeterLevels(v); _volumeSlider->MeterLevels(v); /* TODO: check whether we should show the OSD on startup or not. If so, post * a MSG_VOL_CHNG so that the volume level (or mute) is displayed: */ SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1); } VolumeOSD::~VolumeOSD() { DestroyMenu(_deviceMenu); DestroyMenu(_menu); delete _icon; delete _volumeSlider; delete _callbackMeter; _volumeCtrl->Dispose(); } void VolumeOSD::UpdateDeviceMenu() { if (_menu == NULL || _deviceMenu == NULL) { return; } /* Remove any devices currently in the menu first */ for (unsigned int i = 0; i < _deviceList.size(); ++i) { RemoveMenu(_deviceMenu, 0, MF_BYPOSITION); } _deviceList.clear(); std::list<VolumeController::DeviceInfo> devices = _volumeCtrl->ListDevices(); std::wstring currentDeviceId = _volumeCtrl->DeviceId(); int menuItem = MENU_DEVICE; for (VolumeController::DeviceInfo device : devices) { unsigned int flags = MF_ENABLED; if (currentDeviceId == device.id) { flags |= MF_CHECKED; } InsertMenu(_deviceMenu, -1, flags, menuItem++, device.name.c_str()); _deviceList.push_back(device); } } void VolumeOSD::LoadSkin() { Settings *settings = Settings::Instance(); Skin *skin = SkinManager::Instance()->CurrentSkin(); /* Volume OSD */ /* TODO: should make sure this isn't NULL! */ _mWnd.BackgroundImage(skin->volumeBackground); if (skin->volumeMask != NULL) { _mWnd.EnableGlass(skin->volumeMask); } for (Meter *m : skin->volumeMeters) { _mWnd.AddMeter(m); } /* Add a callback meter with the default volume increment for sounds */ _callbackMeter = new CallbackMeter( skin->DefaultVolumeUnits(), *this); _mWnd.AddMeter(_callbackMeter); /* Default volume increment */ _defaultIncrement = (float) (10000 / skin->DefaultVolumeUnits()) / 10000.0f; CLOG(L"Default volume increment: %f", _defaultIncrement); _mWnd.Update(); /* Mute OSD */ /* TODO: NULL check*/ _muteWnd.BackgroundImage(skin->muteBackground); if (skin->muteMask != NULL) { _muteWnd.EnableGlass(skin->muteMask); } _muteWnd.Update(); /* Create clones for additional monitors */ std::vector<Monitor> monitors = ActiveMonitors(); for (unsigned int i = 1; i < monitors.size(); ++i) { _mWnd.Clone(); _muteWnd.Clone(); } UpdateWindowPositions(monitors); /* Set up notification icon */ if (settings->NotifyIconEnabled()) { _iconImages = skin->volumeIconset; if (_iconImages.size() > 0) { _icon = new NotifyIcon(_hWnd, L"3RVX", _iconImages[0]); } } /* Enable sound effects, if any */ if (settings->SoundEffectsEnabled()) { if (skin->volumeSound) { _soundPlayer = skin->volumeSound; } } } void VolumeOSD::MeterLevels(float level) { _mWnd.MeterLevels(level); _mWnd.Update(); } void VolumeOSD::MeterChangeCallback(int units) { if (_soundPlayer) { _soundPlayer->Play(); } } void VolumeOSD::Hide() { _mWnd.Hide(false); _muteWnd.Hide(false); } void VolumeOSD::HideIcon() { delete _icon; } void VolumeOSD::UpdateIcon() { UpdateIconImage(); UpdateIconTip(); } void VolumeOSD::UpdateIconImage() { if (_icon == NULL) { return; } int icon = 0; if (_volumeCtrl->Muted() == false) { int vUnits = _iconImages.size() - 1; icon = (int) ceil(_volumeCtrl->Volume() * vUnits); } if (icon != _lastIcon) { _icon->UpdateIcon(_iconImages[icon]); _lastIcon = icon; } } void VolumeOSD::UpdateIconTip() { if (_icon == NULL) { return; } if (_volumeCtrl->Muted()) { _icon->UpdateToolTip(_selectedDesc + L": Muted"); } else { float v = _volumeCtrl->Volume(); std::wstring perc = std::to_wstring((int) (v * 100.0f)); std::wstring level = _selectedDesc + L": " + perc + L"%"; _icon->UpdateToolTip(level); } } void VolumeOSD::UnMute() { if (_volumeCtrl->Muted() == true) { _volumeCtrl->Muted(false); } } void VolumeOSD::ProcessHotkeys(HotkeyInfo &hki) { switch (hki.action) { case HotkeyInfo::IncreaseVolume: case HotkeyInfo::DecreaseVolume: UnMute(); ProcessVolumeHotkeys(hki); break; } _volumeCtrl->Volume( (float) (currentUnit + unitIncrement) * _defaultIncrement); SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1); break; case HotkeyInfo::Mute: _volumeCtrl->ToggleMute(); SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1); break; case HotkeyInfo::VolumeSlider: if (_volumeSlider->Visible()) { /* If the slider is already visible, user must want to close it. */ _volumeSlider->Hide(); } else { SendMessage(_hWnd, MSG_NOTIFYICON, NULL, WM_LBUTTONUP); } break; } } void VolumeOSD::ProcessVolumeHotkeys(HotkeyInfo &hki) { float currentVol = _volumeCtrl->Volume(); HotkeyInfo::VolumeKeyArgTypes type = HotkeyInfo::VolumeArgType(hki); if (type == HotkeyInfo::VolumeKeyArgTypes::Percentage) { /* Deal with percentage-based amounts */ float amount = (hki.ArgToDouble(0) / 100.0f); if (hki.action == HotkeyInfo::HotkeyActions::DecreaseVolume) { amount = -amount; } _volumeCtrl->Volume(currentVol + amount); } else { /* Unit-based amounts */ int unitIncrement = 1; int currentUnit = _callbackMeter->CalcUnits(); if (currentVol <= 0.000001f) { currentUnit = 0; } if (hki.action == HotkeyInfo::DecreaseVolume) { unitIncrement = -1; } if (type == HotkeyInfo::VolumeKeyArgTypes::Units) { unitIncrement *= hki.ArgToInt(0); } _volumeCtrl->Volume( (float) (currentUnit + unitIncrement) * _defaultIncrement); } /* Tell 3RVX that we changed the volume */ SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1); } void VolumeOSD::UpdateWindowPositions(std::vector<Monitor> &monitors) { PositionWindow(monitors[0], _mWnd); PositionWindow(monitors[0], _muteWnd); std::vector<LayeredWnd *> meterClones = _mWnd.Clones(); std::vector<LayeredWnd *> muteClones = _muteWnd.Clones(); for (unsigned int i = 1; i < monitors.size(); ++i) { PositionWindow(monitors[i], *meterClones[i - 1]); PositionWindow(monitors[i], *muteClones[i - 1]); } } void VolumeOSD::UpdateVolumeState() { float v = _volumeCtrl->Volume(); MeterLevels(v); _volumeSlider->MeterLevels(v); UpdateIcon(); } LRESULT VolumeOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == MSG_VOL_CHNG) { float v = _volumeCtrl->Volume(); bool muteState = _volumeCtrl->Muted(); _volumeSlider->MeterLevels(v); UpdateIcon(); if (wParam > 0) { /* We manually post a MSG_VOL_CHNG when modifying the volume with * hotkeys, so this CoreAudio-generated event can be ignored * by the OSD. */ CLOG(L"Ignoring volume change notification generated by 3RVX"); return DefWindowProc(hWnd, message, wParam, lParam); } CLOG(L"Volume change notification:\nNew level: %f\nPrevious: %f", v, _lastVolume); if (lParam == 0 && (muteState == _muted)) { if (abs(v - _lastVolume) < 0.0001f) { CLOG(L"No change in volume detected; ignoring event."); return DefWindowProc(hWnd, message, wParam, lParam); } } _lastVolume = v; _muted = muteState; if (_volumeSlider->Visible() == false) { if (_volumeCtrl->Muted() || v == 0.0f) { _muteWnd.Show(); _mWnd.Hide(false); } else { MeterLevels(v); _mWnd.Show(); _muteWnd.Hide(false); } HideOthers(Volume); } } else if (message == MSG_VOL_DEVCHNG) { CLOG(L"Volume device change detected."); if (_selectedDevice == L"") { _volumeCtrl->SelectDefaultDevice(); } else { HRESULT hr = _volumeCtrl->SelectDevice(_selectedDevice); if (FAILED(hr)) { _volumeCtrl->SelectDefaultDevice(); } } _selectedDesc = _volumeCtrl->DeviceDesc(); UpdateDeviceMenu(); UpdateVolumeState(); } else if (message == MSG_NOTIFYICON) { if (lParam == WM_LBUTTONUP) { _volumeSlider->MeterLevels(_volumeCtrl->Volume()); _volumeSlider->Show(); } else if (lParam == WM_RBUTTONUP) { POINT p; GetCursorPos(&p); SetForegroundWindow(hWnd); TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y, _hWnd, NULL); PostMessage(hWnd, WM_NULL, 0, 0); } } else if (message == WM_COMMAND) { int menuItem = LOWORD(wParam); switch (menuItem) { case MENU_SETTINGS: Settings::LaunchSettingsApp(); break; case MENU_MIXER: { CLOG(L"Menu: Mixer"); HINSTANCE code = ShellExecute(NULL, L"open", L"sndvol", NULL, NULL, SW_SHOWNORMAL); break; } case MENU_EXIT: CLOG(L"Menu: Exit: %d", (int) _masterWnd); SendMessage(_masterWnd, WM_CLOSE, NULL, NULL); break; } /* Device menu items */ if ((menuItem & MENU_DEVICE) > 0) { int device = menuItem & 0x0FFF; VolumeController::DeviceInfo selectedDev = _deviceList[device]; if (selectedDev.id != _volumeCtrl->DeviceId()) { /* A different device has been selected */ CLOG(L"Changing to volume device: %s", selectedDev.name.c_str()); _volumeCtrl->SelectDevice(selectedDev.id); UpdateDeviceMenu(); UpdateVolumeState(); } } } return DefWindowProc(hWnd, message, wParam, lParam); }<commit_msg>Implement SetVolume hotkey<commit_after>#include "VolumeOSD.h" #include "..\SoundPlayer.h" #include <string> #include "..\HotkeyInfo.h" #include "..\MeterWnd\Meters\CallbackMeter.h" #include "..\Monitor.h" #include "..\Skin.h" #include "..\SkinManager.h" #include "..\Slider\VolumeSlider.h" #include "..\MeterWnd\LayeredWnd.h" #define MENU_SETTINGS 0 #define MENU_MIXER 1 #define MENU_EXIT 2 #define MENU_DEVICE 0xF000 VolumeOSD::VolumeOSD() : OSD(L"3RVX-VolumeDispatcher"), _mWnd(L"3RVX-VolumeOSD", L"3RVX-VolumeOSD"), _muteWnd(L"3RVX-MuteOSD", L"3RVX-MuteOSD") { LoadSkin(); Settings *settings = Settings::Instance(); /* Start the volume controller */ _volumeCtrl = new CoreAudio(_hWnd); std::wstring device = settings->AudioDeviceID(); _volumeCtrl->Init(device); _selectedDesc = _volumeCtrl->DeviceDesc(); /* Set up volume state variables */ _lastVolume = _volumeCtrl->Volume(); _muted = _volumeCtrl->Muted(); if (settings->SoundEffectsEnabled()) { _sounds = true; } /* Create the slider */ _volumeSlider = new VolumeSlider(*_volumeCtrl); /* Set up context menu */ if (settings->NotifyIconEnabled()) { _menu = CreatePopupMenu(); _deviceMenu = CreatePopupMenu(); InsertMenu(_menu, -1, MF_ENABLED, MENU_SETTINGS, L"Settings"); InsertMenu(_menu, -1, MF_POPUP, UINT(_deviceMenu), L"Audio Device"); InsertMenu(_menu, -1, MF_ENABLED, MENU_MIXER, L"Mixer"); InsertMenu(_menu, -1, MF_ENABLED, MENU_EXIT, L"Exit"); _menuFlags = TPM_RIGHTBUTTON; if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) { _menuFlags |= TPM_RIGHTALIGN; } else { _menuFlags |= TPM_LEFTALIGN; } UpdateDeviceMenu(); } _mWnd.AlwaysOnTop(settings->AlwaysOnTop()); _mWnd.HideAnimation(settings->HideAnim(), settings->HideSpeed()); _mWnd.VisibleDuration(settings->HideDelay()); _muteWnd.AlwaysOnTop(settings->AlwaysOnTop()); _muteWnd.HideAnimation(settings->HideAnim(), settings->HideSpeed()); _muteWnd.VisibleDuration(settings->HideDelay()); UpdateIcon(); float v = _volumeCtrl->Volume(); MeterLevels(v); _volumeSlider->MeterLevels(v); /* TODO: check whether we should show the OSD on startup or not. If so, post * a MSG_VOL_CHNG so that the volume level (or mute) is displayed: */ SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1); } VolumeOSD::~VolumeOSD() { DestroyMenu(_deviceMenu); DestroyMenu(_menu); delete _icon; delete _volumeSlider; delete _callbackMeter; _volumeCtrl->Dispose(); } void VolumeOSD::UpdateDeviceMenu() { if (_menu == NULL || _deviceMenu == NULL) { return; } /* Remove any devices currently in the menu first */ for (unsigned int i = 0; i < _deviceList.size(); ++i) { RemoveMenu(_deviceMenu, 0, MF_BYPOSITION); } _deviceList.clear(); std::list<VolumeController::DeviceInfo> devices = _volumeCtrl->ListDevices(); std::wstring currentDeviceId = _volumeCtrl->DeviceId(); int menuItem = MENU_DEVICE; for (VolumeController::DeviceInfo device : devices) { unsigned int flags = MF_ENABLED; if (currentDeviceId == device.id) { flags |= MF_CHECKED; } InsertMenu(_deviceMenu, -1, flags, menuItem++, device.name.c_str()); _deviceList.push_back(device); } } void VolumeOSD::LoadSkin() { Settings *settings = Settings::Instance(); Skin *skin = SkinManager::Instance()->CurrentSkin(); /* Volume OSD */ /* TODO: should make sure this isn't NULL! */ _mWnd.BackgroundImage(skin->volumeBackground); if (skin->volumeMask != NULL) { _mWnd.EnableGlass(skin->volumeMask); } for (Meter *m : skin->volumeMeters) { _mWnd.AddMeter(m); } /* Add a callback meter with the default volume increment for sounds */ _callbackMeter = new CallbackMeter( skin->DefaultVolumeUnits(), *this); _mWnd.AddMeter(_callbackMeter); /* Default volume increment */ _defaultIncrement = (float) (10000 / skin->DefaultVolumeUnits()) / 10000.0f; CLOG(L"Default volume increment: %f", _defaultIncrement); _mWnd.Update(); /* Mute OSD */ /* TODO: NULL check*/ _muteWnd.BackgroundImage(skin->muteBackground); if (skin->muteMask != NULL) { _muteWnd.EnableGlass(skin->muteMask); } _muteWnd.Update(); /* Create clones for additional monitors */ std::vector<Monitor> monitors = ActiveMonitors(); for (unsigned int i = 1; i < monitors.size(); ++i) { _mWnd.Clone(); _muteWnd.Clone(); } UpdateWindowPositions(monitors); /* Set up notification icon */ if (settings->NotifyIconEnabled()) { _iconImages = skin->volumeIconset; if (_iconImages.size() > 0) { _icon = new NotifyIcon(_hWnd, L"3RVX", _iconImages[0]); } } /* Enable sound effects, if any */ if (settings->SoundEffectsEnabled()) { if (skin->volumeSound) { _soundPlayer = skin->volumeSound; } } } void VolumeOSD::MeterLevels(float level) { _mWnd.MeterLevels(level); _mWnd.Update(); } void VolumeOSD::MeterChangeCallback(int units) { if (_soundPlayer) { _soundPlayer->Play(); } } void VolumeOSD::Hide() { _mWnd.Hide(false); _muteWnd.Hide(false); } void VolumeOSD::HideIcon() { delete _icon; } void VolumeOSD::UpdateIcon() { UpdateIconImage(); UpdateIconTip(); } void VolumeOSD::UpdateIconImage() { if (_icon == NULL) { return; } int icon = 0; if (_volumeCtrl->Muted() == false) { int vUnits = _iconImages.size() - 1; icon = (int) ceil(_volumeCtrl->Volume() * vUnits); } if (icon != _lastIcon) { _icon->UpdateIcon(_iconImages[icon]); _lastIcon = icon; } } void VolumeOSD::UpdateIconTip() { if (_icon == NULL) { return; } if (_volumeCtrl->Muted()) { _icon->UpdateToolTip(_selectedDesc + L": Muted"); } else { float v = _volumeCtrl->Volume(); std::wstring perc = std::to_wstring((int) (v * 100.0f)); std::wstring level = _selectedDesc + L": " + perc + L"%"; _icon->UpdateToolTip(level); } } void VolumeOSD::UnMute() { if (_volumeCtrl->Muted() == true) { _volumeCtrl->Muted(false); } } void VolumeOSD::ProcessHotkeys(HotkeyInfo &hki) { switch (hki.action) { case HotkeyInfo::IncreaseVolume: case HotkeyInfo::DecreaseVolume: UnMute(); ProcessVolumeHotkeys(hki); break; case HotkeyInfo::SetVolume: { HotkeyInfo::VolumeKeyArgTypes type = HotkeyInfo::VolumeArgType(hki); if (type == HotkeyInfo::VolumeKeyArgTypes::NoArgs) { return; } else if (type == HotkeyInfo::VolumeKeyArgTypes::Units) { int numUnits = hki.ArgToInt(0); _volumeCtrl->Volume(numUnits * _defaultIncrement); } else if (type == HotkeyInfo::VolumeKeyArgTypes::Percentage) { double perc = hki.ArgToDouble(0); _volumeCtrl->Volume((float) perc); } } SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1); break; case HotkeyInfo::Mute: _volumeCtrl->ToggleMute(); SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1); break; case HotkeyInfo::VolumeSlider: if (_volumeSlider->Visible()) { /* If the slider is already visible, user must want to close it. */ _volumeSlider->Hide(); } else { SendMessage(_hWnd, MSG_NOTIFYICON, NULL, WM_LBUTTONUP); } break; } } void VolumeOSD::ProcessVolumeHotkeys(HotkeyInfo &hki) { float currentVol = _volumeCtrl->Volume(); HotkeyInfo::VolumeKeyArgTypes type = HotkeyInfo::VolumeArgType(hki); if (type == HotkeyInfo::VolumeKeyArgTypes::Percentage) { /* Deal with percentage-based amounts */ float amount = (hki.ArgToDouble(0) / 100.0f); if (hki.action == HotkeyInfo::HotkeyActions::DecreaseVolume) { amount = -amount; } _volumeCtrl->Volume(currentVol + amount); } else { /* Unit-based amounts */ int unitIncrement = 1; int currentUnit = _callbackMeter->CalcUnits(); if (currentVol <= 0.000001f) { currentUnit = 0; } if (hki.action == HotkeyInfo::DecreaseVolume) { unitIncrement = -1; } if (type == HotkeyInfo::VolumeKeyArgTypes::Units) { unitIncrement *= hki.ArgToInt(0); } _volumeCtrl->Volume( (float) (currentUnit + unitIncrement) * _defaultIncrement); } /* Tell 3RVX that we changed the volume */ SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1); } void VolumeOSD::UpdateWindowPositions(std::vector<Monitor> &monitors) { PositionWindow(monitors[0], _mWnd); PositionWindow(monitors[0], _muteWnd); std::vector<LayeredWnd *> meterClones = _mWnd.Clones(); std::vector<LayeredWnd *> muteClones = _muteWnd.Clones(); for (unsigned int i = 1; i < monitors.size(); ++i) { PositionWindow(monitors[i], *meterClones[i - 1]); PositionWindow(monitors[i], *muteClones[i - 1]); } } void VolumeOSD::UpdateVolumeState() { float v = _volumeCtrl->Volume(); MeterLevels(v); _volumeSlider->MeterLevels(v); UpdateIcon(); } LRESULT VolumeOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == MSG_VOL_CHNG) { float v = _volumeCtrl->Volume(); bool muteState = _volumeCtrl->Muted(); _volumeSlider->MeterLevels(v); UpdateIcon(); if (wParam > 0) { /* We manually post a MSG_VOL_CHNG when modifying the volume with * hotkeys, so this CoreAudio-generated event can be ignored * by the OSD. */ CLOG(L"Ignoring volume change notification generated by 3RVX"); return DefWindowProc(hWnd, message, wParam, lParam); } CLOG(L"Volume change notification:\nNew level: %f\nPrevious: %f", v, _lastVolume); if (lParam == 0 && (muteState == _muted)) { if (abs(v - _lastVolume) < 0.0001f) { CLOG(L"No change in volume detected; ignoring event."); return DefWindowProc(hWnd, message, wParam, lParam); } } _lastVolume = v; _muted = muteState; if (_volumeSlider->Visible() == false) { if (_volumeCtrl->Muted() || v == 0.0f) { _muteWnd.Show(); _mWnd.Hide(false); } else { MeterLevels(v); _mWnd.Show(); _muteWnd.Hide(false); } HideOthers(Volume); } } else if (message == MSG_VOL_DEVCHNG) { CLOG(L"Volume device change detected."); if (_selectedDevice == L"") { _volumeCtrl->SelectDefaultDevice(); } else { HRESULT hr = _volumeCtrl->SelectDevice(_selectedDevice); if (FAILED(hr)) { _volumeCtrl->SelectDefaultDevice(); } } _selectedDesc = _volumeCtrl->DeviceDesc(); UpdateDeviceMenu(); UpdateVolumeState(); } else if (message == MSG_NOTIFYICON) { if (lParam == WM_LBUTTONUP) { _volumeSlider->MeterLevels(_volumeCtrl->Volume()); _volumeSlider->Show(); } else if (lParam == WM_RBUTTONUP) { POINT p; GetCursorPos(&p); SetForegroundWindow(hWnd); TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y, _hWnd, NULL); PostMessage(hWnd, WM_NULL, 0, 0); } } else if (message == WM_COMMAND) { int menuItem = LOWORD(wParam); switch (menuItem) { case MENU_SETTINGS: Settings::LaunchSettingsApp(); break; case MENU_MIXER: { CLOG(L"Menu: Mixer"); HINSTANCE code = ShellExecute(NULL, L"open", L"sndvol", NULL, NULL, SW_SHOWNORMAL); break; } case MENU_EXIT: CLOG(L"Menu: Exit: %d", (int) _masterWnd); SendMessage(_masterWnd, WM_CLOSE, NULL, NULL); break; } /* Device menu items */ if ((menuItem & MENU_DEVICE) > 0) { int device = menuItem & 0x0FFF; VolumeController::DeviceInfo selectedDev = _deviceList[device]; if (selectedDev.id != _volumeCtrl->DeviceId()) { /* A different device has been selected */ CLOG(L"Changing to volume device: %s", selectedDev.name.c_str()); _volumeCtrl->SelectDevice(selectedDev.id); UpdateDeviceMenu(); UpdateVolumeState(); } } } return DefWindowProc(hWnd, message, wParam, lParam); }<|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "ExampleDiffusion.h" // If we use a material pointer we need to include the // material class #include "Material.h" /** * This function defines the valid parameters for * this Kernel and their default values */ template<> InputParameters validParams<ExampleDiffusion>() { InputParameters params = validParams<Diffusion>(); return params; } ExampleDiffusion::ExampleDiffusion(const std::string & name, InputParameters parameters) :Diffusion(name,parameters), _diffusivity(getMaterialProperty<Real>("diffusivity")) {} Real ExampleDiffusion::computeQpResidual() { // We're dereferencing the _diffusivity pointer to get to the // material properties vector... which gives us one property // value per quadrature point. // Also... we're reusing the Diffusion Kernel's residual // so that we don't have to recode that. return _diffusivity[_qp]*Diffusion::computeQpResidual(); } Real ExampleDiffusion::computeQpJacobian() { // We're dereferencing the _diffusivity pointer to get to the // material properties vector... which gives us one property // value per quadrature point. // Also... we're reusing the Diffusion Kernel's residual // so that we don't have to recode that. return _diffusivity[_qp]*Diffusion::computeQpJacobian(); } <commit_msg>No longer need to #include "Material.h" in this file.<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "ExampleDiffusion.h" /** * This function defines the valid parameters for * this Kernel and their default values */ template<> InputParameters validParams<ExampleDiffusion>() { InputParameters params = validParams<Diffusion>(); return params; } ExampleDiffusion::ExampleDiffusion(const std::string & name, InputParameters parameters) :Diffusion(name,parameters), _diffusivity(getMaterialProperty<Real>("diffusivity")) {} Real ExampleDiffusion::computeQpResidual() { // We're dereferencing the _diffusivity pointer to get to the // material properties vector... which gives us one property // value per quadrature point. // Also... we're reusing the Diffusion Kernel's residual // so that we don't have to recode that. return _diffusivity[_qp]*Diffusion::computeQpResidual(); } Real ExampleDiffusion::computeQpJacobian() { // We're dereferencing the _diffusivity pointer to get to the // material properties vector... which gives us one property // value per quadrature point. // Also... we're reusing the Diffusion Kernel's residual // so that we don't have to recode that. return _diffusivity[_qp]*Diffusion::computeQpJacobian(); } <|endoftext|>
<commit_before>/* -*-c++-*- * Copyright (C) 2009 Cedric Pinson <[email protected]> * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <iostream> #include <osgDB/ReadFile> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TerrainManipulator> #include <osg/Drawable> #include <osg/MatrixTransform> #include <osgAnimation/BasicAnimationManager> #include <osgAnimation/RigGeometry> #include <osgAnimation/RigTransformHardware> #include <osgAnimation/MorphGeometry> #include <osgAnimation/MorphTransformHardware> #include <osgAnimation/AnimationManagerBase> #include <osgAnimation/BoneMapVisitor> #include <sstream> static unsigned int getRandomValueinRange(unsigned int v) { return static_cast<unsigned int>((rand() * 1.0 * v)/(RAND_MAX-1)); } //osg::ref_ptr<osg::Program> program; // show how to override the default RigTransformHardware for customized usage struct MyRigTransformHardware : public osgAnimation::RigTransformHardware { virtual bool init(osgAnimation::RigGeometry& rig) { if(!rig.getSkeleton() && !rig.getParents().empty()) { osgAnimation::RigGeometry::FindNearestParentSkeleton finder; if(rig.getParents().size() > 1) osg::notify(osg::WARN) << "A RigGeometry should not have multi parent ( " << rig.getName() << " )" << std::endl; rig.getParents()[0]->accept(finder); if(!finder._root.valid()) { osg::notify(osg::WARN) << "A RigGeometry did not find a parent skeleton for RigGeometry ( " << rig.getName() << " )" << std::endl; return false; } rig.setSkeleton(finder._root.get()); } osgAnimation::BoneMapVisitor mapVisitor; rig.getSkeleton()->accept(mapVisitor); osgAnimation::BoneMap boneMap = mapVisitor.getBoneMap(); if (!buildPalette(boneMap,rig) ) return false; osg::Geometry& source = *rig.getSourceGeometry(); osg::Vec3Array* positionSrc = dynamic_cast<osg::Vec3Array*>(source.getVertexArray()); if (!positionSrc) { OSG_WARN << "RigTransformHardware no vertex array in the geometry " << rig.getName() << std::endl; return false; } // copy shallow from source geometry to rig rig.copyFrom(source); osg::ref_ptr<osg::Program> program ; osg::ref_ptr<osg::Shader> vertexshader; osg::ref_ptr<osg::StateSet> stateset = rig.getOrCreateStateSet(); //grab geom source program and vertex shader if _shader is not setted if(!_shader.valid() && (program = (osg::Program*)stateset->getAttribute(osg::StateAttribute::PROGRAM))) { for(unsigned int i=0; i<program->getNumShaders(); ++i) if(program->getShader(i)->getType()==osg::Shader::VERTEX) { vertexshader=program->getShader(i); program->removeShader(vertexshader); } } else { program = new osg::Program; program->setName("HardwareSkinning"); } //set default source if _shader is not user setted if (!vertexshader.valid()) { if (!_shader.valid()) vertexshader = osg::Shader::readShaderFile(osg::Shader::VERTEX,"shaders/skinning.vert"); else vertexshader=_shader; } if (!vertexshader.valid()) { OSG_WARN << "RigTransformHardware can't load VertexShader" << std::endl; return false; } // replace max matrix by the value from uniform { std::string str = vertexshader->getShaderSource(); std::string toreplace = std::string("MAX_MATRIX"); std::size_t start = str.find(toreplace); if (std::string::npos != start) { std::stringstream ss; ss << getMatrixPaletteUniform()->getNumElements(); str.replace(start, toreplace.size(), ss.str()); vertexshader->setShaderSource(str); } else { OSG_INFO<< "MAX_MATRIX not found in Shader! " << str << std::endl; } OSG_INFO << "Shader " << str << std::endl; } unsigned int attribIndex = 11; unsigned int nbAttribs = getNumVertexAttrib(); if(nbAttribs==0) OSG_WARN << "nbAttribs== " << nbAttribs << std::endl; for (unsigned int i = 0; i < nbAttribs; i++) { std::stringstream ss; ss << "boneWeight" << i; program->addBindAttribLocation(ss.str(), attribIndex + i); if(getVertexAttrib(i)->getNumElements()!=_nbVertices) OSG_WARN << "getVertexAttrib== " << getVertexAttrib(i)->getNumElements() << std::endl; rig.setVertexAttribArray(attribIndex + i, getVertexAttrib(i)); OSG_INFO << "set vertex attrib " << ss.str() << std::endl; } program->addShader(vertexshader.get()); stateset->removeUniform("nbBonesPerVertex"); stateset->addUniform(new osg::Uniform("nbBonesPerVertex",_bonesPerVertex)); stateset->removeUniform("matrixPalette"); stateset->addUniform(getMatrixPaletteUniform()); stateset->removeAttribute(osg::StateAttribute::PROGRAM); if(!stateset->getAttribute(osg::StateAttribute::PROGRAM)) stateset->setAttributeAndModes(program.get()); _needInit = false; return true; } }; struct SetupRigGeometry : public osg::NodeVisitor { bool _hardware; SetupRigGeometry( bool hardware = true) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _hardware(hardware) {} void apply(osg::Geode& geode) { for (unsigned int i = 0; i < geode.getNumDrawables(); i++) apply(*geode.getDrawable(i)); } void apply(osg::Drawable& geom) { if (_hardware) { osgAnimation::RigGeometry* rig = dynamic_cast<osgAnimation::RigGeometry*>(&geom); if (rig){ rig->setRigTransformImplementation(new MyRigTransformHardware); osgAnimation::MorphGeometry *morph=dynamic_cast<osgAnimation::MorphGeometry*>(rig->getSourceGeometry()); if(morph)morph->setMorphTransformImplementation(new osgAnimation::MorphTransformHardware); } } #if 0 if (geom.getName() != std::string("BoundingBox")) // we disable compute of bounding box for all geometry except our bounding box geom.setComputeBoundingBoxCallback(new osg::Drawable::ComputeBoundingBoxCallback); // geom.setInitialBound(new osg::Drawable::ComputeBoundingBoxCallback); #endif } }; osg::Group* createCharacterInstance(osg::Group* character, bool hardware) { osg::ref_ptr<osg::Group> c ; if (hardware) c = osg::clone(character, osg::CopyOp::DEEP_COPY_ALL & ~osg::CopyOp::DEEP_COPY_PRIMITIVES & ~osg::CopyOp::DEEP_COPY_ARRAYS); else c = osg::clone(character, osg::CopyOp::DEEP_COPY_ALL); osgAnimation::AnimationManagerBase* animationManager = dynamic_cast<osgAnimation::AnimationManagerBase*>(c->getUpdateCallback()); osgAnimation::BasicAnimationManager* anim = dynamic_cast<osgAnimation::BasicAnimationManager*>(animationManager); const osgAnimation::AnimationList& list = animationManager->getAnimationList(); int v = getRandomValueinRange(list.size()); if (list[v]->getName() == std::string("MatIpo_ipo")) { anim->playAnimation(list[v].get()); v = (v + 1)%list.size(); } anim->playAnimation(list[v].get()); SetupRigGeometry switcher(hardware); c->accept(switcher); return c.release(); } int main (int argc, char* argv[]) { std::cerr << "This example works better with nathan.osg" << std::endl; osg::ArgumentParser psr(&argc, argv); osgViewer::Viewer viewer(psr); bool hardware = true; int maxChar = 10; while (psr.read("--software")) { hardware = false; } while (psr.read("--number", maxChar)) {} osg::ref_ptr<osg::Node> node = osgDB::readRefNodeFiles(psr); osg::ref_ptr<osg::Group> root = dynamic_cast<osg::Group*>(node.get()); if (!root) { std::cout << psr.getApplicationName() <<": No data loaded" << std::endl; return 1; } { osgAnimation::AnimationManagerBase* animationManager = dynamic_cast<osgAnimation::AnimationManagerBase*>(root->getUpdateCallback()); if(!animationManager) { osg::notify(osg::FATAL) << "no AnimationManagerBase found, updateCallback need to animate elements" << std::endl; return 1; } } osg::ref_ptr<osg::Group> scene = new osg::Group; // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add the thread model handler viewer.addEventHandler(new osgViewer::ThreadingHandler); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add the help handler viewer.addEventHandler(new osgViewer::HelpHandler(psr.getApplicationUsage())); // add the LOD Scale handler viewer.addEventHandler(new osgViewer::LODScaleHandler); // add the screen capture handler viewer.addEventHandler(new osgViewer::ScreenCaptureHandler); viewer.setSceneData(scene.get()); viewer.realize(); double xChar = maxChar; double yChar = xChar * 9.0/16; for (double i = 0.0; i < xChar; i++) { for (double j = 0.0; j < yChar; j++) { osg::ref_ptr<osg::Group> c = createCharacterInstance(root.get(), hardware); osg::MatrixTransform* tr = new osg::MatrixTransform; tr->setMatrix(osg::Matrix::translate( 2.0 * (i - xChar * .5), 0.0, 2.0 * (j - yChar * .5))); tr->addChild(c.get()); scene->addChild(tr); } } std::cout << "created " << xChar * yChar << " instance" << std::endl; return viewer.run(); } <commit_msg>update example to use a common program<commit_after>/* -*-c++-*- * Copyright (C) 2009 Cedric Pinson <[email protected]> * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <iostream> #include <osgDB/ReadFile> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TerrainManipulator> #include <osg/Drawable> #include <osg/MatrixTransform> #include <osgAnimation/BasicAnimationManager> #include <osgAnimation/RigGeometry> #include <osgAnimation/RigTransformHardware> #include <osgAnimation/MorphGeometry> #include <osgAnimation/MorphTransformHardware> #include <osgAnimation/AnimationManagerBase> #include <osgAnimation/BoneMapVisitor> #include <sstream> static unsigned int getRandomValueinRange(unsigned int v) { return static_cast<unsigned int>((rand() * 1.0 * v)/(RAND_MAX-1)); } osg::ref_ptr<osg::Program> CommonProgram; // show how to override the default RigTransformHardware for customized usage struct MyRigTransformHardware : public osgAnimation::RigTransformHardware { int _maxmatrix; MyRigTransformHardware() : _maxmatrix(99){} virtual bool init(osgAnimation::RigGeometry& rig) { if(_perVertexInfluences.empty()) { prepareData(rig); return false; } if(!rig.getSkeleton()) return false; osgAnimation::BoneMapVisitor mapVisitor; rig.getSkeleton()->accept(mapVisitor); osgAnimation::BoneMap boneMap = mapVisitor.getBoneMap(); if (!buildPalette(boneMap,rig) ) return false; osg::Geometry& source = *rig.getSourceGeometry(); osg::Vec3Array* positionSrc = dynamic_cast<osg::Vec3Array*>(source.getVertexArray()); if (!positionSrc) { OSG_WARN << "RigTransformHardware no vertex array in the geometry " << rig.getName() << std::endl; return false; } // copy shallow from source geometry to rig rig.copyFrom(source); osg::ref_ptr<osg::Shader> vertexshader; osg::ref_ptr<osg::StateSet> stateset = rig.getOrCreateStateSet(); if(!CommonProgram.valid()){ CommonProgram = new osg::Program; CommonProgram->setName("HardwareSkinning"); //set default source if _shader is not user setted if (!vertexshader.valid()) { vertexshader = osg::Shader::readShaderFile(osg::Shader::VERTEX,"skinning.vert"); } if (!vertexshader.valid()) { OSG_WARN << "RigTransformHardware can't load VertexShader" << std::endl; return false; } // replace max matrix by the value from uniform { std::string str = vertexshader->getShaderSource(); std::string toreplace = std::string("MAX_MATRIX"); std::size_t start = str.find(toreplace); if (std::string::npos != start) { std::stringstream ss; ss << _maxmatrix;//getMatrixPaletteUniform()->getNumElements(); str.replace(start, toreplace.size(), ss.str()); vertexshader->setShaderSource(str); } else { OSG_WARN<< "MAX_MATRIX not found in Shader! " << str << std::endl; } OSG_INFO << "Shader " << str << std::endl; } CommonProgram->addShader(vertexshader.get()); } unsigned int nbAttribs = getNumVertexAttrib(); for (unsigned int i = 0; i < nbAttribs; i++) { std::stringstream ss; ss << "boneWeight" << i; CommonProgram->addBindAttribLocation(ss.str(), _minAttribIndex + i); rig.setVertexAttribArray(_minAttribIndex + i, getVertexAttrib(i)); OSG_INFO << "set vertex attrib " << ss.str() << std::endl; } stateset->removeUniform("nbBonesPerVertex"); stateset->addUniform(new osg::Uniform("nbBonesPerVertex",_bonesPerVertex)); stateset->removeUniform("matrixPalette"); stateset->addUniform(_uniformMatrixPalette); stateset->setAttribute(CommonProgram.get()); _needInit = false; return true; } }; struct SetupRigGeometry : public osg::NodeVisitor { bool _hardware; SetupRigGeometry( bool hardware = true) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _hardware(hardware) {} void apply(osg::Geode& geode) { for (unsigned int i = 0; i < geode.getNumDrawables(); i++) apply(*geode.getDrawable(i)); } void apply(osg::Drawable& geom) { if (_hardware) { osgAnimation::RigGeometry* rig = dynamic_cast<osgAnimation::RigGeometry*>(&geom); if (rig){ rig->setRigTransformImplementation(new MyRigTransformHardware); osgAnimation::MorphGeometry *morph=dynamic_cast<osgAnimation::MorphGeometry*>(rig->getSourceGeometry()); if(morph)morph->setMorphTransformImplementation(new osgAnimation::MorphTransformHardware); } } #if 0 if (geom.getName() != std::string("BoundingBox")) // we disable compute of bounding box for all geometry except our bounding box geom.setComputeBoundingBoxCallback(new osg::Drawable::ComputeBoundingBoxCallback); // geom.setInitialBound(new osg::Drawable::ComputeBoundingBoxCallback); #endif } }; osg::Group* createCharacterInstance(osg::Group* character, bool hardware) { osg::ref_ptr<osg::Group> c ; if (hardware) c = osg::clone(character, osg::CopyOp::DEEP_COPY_ALL & ~osg::CopyOp::DEEP_COPY_PRIMITIVES & ~osg::CopyOp::DEEP_COPY_ARRAYS); else c = osg::clone(character, osg::CopyOp::DEEP_COPY_ALL); osgAnimation::AnimationManagerBase* animationManager = dynamic_cast<osgAnimation::AnimationManagerBase*>(c->getUpdateCallback()); osgAnimation::BasicAnimationManager* anim = dynamic_cast<osgAnimation::BasicAnimationManager*>(animationManager); const osgAnimation::AnimationList& list = animationManager->getAnimationList(); int v = getRandomValueinRange(list.size()); if (list[v]->getName() == std::string("MatIpo_ipo")) { anim->playAnimation(list[v].get()); v = (v + 1)%list.size(); } anim->playAnimation(list[v].get()); SetupRigGeometry switcher(hardware); c->accept(switcher); return c.release(); } int main (int argc, char* argv[]) { std::cerr << "This example works better with nathan.osg" << std::endl; osg::ArgumentParser psr(&argc, argv); osgViewer::Viewer viewer(psr); bool hardware = true; int maxChar = 10; while (psr.read("--software")) { hardware = false; } while (psr.read("--number", maxChar)) {} osg::ref_ptr<osg::Node> node = osgDB::readRefNodeFiles(psr); osg::ref_ptr<osg::Group> root = dynamic_cast<osg::Group*>(node.get()); if (!root) { std::cout << psr.getApplicationName() <<": No data loaded" << std::endl; return 1; } { osgAnimation::AnimationManagerBase* animationManager = dynamic_cast<osgAnimation::AnimationManagerBase*>(root->getUpdateCallback()); if(!animationManager) { osg::notify(osg::FATAL) << "no AnimationManagerBase found, updateCallback need to animate elements" << std::endl; return 1; } } osg::ref_ptr<osg::Group> scene = new osg::Group; // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add the thread model handler viewer.addEventHandler(new osgViewer::ThreadingHandler); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add the help handler viewer.addEventHandler(new osgViewer::HelpHandler(psr.getApplicationUsage())); // add the LOD Scale handler viewer.addEventHandler(new osgViewer::LODScaleHandler); // add the screen capture handler viewer.addEventHandler(new osgViewer::ScreenCaptureHandler); viewer.setSceneData(scene.get()); viewer.realize(); double xChar = maxChar; double yChar = xChar * 9.0/16; for (double i = 0.0; i < xChar; i++) { for (double j = 0.0; j < yChar; j++) { osg::ref_ptr<osg::Group> c = createCharacterInstance(root.get(), hardware); osg::MatrixTransform* tr = new osg::MatrixTransform; tr->setMatrix(osg::Matrix::translate( 2.0 * (i - xChar * .5), 0.0, 2.0 * (j - yChar * .5))); tr->addChild(c.get()); scene->addChild(tr); } } std::cout << "created " << xChar * yChar << " instance" << std::endl; return viewer.run(); } <|endoftext|>
<commit_before>/* MIT License Copyright (c) 2017 Leonid Keselman 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. https://github.com/leonidk/imshow/blob/master/LICENSE */ #include "imshow/imshow.h" #include <GLFW/glfw3.h> #include <mutex> #include <unordered_map> #include <string> #include <stdint.h> #include <memory> #include <iostream> #include <vector> #pragma comment( lib, "opengl32" ) namespace glfw { char g_key; bool g_key_update = false; bool g_close = true; std::mutex g_mutex; struct winState { GLFWwindow* win; GLuint tex; Image image; int x, y; // screen position }; std::unordered_map<std::string, winState> g_windows; static winState * getWindowState(GLFWwindow *window) { for (auto & win : g_windows) { if (win.second.win == window) { return &win.second; } } return nullptr; } static void render_callback(GLFWwindow * window) { glPushAttrib(GL_ALL_ATTRIB_BITS); glPushMatrix(); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA); glClearColor(0, 0, 0, 1.0f); glClear(GL_COLOR_BUFFER_BIT); { const auto win = getWindowState(window); glBindTexture(GL_TEXTURE_2D, win->tex); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex2f(-1, -1); glTexCoord2f(1, 1); glVertex2f(1, -1); glTexCoord2f(1, 0); glVertex2f(1, 1); glTexCoord2f(0, 0); glVertex2f(-1, 1); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); } glDisable(GL_TEXTURE_2D); glDisable(GL_ALPHA); glPopMatrix(); glPopAttrib(); } static void position_callback(GLFWwindow *window, int x, int y) { if(auto win = getWindowState(window)) { win->x = x; win->y = y; } } static void focus_callback(GLFWwindow *window, int focus) { if(focus) { glfwMakeContextCurrent(window); render_callback(window); glfwSwapBuffers(window); } } static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { g_key = tolower(key); g_key_update = true; } } static void framebuffer_size_callback(GLFWwindow* window, int width, int height) { const auto win = getWindowState(window); const float wScale = ((float)width) / ((float)win->image.width); const float hScale = ((float)height) / ((float)win->image.height); const float minScale = (wScale < hScale) ? wScale : hScale; const int wShift = (int)nearbyint((width - minScale*win->image.width) / 2.0f); const int hShift = (int)nearbyint((height - minScale*win->image.height) / 2.0f); glfwMakeContextCurrent(window); glViewport(wShift, hShift, (int)nearbyint(win->image.width*minScale), (int)nearbyint(win->image.height*minScale)); render_callback(window); glfwSwapBuffers(window); } static void refresh_callback(GLFWwindow *window) { glfwMakeContextCurrent(window); render_callback(window); glfwSwapBuffers(window); } static void window_close_callback(GLFWwindow *window) { // For a key update for the main loop g_close = true; glfwMakeContextCurrent(window); glfwSetWindowShouldClose(window, GLFW_TRUE); glfwPostEmptyEvent(); } static void eraseWindow(std::unordered_map<std::string, winState>::const_iterator iter) { // Always invalidate window with existing name glfwMakeContextCurrent(iter->second.win); glfwDestroyWindow(iter->second.win); glDeleteTextures(1,&iter->second.tex); g_windows.erase(iter); } static void eraseWindow(const char *name) { auto iter = g_windows.find(name); if(iter != g_windows.end()) { eraseWindow(iter); } } void imshow(const char * name, const Image & img) { std::unique_lock<std::mutex> lock(g_mutex); if(g_windows.empty()) { glfwInit(); } std::string s_name(name); bool hasWindow = false; int x, y; auto iter = g_windows.find(s_name); if(iter != g_windows.end()) { hasWindow = true; x = iter->second.x; y = iter->second.y; eraseWindow(iter); iter = g_windows.end(); } if (iter == g_windows.end()) { // OS X: // * must create window prior to glGenTextures on OS X // * glfw complains w/ the following error on >= 10.12 auto window = glfwCreateWindow(img.width, img.height, s_name.c_str(), NULL, NULL); glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetWindowRefreshCallback(window, render_callback); glfwSetWindowFocusCallback(window, focus_callback); glfwSetWindowPosCallback(window, position_callback); glfwSetWindowRefreshCallback(window, refresh_callback); glfwSetWindowCloseCallback(window, window_close_callback); GLuint tex; glGenTextures(1, &tex); if(hasWindow) { glfwSetWindowPos(window, x, y); } else { glfwGetWindowPos(window, &x, &y); } g_windows[s_name] = {window, tex, img, x, y}; } GLuint format, type; switch (img.type) { case IM_8U: type = GL_UNSIGNED_BYTE; break; case IM_8I: type = GL_BYTE; break; case IM_16U: type = GL_UNSIGNED_SHORT; break; case IM_16I: type = GL_SHORT; break; case IM_32U: type = GL_UNSIGNED_INT; break; case IM_32I: type = GL_INT; break; case IM_32F: type = GL_FLOAT; break; case IM_64F: type = GL_DOUBLE; break; default: return; } switch (img.channels) { case 0: case 1: format = GL_LUMINANCE; break; case 2: format = GL_LUMINANCE_ALPHA; break; case 3: format = GL_BGR; break; case 4: format = GL_BGRA; break; } auto window = g_windows[s_name]; glfwMakeContextCurrent(window.win); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D, window.tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, img.width, img.height, 0, format, type, img.data); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glBindTexture(GL_TEXTURE_2D, 0); render_callback(window.win); glfwSwapBuffers(window.win); } char getKey(bool wait) { std::unique_lock<std::mutex> lock(g_mutex); g_close = false; std::vector<std::string> toDelete; for (const auto & win : g_windows) { if (glfwWindowShouldClose(win.second.win)) { g_close = true; toDelete.push_back(win.first); } else { glfwMakeContextCurrent(win.second.win); glfwSwapBuffers(win.second.win); lock.unlock(); if (wait && !g_close) { do { glfwWaitEvents(); if(glfwWindowShouldClose(win.second.win)) { g_close = true; toDelete.push_back(win.first); } } while (!g_key_update && !g_close); } else { glfwPollEvents(); } lock.lock(); if (!g_key_update) { g_key = '\0'; } } } g_key_update = false; for (const auto & name : toDelete) { eraseWindow(name.c_str()); } return g_key; } } <commit_msg>fix startup aspect ratio<commit_after>/* MIT License Copyright (c) 2017 Leonid Keselman 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. https://github.com/leonidk/imshow/blob/master/LICENSE */ #include "imshow/imshow.h" #include <GLFW/glfw3.h> #include <mutex> #include <unordered_map> #include <string> #include <stdint.h> #include <memory> #include <iostream> #include <vector> #pragma comment( lib, "opengl32" ) namespace glfw { char g_key; bool g_key_update = false; bool g_close = true; std::mutex g_mutex; struct winState { GLFWwindow* win; GLuint tex; Image image; int x, y; // screen position }; std::unordered_map<std::string, winState> g_windows; static winState * getWindowState(GLFWwindow *window) { for (auto & win : g_windows) { if (win.second.win == window) { return &win.second; } } return nullptr; } static void render_callback(GLFWwindow * window) { glPushAttrib(GL_ALL_ATTRIB_BITS); glPushMatrix(); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA); glClearColor(0, 0, 0, 1.0f); glClear(GL_COLOR_BUFFER_BIT); { const auto win = getWindowState(window); glBindTexture(GL_TEXTURE_2D, win->tex); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex2f(-1, -1); glTexCoord2f(1, 1); glVertex2f(1, -1); glTexCoord2f(1, 0); glVertex2f(1, 1); glTexCoord2f(0, 0); glVertex2f(-1, 1); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); } glDisable(GL_TEXTURE_2D); glDisable(GL_ALPHA); glPopMatrix(); glPopAttrib(); } static void position_callback(GLFWwindow *window, int x, int y) { if(auto win = getWindowState(window)) { win->x = x; win->y = y; } } static void focus_callback(GLFWwindow *window, int focus) { if(focus) { glfwMakeContextCurrent(window); render_callback(window); glfwSwapBuffers(window); } } static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { g_key = tolower(key); g_key_update = true; } } static void framebuffer_size_callback(GLFWwindow* window, int width, int height) { const auto win = getWindowState(window); const float wScale = ((float)width) / ((float)win->image.width); const float hScale = ((float)height) / ((float)win->image.height); const float minScale = (wScale < hScale) ? wScale : hScale; const int wShift = (int)nearbyint((width - minScale*win->image.width) / 2.0f); const int hShift = (int)nearbyint((height - minScale*win->image.height) / 2.0f); glfwMakeContextCurrent(window); glViewport(wShift, hShift, (int)nearbyint(win->image.width*minScale), (int)nearbyint(win->image.height*minScale)); render_callback(window); glfwSwapBuffers(window); } static void refresh_callback(GLFWwindow *window) { glfwMakeContextCurrent(window); render_callback(window); glfwSwapBuffers(window); } static void window_close_callback(GLFWwindow *window) { // For a key update for the main loop g_close = true; glfwMakeContextCurrent(window); glfwSetWindowShouldClose(window, GLFW_TRUE); glfwPostEmptyEvent(); } static void eraseWindow(std::unordered_map<std::string, winState>::const_iterator iter) { // Always invalidate window with existing name glfwMakeContextCurrent(iter->second.win); glfwDestroyWindow(iter->second.win); glDeleteTextures(1,&iter->second.tex); g_windows.erase(iter); } static void eraseWindow(const char *name) { auto iter = g_windows.find(name); if(iter != g_windows.end()) { eraseWindow(iter); } } void imshow(const char * name, const Image & img) { std::unique_lock<std::mutex> lock(g_mutex); if(g_windows.empty()) { glfwInit(); } std::string s_name(name); bool hasWindow = false; int x, y; auto iter = g_windows.find(s_name); if(iter != g_windows.end()) { hasWindow = true; x = iter->second.x; y = iter->second.y; eraseWindow(iter); iter = g_windows.end(); } if (iter == g_windows.end()) { // OS X: // * must create window prior to glGenTextures on OS X // * glfw complains w/ the following error on >= 10.12 auto window = glfwCreateWindow(img.width, img.height, s_name.c_str(), NULL, NULL); glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetWindowRefreshCallback(window, render_callback); glfwSetWindowFocusCallback(window, focus_callback); glfwSetWindowPosCallback(window, position_callback); glfwSetWindowRefreshCallback(window, refresh_callback); glfwSetWindowCloseCallback(window, window_close_callback); GLuint tex; glGenTextures(1, &tex); if(hasWindow) { glfwSetWindowPos(window, x, y); } else { glfwGetWindowPos(window, &x, &y); } g_windows[s_name] = {window, tex, img, x, y}; } GLuint format, type; switch (img.type) { case IM_8U: type = GL_UNSIGNED_BYTE; break; case IM_8I: type = GL_BYTE; break; case IM_16U: type = GL_UNSIGNED_SHORT; break; case IM_16I: type = GL_SHORT; break; case IM_32U: type = GL_UNSIGNED_INT; break; case IM_32I: type = GL_INT; break; case IM_32F: type = GL_FLOAT; break; case IM_64F: type = GL_DOUBLE; break; default: return; } switch (img.channels) { case 0: case 1: format = GL_LUMINANCE; break; case 2: format = GL_LUMINANCE_ALPHA; break; case 3: format = GL_BGR; break; case 4: format = GL_BGRA; break; } auto window = g_windows[s_name]; glfwMakeContextCurrent(window.win); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D, window.tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, img.width, img.height, 0, format, type, img.data); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glBindTexture(GL_TEXTURE_2D, 0); // Retrieve actual size of allocated window framebuffer: int width, height; glfwGetFramebufferSize(window.win, &width, &height); framebuffer_size_callback(window.win, width, height); } char getKey(bool wait) { std::unique_lock<std::mutex> lock(g_mutex); g_close = false; std::vector<std::string> toDelete; for (const auto & win : g_windows) { if (glfwWindowShouldClose(win.second.win)) { g_close = true; toDelete.push_back(win.first); } else { glfwMakeContextCurrent(win.second.win); glfwSwapBuffers(win.second.win); lock.unlock(); if (wait && !g_close) { do { glfwWaitEvents(); if(glfwWindowShouldClose(win.second.win)) { g_close = true; toDelete.push_back(win.first); } } while (!g_key_update && !g_close); } else { glfwPollEvents(); } lock.lock(); if (!g_key_update) { g_key = '\0'; } } } g_key_update = false; for (const auto & name : toDelete) { eraseWindow(name.c_str()); } return g_key; } } <|endoftext|>
<commit_before>/* * 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. * * Written (W) 2012 Michal Uricar * Copyright (C) 2012 Michal Uricar */ #include <shogun/classifier/svm/LibLinear.h> #include <shogun/features/DenseFeatures.h> #include <shogun/io/SGIO.h> #include <shogun/labels/MulticlassLabels.h> #include <shogun/labels/StructuredLabels.h> #include <shogun/lib/common.h> #include <shogun/loss/HingeLoss.h> #include <shogun/machine/LinearMulticlassMachine.h> #include <shogun/mathematics/Math.h> #include <shogun/multiclass/MulticlassOneVsRestStrategy.h> #include <shogun/structure/MulticlassSOLabels.h> #include <shogun/structure/MulticlassModel.h> #include <shogun/structure/DualLibQPBMSOSVM.h> #include <shogun/io/streaming/StreamingAsciiFile.h> #include <shogun/features/streaming/StreamingSparseFeatures.h> using namespace shogun; /** Reads multiclass trainig data stored in svmlight format (i.e. label nz_idx_1:value1 nz_idx_2:value2 ... nz_idx_N:valueN ) * * @param fname path to file with training data * @param DIM dimension of features * @param N number of feature vectors * @param labs vector with labels * @param feats matrix with features */ void read_data(const char fname[], uint32_t DIM, uint32_t N, SGVector< float64_t > *labs, SGMatrix< float64_t > *feats) { CStreamingAsciiFile* file=new CStreamingAsciiFile(fname); SG_REF(file); CStreamingSparseFeatures< float64_t >* stream_features= new CStreamingSparseFeatures< float64_t >(file, true, 1024); SG_REF(stream_features); SGVector<float64_t > vec(DIM); stream_features->start_parser(); uint32_t num_vectors=0; while( stream_features->get_next_example() ) { vec.zero(); stream_features->add_to_dense_vec(1.0, vec, DIM); (*labs)[num_vectors]=stream_features->get_label(); for(uint32_t i=0; i<DIM; ++i) { (*feats)[num_vectors*DIM+i]=vec[i]; } num_vectors++; stream_features->release_example(); } stream_features->end_parser(); SG_UNREF(stream_features); } int main(int argc, char * argv[]) { // initialization //------------------------------------------------------------------------- float64_t lambda=0.01, eps=0.01; bool icp=1; uint32_t cp_models=1; ESolver solver=BMRM; uint32_t feat_dim, num_feat; init_shogun_with_defaults(); if (argc < 8) { SG_SERROR("Usage: so_multiclass_BMRM <data.in> <feat_dim> <num_feat> <lambda> <icp> <epsilon> <solver> [<cp_models>]\n"); return -1; } SG_SPRINT("arg[1] = %s\n", argv[1]); feat_dim=::atoi(argv[2]); num_feat=::atoi(argv[3]); lambda=::atof(argv[4]); icp=::atoi(argv[5]); eps=::atof(argv[6]); if (strcmp("BMRM", argv[7])==0) solver=BMRM; if (strcmp("PPBMRM", argv[7])==0) solver=PPBMRM; if (strcmp("P3BMRM", argv[7])==0) solver=P3BMRM; if (argc > 8) { cp_models=::atoi(argv[8]); } SGVector< float64_t >* labs= new SGVector< float64_t >(num_feat); SGMatrix< float64_t >* feats= new SGMatrix< float64_t >(feat_dim, num_feat); // read data read_data(argv[1], feat_dim, num_feat, labs, feats); // Create train labels CMulticlassSOLabels* labels = new CMulticlassSOLabels(*labs); // Create train features CDenseFeatures< float64_t >* features = new CDenseFeatures< float64_t >(*feats); // Create structured model CMulticlassModel* model = new CMulticlassModel(features, labels); // Create loss function CHingeLoss* loss = new CHingeLoss(); // Create SO-SVM CDualLibQPBMSOSVM* sosvm = new CDualLibQPBMSOSVM( model, loss, labels, lambda); SG_REF(sosvm); sosvm->set_cleanAfter(10); sosvm->set_cleanICP(icp); sosvm->set_TolRel(eps); sosvm->set_cp_models(cp_models); sosvm->set_solver(solver); // Train //------------------------------------------------------------------------- SG_SPRINT("Train using lambda = %lf ICP removal = %d \n", sosvm->get_lambda(), sosvm->get_cleanICP()); sosvm->train(); bmrm_return_value_T res = sosvm->get_result(); SG_SPRINT("result = { Fp=%lf, Fd=%lf, nIter=%d, nCP=%d, nzA=%d, exitflag=%d }\n", res.Fp, res.Fd, res.nIter, res.nCP, res.nzA, res.exitflag); CStructuredLabels* out = CStructuredLabels::obtain_from_generic(sosvm->apply()); SG_REF(out); SG_SPRINT("\n"); // Compute error //------------------------------------------------------------------------- float64_t error=0.0; for (uint32_t i=0; i<num_feat; ++i) { error+=(( (CRealNumber*) out->get_label(i) )->value==labs->get_element(i)) ? 0.0 : 1.0; } SG_SPRINT("Error = %lf %% \n", error/num_feat*100); // Free memory SG_UNREF(sosvm); SG_UNREF(out); exit_shogun(); return 0; } <commit_msg>BMRM libshogun example fix (runnable without cmd arguments)<commit_after>/* * 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. * * Written (W) 2012 Michal Uricar * Copyright (C) 2012 Michal Uricar */ #include <shogun/classifier/svm/LibLinear.h> #include <shogun/features/DenseFeatures.h> #include <shogun/io/SGIO.h> #include <shogun/labels/MulticlassLabels.h> #include <shogun/labels/StructuredLabels.h> #include <shogun/lib/common.h> #include <shogun/loss/HingeLoss.h> #include <shogun/machine/LinearMulticlassMachine.h> #include <shogun/mathematics/Math.h> #include <shogun/multiclass/MulticlassOneVsRestStrategy.h> #include <shogun/structure/MulticlassSOLabels.h> #include <shogun/structure/MulticlassModel.h> #include <shogun/structure/DualLibQPBMSOSVM.h> #include <shogun/io/streaming/StreamingAsciiFile.h> #include <shogun/features/streaming/StreamingSparseFeatures.h> using namespace shogun; #define DIMS 2 #define EPSILON 10e-5 #define NUM_SAMPLES 100 #define NUM_CLASSES 10 char FNAME[] = "data.svmlight"; /** Reads multiclass trainig data stored in svmlight format (i.e. label nz_idx_1:value1 nz_idx_2:value2 ... nz_idx_N:valueN ) * * @param fname path to file with training data * @param DIM dimension of features * @param N number of feature vectors * @param labs vector with labels * @param feats matrix with features */ void read_data(const char fname[], uint32_t DIM, uint32_t N, SGVector< float64_t > *labs, SGMatrix< float64_t > *feats) { CStreamingAsciiFile* file=new CStreamingAsciiFile(fname); SG_REF(file); CStreamingSparseFeatures< float64_t >* stream_features= new CStreamingSparseFeatures< float64_t >(file, true, 1024); SG_REF(stream_features); SGVector<float64_t > vec(DIM); stream_features->start_parser(); uint32_t num_vectors=0; while( stream_features->get_next_example() ) { vec.zero(); stream_features->add_to_dense_vec(1.0, vec, DIM); (*labs)[num_vectors]=stream_features->get_label(); for(uint32_t i=0; i<DIM; ++i) { (*feats)[num_vectors*DIM+i]=vec[i]; } num_vectors++; stream_features->release_example(); } stream_features->end_parser(); SG_UNREF(stream_features); } /** Generates random multiclass training data and stores them in svmlight format * * @param labs returned vector with labels * @param feats returned matrix with features */ void gen_rand_data(SGVector< float64_t > labs, SGMatrix< float64_t > feats) { float64_t means[DIMS]; float64_t stds[DIMS]; FILE* pfile = fopen(FNAME, "w"); for ( int32_t c = 0 ; c < NUM_CLASSES ; ++c ) { for ( int32_t j = 0 ; j < DIMS ; ++j ) { means[j] = CMath::random(-100, 100); stds[j] = CMath::random( 1, 5); } for ( int32_t i = 0 ; i < NUM_SAMPLES ; ++i ) { labs[c*NUM_SAMPLES+i] = c; fprintf(pfile, "%d", c); for ( int32_t j = 0 ; j < DIMS ; ++j ) { feats[(c*NUM_SAMPLES+i)*DIMS + j] = CMath::normal_random(means[j], stds[j]); fprintf(pfile, " %d:%f", j+1, feats[(c*NUM_SAMPLES+i)*DIMS + j]); } fprintf(pfile, "\n"); } } fclose(pfile); } int main(int argc, char * argv[]) { // initialization //------------------------------------------------------------------------- float64_t lambda=0.01, eps=0.01; bool icp=1; uint32_t cp_models=1; ESolver solver=BMRM; uint32_t feat_dim, num_feat; init_shogun_with_defaults(); if (argc > 1 && argc < 8) { SG_SERROR("Usage: so_multiclass_BMRM <data.in> <feat_dim> <num_feat> <lambda> <icp> <epsilon> <solver> [<cp_models>]\n"); return -1; } if (argc > 1) { // parse command line arguments for parameters setting SG_SPRINT("arg[1] = %s\n", argv[1]); feat_dim=::atoi(argv[2]); num_feat=::atoi(argv[3]); lambda=::atof(argv[4]); icp=::atoi(argv[5]); eps=::atof(argv[6]); if (strcmp("BMRM", argv[7])==0) solver=BMRM; if (strcmp("PPBMRM", argv[7])==0) solver=PPBMRM; if (strcmp("P3BMRM", argv[7])==0) solver=P3BMRM; if (argc > 8) { cp_models=::atoi(argv[8]); } } else { // default parameters feat_dim=DIMS; num_feat=NUM_SAMPLES*NUM_CLASSES; lambda=1e3; icp=1; eps=0.01; solver=BMRM; } SGVector< float64_t >* labs= new SGVector< float64_t >(num_feat); SGMatrix< float64_t >* feats= new SGMatrix< float64_t >(feat_dim, num_feat); if (argc==1) { gen_rand_data(*labs, *feats); } else { // read data read_data(argv[1], feat_dim, num_feat, labs, feats); } // Create train labels CMulticlassSOLabels* labels = new CMulticlassSOLabels(*labs); // Create train features CDenseFeatures< float64_t >* features = new CDenseFeatures< float64_t >(*feats); // Create structured model CMulticlassModel* model = new CMulticlassModel(features, labels); // Create loss function CHingeLoss* loss = new CHingeLoss(); // Create SO-SVM CDualLibQPBMSOSVM* sosvm = new CDualLibQPBMSOSVM( model, loss, labels, lambda); SG_REF(sosvm); sosvm->set_cleanAfter(10); sosvm->set_cleanICP(icp); sosvm->set_TolRel(eps); sosvm->set_cp_models(cp_models); sosvm->set_solver(solver); // Train //------------------------------------------------------------------------- SG_SPRINT("Train using lambda = %lf ICP removal = %d \n", sosvm->get_lambda(), sosvm->get_cleanICP()); sosvm->train(); bmrm_return_value_T res = sosvm->get_result(); SG_SPRINT("result = { Fp=%lf, Fd=%lf, nIter=%d, nCP=%d, nzA=%d, exitflag=%d }\n", res.Fp, res.Fd, res.nIter, res.nCP, res.nzA, res.exitflag); CStructuredLabels* out = CStructuredLabels::obtain_from_generic(sosvm->apply()); SG_REF(out); SG_SPRINT("\n"); // Compute error //------------------------------------------------------------------------- float64_t error=0.0; for (uint32_t i=0; i<num_feat; ++i) { error+=(( (CRealNumber*) out->get_label(i) )->value==labs->get_element(i)) ? 0.0 : 1.0; } SG_SPRINT("Error = %lf %% \n", error/num_feat*100); // Free memory SG_UNREF(sosvm); SG_UNREF(out); exit_shogun(); return 0; } <|endoftext|>
<commit_before>// // Copyright (c) 2018-2020, University of Edinburgh, University of Oxford // 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 nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <exotica_core_task_maps/eff_position.h> REGISTER_TASKMAP_TYPE("EffPosition", exotica::EffPosition); namespace exotica { void EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed("Wrong size of Phi!"); for (int i = 0; i < kinematics[0].Phi.rows(); ++i) { phi(i * 3) = kinematics[0].Phi(i).p[0]; phi(i * 3 + 1) = kinematics[0].Phi(i).p[1]; phi(i * 3 + 2) = kinematics[0].Phi(i).p[2]; } } void EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian) { if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed("Wrong size of Phi!"); if (jacobian.rows() != kinematics[0].jacobian.rows() * 3 || jacobian.cols() != kinematics[0].jacobian(0).data.cols()) ThrowNamed("Wrong size of jacobian! " << kinematics[0].jacobian(0).data.cols()); for (int i = 0; i < kinematics[0].Phi.rows(); ++i) { phi(i * 3) = kinematics[0].Phi(i).p[0]; phi(i * 3 + 1) = kinematics[0].Phi(i).p[1]; phi(i * 3 + 2) = kinematics[0].Phi(i).p[2]; jacobian.middleRows(i * 3, 3) = kinematics[0].jacobian[i].data.topRows(3); } } void EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian, HessianRef hessian) { if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed("Wrong size of Phi!"); if (jacobian.rows() != kinematics[0].jacobian.rows() * 3 || jacobian.cols() != kinematics[0].jacobian(0).data.cols()) ThrowNamed("Wrong size of jacobian! " << kinematics[0].jacobian(0).data.cols()); for (int i = 0; i < kinematics[0].Phi.rows(); ++i) { phi(i * 3) = kinematics[0].Phi(i).p[0]; phi(i * 3 + 1) = kinematics[0].Phi(i).p[1]; phi(i * 3 + 2) = kinematics[0].Phi(i).p[2]; jacobian.middleRows(i * 3, 3) = kinematics[0].jacobian[i].data.topRows(3); for (int j = 0; j < 3; ++j) { hessian(j).block(i * 3, 0, jacobian.cols(), jacobian.cols()) = kinematics[0].hessian[i](j); } } } int EffPosition::TaskSpaceDim() { return kinematics[0].Phi.rows() * 3; } } // namespace exotica <commit_msg>[exotica_core_task_maps] EffPosition: Fix Hessian indexing<commit_after>// // Copyright (c) 2018-2020, University of Edinburgh, University of Oxford // 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 nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <exotica_core_task_maps/eff_position.h> REGISTER_TASKMAP_TYPE("EffPosition", exotica::EffPosition); namespace exotica { void EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed("Wrong size of Phi!"); for (int i = 0; i < kinematics[0].Phi.rows(); ++i) { phi(i * 3) = kinematics[0].Phi(i).p[0]; phi(i * 3 + 1) = kinematics[0].Phi(i).p[1]; phi(i * 3 + 2) = kinematics[0].Phi(i).p[2]; } } void EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian) { if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed("Wrong size of Phi!"); if (jacobian.rows() != kinematics[0].jacobian.rows() * 3 || jacobian.cols() != kinematics[0].jacobian(0).data.cols()) ThrowNamed("Wrong size of jacobian! " << kinematics[0].jacobian(0).data.cols()); for (int i = 0; i < kinematics[0].Phi.rows(); ++i) { phi(i * 3) = kinematics[0].Phi(i).p[0]; phi(i * 3 + 1) = kinematics[0].Phi(i).p[1]; phi(i * 3 + 2) = kinematics[0].Phi(i).p[2]; jacobian.middleRows(i * 3, 3) = kinematics[0].jacobian[i].data.topRows(3); } } void EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian, HessianRef hessian) { if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed("Wrong size of Phi!"); if (jacobian.rows() != kinematics[0].jacobian.rows() * 3 || jacobian.cols() != kinematics[0].jacobian(0).data.cols()) ThrowNamed("Wrong size of jacobian! " << kinematics[0].jacobian(0).data.cols()); for (int i = 0; i < kinematics[0].Phi.rows(); ++i) { phi(i * 3) = kinematics[0].Phi(i).p[0]; phi(i * 3 + 1) = kinematics[0].Phi(i).p[1]; phi(i * 3 + 2) = kinematics[0].Phi(i).p[2]; jacobian.middleRows(i * 3, 3) = kinematics[0].jacobian[i].data.topRows(3); for (int j = 0; j < 3; ++j) { hessian(i * 3 + j).block(0, 0, jacobian.cols(), jacobian.cols()) = kinematics[0].hessian[i](j); } } } int EffPosition::TaskSpaceDim() { return kinematics[0].Phi.rows() * 3; } } // namespace exotica <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <iostream> #include <Eigen/Core> #include <chrono> #include "eigen_spatial_convolutions.h" #include "eigen_cuboid_convolution.h" int main() { std::cout << "Hello World!\n"; const int input_depth = 3; const int input_rows = 227; const int input_cols = 227; const int num_batches = 1; const int output_depth = 96; const int patch_rows = 11; const int patch_cols = 11; const int output_rows = input_rows - patch_rows + 1; const int output_cols = input_cols - patch_cols + 1; using namespace Eigen; Tensor<float, 4, RowMajor> input(num_batches, input_cols, input_rows, input_depth); Tensor<float, 4, RowMajor> kernel(patch_cols, patch_rows, input_depth, output_depth); Tensor<float, 4, RowMajor> result(num_batches, output_cols, output_rows, output_depth); input = input.constant(11.0f) + input.random(); kernel = kernel.constant(2.0f) + kernel.random(); using namespace std::chrono; milliseconds t0 = duration_cast< milliseconds >(system_clock::now().time_since_epoch()); result = SpatialConvolution(input, kernel, 4, 4, PADDING_SAME); milliseconds t1 = duration_cast< milliseconds >(system_clock::now().time_since_epoch()); auto difference = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count(); std::cout << difference << " ms" << std::endl; return 0; } <commit_msg>exp ..<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <iostream> #include <Eigen/Core> #include <chrono> #include "eigen_spatial_convolutions.h" #include "eigen_cuboid_convolution.h" void test_conv2d () { const int input_depth = 3; const int input_rows = 227; const int input_cols = 227; const int num_batches = 1; const int output_depth = 96; const int patch_rows = 11; const int patch_cols = 11; const int output_rows = input_rows - patch_rows + 1; const int output_cols = input_cols - patch_cols + 1; using namespace Eigen; Tensor<float, 4, RowMajor> input(num_batches, input_cols, input_rows, input_depth); Tensor<float, 4, RowMajor> kernel(patch_cols, patch_rows, input_depth, output_depth); Tensor<float, 4, RowMajor> result(num_batches, output_cols, output_rows, output_depth); input = input.constant(11.0f) + input.random(); kernel = kernel.constant(2.0f) + kernel.random(); using namespace std::chrono; milliseconds t0 = duration_cast< milliseconds >(system_clock::now().time_since_epoch()); result = SpatialConvolution(input, kernel, 4, 4, PADDING_SAME); milliseconds t1 = duration_cast< milliseconds >(system_clock::now().time_since_epoch()); int difference = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count(); std::cout << difference << " ms" << std::endl; } void test_conv2d_back_input () { } int main() { std::cout << "Hello World!\n"; test_conv2d (); return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <cstddef> #include <cstring> #include <memory> #include "caf/allowed_unsafe_message_type.hpp" #include "caf/detail/io_export.hpp" namespace caf::io::network { /// A container that does not call constructors and destructors for its values. class CAF_IO_EXPORT receive_buffer { public: using value_type = char; using size_type = size_t; using difference_type = std::ptrdiff_t; using reference = value_type&; using const_reference = const value_type&; using pointer = value_type*; using const_pointer = std::pointer_traits<pointer>::rebind<const value_type>; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using buffer_ptr = std::unique_ptr<value_type[], std::default_delete<value_type[]>>; /// Create an empty container. receive_buffer() noexcept; /// Create an empty container of size `count`. Data in the storage is not /// initialized. receive_buffer(size_t count); /// Move constructor. receive_buffer(receive_buffer&& other) noexcept; /// Copy constructor. receive_buffer(const receive_buffer& other); /// Move assignment operator. receive_buffer& operator=(receive_buffer&& other) noexcept; /// Copy assignment operator. receive_buffer& operator=(const receive_buffer& other); /// Returns a pointer to the underlying buffer. pointer data() noexcept { return buffer_.get(); } /// Returns a const pointer to the data. const_pointer data() const noexcept { return buffer_.get(); } /// Returns the number of stored elements. size_type size() const noexcept { return size_; } /// Returns the number of elements that the container has allocated space for. size_type capacity() const noexcept { return capacity_; } /// Returns the maximum possible number of elements the container /// could theoretically hold. size_type max_size() const noexcept { return std::numeric_limits<size_t>::max(); } /// Resize the container to `new_size`. While this may increase its storage, /// no storage will be released. void resize(size_type new_size); /// Set the size of the storage to `new_size`. If `new_size` is smaller than /// the current capacity nothing happens. If `new_size` is larger than the /// current capacity all iterators are invalidated. void reserve(size_type new_size); /// Shrink the container to its current size. void shrink_to_fit(); /// Check if the container is empty. bool empty() const noexcept { return size_ == 0; } /// Clears the content of the container and releases the allocated storage. void clear(); /// Swap contents with `other` receive buffer. void swap(receive_buffer& other) noexcept; /// Returns an iterator to the beginning. iterator begin() noexcept { return buffer_.get(); } /// Returns an iterator to the end. iterator end() noexcept { return buffer_.get() + size_; } /// Returns an iterator to the beginning. const_iterator begin() const noexcept { return buffer_.get(); } /// Returns an iterator to the end. const_iterator end() const noexcept { return buffer_.get() + size_; } /// Returns an iterator to the beginning. const_iterator cbegin() const noexcept { return buffer_.get(); } /// Returns an iterator to the end. const_iterator cend() const noexcept { return buffer_.get() + size_; } /// Returns jan iterator to the reverse beginning. reverse_iterator rbegin() noexcept { return reverse_iterator{buffer_.get() + size_}; } /// Returns an iterator to the reverse end of the data. reverse_iterator rend() noexcept { return reverse_iterator{buffer_.get()}; } /// Returns an iterator to the reverse beginning. const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator{buffer_.get() + size_}; } /// Returns an iterator to the reverse end of the data. const_reverse_iterator rend() const noexcept { return const_reverse_iterator{buffer_.get()}; } /// Returns an iterator to the reverse beginning. const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator{buffer_.get() + size_}; } /// Returns an iterator to the reverse end of the data. const_reverse_iterator crend() const noexcept { return const_reverse_iterator{buffer_.get()}; } /// Insert `value` before `pos`. iterator insert(iterator pos, value_type value); /// Insert `value` before `pos`. template <class InputIterator> iterator insert(iterator pos, InputIterator first, InputIterator last) { auto n = std::distance(first, last); if (n == 0) return pos; auto offset = static_cast<size_t>(std::distance(begin(), pos)); auto old_size = size_; resize(old_size + static_cast<size_t>(n)); pos = begin() + offset; if (offset != old_size) { memmove(pos + n, pos, old_size - offset); } return std::copy(first, last, pos); } /// Append `value`. void push_back(value_type value); private: // Increse the buffer capacity, maintaining its data. May invalidate // iterators. void increase_by(size_t bytes); // Reduce the buffer capacity, maintaining its data. May invalidate iterators. void shrink_by(size_t bytes); buffer_ptr buffer_; size_type capacity_; size_type size_; }; } // namespace caf::io::network <commit_msg>Add missing include<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <cstddef> #include <cstring> #include <limits> #include <memory> #include "caf/allowed_unsafe_message_type.hpp" #include "caf/detail/io_export.hpp" namespace caf::io::network { /// A container that does not call constructors and destructors for its values. class CAF_IO_EXPORT receive_buffer { public: using value_type = char; using size_type = size_t; using difference_type = std::ptrdiff_t; using reference = value_type&; using const_reference = const value_type&; using pointer = value_type*; using const_pointer = std::pointer_traits<pointer>::rebind<const value_type>; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using buffer_ptr = std::unique_ptr<value_type[], std::default_delete<value_type[]>>; /// Create an empty container. receive_buffer() noexcept; /// Create an empty container of size `count`. Data in the storage is not /// initialized. receive_buffer(size_t count); /// Move constructor. receive_buffer(receive_buffer&& other) noexcept; /// Copy constructor. receive_buffer(const receive_buffer& other); /// Move assignment operator. receive_buffer& operator=(receive_buffer&& other) noexcept; /// Copy assignment operator. receive_buffer& operator=(const receive_buffer& other); /// Returns a pointer to the underlying buffer. pointer data() noexcept { return buffer_.get(); } /// Returns a const pointer to the data. const_pointer data() const noexcept { return buffer_.get(); } /// Returns the number of stored elements. size_type size() const noexcept { return size_; } /// Returns the number of elements that the container has allocated space for. size_type capacity() const noexcept { return capacity_; } /// Returns the maximum possible number of elements the container /// could theoretically hold. size_type max_size() const noexcept { return std::numeric_limits<size_t>::max(); } /// Resize the container to `new_size`. While this may increase its storage, /// no storage will be released. void resize(size_type new_size); /// Set the size of the storage to `new_size`. If `new_size` is smaller than /// the current capacity nothing happens. If `new_size` is larger than the /// current capacity all iterators are invalidated. void reserve(size_type new_size); /// Shrink the container to its current size. void shrink_to_fit(); /// Check if the container is empty. bool empty() const noexcept { return size_ == 0; } /// Clears the content of the container and releases the allocated storage. void clear(); /// Swap contents with `other` receive buffer. void swap(receive_buffer& other) noexcept; /// Returns an iterator to the beginning. iterator begin() noexcept { return buffer_.get(); } /// Returns an iterator to the end. iterator end() noexcept { return buffer_.get() + size_; } /// Returns an iterator to the beginning. const_iterator begin() const noexcept { return buffer_.get(); } /// Returns an iterator to the end. const_iterator end() const noexcept { return buffer_.get() + size_; } /// Returns an iterator to the beginning. const_iterator cbegin() const noexcept { return buffer_.get(); } /// Returns an iterator to the end. const_iterator cend() const noexcept { return buffer_.get() + size_; } /// Returns jan iterator to the reverse beginning. reverse_iterator rbegin() noexcept { return reverse_iterator{buffer_.get() + size_}; } /// Returns an iterator to the reverse end of the data. reverse_iterator rend() noexcept { return reverse_iterator{buffer_.get()}; } /// Returns an iterator to the reverse beginning. const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator{buffer_.get() + size_}; } /// Returns an iterator to the reverse end of the data. const_reverse_iterator rend() const noexcept { return const_reverse_iterator{buffer_.get()}; } /// Returns an iterator to the reverse beginning. const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator{buffer_.get() + size_}; } /// Returns an iterator to the reverse end of the data. const_reverse_iterator crend() const noexcept { return const_reverse_iterator{buffer_.get()}; } /// Insert `value` before `pos`. iterator insert(iterator pos, value_type value); /// Insert `value` before `pos`. template <class InputIterator> iterator insert(iterator pos, InputIterator first, InputIterator last) { auto n = std::distance(first, last); if (n == 0) return pos; auto offset = static_cast<size_t>(std::distance(begin(), pos)); auto old_size = size_; resize(old_size + static_cast<size_t>(n)); pos = begin() + offset; if (offset != old_size) { memmove(pos + n, pos, old_size - offset); } return std::copy(first, last, pos); } /// Append `value`. void push_back(value_type value); private: // Increse the buffer capacity, maintaining its data. May invalidate // iterators. void increase_by(size_t bytes); // Reduce the buffer capacity, maintaining its data. May invalidate iterators. void shrink_by(size_t bytes); buffer_ptr buffer_; size_type capacity_; size_type size_; }; } // namespace caf::io::network <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-443271. // // This file is part of the GLVis visualization tool and library. For more // information and source code availability see https://glvis.org. // // GLVis is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "visual.hpp" #include "palettes.hpp" #include "stream_reader.hpp" #include <SDL2/SDL_hints.h> #include <emscripten/bind.h> #include <emscripten/html5.h> std::string plot_caption; std::string extra_caption; // used in extern context mfem::GeometryRefiner GLVisGeometryRefiner; // used in extern context static VisualizationSceneScalarData * vs = nullptr; namespace js { using namespace mfem; // Replace a given VectorFiniteElement-based grid function (e.g. from a Nedelec // or Raviart-Thomas space) with a discontinuous piece-wise polynomial Cartesian // product vector grid function of the same order. GridFunction *ProjectVectorFEGridFunction(GridFunction *gf) { if ((gf->VectorDim() == 3) && (gf->FESpace()->GetVDim() == 1)) { int p = gf->FESpace()->GetOrder(0); cout << "Switching to order " << p << " discontinuous vector grid function..." << endl; int dim = gf->FESpace()->GetMesh()->Dimension(); FiniteElementCollection *d_fec = new L2_FECollection(p, dim, 1); FiniteElementSpace *d_fespace = new FiniteElementSpace(gf->FESpace()->GetMesh(), d_fec, 3); GridFunction *d_gf = new GridFunction(d_fespace); d_gf->MakeOwner(d_fec); gf->ProjectVectorFieldOn(*d_gf); delete gf; return d_gf; } return gf; } bool startVisualization(const std::string input, const std::string data_type, int w, int h) { std::stringstream ss(input); // 0 - scalar data, 1 - vector data, 2 - mesh only, (-1) - unknown const int field_type = ReadStream(ss, data_type); // reset antialiasing GetAppWindow()->getRenderer().setAntialiasing(0); std::string line; while (ss >> line) { if (line == "keys") { std::cout << "parsing 'keys'" << std::endl; ss >> stream_state.keys; } else { std::cout << "unknown line '" << line << "'" << std::endl; } } if (field_type < 0 || field_type > 2) { return false; } if (InitVisualization("glvis", 0, 0, w, h)) { return false; } delete vs; vs = nullptr; double mesh_range = -1.0; if (field_type == 0 || field_type == 2) { if (stream_state.grid_f) { stream_state.grid_f->GetNodalValues(stream_state.sol); } if (stream_state.mesh->SpaceDimension() == 2) { VisualizationSceneSolution * vss; if (stream_state.normals.Size() > 0) { vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol, &stream_state.normals); } else { vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol); } if (stream_state.grid_f) { vss->SetGridFunction(*stream_state.grid_f); } if (field_type == 2) { vs->OrthogonalProjection = 1; vs->SetLight(0); vs->Zoom(1.8); // Use the 'bone' palette when visualizing a 2D mesh only (otherwise // the 'jet-like' palette is used in 2D, see vssolution.cpp). paletteSet(4); } } else if (stream_state.mesh->SpaceDimension() == 3) { VisualizationSceneSolution3d * vss; vs = vss = new VisualizationSceneSolution3d(*stream_state.mesh, stream_state.sol); if (stream_state.grid_f) { vss->SetGridFunction(stream_state.grid_f); } if (field_type == 2) { if (stream_state.mesh->Dimension() == 3) { // Use the 'white' palette when visualizing a 3D volume mesh only // paletteSet(4); paletteSet(11); vss->SetLightMatIdx(4); } else { // Use the 'bone' palette when visualizing a surface mesh only // (the same as when visualizing a 2D mesh only) paletteSet(4); } // Otherwise, the 'vivid' palette is used in 3D see vssolution3d.cpp vss->ToggleDrawAxes(); vss->ToggleDrawMesh(); } } if (field_type == 2) { if (stream_state.grid_f) { mesh_range = stream_state.grid_f->Max() + 1.0; } else { mesh_range = stream_state.sol.Max() + 1.0; } } } else if (field_type == 1) { if (stream_state.mesh->SpaceDimension() == 2) { if (stream_state.grid_f) { vs = new VisualizationSceneVector(*stream_state.grid_f); } else { vs = new VisualizationSceneVector(*stream_state.mesh, stream_state.solu, stream_state.solv); } } else if (stream_state.mesh->SpaceDimension() == 3) { if (stream_state.grid_f) { stream_state.grid_f = ProjectVectorFEGridFunction(stream_state.grid_f); vs = new VisualizationSceneVector3d(*stream_state.grid_f); } else { vs = new VisualizationSceneVector3d(*stream_state.mesh, stream_state.solu, stream_state.solv, stream_state.solw); } } } if (vs) { // increase the refinement factors if visualizing a GridFunction if (stream_state.grid_f) { vs->AutoRefine(); vs->SetShading(2, true); } if (mesh_range > 0.0) { vs->SetValueRange(-mesh_range, mesh_range); vs->SetAutoscale(0); } if (stream_state.mesh->SpaceDimension() == 2 && field_type == 2) { SetVisualizationScene(vs, 2); } else { SetVisualizationScene(vs, 3); } } CallKeySequence(stream_state.keys.c_str()); SendExposeEvent(); return true; } int updateVisualization(std::string data_type, std::string stream) { std::stringstream ss(stream); if (data_type != "solution") { std::cerr << "unsupported data type '" << data_type << "' for stream update" << std::endl; return 1; } auto * new_m = new Mesh(ss, 1, 0, stream_state.fix_elem_orient); auto * new_g = new GridFunction(new_m, ss); double mesh_range = -1.0; if (new_m->SpaceDimension() == stream_state.mesh->SpaceDimension() && new_g->VectorDim() == stream_state.grid_f->VectorDim()) { if (new_m->SpaceDimension() == 2) { if (new_g->VectorDim() == 1) { VisualizationSceneSolution *vss = dynamic_cast<VisualizationSceneSolution *>(vs); new_g->GetNodalValues(stream_state.sol); vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g); } else { VisualizationSceneVector *vsv = dynamic_cast<VisualizationSceneVector *>(vs); vsv->NewMeshAndSolution(*new_g); } } else { if (new_g->VectorDim() == 1) { VisualizationSceneSolution3d *vss = dynamic_cast<VisualizationSceneSolution3d *>(vs); new_g->GetNodalValues(stream_state.sol); vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g); } else { new_g = ProjectVectorFEGridFunction(new_g); VisualizationSceneVector3d *vss = dynamic_cast<VisualizationSceneVector3d *>(vs); vss->NewMeshAndSolution(new_m, new_g); } } if (mesh_range > 0.0) { vs->SetValueRange(-mesh_range, mesh_range); } delete stream_state.grid_f; stream_state.grid_f = new_g; delete stream_state.mesh; stream_state.mesh = new_m; SendExposeEvent(); return 0; } else { cout << "Stream: field type does not match!" << endl; delete new_g; delete new_m; return 1; } } void iterVisualization() { GetAppWindow()->mainIter(); } void setCanvasId(const std::string & id) { std::cout << "glvis: setting canvas id to " << id << std::endl; GetAppWindow()->setCanvasId(id); } void disableKeyHandling() { SDL_EventState(SDL_KEYDOWN, SDL_DISABLE); SDL_EventState(SDL_KEYUP, SDL_DISABLE); } void enableKeyHandling() { SDL_EventState(SDL_KEYDOWN, SDL_ENABLE); SDL_EventState(SDL_KEYUP, SDL_ENABLE); } void setKeyboardListeningElementId(const std::string & id) { SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, id.c_str()); } void setupResizeEventCallback(const std::string & id) { // typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData); std::cout << "glvis: adding resize callback for " << id << std::endl; auto err = emscripten_set_resize_callback(id.c_str(), nullptr, true, [](int eventType, const EmscriptenUiEvent *uiEvent, void *userData) -> EM_BOOL { std::cout << "got resize event" << std::endl; return true; }); // TODO: macro to wrap this if (err != EMSCRIPTEN_RESULT_SUCCESS) { std::cerr << "error (emscripten_set_resize_callback): " << err << std::endl; } } std::string getHelpString() { VisualizationSceneScalarData* vss = dynamic_cast<VisualizationSceneScalarData*>(GetVisualizationScene()); return vss->GetHelpString(); } } // namespace js namespace em = emscripten; EMSCRIPTEN_BINDINGS(js_funcs) { em::function("startVisualization", &js::startVisualization); em::function("updateVisualization", &js::updateVisualization); em::function("iterVisualization", &js::iterVisualization); em::function("sendExposeEvent", &SendExposeEvent); em::function("disableKeyHanding", &js::disableKeyHandling); em::function("enableKeyHandling", &js::enableKeyHandling); em::function("setKeyboardListeningElementId", js::setKeyboardListeningElementId); em::function("getTextureMode", &GetUseTexture); em::function("setTextureMode", &SetUseTexture); em::function("resizeWindow", &ResizeWindow); em::function("setCanvasId", &js::setCanvasId); em::function("setupResizeEventCallback", &js::setupResizeEventCallback); em::function("getHelpString", &js::getHelpString); } <commit_msg>Parse the valuerange command in JS streams<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-443271. // // This file is part of the GLVis visualization tool and library. For more // information and source code availability see https://glvis.org. // // GLVis is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "visual.hpp" #include "palettes.hpp" #include "stream_reader.hpp" #include <SDL2/SDL_hints.h> #include <emscripten/bind.h> #include <emscripten/html5.h> std::string plot_caption; std::string extra_caption; // used in extern context mfem::GeometryRefiner GLVisGeometryRefiner; // used in extern context static VisualizationSceneScalarData * vs = nullptr; namespace js { using namespace mfem; // Replace a given VectorFiniteElement-based grid function (e.g. from a Nedelec // or Raviart-Thomas space) with a discontinuous piece-wise polynomial Cartesian // product vector grid function of the same order. GridFunction *ProjectVectorFEGridFunction(GridFunction *gf) { if ((gf->VectorDim() == 3) && (gf->FESpace()->GetVDim() == 1)) { int p = gf->FESpace()->GetOrder(0); cout << "Switching to order " << p << " discontinuous vector grid function..." << endl; int dim = gf->FESpace()->GetMesh()->Dimension(); FiniteElementCollection *d_fec = new L2_FECollection(p, dim, 1); FiniteElementSpace *d_fespace = new FiniteElementSpace(gf->FESpace()->GetMesh(), d_fec, 3); GridFunction *d_gf = new GridFunction(d_fespace); d_gf->MakeOwner(d_fec); gf->ProjectVectorFieldOn(*d_gf); delete gf; return d_gf; } return gf; } bool startVisualization(const std::string input, const std::string data_type, int w, int h) { std::stringstream ss(input); // 0 - scalar data, 1 - vector data, 2 - mesh only, (-1) - unknown const int field_type = ReadStream(ss, data_type); // reset antialiasing GetAppWindow()->getRenderer().setAntialiasing(0); std::string line; double minv = 0.0, maxv = 0.0; while (ss >> line) { if (line == "keys") { std::cout << "parsing 'keys'" << std::endl; ss >> stream_state.keys; } else if (line == "valuerange") { std::cout << "parsing 'valuerange'" << std::endl; ss >> minv >> maxv; } else { std::cout << "unknown line '" << line << "'" << std::endl; } } if (field_type < 0 || field_type > 2) { return false; } if (InitVisualization("glvis", 0, 0, w, h)) { return false; } delete vs; vs = nullptr; double mesh_range = -1.0; if (field_type == 0 || field_type == 2) { if (stream_state.grid_f) { stream_state.grid_f->GetNodalValues(stream_state.sol); } if (stream_state.mesh->SpaceDimension() == 2) { VisualizationSceneSolution * vss; if (stream_state.normals.Size() > 0) { vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol, &stream_state.normals); } else { vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol); } if (stream_state.grid_f) { vss->SetGridFunction(*stream_state.grid_f); } if (field_type == 2) { vs->OrthogonalProjection = 1; vs->SetLight(0); vs->Zoom(1.8); // Use the 'bone' palette when visualizing a 2D mesh only (otherwise // the 'jet-like' palette is used in 2D, see vssolution.cpp). paletteSet(4); } } else if (stream_state.mesh->SpaceDimension() == 3) { VisualizationSceneSolution3d * vss; vs = vss = new VisualizationSceneSolution3d(*stream_state.mesh, stream_state.sol); if (stream_state.grid_f) { vss->SetGridFunction(stream_state.grid_f); } if (field_type == 2) { if (stream_state.mesh->Dimension() == 3) { // Use the 'white' palette when visualizing a 3D volume mesh only // paletteSet(4); paletteSet(11); vss->SetLightMatIdx(4); } else { // Use the 'bone' palette when visualizing a surface mesh only // (the same as when visualizing a 2D mesh only) paletteSet(4); } // Otherwise, the 'vivid' palette is used in 3D see vssolution3d.cpp vss->ToggleDrawAxes(); vss->ToggleDrawMesh(); } } if (field_type == 2) { if (stream_state.grid_f) { mesh_range = stream_state.grid_f->Max() + 1.0; } else { mesh_range = stream_state.sol.Max() + 1.0; } } } else if (field_type == 1) { if (stream_state.mesh->SpaceDimension() == 2) { if (stream_state.grid_f) { vs = new VisualizationSceneVector(*stream_state.grid_f); } else { vs = new VisualizationSceneVector(*stream_state.mesh, stream_state.solu, stream_state.solv); } } else if (stream_state.mesh->SpaceDimension() == 3) { if (stream_state.grid_f) { stream_state.grid_f = ProjectVectorFEGridFunction(stream_state.grid_f); vs = new VisualizationSceneVector3d(*stream_state.grid_f); } else { vs = new VisualizationSceneVector3d(*stream_state.mesh, stream_state.solu, stream_state.solv, stream_state.solw); } } } if (vs) { // increase the refinement factors if visualizing a GridFunction if (stream_state.grid_f) { vs->AutoRefine(); vs->SetShading(2, true); } if (mesh_range > 0.0) { vs->SetValueRange(-mesh_range, mesh_range); vs->SetAutoscale(0); } if (stream_state.mesh->SpaceDimension() == 2 && field_type == 2) { SetVisualizationScene(vs, 2); } else { SetVisualizationScene(vs, 3); } } CallKeySequence(stream_state.keys.c_str()); if (minv || maxv) { vs->SetValueRange(minv, maxv); } SendExposeEvent(); return true; } int updateVisualization(std::string data_type, std::string stream) { std::stringstream ss(stream); if (data_type != "solution") { std::cerr << "unsupported data type '" << data_type << "' for stream update" << std::endl; return 1; } auto * new_m = new Mesh(ss, 1, 0, stream_state.fix_elem_orient); auto * new_g = new GridFunction(new_m, ss); double mesh_range = -1.0; if (new_m->SpaceDimension() == stream_state.mesh->SpaceDimension() && new_g->VectorDim() == stream_state.grid_f->VectorDim()) { if (new_m->SpaceDimension() == 2) { if (new_g->VectorDim() == 1) { VisualizationSceneSolution *vss = dynamic_cast<VisualizationSceneSolution *>(vs); new_g->GetNodalValues(stream_state.sol); vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g); } else { VisualizationSceneVector *vsv = dynamic_cast<VisualizationSceneVector *>(vs); vsv->NewMeshAndSolution(*new_g); } } else { if (new_g->VectorDim() == 1) { VisualizationSceneSolution3d *vss = dynamic_cast<VisualizationSceneSolution3d *>(vs); new_g->GetNodalValues(stream_state.sol); vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g); } else { new_g = ProjectVectorFEGridFunction(new_g); VisualizationSceneVector3d *vss = dynamic_cast<VisualizationSceneVector3d *>(vs); vss->NewMeshAndSolution(new_m, new_g); } } if (mesh_range > 0.0) { vs->SetValueRange(-mesh_range, mesh_range); } delete stream_state.grid_f; stream_state.grid_f = new_g; delete stream_state.mesh; stream_state.mesh = new_m; SendExposeEvent(); return 0; } else { cout << "Stream: field type does not match!" << endl; delete new_g; delete new_m; return 1; } } void iterVisualization() { GetAppWindow()->mainIter(); } void setCanvasId(const std::string & id) { std::cout << "glvis: setting canvas id to " << id << std::endl; GetAppWindow()->setCanvasId(id); } void disableKeyHandling() { SDL_EventState(SDL_KEYDOWN, SDL_DISABLE); SDL_EventState(SDL_KEYUP, SDL_DISABLE); } void enableKeyHandling() { SDL_EventState(SDL_KEYDOWN, SDL_ENABLE); SDL_EventState(SDL_KEYUP, SDL_ENABLE); } void setKeyboardListeningElementId(const std::string & id) { SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, id.c_str()); } void setupResizeEventCallback(const std::string & id) { // typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData); std::cout << "glvis: adding resize callback for " << id << std::endl; auto err = emscripten_set_resize_callback(id.c_str(), nullptr, true, [](int eventType, const EmscriptenUiEvent *uiEvent, void *userData) -> EM_BOOL { std::cout << "got resize event" << std::endl; return true; }); // TODO: macro to wrap this if (err != EMSCRIPTEN_RESULT_SUCCESS) { std::cerr << "error (emscripten_set_resize_callback): " << err << std::endl; } } std::string getHelpString() { VisualizationSceneScalarData* vss = dynamic_cast<VisualizationSceneScalarData*>(GetVisualizationScene()); return vss->GetHelpString(); } } // namespace js namespace em = emscripten; EMSCRIPTEN_BINDINGS(js_funcs) { em::function("startVisualization", &js::startVisualization); em::function("updateVisualization", &js::updateVisualization); em::function("iterVisualization", &js::iterVisualization); em::function("sendExposeEvent", &SendExposeEvent); em::function("disableKeyHanding", &js::disableKeyHandling); em::function("enableKeyHandling", &js::enableKeyHandling); em::function("setKeyboardListeningElementId", js::setKeyboardListeningElementId); em::function("getTextureMode", &GetUseTexture); em::function("setTextureMode", &SetUseTexture); em::function("resizeWindow", &ResizeWindow); em::function("setCanvasId", &js::setCanvasId); em::function("setupResizeEventCallback", &js::setupResizeEventCallback); em::function("getHelpString", &js::getHelpString); } <|endoftext|>
<commit_before>/* +---------------------------------------------------------------------------+ | The Mobile Robot Programming Toolkit (MRPT) | | | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file | | Copyright (c) 2005-2013, MAPIR group, University of Malaga | | Copyright (c) 2012-2013, University of Almeria | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are | | met: | | * Redistributions of source code must retain the above copyright | | notice, this list of conditions and the following disclaimer. | | * Redistributions in binary form must reproduce the above copyright | | notice, this list of conditions and the following disclaimer in the | | documentation and/or other materials provided with the distribution. | | * Neither the name of the copyright holders 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 HOLDERS 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 <mrpt/base.h> // Precompiled headers #include <mrpt/utils/CDebugOutputCapable.h> #include <mrpt/system/memory.h> #ifdef MRPT_OS_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include <cstdarg> #include <iostream> using namespace mrpt::utils; using namespace mrpt::system; /*--------------------------------------------------------------- printf_debug ---------------------------------------------------------------*/ void CDebugOutputCapable::printf_debug( const char *fmt, ... ) { if (!fmt) return; int result = -1, length = 1024; std::vector<char> buffer; while (result == -1) { buffer.resize(length + 10); va_list args; // This must be done WITHIN the loop va_start(args,fmt); result = os::vsnprintf(&buffer[0], length, fmt, args); va_end(args); // Truncated? if (result>=length) result=-1; length*=2; } // Output: std::cout << &buffer[0]; #ifdef MRPT_OS_WINDOWS OutputDebugStringA(&buffer[0]); #endif } <commit_msg>CDebugOutputCapable: enable Output to MSVC out window only when compiling in MSVC<commit_after>/* +---------------------------------------------------------------------------+ | The Mobile Robot Programming Toolkit (MRPT) | | | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file | | Copyright (c) 2005-2013, MAPIR group, University of Malaga | | Copyright (c) 2012-2013, University of Almeria | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are | | met: | | * Redistributions of source code must retain the above copyright | | notice, this list of conditions and the following disclaimer. | | * Redistributions in binary form must reproduce the above copyright | | notice, this list of conditions and the following disclaimer in the | | documentation and/or other materials provided with the distribution. | | * Neither the name of the copyright holders 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 HOLDERS 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 <mrpt/base.h> // Precompiled headers #include <mrpt/utils/CDebugOutputCapable.h> #include <mrpt/system/memory.h> #ifdef MRPT_OS_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include <cstdarg> #include <iostream> using namespace mrpt::utils; using namespace mrpt::system; /*--------------------------------------------------------------- printf_debug ---------------------------------------------------------------*/ void CDebugOutputCapable::printf_debug( const char *fmt, ... ) { if (!fmt) return; int result = -1, length = 1024; std::vector<char> buffer; while (result == -1) { buffer.resize(length + 10); va_list args; // This must be done WITHIN the loop va_start(args,fmt); result = os::vsnprintf(&buffer[0], length, fmt, args); va_end(args); // Truncated? if (result>=length) result=-1; length*=2; } // Output: std::cout << &buffer[0]; #ifdef _MSC_VER OutputDebugStringA(&buffer[0]); #endif } <|endoftext|>
<commit_before>// // LookupTable takes PolyData as input // #ifndef __vlLookupTable_h #define __vlLookupTable_h #include "Object.hh" #include "RGBArray.hh" class vlLookupTable : public vlObject { public: vlLookupTable(); int Initialize(const int sz=256, const int ext=256); int GetTableSize(); void Build(); vlSetVector2Macro(TableRange,float); vlGetVectorMacro(TableRange,float); vlSetVector2Macro(HueRange,float); vlGetVectorMacro(HueRange,float); vlSetVector2Macro(SaturationRange,float); vlGetVectorMacro(SaturationRange,float); vlSetVector2Macro(ValueRange,float); vlGetVectorMacro(ValueRange,float); vlRGBColor &MapValue(float v); void SetTableValue (int indx, vlRGBColor &rgb_c); vlRGBColor &GetTableValue (int); protected: vlRGBArray Table; float TableRange[2]; float HueRange[2]; float SaturationRange[2]; float ValueRange[2]; }; #endif <commit_msg>ENH: Removed interface using RGBColor.<commit_after>// // LookupTable takes PolyData as input // #ifndef __vlLookupTable_h #define __vlLookupTable_h #include "Object.hh" #include "RGBArray.hh" class vlLookupTable : public vlObject { public: vlLookupTable(); int Initialize(const int sz=256, const int ext=256); int GetTableSize(); void Build(); vlSetVector2Macro(TableRange,float); vlGetVectorMacro(TableRange,float); vlSetVector2Macro(HueRange,float); vlGetVectorMacro(HueRange,float); vlSetVector2Macro(SaturationRange,float); vlGetVectorMacro(SaturationRange,float); vlSetVector2Macro(ValueRange,float); vlGetVectorMacro(ValueRange,float); float *MapValue(float v); void SetTableValue (int indx, float rgb[3]); float *GetTableValue (int); protected: vlRGBArray Table; float TableRange[2]; float HueRange[2]; float SaturationRange[2]; float ValueRange[2]; }; #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pavel Kirienko <[email protected]> */ #include <cassert> #include <cstdlib> #include <uavcan/global_data_type_registry.hpp> #include <uavcan/internal/debug.hpp> namespace uavcan { const GlobalDataTypeRegistry::List* GlobalDataTypeRegistry::selectList(DataTypeKind kind) const { switch (kind) { case DataTypeKindMessage: return &msgs_; case DataTypeKindService: return &srvs_; default: assert(0); return NULL; } } GlobalDataTypeRegistry::List* GlobalDataTypeRegistry::selectList(DataTypeKind kind) { switch (kind) { case DataTypeKindMessage: return &msgs_; case DataTypeKindService: return &srvs_; default: assert(0); return NULL; } } GlobalDataTypeRegistry::RegistResult GlobalDataTypeRegistry::remove(Entry* dtd) { if (!dtd) { assert(0); return RegistResultInvalidParams; } if (isFrozen()) return RegistResultFrozen; List* list = selectList(dtd->descriptor.getKind()); if (!list) return RegistResultInvalidParams; list->remove(dtd); // If this call came from regist<>(), that would be enough Entry* p = list->get(); // But anyway while (p) { Entry* const next = p->getNextListNode(); if (p->descriptor.match(dtd->descriptor.getKind(), dtd->descriptor.getFullName())) list->remove(p); p = next; } return RegistResultOk; } GlobalDataTypeRegistry::RegistResult GlobalDataTypeRegistry::registImpl(Entry* dtd) { if (!dtd || (dtd->descriptor.getID() > DataTypeID::Max)) { assert(0); return RegistResultInvalidParams; } if (isFrozen()) return RegistResultFrozen; List* list = selectList(dtd->descriptor.getKind()); if (!list) return RegistResultInvalidParams; { // Collision check Entry* p = list->get(); while (p) { if (p->descriptor.getID() == dtd->descriptor.getID()) // ID collision return RegistResultCollision; if (!std::strcmp(p->descriptor.getFullName(), dtd->descriptor.getFullName())) // Name collision return RegistResultCollision; p = p->getNextListNode(); } } list->insertBefore(dtd, EntryInsertionComparator(dtd)); #if UAVCAN_DEBUG { // Order check Entry* p = list->get(); int id = -1; while (p) { if (id >= p->descriptor.getID().get()) { assert(0); std::abort(); } id = p->descriptor.getID().get(); p = p->getNextListNode(); } } #endif return RegistResultOk; } GlobalDataTypeRegistry& GlobalDataTypeRegistry::instance() { static GlobalDataTypeRegistry inst; return inst; } void GlobalDataTypeRegistry::freeze() { if (!frozen_) { frozen_ = true; UAVCAN_TRACE("GlobalDataTypeRegistry", "Frozen"); } } const DataTypeDescriptor* GlobalDataTypeRegistry::find(DataTypeKind kind, const char* name) const { const List* list = selectList(kind); if (!list) { assert(0); return NULL; } Entry* p = list->get(); while (p) { if (p->descriptor.match(kind, name)) return &p->descriptor; p = p->getNextListNode(); } return NULL; } DataTypeSignature GlobalDataTypeRegistry::computeAggregateSignature(DataTypeKind kind, DataTypeIDMask& inout_id_mask) const { assert(isFrozen()); // Computing the signature if the registry is not frozen is pointless const List* list = selectList(kind); if (!list) { assert(0); return DataTypeSignature(); } int prev_dtid = -1; DataTypeSignature signature; bool signature_initialized = false; Entry* p = list->get(); while (p) { const DataTypeDescriptor& desc = p->descriptor; const int dtid = desc.getID().get(); if (inout_id_mask[dtid]) { if (signature_initialized) signature.extend(desc.getSignature()); else signature = DataTypeSignature(desc.getSignature()); signature_initialized = true; } assert(prev_dtid < dtid); // Making sure that list is ordered properly prev_dtid++; while (prev_dtid < dtid) inout_id_mask[prev_dtid++] = false; // Erasing bits for missing types assert(prev_dtid == dtid); p = p->getNextListNode(); } prev_dtid++; while (prev_dtid <= DataTypeID::Max) inout_id_mask[prev_dtid++] = false; return signature; } void GlobalDataTypeRegistry::getDataTypeIDMask(DataTypeKind kind, DataTypeIDMask& mask) const { mask.reset(); const List* list = selectList(kind); if (!list) { assert(0); return; } Entry* p = list->get(); while (p) { assert(p->descriptor.getKind() == kind); mask[p->descriptor.getID().get()] = true; p = p->getNextListNode(); } } } <commit_msg>Added logging for GDTR<commit_after>/* * Copyright (C) 2014 Pavel Kirienko <[email protected]> */ #include <cassert> #include <cstdlib> #include <uavcan/global_data_type_registry.hpp> #include <uavcan/internal/debug.hpp> namespace uavcan { const GlobalDataTypeRegistry::List* GlobalDataTypeRegistry::selectList(DataTypeKind kind) const { switch (kind) { case DataTypeKindMessage: return &msgs_; case DataTypeKindService: return &srvs_; default: assert(0); return NULL; } } GlobalDataTypeRegistry::List* GlobalDataTypeRegistry::selectList(DataTypeKind kind) { switch (kind) { case DataTypeKindMessage: return &msgs_; case DataTypeKindService: return &srvs_; default: assert(0); return NULL; } } GlobalDataTypeRegistry::RegistResult GlobalDataTypeRegistry::remove(Entry* dtd) { if (!dtd) { assert(0); return RegistResultInvalidParams; } if (isFrozen()) return RegistResultFrozen; List* list = selectList(dtd->descriptor.getKind()); if (!list) return RegistResultInvalidParams; list->remove(dtd); // If this call came from regist<>(), that would be enough Entry* p = list->get(); // But anyway while (p) { Entry* const next = p->getNextListNode(); if (p->descriptor.match(dtd->descriptor.getKind(), dtd->descriptor.getFullName())) list->remove(p); p = next; } return RegistResultOk; } GlobalDataTypeRegistry::RegistResult GlobalDataTypeRegistry::registImpl(Entry* dtd) { if (!dtd || (dtd->descriptor.getID() > DataTypeID::Max)) { assert(0); return RegistResultInvalidParams; } if (isFrozen()) return RegistResultFrozen; List* list = selectList(dtd->descriptor.getKind()); if (!list) return RegistResultInvalidParams; { // Collision check Entry* p = list->get(); while (p) { if (p->descriptor.getID() == dtd->descriptor.getID()) // ID collision return RegistResultCollision; if (!std::strcmp(p->descriptor.getFullName(), dtd->descriptor.getFullName())) // Name collision return RegistResultCollision; p = p->getNextListNode(); } } list->insertBefore(dtd, EntryInsertionComparator(dtd)); #if UAVCAN_DEBUG { // Order check Entry* p = list->get(); int id = -1; while (p) { if (id >= p->descriptor.getID().get()) { assert(0); std::abort(); } id = p->descriptor.getID().get(); p = p->getNextListNode(); } } #endif return RegistResultOk; } GlobalDataTypeRegistry& GlobalDataTypeRegistry::instance() { static GlobalDataTypeRegistry inst; return inst; } void GlobalDataTypeRegistry::freeze() { if (!frozen_) { frozen_ = true; UAVCAN_TRACE("GlobalDataTypeRegistry", "Frozen; num msgs: %u, num srvs: %u", getNumMessageTypes(), getNumServiceTypes()); } } const DataTypeDescriptor* GlobalDataTypeRegistry::find(DataTypeKind kind, const char* name) const { const List* list = selectList(kind); if (!list) { assert(0); return NULL; } Entry* p = list->get(); while (p) { if (p->descriptor.match(kind, name)) return &p->descriptor; p = p->getNextListNode(); } return NULL; } DataTypeSignature GlobalDataTypeRegistry::computeAggregateSignature(DataTypeKind kind, DataTypeIDMask& inout_id_mask) const { assert(isFrozen()); // Computing the signature if the registry is not frozen is pointless const List* list = selectList(kind); if (!list) { assert(0); return DataTypeSignature(); } int prev_dtid = -1; DataTypeSignature signature; bool signature_initialized = false; Entry* p = list->get(); while (p) { const DataTypeDescriptor& desc = p->descriptor; const int dtid = desc.getID().get(); if (inout_id_mask[dtid]) { if (signature_initialized) signature.extend(desc.getSignature()); else signature = DataTypeSignature(desc.getSignature()); signature_initialized = true; } assert(prev_dtid < dtid); // Making sure that list is ordered properly prev_dtid++; while (prev_dtid < dtid) inout_id_mask[prev_dtid++] = false; // Erasing bits for missing types assert(prev_dtid == dtid); p = p->getNextListNode(); } prev_dtid++; while (prev_dtid <= DataTypeID::Max) inout_id_mask[prev_dtid++] = false; return signature; } void GlobalDataTypeRegistry::getDataTypeIDMask(DataTypeKind kind, DataTypeIDMask& mask) const { mask.reset(); const List* list = selectList(kind); if (!list) { assert(0); return; } Entry* p = list->get(); while (p) { assert(p->descriptor.getKind() == kind); mask[p->descriptor.getID().get()] = true; p = p->getNextListNode(); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Jake Horsfield * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef INI_PARSER_H #define INI_PARSER_H #include <map> #include <string> #include <vector> #include <utility> #include <fstream> #include <stdexcept> /* * Adds support for functions not available in minGW. * http://pastebin.com/KMTd7Xtk# */ #ifdef __MINGW32__ namespace std { template <class T> std::string to_string(T val) { std::stringstream ss; ss << val; return ss.str(); } int stoi(const std::string& str) { std::stringstream ss; int ret; ss << str; ss >> ret; return ret; } long stol(const std::string& str) { std::stringstream ss; long ret; ss << str; ss >> ret; return ret; } float stof(const std::string& str) { std::stringstream ss; float ret; ss << str; ss >> ret; return ret; } double stod(const std::string& str) { std::stringstream ss; double ret; ss << str; ss >> ret; return ret; } } #endif // __MINGW32__ class ini_parser { public: ini_parser(const std::string& filename) : filename(filename) , current_section("") { parse(filename); } void create_property(const std::string& name, const std::string& value, const std::string& section = "") { if (name.empty() || value.empty()) { throw std::runtime_error("when creating a property, the name or value cannot be empty"); } if (section.empty()) { create_property_no_section(name, value); } else { create_property_in_section(name, value, section); } } /* Writes a new line at the bottom of the file, followed by the start of the section. */ void create_section(const std::string& name) { if (name.empty()) { throw std::runtime_error("when creating section, its name cannot be empty"); } std::string line = "\n[" + name + "]"; input.push_back(line); write_input_to_file(); } int get_int(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); return std::stoi(sections.at(section).at(name)); } /* * The legal values for bools are BOOL_TRUE and BOOL_FALSE. * Anything other than these values are illegal. */ bool get_bool(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); std::string value = sections.at(section).at(name); if (value == BOOL_TRUE) { return true; } else if (value == BOOL_FALSE) { return false; } else { throw std::runtime_error("unable to cast to bool"); } } long get_long(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); return std::stol(sections.at(section).at(name)); } float get_float(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); return std::stof(sections.at(section).at(name)); } double get_double(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); return std::stod(sections.at(section).at(name)); } std::string get_string(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); return sections.at(section).at(name); } void set_value(const std::string& name, int value, const std::string& section = "") { set_value(name, std::to_string(value), section); } void set_value(const std::string& name, bool value, const std::string& section = "") { set_value(name, (value ? BOOL_TRUE : BOOL_FALSE), section); } void set_value(const std::string& name, long value, const std::string& section = "") { set_value(name, std::to_string(value), section); } void set_value(const std::string& name, float value, const std::string& section = "") { set_value(name, std::to_string(value), section); } void set_value(const std::string& name, double value, const std::string& section = "") { set_value(name, std::to_string(value), section); } void set_value(const std::string& name, const std::string& value, const std::string& section = "") { ensure_property_exists(section, name); sections[section][name] = value; bool replaced = false; std::string current_section = ""; /* * Note that references to "current_section" refer to the local * variable defined above, not the member variable. */ for (int i = 0; i < input.size(); ++i) { std::string& line = input[i]; if (is_section_start_line(line)) { current_section = extract_section_name(line); } else if (is_assignment_line(line)) { std::string key = extract_key(line); if (key == name && current_section == section) { line = key; line += "="; line += value; replaced = true; } } } if (replaced) { write_input_to_file(); } else { throw std::runtime_error("property does not exist so cannot change its value"); } } private: void create_property_no_section(const std::string& name, const std::string& value) { std::string line = name + "=" + value; input.insert(input.begin(), line); write_input_to_file(); sections[""][name] = value; } void create_property_in_section(const std::string& name, const std::string& value, const std::string& section) { std::string line = name + "=" + value; std::string tmp_current_section = ""; for (auto it = input.begin(); it != input.end(); ++it) { if (is_section_start_line(*it)) { tmp_current_section = extract_section_name(*it); if (tmp_current_section == section) { input.insert(it + 1, line); write_input_to_file(); sections[section][name] = value; return; } } } /* Section was not found. */ throw std::runtime_error("unable to create property in section"); } void write_input_to_file() { std::fstream file(filename); for (const std::string& line : input) { file << line << std::endl; } file.close(); } void parse(const std::string& filename) { std::fstream file; file.open(filename); if (!file.is_open()) { std::printf("error: could not open \"%s\". terminated parsing.\n", filename.c_str()); file.close(); return; } std::string line; while (std::getline(file, line)) { input.push_back(line); if (is_comment_line(line)) { continue; } else if (is_section_start_line(line)) { start_section(line); } else if (is_assignment_line(line)) { handle_assignment(line); } } } void start_section(const std::string& line) { current_section = extract_section_name(line); } std::string extract_section_name(const std::string& line) const { std::string name; for (int i = 1; line[i] != ']'; ++i) { name += line[i]; } return name; } void handle_assignment(const std::string& line) { std::string key = extract_key(line); std::string value = extract_value(line); sections[current_section][key] = value; } std::string extract_key(const std::string& line) const { std::string key; for (int i = 0; line[i] != '='; ++i) { key += line[i]; } return key; } std::string extract_value(const std::string& line) const { std::string value; int equals_pos; for (equals_pos = 0; line[equals_pos] != '='; ++equals_pos) { /* Skip to equals sign. */ } /* Get everything from the character following the equals sign to the end of the line. */ for (int i = equals_pos + 1; i < line.length(); ++i) { value += line[i]; } return value; } /* * A line is a comment if the first character is a semi-colon. */ bool is_comment_line(const std::string& line) const { return (line.length() > 0) && (line[0] == ';'); } /* * A line is the start of a section if the first character is an open * bracket and the last character is a closing bracket. */ bool is_section_start_line(const std::string& line) const { return (line.length() > 0) && (line[0] == '[') && (line[line.length() - 1] == ']'); } /* * A line contains an assignment if it contains an equals sign and * there is text before and after this equals sign. */ bool is_assignment_line(const std::string& line) const { std::size_t equals_pos = line.find("="); return (equals_pos != std::string::npos) && (equals_pos != 0) && (equals_pos != line.length() - 1); } void ensure_property_exists(const std::string& section, const std::string& name) const { if (section != "" && sections.find(section) == sections.end()) { throw std::runtime_error("section does not exist"); } if (sections.at(section).find(name) == sections.at(section).end()) { throw std::runtime_error("property does not exist"); } } private: const std::string filename; std::vector<std::string> input; typedef std::map<std::string, std::string> properties; std::map<std::string, properties> sections; std::string current_section; static constexpr const char* BOOL_TRUE = "TRUE"; static constexpr const char* BOOL_FALSE = "FALSE"; }; #endif <commit_msg>Accidently deleted the sstream include<commit_after>/* * Copyright (c) 2014 Jake Horsfield * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef INI_PARSER_H #define INI_PARSER_H #include <map> #include <string> #include <vector> #include <utility> #include <sstream> #include <fstream> #include <stdexcept> /* * Adds support for functions not available in minGW. * http://pastebin.com/KMTd7Xtk# */ #ifdef __MINGW32__ namespace std { template <class T> std::string to_string(T val) { std::stringstream ss; ss << val; return ss.str(); } int stoi(const std::string& str) { std::stringstream ss; int ret; ss << str; ss >> ret; return ret; } long stol(const std::string& str) { std::stringstream ss; long ret; ss << str; ss >> ret; return ret; } float stof(const std::string& str) { std::stringstream ss; float ret; ss << str; ss >> ret; return ret; } double stod(const std::string& str) { std::stringstream ss; double ret; ss << str; ss >> ret; return ret; } } #endif // __MINGW32__ class ini_parser { public: ini_parser(const std::string& filename) : filename(filename) , current_section("") { parse(filename); } void create_property(const std::string& name, const std::string& value, const std::string& section = "") { if (name.empty() || value.empty()) { throw std::runtime_error("when creating a property, the name or value cannot be empty"); } if (section.empty()) { create_property_no_section(name, value); } else { create_property_in_section(name, value, section); } } /* Writes a new line at the bottom of the file, followed by the start of the section. */ void create_section(const std::string& name) { if (name.empty()) { throw std::runtime_error("when creating section, its name cannot be empty"); } std::string line = "\n[" + name + "]"; input.push_back(line); write_input_to_file(); } int get_int(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); return std::stoi(sections.at(section).at(name)); } /* * The legal values for bools are BOOL_TRUE and BOOL_FALSE. * Anything other than these values are illegal. */ bool get_bool(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); std::string value = sections.at(section).at(name); if (value == BOOL_TRUE) { return true; } else if (value == BOOL_FALSE) { return false; } else { throw std::runtime_error("unable to cast to bool"); } } long get_long(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); return std::stol(sections.at(section).at(name)); } float get_float(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); return std::stof(sections.at(section).at(name)); } double get_double(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); return std::stod(sections.at(section).at(name)); } std::string get_string(const std::string& name, const std::string& section = "") const { ensure_property_exists(section, name); return sections.at(section).at(name); } void set_value(const std::string& name, int value, const std::string& section = "") { set_value(name, std::to_string(value), section); } void set_value(const std::string& name, bool value, const std::string& section = "") { set_value(name, (value ? BOOL_TRUE : BOOL_FALSE), section); } void set_value(const std::string& name, long value, const std::string& section = "") { set_value(name, std::to_string(value), section); } void set_value(const std::string& name, float value, const std::string& section = "") { set_value(name, std::to_string(value), section); } void set_value(const std::string& name, double value, const std::string& section = "") { set_value(name, std::to_string(value), section); } void set_value(const std::string& name, const std::string& value, const std::string& section = "") { ensure_property_exists(section, name); sections[section][name] = value; bool replaced = false; std::string current_section = ""; /* * Note that references to "current_section" refer to the local * variable defined above, not the member variable. */ for (int i = 0; i < input.size(); ++i) { std::string& line = input[i]; if (is_section_start_line(line)) { current_section = extract_section_name(line); } else if (is_assignment_line(line)) { std::string key = extract_key(line); if (key == name && current_section == section) { line = key; line += "="; line += value; replaced = true; } } } if (replaced) { write_input_to_file(); } else { throw std::runtime_error("property does not exist so cannot change its value"); } } private: void create_property_no_section(const std::string& name, const std::string& value) { std::string line = name + "=" + value; input.insert(input.begin(), line); write_input_to_file(); sections[""][name] = value; } void create_property_in_section(const std::string& name, const std::string& value, const std::string& section) { std::string line = name + "=" + value; std::string tmp_current_section = ""; for (auto it = input.begin(); it != input.end(); ++it) { if (is_section_start_line(*it)) { tmp_current_section = extract_section_name(*it); if (tmp_current_section == section) { input.insert(it + 1, line); write_input_to_file(); sections[section][name] = value; return; } } } /* Section was not found. */ throw std::runtime_error("unable to create property in section"); } void write_input_to_file() { std::fstream file(filename); for (const std::string& line : input) { file << line << std::endl; } file.close(); } void parse(const std::string& filename) { std::fstream file; file.open(filename); if (!file.is_open()) { std::printf("error: could not open \"%s\". terminated parsing.\n", filename.c_str()); file.close(); return; } std::string line; while (std::getline(file, line)) { input.push_back(line); if (is_comment_line(line)) { continue; } else if (is_section_start_line(line)) { start_section(line); } else if (is_assignment_line(line)) { handle_assignment(line); } } } void start_section(const std::string& line) { current_section = extract_section_name(line); } std::string extract_section_name(const std::string& line) const { std::string name; for (int i = 1; line[i] != ']'; ++i) { name += line[i]; } return name; } void handle_assignment(const std::string& line) { std::string key = extract_key(line); std::string value = extract_value(line); sections[current_section][key] = value; } std::string extract_key(const std::string& line) const { std::string key; for (int i = 0; line[i] != '='; ++i) { key += line[i]; } return key; } std::string extract_value(const std::string& line) const { std::string value; int equals_pos; for (equals_pos = 0; line[equals_pos] != '='; ++equals_pos) { /* Skip to equals sign. */ } /* Get everything from the character following the equals sign to the end of the line. */ for (int i = equals_pos + 1; i < line.length(); ++i) { value += line[i]; } return value; } /* * A line is a comment if the first character is a semi-colon. */ bool is_comment_line(const std::string& line) const { return (line.length() > 0) && (line[0] == ';'); } /* * A line is the start of a section if the first character is an open * bracket and the last character is a closing bracket. */ bool is_section_start_line(const std::string& line) const { return (line.length() > 0) && (line[0] == '[') && (line[line.length() - 1] == ']'); } /* * A line contains an assignment if it contains an equals sign and * there is text before and after this equals sign. */ bool is_assignment_line(const std::string& line) const { std::size_t equals_pos = line.find("="); return (equals_pos != std::string::npos) && (equals_pos != 0) && (equals_pos != line.length() - 1); } void ensure_property_exists(const std::string& section, const std::string& name) const { if (section != "" && sections.find(section) == sections.end()) { throw std::runtime_error("section does not exist"); } if (sections.at(section).find(name) == sections.at(section).end()) { throw std::runtime_error("property does not exist"); } } private: const std::string filename; std::vector<std::string> input; typedef std::map<std::string, std::string> properties; std::map<std::string, properties> sections; std::string current_section; static constexpr const char* BOOL_TRUE = "TRUE"; static constexpr const char* BOOL_FALSE = "FALSE"; }; #endif <|endoftext|>
<commit_before><commit_msg>Extract the group token conversion loop out into a separate class.<commit_after><|endoftext|>
<commit_before><commit_msg>Planning: add weight_end_dx on piecewise_jerk_speed<commit_after><|endoftext|>
<commit_before><commit_msg>fix coverity#1187656<commit_after><|endoftext|>
<commit_before>//---------------------------------------------------------------------------// /* Copyright (c) 2012, Stuart R. Slattery All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: *: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. *: Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. *: Neither the name of the University of Wisconsin - Madison nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------------// /*! * \brief DTK_ConsistentInterpolationOperator.cpp * \author Stuart R. Slattery * \brief Consistent interpolation operator. */ //---------------------------------------------------------------------------// #include <algorithm> #include <unordered_map> #include "DTK_BasicEntityPredicates.hpp" #include "DTK_ConsistentInterpolationOperator.hpp" #include "DTK_DBC.hpp" #include "DTK_ParallelSearch.hpp" #include "DTK_PredicateComposition.hpp" #include <Teuchos_OrdinalTraits.hpp> #include <Tpetra_Distributor.hpp> #include <Tpetra_Map.hpp> namespace DataTransferKit { //---------------------------------------------------------------------------// // Constructor. ConsistentInterpolationOperator::ConsistentInterpolationOperator( const Teuchos::RCP<const TpetraMap> &domain_map, const Teuchos::RCP<const TpetraMap> &range_map, const Teuchos::ParameterList &parameters ) : Base( domain_map, range_map ) , d_range_entity_dim( 0 ) , d_keep_missed_sol( false ) , d_missed_range_entity_ids( 0 ) { // Get the topological dimension of the range entities. Teuchos::ParameterList map_list = parameters.sublist( "Consistent Interpolation" ); if ( map_list.isParameter( "Range Entity Dimension" ) ) { d_range_entity_dim = map_list.get<int>( "Range Entity Dimension" ); } // Get the search list. d_search_list = parameters.sublist( "Search" ); // If we want to keep the range data when we miss entities instead of // zeros, turn this on. if ( map_list.isParameter( "Keep Missed Range Data" ) ) { d_keep_missed_sol = map_list.get<bool>( "Keep Missed Range Data" ); if ( d_keep_missed_sol ) { d_search_list.set( "Track Missed Range Entities", true ); } } } //---------------------------------------------------------------------------// // Setup the map operator. void ConsistentInterpolationOperator::setupImpl( const Teuchos::RCP<FunctionSpace> &domain_space, const Teuchos::RCP<FunctionSpace> &range_space ) { DTK_REQUIRE( Teuchos::nonnull( domain_space ) ); DTK_REQUIRE( Teuchos::nonnull( range_space ) ); // Extract the Support maps. const Teuchos::RCP<const typename Base::TpetraMap> domain_map = this->getDomainMap(); const Teuchos::RCP<const typename Base::TpetraMap> range_map = this->getRangeMap(); // Get the parallel communicator. Teuchos::RCP<const Teuchos::Comm<int>> comm = domain_map->getComm(); // Determine if we have range and domain data on this process. bool nonnull_domain = Teuchos::nonnull( domain_space->entitySet() ); bool nonnull_range = Teuchos::nonnull( range_space->entitySet() ); // Get the physical dimension. int physical_dimension = 0; if ( nonnull_domain ) { physical_dimension = domain_space->entitySet()->physicalDimension(); } else if ( nonnull_range ) { physical_dimension = range_space->entitySet()->physicalDimension(); } // Get an iterator over the domain entities. EntityIterator domain_iterator; if ( nonnull_domain ) { LocalEntityPredicate local_predicate( domain_space->entitySet()->communicator()->getRank() ); PredicateFunction domain_predicate = PredicateComposition::And( domain_space->selectFunction(), local_predicate.getFunction() ); domain_iterator = domain_space->entitySet()->entityIterator( domain_space->entitySet()->physicalDimension(), domain_predicate ); } // Build a parallel search over the domain. ParallelSearch psearch( comm, physical_dimension, domain_iterator, domain_space->localMap(), d_search_list ); // Get an iterator over the range entities. EntityIterator range_iterator; if ( nonnull_range ) { LocalEntityPredicate local_predicate( range_space->entitySet()->communicator()->getRank() ); PredicateFunction range_predicate = PredicateComposition::And( range_space->selectFunction(), local_predicate.getFunction() ); range_iterator = range_space->entitySet()->entityIterator( d_range_entity_dim, range_predicate ); } // Search the domain with the range. psearch.search( range_iterator, range_space->localMap(), d_search_list ); // If we are keeping track of range entities that were not mapped, extract // them. d_missed_range_entity_ids = Teuchos::Array<EntityId>( psearch.getMissedRangeEntityIds() ); // Determine the Support ids for the range entities found in the local // domain // on this process and the number of domain entities they were found in // globally for averaging. std::unordered_map<EntityId, GO> range_support_id_map; Teuchos::RCP<Tpetra::Vector<double, int, SupportId, Node>> scale_vector = Tpetra::createVector<double, int, SupportId, Node>( range_map ); { // Extract the set of local range entities that were found in domain // entities. Teuchos::Array<int> export_ranks; Teuchos::Array<GO> export_data; Teuchos::Array<EntityId> domain_ids; Teuchos::Array<EntityId>::const_iterator domain_id_it; Teuchos::Array<GO> range_support_ids; EntityIterator range_it; EntityIterator range_begin = range_iterator.begin(); EntityIterator range_end = range_iterator.end(); for ( range_it = range_begin; range_it != range_end; ++range_it ) { // Get the support id for the range entity. range_space->shapeFunction()->entitySupportIds( *range_it, range_support_ids ); DTK_CHECK( 1 == range_support_ids.size() ); // Get the domain entities in which the range entity was found. psearch.getDomainEntitiesFromRange( range_it->id(), domain_ids ); // Add a scale factor for this range entity to the scaling vector. DTK_CHECK( range_map->isNodeGlobalElement( range_support_ids[0] ) ); scale_vector->replaceGlobalValue( range_support_ids[0], 1.0 / domain_ids.size() ); // For each supporting domain entity, pair the range entity id and // its support id. for ( domain_id_it = domain_ids.begin(); domain_id_it != domain_ids.end(); ++domain_id_it ) { export_ranks.push_back( psearch.domainEntityOwnerRank( *domain_id_it ) ); export_data.push_back( range_support_ids[0] ); export_data.push_back( Teuchos::as<GO>( range_it->id() ) ); } } // Communicate the range entity Support data back to the domain parallel // decomposition. Tpetra::Distributor range_to_domain_dist( comm ); int num_import = range_to_domain_dist.createFromSends( export_ranks() ); Teuchos::Array<GO> import_data( 2 * num_import ); Teuchos::ArrayView<const GO> export_data_view = export_data(); range_to_domain_dist.doPostsAndWaits( export_data_view, 2, import_data() ); // Map the range entities to their support ids. for ( int i = 0; i < num_import; ++i ) { range_support_id_map.emplace( Teuchos::as<EntityId>( import_data[2 * i + 1] ), import_data[2 * i] ); } } // Allocate the coupling matrix. d_coupling_matrix = Tpetra::createCrsMatrix<double, LO, GO>( range_map ); // Construct the entries of the coupling matrix. Teuchos::Array<EntityId> range_entity_ids; Teuchos::Array<EntityId>::const_iterator range_entity_id_it; Teuchos::ArrayView<const double> range_parametric_coords; Teuchos::Array<double> domain_shape_values; Teuchos::Array<double>::iterator domain_shape_it; Teuchos::Array<GO> domain_support_ids; EntityIterator domain_it; EntityIterator domain_begin = domain_iterator.begin(); EntityIterator domain_end = domain_iterator.end(); for ( domain_it = domain_begin; domain_it != domain_end; ++domain_it ) { // Get the domain Support ids supporting the domain entity. domain_space->shapeFunction()->entitySupportIds( *domain_it, domain_support_ids ); // Get the range entities that mapped into this domain entity. psearch.getRangeEntitiesFromDomain( domain_it->id(), range_entity_ids ); // Sum into the global coupling matrix row for each domain. for ( range_entity_id_it = range_entity_ids.begin(); range_entity_id_it != range_entity_ids.end(); ++range_entity_id_it ) { // Get the parametric coordinates of the range entity in the // domain entity. psearch.rangeParametricCoordinatesInDomain( domain_it->id(), *range_entity_id_it, range_parametric_coords ); // Evaluate the shape function at the coordinates. domain_space->shapeFunction()->evaluateValue( *domain_it, range_parametric_coords, domain_shape_values ); DTK_CHECK( domain_shape_values.size() == domain_support_ids.size() ); // Consistent interpolation requires one support location per // range entity. Load the row for this range support location into // the matrix. DTK_CHECK( range_support_id_map.count( *range_entity_id_it ) ); d_coupling_matrix->insertGlobalValues( range_support_id_map.find( *range_entity_id_it )->second, domain_support_ids(), domain_shape_values() ); } } // Finalize the coupling matrix. d_coupling_matrix->fillComplete( domain_map, range_map ); // Left-scale the matrix with the number of domain entities in which each // range entity was found. d_coupling_matrix->leftScale( *scale_vector ); // If we want to keep the range data when we miss points, create the // scaling vector. if ( d_keep_missed_sol ) { d_keep_range_vec = Tpetra::createVector<double, LO, GO, Node>( range_map ); for ( auto &m : d_missed_range_entity_ids ) { d_keep_range_vec->replaceGlobalValue( m, 1.0 ); } } } //---------------------------------------------------------------------------// // Apply the operator. void ConsistentInterpolationOperator::applyImpl( const TpetraMultiVector &X, TpetraMultiVector &Y, Teuchos::ETransp mode, double alpha, double beta ) const { // If we want to keep the range data when we miss points, make a work vec // and get the parts we will zero out. Beta must be zero or the interface // is violated. Teuchos::RCP<Tpetra::Vector<Scalar, LO, GO, Node>> work_vec; if ( d_keep_missed_sol ) { DTK_REQUIRE( 0.0 == beta ); DTK_REQUIRE( Teuchos::nonnull( d_keep_range_vec ) ); work_vec = Tpetra::createVector<double, LO, GO, Node>( this->getRangeMap() ); work_vec->elementWiseMultiply( 1.0, *d_keep_range_vec, Y, 0.0 ); } // Apply the coupling matrix. d_coupling_matrix->apply( X, Y, mode, alpha, beta ); // If we want to keep the range data when we miss points, add back in the // components that got zeroed out. if ( d_keep_missed_sol ) { Y.update( 1.0, *work_vec, 1.0 ); } } //---------------------------------------------------------------------------// // Transpose apply option. bool ConsistentInterpolationOperator::hasTransposeApplyImpl() const { return true; } //---------------------------------------------------------------------------// // Return the ids of the range entities that were not mapped during the last // setup phase (i.e. those that are guaranteed to not receive data from the // transfer). Teuchos::ArrayView<const EntityId> ConsistentInterpolationOperator::getMissedRangeEntityIds() const { return d_missed_range_entity_ids(); } //---------------------------------------------------------------------------// } // end namespace DataTransferKit //---------------------------------------------------------------------------// // end DTK_ConsistentInterpolationOperator.cpp //---------------------------------------------------------------------------// <commit_msg>Do not divide by zero.<commit_after>//---------------------------------------------------------------------------// /* Copyright (c) 2012, Stuart R. Slattery All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: *: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. *: Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. *: Neither the name of the University of Wisconsin - Madison nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------------// /*! * \brief DTK_ConsistentInterpolationOperator.cpp * \author Stuart R. Slattery * \brief Consistent interpolation operator. */ //---------------------------------------------------------------------------// #include <algorithm> #include <unordered_map> #include "DTK_BasicEntityPredicates.hpp" #include "DTK_ConsistentInterpolationOperator.hpp" #include "DTK_DBC.hpp" #include "DTK_ParallelSearch.hpp" #include "DTK_PredicateComposition.hpp" #include <Teuchos_OrdinalTraits.hpp> #include <Tpetra_Distributor.hpp> #include <Tpetra_Map.hpp> namespace DataTransferKit { //---------------------------------------------------------------------------// // Constructor. ConsistentInterpolationOperator::ConsistentInterpolationOperator( const Teuchos::RCP<const TpetraMap> &domain_map, const Teuchos::RCP<const TpetraMap> &range_map, const Teuchos::ParameterList &parameters ) : Base( domain_map, range_map ) , d_range_entity_dim( 0 ) , d_keep_missed_sol( false ) , d_missed_range_entity_ids( 0 ) { // Get the topological dimension of the range entities. Teuchos::ParameterList map_list = parameters.sublist( "Consistent Interpolation" ); if ( map_list.isParameter( "Range Entity Dimension" ) ) { d_range_entity_dim = map_list.get<int>( "Range Entity Dimension" ); } // Get the search list. d_search_list = parameters.sublist( "Search" ); // If we want to keep the range data when we miss entities instead of // zeros, turn this on. if ( map_list.isParameter( "Keep Missed Range Data" ) ) { d_keep_missed_sol = map_list.get<bool>( "Keep Missed Range Data" ); if ( d_keep_missed_sol ) { d_search_list.set( "Track Missed Range Entities", true ); } } } //---------------------------------------------------------------------------// // Setup the map operator. void ConsistentInterpolationOperator::setupImpl( const Teuchos::RCP<FunctionSpace> &domain_space, const Teuchos::RCP<FunctionSpace> &range_space ) { DTK_REQUIRE( Teuchos::nonnull( domain_space ) ); DTK_REQUIRE( Teuchos::nonnull( range_space ) ); // Extract the Support maps. const Teuchos::RCP<const typename Base::TpetraMap> domain_map = this->getDomainMap(); const Teuchos::RCP<const typename Base::TpetraMap> range_map = this->getRangeMap(); // Get the parallel communicator. Teuchos::RCP<const Teuchos::Comm<int>> comm = domain_map->getComm(); // Determine if we have range and domain data on this process. bool nonnull_domain = Teuchos::nonnull( domain_space->entitySet() ); bool nonnull_range = Teuchos::nonnull( range_space->entitySet() ); // Get the physical dimension. int physical_dimension = 0; if ( nonnull_domain ) { physical_dimension = domain_space->entitySet()->physicalDimension(); } else if ( nonnull_range ) { physical_dimension = range_space->entitySet()->physicalDimension(); } // Get an iterator over the domain entities. EntityIterator domain_iterator; if ( nonnull_domain ) { LocalEntityPredicate local_predicate( domain_space->entitySet()->communicator()->getRank() ); PredicateFunction domain_predicate = PredicateComposition::And( domain_space->selectFunction(), local_predicate.getFunction() ); domain_iterator = domain_space->entitySet()->entityIterator( domain_space->entitySet()->physicalDimension(), domain_predicate ); } // Build a parallel search over the domain. ParallelSearch psearch( comm, physical_dimension, domain_iterator, domain_space->localMap(), d_search_list ); // Get an iterator over the range entities. EntityIterator range_iterator; if ( nonnull_range ) { LocalEntityPredicate local_predicate( range_space->entitySet()->communicator()->getRank() ); PredicateFunction range_predicate = PredicateComposition::And( range_space->selectFunction(), local_predicate.getFunction() ); range_iterator = range_space->entitySet()->entityIterator( d_range_entity_dim, range_predicate ); } // Search the domain with the range. psearch.search( range_iterator, range_space->localMap(), d_search_list ); // If we are keeping track of range entities that were not mapped, extract // them. d_missed_range_entity_ids = Teuchos::Array<EntityId>( psearch.getMissedRangeEntityIds() ); // Determine the Support ids for the range entities found in the local // domain // on this process and the number of domain entities they were found in // globally for averaging. std::unordered_map<EntityId, GO> range_support_id_map; Teuchos::RCP<Tpetra::Vector<double, int, SupportId, Node>> scale_vector = Tpetra::createVector<double, int, SupportId, Node>( range_map ); { // Extract the set of local range entities that were found in domain // entities. Teuchos::Array<int> export_ranks; Teuchos::Array<GO> export_data; Teuchos::Array<EntityId> domain_ids; Teuchos::Array<EntityId>::const_iterator domain_id_it; Teuchos::Array<GO> range_support_ids; EntityIterator range_it; EntityIterator range_begin = range_iterator.begin(); EntityIterator range_end = range_iterator.end(); for ( range_it = range_begin; range_it != range_end; ++range_it ) { // Get the support id for the range entity. range_space->shapeFunction()->entitySupportIds( *range_it, range_support_ids ); DTK_CHECK( 1 == range_support_ids.size() ); // Get the domain entities in which the range entity was found. psearch.getDomainEntitiesFromRange( range_it->id(), domain_ids ); // Add a scale factor for this range entity to the scaling vector. DTK_CHECK( range_map->isNodeGlobalElement( range_support_ids[0] ) ); const double scale_factor = ( domain_ids.size() != 0 ) ? 1.0 / domain_ids.size() : 1.; scale_vector->replaceGlobalValue( range_support_ids[0], scale_factor ); // For each supporting domain entity, pair the range entity id and // its support id. for ( domain_id_it = domain_ids.begin(); domain_id_it != domain_ids.end(); ++domain_id_it ) { export_ranks.push_back( psearch.domainEntityOwnerRank( *domain_id_it ) ); export_data.push_back( range_support_ids[0] ); export_data.push_back( Teuchos::as<GO>( range_it->id() ) ); } } // Communicate the range entity Support data back to the domain parallel // decomposition. Tpetra::Distributor range_to_domain_dist( comm ); int num_import = range_to_domain_dist.createFromSends( export_ranks() ); Teuchos::Array<GO> import_data( 2 * num_import ); Teuchos::ArrayView<const GO> export_data_view = export_data(); range_to_domain_dist.doPostsAndWaits( export_data_view, 2, import_data() ); // Map the range entities to their support ids. for ( int i = 0; i < num_import; ++i ) { range_support_id_map.emplace( Teuchos::as<EntityId>( import_data[2 * i + 1] ), import_data[2 * i] ); } } // Allocate the coupling matrix. d_coupling_matrix = Tpetra::createCrsMatrix<double, LO, GO>( range_map ); // Construct the entries of the coupling matrix. Teuchos::Array<EntityId> range_entity_ids; Teuchos::Array<EntityId>::const_iterator range_entity_id_it; Teuchos::ArrayView<const double> range_parametric_coords; Teuchos::Array<double> domain_shape_values; Teuchos::Array<double>::iterator domain_shape_it; Teuchos::Array<GO> domain_support_ids; EntityIterator domain_it; EntityIterator domain_begin = domain_iterator.begin(); EntityIterator domain_end = domain_iterator.end(); for ( domain_it = domain_begin; domain_it != domain_end; ++domain_it ) { // Get the domain Support ids supporting the domain entity. domain_space->shapeFunction()->entitySupportIds( *domain_it, domain_support_ids ); // Get the range entities that mapped into this domain entity. psearch.getRangeEntitiesFromDomain( domain_it->id(), range_entity_ids ); // Sum into the global coupling matrix row for each domain. for ( range_entity_id_it = range_entity_ids.begin(); range_entity_id_it != range_entity_ids.end(); ++range_entity_id_it ) { // Get the parametric coordinates of the range entity in the // domain entity. psearch.rangeParametricCoordinatesInDomain( domain_it->id(), *range_entity_id_it, range_parametric_coords ); // Evaluate the shape function at the coordinates. domain_space->shapeFunction()->evaluateValue( *domain_it, range_parametric_coords, domain_shape_values ); DTK_CHECK( domain_shape_values.size() == domain_support_ids.size() ); // Consistent interpolation requires one support location per // range entity. Load the row for this range support location into // the matrix. DTK_CHECK( range_support_id_map.count( *range_entity_id_it ) ); d_coupling_matrix->insertGlobalValues( range_support_id_map.find( *range_entity_id_it )->second, domain_support_ids(), domain_shape_values() ); } } // Finalize the coupling matrix. d_coupling_matrix->fillComplete( domain_map, range_map ); // Left-scale the matrix with the number of domain entities in which each // range entity was found. d_coupling_matrix->leftScale( *scale_vector ); // If we want to keep the range data when we miss points, create the // scaling vector. if ( d_keep_missed_sol ) { d_keep_range_vec = Tpetra::createVector<double, LO, GO, Node>( range_map ); for ( auto &m : d_missed_range_entity_ids ) { d_keep_range_vec->replaceGlobalValue( m, 1.0 ); } } } //---------------------------------------------------------------------------// // Apply the operator. void ConsistentInterpolationOperator::applyImpl( const TpetraMultiVector &X, TpetraMultiVector &Y, Teuchos::ETransp mode, double alpha, double beta ) const { // If we want to keep the range data when we miss points, make a work vec // and get the parts we will zero out. Beta must be zero or the interface // is violated. Teuchos::RCP<Tpetra::Vector<Scalar, LO, GO, Node>> work_vec; if ( d_keep_missed_sol ) { DTK_REQUIRE( 0.0 == beta ); DTK_REQUIRE( Teuchos::nonnull( d_keep_range_vec ) ); work_vec = Tpetra::createVector<double, LO, GO, Node>( this->getRangeMap() ); work_vec->elementWiseMultiply( 1.0, *d_keep_range_vec, Y, 0.0 ); } // Apply the coupling matrix. d_coupling_matrix->apply( X, Y, mode, alpha, beta ); // If we want to keep the range data when we miss points, add back in the // components that got zeroed out. if ( d_keep_missed_sol ) { Y.update( 1.0, *work_vec, 1.0 ); } } //---------------------------------------------------------------------------// // Transpose apply option. bool ConsistentInterpolationOperator::hasTransposeApplyImpl() const { return true; } //---------------------------------------------------------------------------// // Return the ids of the range entities that were not mapped during the last // setup phase (i.e. those that are guaranteed to not receive data from the // transfer). Teuchos::ArrayView<const EntityId> ConsistentInterpolationOperator::getMissedRangeEntityIds() const { return d_missed_range_entity_ids(); } //---------------------------------------------------------------------------// } // end namespace DataTransferKit //---------------------------------------------------------------------------// // end DTK_ConsistentInterpolationOperator.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>#ifndef STAN__MATH__MATRIX__EXP_HPP #define STAN__MATH__MATRIX__EXP_HPP #include <stan/math/matrix/Eigen.hpp> namespace stan { namespace math { /** * Return the element-wise exponentiation of the matrix or vector. * * @param m The matrix or vector. * @return ret(i,j) = exp(m(i,j)) */ template<typename T, int Rows, int Cols> inline Eigen::Matrix<T,Rows,Cols> exp(const Eigen::Matrix<T,Rows,Cols>& m) { return m.array().exp().matrix(); } } } #endif <commit_msg>Fix stan::math::exp behaviour for NaN (for matrices of doubles)<commit_after>#ifndef STAN__MATH__MATRIX__EXP_HPP #define STAN__MATH__MATRIX__EXP_HPP #include <stan/math/matrix/Eigen.hpp> namespace stan { namespace math { /** * Return the element-wise exponentiation of the matrix or vector. * * @param m The matrix or vector. * @return ret(i,j) = exp(m(i,j)) */ template<typename T, int Rows, int Cols> inline Eigen::Matrix<T,Rows,Cols> exp(Eigen::Matrix<T,Rows,Cols> mat) { T * mat_ = mat.data(); for (int i = 0, size_ = mat.size(); i < size_; i++) mat_[i] = std::exp(mat_[i]); return mat; } } } #endif <|endoftext|>
<commit_before>#ifndef STAN__MATH__MATRIX__EXP_HPP #define STAN__MATH__MATRIX__EXP_HPP #include <stan/math/matrix/Eigen.hpp> namespace stan { namespace math { /** * Return the element-wise exponentiation of the matrix or vector. * * @param m The matrix or vector. * @return ret(i,j) = exp(m(i,j)) */ template<typename T, int Rows, int Cols> inline Eigen::Matrix<T,Rows,Cols> exp(Eigen::Matrix<T,Rows,Cols> mat) { for (T * it = mat.data(), * end_ = it + mat.size(); it != end_; it++) *it = exp(*it); return mat; } } } #endif <commit_msg>stan::math::exp(Eigen::Matrix) will have an specialized version for double that will check for nan inputs<commit_after>#ifndef STAN__MATH__MATRIX__EXP_HPP #define STAN__MATH__MATRIX__EXP_HPP #include <stan/math/matrix/Eigen.hpp> #include <boost/math/special_functions/fpclassify.hpp> namespace stan { namespace math { /** * Return the element-wise exponentiation of the matrix or vector. * * @param m The matrix or vector. * @return ret(i,j) = exp(m(i,j)) */ template<typename T, int Rows, int Cols> inline Eigen::Matrix<T,Rows,Cols> exp(const Eigen::Matrix<T,Rows,Cols> & m) { return m.array().exp().matrix(); } template<int Rows, int Cols> inline Eigen::Matrix<double,Rows,Cols> exp(const Eigen::Matrix<double,Rows,Cols> & m) { for (const double * it = m.data(), * end_ = it + m.size(); it != end_; it++) if (boost::math::isnan(*it)) { Eigen::Matrix<double,Rows,Cols> mat = m; for (double * it = mat.data(), * end_ = it + mat.size(); it != end_; it++) *it = std::exp(*it); return mat; } return m.array().exp().matrix(); } } } #endif <|endoftext|>
<commit_before>#pragma once #include "common/Emotemap.hpp" #include "messages/Image.hpp" #include "messages/Link.hpp" #include "messages/MessageColor.hpp" #include "singletons/Fonts.hpp" #include <QRect> #include <QString> #include <QTime> #include <boost/noncopyable.hpp> #include <cstdint> #include <memory> namespace chatterino { class Channel; struct EmoteData; struct MessageLayoutContainer; class MessageElement : boost::noncopyable { public: enum Flags : uint32_t { None = 0, Misc = (1 << 0), Text = (1 << 1), Username = (1 << 2), Timestamp = (1 << 3), TwitchEmoteImage = (1 << 4), TwitchEmoteText = (1 << 5), TwitchEmote = TwitchEmoteImage | TwitchEmoteText, BttvEmoteImage = (1 << 6), BttvEmoteText = (1 << 7), BttvEmote = BttvEmoteImage | BttvEmoteText, FfzEmoteImage = (1 << 10), FfzEmoteText = (1 << 11), FfzEmote = FfzEmoteImage | FfzEmoteText, EmoteImages = TwitchEmoteImage | BttvEmoteImage | FfzEmoteImage, BitsStatic = (1 << 12), BitsAnimated = (1 << 13), // Slot 1: Twitch // - Staff badge // - Admin badge // - Global Moderator badge BadgeGlobalAuthority = (1 << 14), // Slot 2: Twitch // - Moderator badge // - Broadcaster badge BadgeChannelAuthority = (1 << 15), // Slot 3: Twitch // - Subscription badges BadgeSubscription = (1 << 16), // Slot 4: Twitch // - Turbo badge // - Prime badge // - Bit badges // - Game badges BadgeVanity = (1 << 17), // Slot 5: Chatterino // - Chatterino developer badge // - Chatterino donator badge // - Chatterino top donator badge BadgeChatterino = (1 << 18), // Rest of slots: ffz custom badge? bttv custom badge? mywaifu (puke) custom badge? Badges = BadgeGlobalAuthority | BadgeChannelAuthority | BadgeSubscription | BadgeVanity | BadgeChatterino, ChannelName = (1 << 19), BitsAmount = (1 << 20), ModeratorTools = (1 << 21), EmojiImage = (1 << 23), EmojiText = (1 << 24), EmojiAll = EmojiImage | EmojiText, AlwaysShow = (1 << 25), // used in the ChannelView class to make the collapse buttons visible if needed Collapsed = (1 << 26), Default = Timestamp | Badges | Username | BitsStatic | FfzEmoteImage | BttvEmoteImage | TwitchEmoteImage | BitsAmount | Text | AlwaysShow, }; enum UpdateFlags : char { Update_Text, Update_Emotes, Update_Images, Update_All = Update_Text | Update_Emotes | Update_Images }; virtual ~MessageElement(); MessageElement *setLink(const Link &link); MessageElement *setTooltip(const QString &tooltip); MessageElement *setTrailingSpace(bool value); const QString &getTooltip() const; const Link &getLink() const; bool hasTrailingSpace() const; Flags getFlags() const; virtual void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) = 0; protected: MessageElement(Flags flags); bool trailingSpace = true; private: Link link; QString tooltip; Flags flags; }; // contains a simple image class ImageElement : public MessageElement { Image *image; public: ImageElement(Image *image, MessageElement::Flags flags); void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; }; // contains a text, it will split it into words class TextElement : public MessageElement { MessageColor color; FontStyle style; struct Word { QString text; int width = -1; }; std::vector<Word> words; public: TextElement(const QString &text, MessageElement::Flags flags, const MessageColor &color = MessageColor::Text, FontStyle style = FontStyle::ChatMedium); ~TextElement() override = default; void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; }; // contains emote data and will pick the emote based on : // a) are images for the emote type enabled // b) which size it wants class EmoteElement : public MessageElement { std::unique_ptr<TextElement> textElement; public: EmoteElement(const EmoteData &data, MessageElement::Flags flags); ~EmoteElement() override = default; void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; const EmoteData data; }; // contains a text, formated depending on the preferences class TimestampElement : public MessageElement { QTime time; std::unique_ptr<TextElement> element; QString format; public: TimestampElement(QTime time = QTime::currentTime()); ~TimestampElement() override = default; void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; TextElement *formatTime(const QTime &time); }; // adds all the custom moderation buttons, adds a variable amount of items depending on settings // fourtf: implement class TwitchModerationElement : public MessageElement { public: TwitchModerationElement(); void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; }; } // namespace chatterino <commit_msg>Changed some stuff<commit_after>#pragma once #include "common/Emotemap.hpp" #include "messages/Image.hpp" #include "messages/Link.hpp" #include "messages/MessageColor.hpp" #include "singletons/Fonts.hpp" #include <QRect> #include <QString> #include <QTime> #include <boost/noncopyable.hpp> #include <cstdint> #include <memory> namespace chatterino { class Channel; struct EmoteData; struct MessageLayoutContainer; class MessageElement : boost::noncopyable { public: enum Flags : uint32_t { None = 0, Misc = (1 << 0), Text = (1 << 1), Username = (1 << 2), Timestamp = (1 << 3), TwitchEmoteImage = (1 << 4), TwitchEmoteText = (1 << 5), TwitchEmote = TwitchEmoteImage | TwitchEmoteText, BttvEmoteImage = (1 << 6), BttvEmoteText = (1 << 7), BttvEmote = BttvEmoteImage | BttvEmoteText, FfzEmoteImage = (1 << 10), FfzEmoteText = (1 << 11), FfzEmote = FfzEmoteImage | FfzEmoteText, EmoteImages = TwitchEmoteImage | BttvEmoteImage | FfzEmoteImage, BitsStatic = (1 << 12), BitsAnimated = (1 << 13), // Slot 1: Twitch // - Staff badge // - Admin badge // - Global Moderator badge BadgeGlobalAuthority = (1 << 14), // Slot 2: Twitch // - Moderator badge // - Broadcaster badge BadgeChannelAuthority = (1 << 15), // Slot 3: Twitch // - Subscription badges BadgeSubscription = (1 << 16), // Slot 4: Twitch // - Turbo badge // - Prime badge // - Bit badges // - Game badges BadgeVanity = (1 << 17), // Slot 5: Chatterino // - Chatterino developer badge // - Chatterino donator badge // - Chatterino top donator badge BadgeChatterino = (1 << 18), // Rest of slots: ffz custom badge? bttv custom badge? mywaifu (puke) custom badge? Badges = BadgeGlobalAuthority | BadgeChannelAuthority | BadgeSubscription | BadgeVanity | BadgeChatterino, ChannelName = (1 << 19), BitsAmount = (1 << 20), ModeratorTools = (1 << 21), EmojiImage = (1 << 23), EmojiText = (1 << 24), EmojiAll = EmojiImage | EmojiText, AlwaysShow = (1 << 25), // used in the ChannelView class to make the collapse buttons visible if needed Collapsed = (1 << 26), Default = Timestamp | Badges | Username | BitsStatic | FfzEmoteImage | BttvEmoteImage | TwitchEmoteImage | BitsAmount | Text | AlwaysShow, }; enum UpdateFlags : char { Update_Text, Update_Emotes, Update_Images, Update_All = Update_Text | Update_Emotes | Update_Images }; virtual ~MessageElement(); MessageElement *setLink(const Link &link); MessageElement *setTooltip(const QString &tooltip); MessageElement *setTrailingSpace(bool value); const QString &getTooltip() const; const Link &getLink() const; bool hasTrailingSpace() const; Flags getFlags() const; virtual void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) = 0; protected: MessageElement(Flags flags); bool trailingSpace = true; private: Link link; QString tooltip; Flags flags; }; // contains a simple image class ImageElement : public MessageElement { Image *image; public: ImageElement(Image *image, MessageElement::Flags flags); void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; }; // contains a text, it will split it into words class TextElement : public MessageElement { MessageColor color; FontStyle style; struct Word { QString text; int width = -1; }; std::vector<Word> words; public: TextElement(const QString &text, MessageElement::Flags flags, const MessageColor &color = MessageColor::Text, FontStyle style = FontStyle::ChatMedium); ~TextElement() override = default; void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; }; // contains emote data and will pick the emote based on : // a) are images for the emote type enabled // b) which size it wants class EmoteElement : public MessageElement { std::unique_ptr<TextElement> textElement; public: EmoteElement(const EmoteData &data, MessageElement::Flags flags); ~EmoteElement() override = default; void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; const EmoteData data; }; // contains a text, formated depending on the preferences class TimestampElement : public MessageElement { public: TimestampElement(QTime time_ = QTime::currentTime()); ~TimestampElement() override = default; void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; TextElement *formatTime(const QTime &time_); private: QTime time_; std::unique_ptr<TextElement> element_; QString format_; }; // adds all the custom moderation buttons, adds a variable amount of items depending on settings // fourtf: implement class TwitchModerationElement : public MessageElement { public: TwitchModerationElement(); void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; }; } // namespace chatterino <|endoftext|>