text
stringlengths
54
60.6k
<commit_before>#include "HelloWorldScene.h" #include "SimpleAudioEngine.h" #include "AnalyticX.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include <jni.h> #include "platform/android/jni/JniHelper.h" #include <android/log.h> #endif using namespace cocos2d; using namespace CocosDenshion; CCScene* HelloWorld::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::node(); // 'layer' is an autorelease object HelloWorld *layer = HelloWorld::node(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object CCMenuItemImage *pCloseItem = CCMenuItemImage::itemWithNormalImage( "CloseNormal.png", "CloseSelected.png", this, menu_selector(HelloWorld::menuCloseCallback) ); pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) ); // create menu, it's an autorelease object CCMenu* pMenu = CCMenu::menuWithItems(pCloseItem, NULL); pMenu->setPosition( CCPointZero ); this->addChild(pMenu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label CCLabelTTF* pLabel = CCLabelTTF::labelWithString("Hello World", "Thonburi", 34); // ask director the window size CCSize size = CCDirector::sharedDirector()->getWinSize(); // position the label on the center of the screen pLabel->setPosition( ccp(size.width / 2, size.height - 20) ); // add the label as a child to this layer this->addChild(pLabel, 1); // add "HelloWorld" splash screen" CCSprite* pSprite = CCSprite::spriteWithFile("HelloWorld.png"); // position the sprite on the center of the screen pSprite->setPosition( ccp(size.width/2, size.height/2) ); // add the sprite as a child to this layer this->addChild(pSprite, 0); AnalyticX::flurrySetAppVersion("v_1_97"); cocos2d::CCLog("--->>>get flurry version = %s", AnalyticX::flurryGetFlurryAgentVersion()); AnalyticX::flurrySetDebugLogEnabled(false); AnalyticX::flurrySetSessionContinueSeconds(143); AnalyticX::flurrySetSecureTransportEnabled(false); AnalyticX::flurrySetUserID("fake_user_id"); AnalyticX::flurrySetAge(34); AnalyticX::flurrySetGender("f"); AnalyticX::flurrySetReportLocation(false); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) AnalyticX::flurryStartSession("QFNXVFK2XX4P56GS76EA"); #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) AnalyticX::flurryStartSession("W7IBK43RJCHPT4IRP4HI"); #endif AnalyticX::flurryLogEvent(" #2 log event test..."); AnalyticX::flurryLogEventTimed(" log event timed test...", false); CCDictionary *testDict = new CCDictionary(); CCString *testCCString; testCCString = CCString::stringWithCString("obj 0"); testDict->setObject(testCCString, "key 0"); testCCString = CCString::stringWithCString("obj 1"); testDict->setObject(testCCString, "key 1"); AnalyticX::flurryLogEventWithParameters(" - test flurryLogEventWithParameters", testDict); AnalyticX::flurryLogEventWithParametersTimed("test flurryLogEventWithParameters + timed", testDict, true); AnalyticX::flurryEndTimedEventWithParameters("test end event...", NULL); AnalyticX::flurryLogPageView(); //AnalyticX::flurryEndSession(); return true; } void HelloWorld::menuCloseCallback(CCObject* pSender) { CCDirector::sharedDirector()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif } <commit_msg>minor fix<commit_after>#include "HelloWorldScene.h" #include "SimpleAudioEngine.h" #include "AnalyticX.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include <jni.h> #include "platform/android/jni/JniHelper.h" #include <android/log.h> #endif using namespace cocos2d; using namespace CocosDenshion; CCScene* HelloWorld::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::node(); // 'layer' is an autorelease object HelloWorld *layer = HelloWorld::node(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object CCMenuItemImage *pCloseItem = CCMenuItemImage::itemWithNormalImage( "CloseNormal.png", "CloseSelected.png", this, menu_selector(HelloWorld::menuCloseCallback) ); pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) ); // create menu, it's an autorelease object CCMenu* pMenu = CCMenu::menuWithItems(pCloseItem, NULL); pMenu->setPosition( CCPointZero ); this->addChild(pMenu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label CCLabelTTF* pLabel = CCLabelTTF::labelWithString("Hello World", "Thonburi", 34); // ask director the window size CCSize size = CCDirector::sharedDirector()->getWinSize(); // position the label on the center of the screen pLabel->setPosition( ccp(size.width / 2, size.height - 20) ); // add the label as a child to this layer this->addChild(pLabel, 1); // add "HelloWorld" splash screen" CCSprite* pSprite = CCSprite::spriteWithFile("HelloWorld.png"); // position the sprite on the center of the screen pSprite->setPosition( ccp(size.width/2, size.height/2) ); // add the sprite as a child to this layer this->addChild(pSprite, 0); AnalyticX::flurrySetAppVersion("v_1_97"); cocos2d::CCLog("--->>>get flurry version = %s", AnalyticX::flurryGetFlurryAgentVersion()); AnalyticX::flurrySetDebugLogEnabled(false); AnalyticX::flurrySetSessionContinueSeconds(143); AnalyticX::flurrySetSecureTransportEnabled(false); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) AnalyticX::flurryStartSession("QFNXVFK2XX4P56GS76EA"); #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) AnalyticX::flurryStartSession("W7IBK43RJCHPT4IRP4HI"); #endif AnalyticX::flurrySetUserID("fake_user_id"); AnalyticX::flurrySetAge(34); AnalyticX::flurrySetGender("f"); AnalyticX::flurrySetReportLocation(false); AnalyticX::flurryLogEvent("event_3"); AnalyticX::flurryLogEventTimed(" log event timed test...", false); CCDictionary *testDict = new CCDictionary(); CCString *testCCString; testCCString = CCString::stringWithCString("obj 0"); testDict->setObject(testCCString, "key 0"); testCCString = CCString::stringWithCString("obj 1"); testDict->setObject(testCCString, "key 1"); AnalyticX::flurryLogEventWithParameters("event_5_with_params_no_timed", testDict); AnalyticX::flurryLogEventWithParametersTimed("test flurryLogEventWithParameters + timed", testDict, true); AnalyticX::flurryEndTimedEventWithParameters("test end event...", NULL); AnalyticX::flurryLogPageView(); //AnalyticX::flurryEndSession(); return true; } void HelloWorld::menuCloseCallback(CCObject* pSender) { CCDirector::sharedDirector()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif } <|endoftext|>
<commit_before>void plotField(Int_t iField = 0) { // // iField = 0 2 kG solenoid // 1 4 kG solenoid // 2 5 kG solenoid // // load necessary libraries gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libminicern"); gSystem->Load("$(ROOTSYS)/lib/libPhysics"); gSystem->Load("$(ROOTSYS)/lib/libEG"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTEER"); // // // create field map AliMagFMaps* field = new AliMagFMaps( "Maps","Maps", 2, 1., 10., iField); // field-SetL3ConstField(1); // // get parameters Float_t xMin, xMax, yMin, yMax, zMin, zMax; Float_t dX, dY, dZ; xMin = -350.; xMax = 350.; dX = (field->FieldMap(0))->DelX(); yMin = -350.; yMax = 350.; dY = (field->FieldMap(0))->DelY(); zMin = 250.; zMax = 1450.; dZ = (field->FieldMap(0))->DelZ(); Int_t nx = (xMax-xMin)/dX; Int_t ny = (yMax-yMin)/dY; Int_t nz = (zMax-zMin)/dZ; // // create histogram TH2F* hMap = new TH2F("hMap", "Field Map y-z", nz, zMin, zMax, ny, yMin, yMax); TH2F* hMap1 = new TH2F("hMap1", "Field Map y-z", nz, zMin, zMax, ny, yMin, yMax); TH1F* hZ = new TH1F("hZ", "Field along Z", nz, zMin, zMax); TH2F* hVec = new TH2F("hVec", "Field Map y-z", nz, zMin, zMax, ny, yMin, yMax); TH2F* hCir = new TH2F("hCir", "Field Map y-z", nz, zMin, zMax, ny, yMin, yMax); Float_t bMax = 0.; for (Int_t i = 0; i < nz; i++) { for (Int_t j = 0; j < ny; j++) { Float_t x[3]; Float_t b[3]; x[2] = zMin + i * dZ; x[1] = yMin + j * dY; x[0] = 0.; field->Field(x, b); Float_t bb = TMath::Sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]); if (bb > bMax) bMax = bb; hMap->Fill(x[2], x[1], bb); } } for (Int_t i = 0; i < nz; i++) { for (Int_t j = 0; j < ny; j++) { x[2] = zMin + i * dZ; x[1] = yMin + j * dY; x[0] = 0.; field->Field(x, b); Float_t bb = TMath::Sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]); Float_t db = (bMax-bb)/bMax*100.; hMap1->Fill(x[2], x[1], db); } } for (Int_t i = 0; i < nz; i++) { x[2] = zMin + i * dZ +dZ/2.; x[1] = 0.; x[0] = 0.; field->Field(x, b); Float_t bb = TMath::Sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]); hZ->Fill(x[2], bb); } TCanvas *c1 = new TCanvas("c1","Canvas 1",400,10,600,700); hMap->Draw(); TCanvas *c2 = new TCanvas("c2","Canvas 2",400,10,600,700); hZ->Draw(); TCanvas *c3 = new TCanvas("c3","Canvas 3",400,10,600,700); hVec->Draw(); Float_t scale1 = 0.9*TMath::Sqrt(dZ*dZ+dY*dY)/bMax/2.; Float_t scale2 = 0.005/bMax; TArrow* arrow; for (Int_t i = 0; i < nz; i++) { for (Int_t j = 0; j < nx; j++) { x[2] = zMin + i * dZ + dZ/2.; x[0] = xMin + j * dX + dX/2.; x[1] = 0.; field->Field(x, b); Float_t bb = TMath::Sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]); b[2] *= scale1; b[0] *= scale1; Float_t width = 0.005+scale2*b[1]; arrow = new TArrow(x[2], x[0], x[2]+b[2], x[0]+b[0], width,"|>"); arrow->SetFillColor(1); arrow->SetFillStyle(1001); arrow->Draw(); c3->Modified(); c3->cd(); } } TCanvas *c4 = new TCanvas("c4","Canvas 4",400,10,600,700); hCir->Draw(); for (Int_t i = 0; i < nz; i++) { for (Int_t j = 0; j < ny; j++) { x[2] = zMin + i * dZ + dZ/2.; x[1] = yMin + j * dY + dY/2.; x[0] = 0.; field->Field(x, b); Float_t bb = TMath::Sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]); TEllipse *ellipse; ellipse= new TEllipse(x[2], x[1], b[1]*scale1/4., b[1]*scale1/4.,0,360,0); ellipse->Draw(); c4->Modified(); c4->cd(); } } } <commit_msg>libminicern is not needed anymore<commit_after>void plotField(Int_t iField = 0) { // // iField = 0 2 kG solenoid // 1 4 kG solenoid // 2 5 kG solenoid // // load necessary libraries // gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libminicern"); gSystem->Load("$(ROOTSYS)/lib/libPhysics"); gSystem->Load("$(ROOTSYS)/lib/libEG"); gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTEER"); // // // create field map AliMagFMaps* field = new AliMagFMaps( "Maps","Maps", 2, 1., 10., iField); // field-SetL3ConstField(1); // // get parameters Float_t xMin, xMax, yMin, yMax, zMin, zMax; Float_t dX, dY, dZ; xMin = -350.; xMax = 350.; dX = (field->FieldMap(0))->DelX(); yMin = -350.; yMax = 350.; dY = (field->FieldMap(0))->DelY(); zMin = 250.; zMax = 1450.; dZ = (field->FieldMap(0))->DelZ(); Int_t nx = (xMax-xMin)/dX; Int_t ny = (yMax-yMin)/dY; Int_t nz = (zMax-zMin)/dZ; // // create histogram TH2F* hMap = new TH2F("hMap", "Field Map y-z", nz, zMin, zMax, ny, yMin, yMax); TH2F* hMap1 = new TH2F("hMap1", "Field Map y-z", nz, zMin, zMax, ny, yMin, yMax); TH1F* hZ = new TH1F("hZ", "Field along Z", nz, zMin, zMax); TH2F* hVec = new TH2F("hVec", "Field Map y-z", nz, zMin, zMax, ny, yMin, yMax); TH2F* hCir = new TH2F("hCir", "Field Map y-z", nz, zMin, zMax, ny, yMin, yMax); Float_t bMax = 0.; for (Int_t i = 0; i < nz; i++) { for (Int_t j = 0; j < ny; j++) { Float_t x[3]; Float_t b[3]; x[2] = zMin + i * dZ; x[1] = yMin + j * dY; x[0] = 0.; field->Field(x, b); Float_t bb = TMath::Sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]); if (bb > bMax) bMax = bb; hMap->Fill(x[2], x[1], bb); } } for (Int_t i = 0; i < nz; i++) { for (Int_t j = 0; j < ny; j++) { x[2] = zMin + i * dZ; x[1] = yMin + j * dY; x[0] = 0.; field->Field(x, b); Float_t bb = TMath::Sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]); Float_t db = (bMax-bb)/bMax*100.; hMap1->Fill(x[2], x[1], db); } } for (Int_t i = 0; i < nz; i++) { x[2] = zMin + i * dZ +dZ/2.; x[1] = 0.; x[0] = 0.; field->Field(x, b); Float_t bb = TMath::Sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]); hZ->Fill(x[2], bb); } TCanvas *c1 = new TCanvas("c1","Canvas 1",400,10,600,700); hMap->Draw(); TCanvas *c2 = new TCanvas("c2","Canvas 2",400,10,600,700); hZ->Draw(); TCanvas *c3 = new TCanvas("c3","Canvas 3",400,10,600,700); hVec->Draw(); Float_t scale1 = 0.9*TMath::Sqrt(dZ*dZ+dY*dY)/bMax/2.; Float_t scale2 = 0.005/bMax; TArrow* arrow; for (Int_t i = 0; i < nz; i++) { for (Int_t j = 0; j < nx; j++) { x[2] = zMin + i * dZ + dZ/2.; x[0] = xMin + j * dX + dX/2.; x[1] = 0.; field->Field(x, b); Float_t bb = TMath::Sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]); b[2] *= scale1; b[0] *= scale1; Float_t width = 0.005+scale2*b[1]; arrow = new TArrow(x[2], x[0], x[2]+b[2], x[0]+b[0], width,"|>"); arrow->SetFillColor(1); arrow->SetFillStyle(1001); arrow->Draw(); c3->Modified(); c3->cd(); } } TCanvas *c4 = new TCanvas("c4","Canvas 4",400,10,600,700); hCir->Draw(); for (Int_t i = 0; i < nz; i++) { for (Int_t j = 0; j < ny; j++) { x[2] = zMin + i * dZ + dZ/2.; x[1] = yMin + j * dY + dY/2.; x[0] = 0.; field->Field(x, b); Float_t bb = TMath::Sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]); TEllipse *ellipse; ellipse= new TEllipse(x[2], x[1], b[1]*scale1/4., b[1]*scale1/4.,0,360,0); ellipse->Draw(); c4->Modified(); c4->cd(); } } } <|endoftext|>
<commit_before>/* * * Copyright (C) 2000 Frans Kaashoek (kaashoek@lcs.mit.edu) * Copyright (C) 2001 Frans Kaashoek (kaashoek@lcs.mit.edu) and * Frank Dabek (fdabek@lcs.mit.edu). * Copyright (C) 2001 Frans Kaashoek (kaashoek@lcs.mit.edu), * Frank Dabek (fdabek@lcs.mit.edu) and * Emil Sit (sit@lcs.mit.edu). * * 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. * */ // Chord's RPC manager is designed to perform flow control on all // Chord RPCs. It maintains a cache of hosts (i.e. IP addresses) // that it has connected to and maintains statistics about latency // and such to those hosts. It uses these statistics to calculate // optimal window sizes and delays. // #define __J__ 1 #include <crypt.h> #include <chord_prot.h> #include <misc_utils.h> #include "comm.h" #include <location.h> #include "modlogger.h" #include "coord.h" chord_rpc_style_t chord_rpc_style (CHORD_RPC_STP); ihash<str, rpcstats, &rpcstats::key, &rpcstats::h_link> rpc_stats_tab; u_int64_t rpc_stats_lastclear (getusec ()); static inline rpcstats * getstats (int progno, int procno) { str key = strbuf ("%d:%d", progno, procno); rpcstats *stats = rpc_stats_tab[key]; if (!stats) { stats = New rpcstats (key); rpc_stats_tab.insert (stats); } return stats; } void track_call (const rpc_program &prog, int procno, size_t b) { rpcstats *stats = getstats (prog.progno, procno); stats->call (b); } void track_rexmit (const rpc_program &prog, int procno, size_t b) { rpcstats *stats = getstats (prog.progno, procno); stats->rexmit (b); } void track_rexmit (int progno, int procno, size_t b) { rpcstats *stats = getstats (progno, procno); stats->rexmit (b); } void track_reply (const rpc_program &prog, int procno, size_t b) { rpcstats *stats = getstats (prog.progno, procno); stats->reply (b); } // ----------------------------------------------------- rpc_state::rpc_state (ptr<location> from, ref<location> l, aclnt_cb c, cbtmo_t _cb_tmo, long s, int p, void *out) : loc (l), from (from), cb (c), progno (p), seqno (s), b (NULL), rexmits (0), cb_tmo (_cb_tmo), out (out) { ID = l->id (); in_window = true; }; // ----------------------------------------------------- hostinfo::hostinfo (const net_address &r) : host (r.hostname), nrpc (0), maxdelay (0), a_lat (0.0), a_var (0.0), fd (-2), orpc (0) { } // ----------------------------------------------------- rpc_manager::rpc_manager (ptr<u_int32_t> _nrcv) : a_lat (0.0), a_var (0.0), c_err (0.0), c_var (0.0), nrpc (0), nrpcfailed (0), nsent (0), npending (0), nrcv (_nrcv) { warn << "CREATED RPC MANAGER\n"; int dgram_fd = inetsocket (SOCK_DGRAM); if (dgram_fd < 0) fatal << "Failed to allocate dgram socket\n"; dgram_xprt = axprt_dgram::alloc (dgram_fd, sizeof(sockaddr), 230000); if (!dgram_xprt) fatal << "Failed to allocate dgram xprt\n"; next_xid = &random_getword; } float rpc_manager::get_a_lat (ptr<location> l) { hostinfo *h = lookup_host (l->address ()); return h->a_lat; } float rpc_manager::get_a_var (ptr<location> l) { hostinfo *h = lookup_host (l->address ()); return h->a_var; } void rpc_manager::remove_host (hostinfo *h) { } hostinfo * rpc_manager::lookup_host (const net_address &r) { str key = strbuf () << r.hostname << ":" << r.port << "\n"; hostinfo *h = hosts[key]; if (!h) { if (hosts.size () > max_host_cache) { hostinfo *o = hostlru.first; hostlru.remove (o); hosts.remove (o); remove_host (o); delete (o); } h = New hostinfo (r); h->key = key; hostlru.insert_tail (h); hosts.insert (h); } else { // record recent access hostlru.remove (h); hostlru.insert_tail (h); } assert (h); return h; } long rpc_manager::doRPC (ptr<location> from, ptr<location> l, const rpc_program &prog, int procno, ptr<void> in, void *out, aclnt_cb cb, cbtmo_t cb_tmo, long fake_seqno /* = 0 */) { ref<aclnt> c = aclnt::alloc (dgram_xprt, prog, (sockaddr *)&(l->saddr ())); // Make sure that there is an entry in the table for this guy. (void) lookup_host (l->address ()); u_int64_t sent = getusec (); c->call (procno, in, out, wrap (this, &rpc_manager::doRPCcb, cb, l, sent)); return 0; } long rpc_manager::doRPC_dead (ptr<location> l, const rpc_program &prog, int procno, ptr<void> in, void *out, aclnt_cb cb, long fake_seqno /* = 0 */) { return doRPC (NULL, l, prog, procno, in, out, cb, NULL, fake_seqno); } void rpc_manager::doRPCcb (aclnt_cb realcb, ptr<location> l, u_int64_t sent, clnt_stat err) { if (err) { nrpcfailed++; l->set_alive (false); } else { nrpc++; // Only update latency on successful RPC. // This probably includes time needed for rexmits. u_int64_t now = getusec (); // prevent overflow, caused by time reversal if (now >= sent) { u_int64_t lat = now - sent; update_latency (NULL, l, lat); } else { warn << "*** Ignoring timewarp: sent " << sent << " > now " << now << "\n"; } } (realcb) (err); } // ----------------------------------------------------- long tcp_manager::doRPC (ptr<location> from, ptr<location> l, const rpc_program &prog, int procno, ptr<void> in, void *out, aclnt_cb cb, cbtmo_t cb_tmo, long fake_seqno /* = 0 */) { // hack to avoid limit on wrap()'s number of arguments RPC_delay_args *args = New RPC_delay_args (from, l, prog, procno, in, out, cb, NULL); if (chord_rpc_style == CHORD_RPC_SFSBT) { tcpconnect (l->saddr ().sin_addr, ntohs (l->saddr ().sin_port), wrap (this, &tcp_manager::doRPC_tcp_connect_cb, args)); } else { hostinfo *hi = lookup_host (l->address ()); if (hi->fd == -2) { //no connect initiated // weird: tcpconnect wants the address in NBO, and port in HBO hi->fd = -1; // signal pending connect tcpconnect (l->saddr ().sin_addr, ntohs (l->saddr ().sin_port), wrap (this, &tcp_manager::doRPC_tcp_connect_cb, args)); } else if (hi->fd == -1) { //connect pending, add to waiters hi->connect_waiters.push_back (args); } else if (hi->fd > 0) { //already connected send_RPC (args); } } return 0; } long tcp_manager::doRPC_dead (ptr<location> l, const rpc_program &prog, int procno, ptr<void> in, void *out, aclnt_cb cb, long fake_seqno /* = 0 */) { return doRPC (NULL, l, prog, procno, in, out, cb, NULL, fake_seqno); } void tcp_manager::remove_host (hostinfo *h) { // unnecessary SO_LINGER already set // tcp_abort (h->fd); if (chord_rpc_style == CHORD_RPC_SFST) { h->fd = -2; h->xp = NULL; while (h->connect_waiters.size ()) { RPC_delay_args *a = h->connect_waiters.pop_front (); a->cb (RPC_CANTSEND); delete a; } } } void tcp_manager::send_RPC (RPC_delay_args *args) { hostinfo *hi = lookup_host (args->l->address ()); if (!hi->xp) { delaycb (0, 0, wrap (this, &tcp_manager::send_RPC_ateofcb, args)); } else if (hi->xp->ateof()) { hostlru.remove (hi); hostlru.insert_tail (hi); args->l->set_alive (false); remove_host (hi); delaycb (0, 0, wrap (this, &tcp_manager::send_RPC_ateofcb, args)); } else { hi->orpc++; args->now = getusec (); ptr<aclnt> c = aclnt::alloc (hi->xp, args->prog); c->call (args->procno, args->in, args->out, wrap (this, &tcp_manager::doRPC_tcp_cleanup, c, args)); } } void tcp_manager::send_RPC_ateofcb (RPC_delay_args *args) { (args->cb) (RPC_CANTSEND); delete args; } void tcp_manager::doRPC_tcp_connect_cb (RPC_delay_args *args, int fd) { hostinfo *hi = lookup_host (args->l->address ()); if (fd < 0) { warn << "locationtable: connect failed: " << strerror (errno) << "\n"; (args->cb) (RPC_CANTSEND); args->l->set_alive (false); remove_host (hi); delete args; } else { struct linger li; li.l_onoff = 1; li.l_linger = 0; setsockopt (fd, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof (li)); tcp_nodelay (fd); make_async(fd); if (chord_rpc_style == CHORD_RPC_SFST) { hi->fd = fd; hi->xp = axprt_stream::alloc (fd); assert (hi->xp); send_RPC (args); while (hi->connect_waiters.size ()) send_RPC (hi->connect_waiters.pop_front ()); } else { ptr<axprt_stream> xp = axprt_stream::alloc (fd); assert (xp); ptr<aclnt> c = aclnt::alloc (xp, args->prog); assert (c); c->call (args->procno, args->in, args->out, wrap (this, &tcp_manager::doRPC_tcp_cleanup, c, args)); } } } void tcp_manager::doRPC_tcp_cleanup (ptr<aclnt> c, RPC_delay_args *args, clnt_stat err) { hostinfo *hi = lookup_host (args->l->address ()); u_int64_t diff; if (args->from && args->from->address ().hostname == args->l->address ().hostname) diff = 5000; else { u_int64_t now = getusec (); diff = now - args->now; if (diff > 5000000) warn << "long tcp latency to " << args->l->address ().hostname << ": " << diff << ", orpc " << hi->orpc << "\n"; } hi->orpc--; if (diff < 5000000) update_latency (NULL, args->l, diff); (*args->cb)(err); delete args; } void tcp_manager::stats () { char buf[1024]; rpc_manager::stats (); for (hostinfo *h = hosts.first (); h ; h = hosts.next (h)) { warnx << " host " << h->host << ": rpcs " << h->nrpc << ", orpcs " << h->orpc; sprintf (buf, ", lat %.1f, var %.1f\n", h->a_lat/1000, h->a_var/1000); warnx << buf; } } <commit_msg>Initialize c_err_rel, found by valgrind.<commit_after>/* * * Copyright (C) 2000 Frans Kaashoek (kaashoek@lcs.mit.edu) * Copyright (C) 2001 Frans Kaashoek (kaashoek@lcs.mit.edu) and * Frank Dabek (fdabek@lcs.mit.edu). * Copyright (C) 2001 Frans Kaashoek (kaashoek@lcs.mit.edu), * Frank Dabek (fdabek@lcs.mit.edu) and * Emil Sit (sit@lcs.mit.edu). * * 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. * */ // Chord's RPC manager is designed to perform flow control on all // Chord RPCs. It maintains a cache of hosts (i.e. IP addresses) // that it has connected to and maintains statistics about latency // and such to those hosts. It uses these statistics to calculate // optimal window sizes and delays. // #define __J__ 1 #include <crypt.h> #include <chord_prot.h> #include <misc_utils.h> #include "comm.h" #include <location.h> #include "modlogger.h" #include "coord.h" chord_rpc_style_t chord_rpc_style (CHORD_RPC_STP); ihash<str, rpcstats, &rpcstats::key, &rpcstats::h_link> rpc_stats_tab; u_int64_t rpc_stats_lastclear (getusec ()); static inline rpcstats * getstats (int progno, int procno) { str key = strbuf ("%d:%d", progno, procno); rpcstats *stats = rpc_stats_tab[key]; if (!stats) { stats = New rpcstats (key); rpc_stats_tab.insert (stats); } return stats; } void track_call (const rpc_program &prog, int procno, size_t b) { rpcstats *stats = getstats (prog.progno, procno); stats->call (b); } void track_rexmit (const rpc_program &prog, int procno, size_t b) { rpcstats *stats = getstats (prog.progno, procno); stats->rexmit (b); } void track_rexmit (int progno, int procno, size_t b) { rpcstats *stats = getstats (progno, procno); stats->rexmit (b); } void track_reply (const rpc_program &prog, int procno, size_t b) { rpcstats *stats = getstats (prog.progno, procno); stats->reply (b); } // ----------------------------------------------------- rpc_state::rpc_state (ptr<location> from, ref<location> l, aclnt_cb c, cbtmo_t _cb_tmo, long s, int p, void *out) : loc (l), from (from), cb (c), progno (p), seqno (s), b (NULL), rexmits (0), cb_tmo (_cb_tmo), out (out) { ID = l->id (); in_window = true; }; // ----------------------------------------------------- hostinfo::hostinfo (const net_address &r) : host (r.hostname), nrpc (0), maxdelay (0), a_lat (0.0), a_var (0.0), fd (-2), orpc (0) { } // ----------------------------------------------------- rpc_manager::rpc_manager (ptr<u_int32_t> _nrcv) : a_lat (0.0), a_var (0.0), c_err (0.0), c_err_rel (0.0), c_var (0.0), nrpc (0), nrpcfailed (0), nsent (0), npending (0), nrcv (_nrcv) { warn << "CREATED RPC MANAGER\n"; int dgram_fd = inetsocket (SOCK_DGRAM); if (dgram_fd < 0) fatal << "Failed to allocate dgram socket\n"; dgram_xprt = axprt_dgram::alloc (dgram_fd, sizeof(sockaddr), 230000); if (!dgram_xprt) fatal << "Failed to allocate dgram xprt\n"; next_xid = &random_getword; } float rpc_manager::get_a_lat (ptr<location> l) { hostinfo *h = lookup_host (l->address ()); return h->a_lat; } float rpc_manager::get_a_var (ptr<location> l) { hostinfo *h = lookup_host (l->address ()); return h->a_var; } void rpc_manager::remove_host (hostinfo *h) { } hostinfo * rpc_manager::lookup_host (const net_address &r) { str key = strbuf () << r.hostname << ":" << r.port << "\n"; hostinfo *h = hosts[key]; if (!h) { if (hosts.size () > max_host_cache) { hostinfo *o = hostlru.first; hostlru.remove (o); hosts.remove (o); remove_host (o); delete (o); } h = New hostinfo (r); h->key = key; hostlru.insert_tail (h); hosts.insert (h); } else { // record recent access hostlru.remove (h); hostlru.insert_tail (h); } assert (h); return h; } long rpc_manager::doRPC (ptr<location> from, ptr<location> l, const rpc_program &prog, int procno, ptr<void> in, void *out, aclnt_cb cb, cbtmo_t cb_tmo, long fake_seqno /* = 0 */) { ref<aclnt> c = aclnt::alloc (dgram_xprt, prog, (sockaddr *)&(l->saddr ())); // Make sure that there is an entry in the table for this guy. (void) lookup_host (l->address ()); u_int64_t sent = getusec (); c->call (procno, in, out, wrap (this, &rpc_manager::doRPCcb, cb, l, sent)); return 0; } long rpc_manager::doRPC_dead (ptr<location> l, const rpc_program &prog, int procno, ptr<void> in, void *out, aclnt_cb cb, long fake_seqno /* = 0 */) { return doRPC (NULL, l, prog, procno, in, out, cb, NULL, fake_seqno); } void rpc_manager::doRPCcb (aclnt_cb realcb, ptr<location> l, u_int64_t sent, clnt_stat err) { if (err) { nrpcfailed++; l->set_alive (false); } else { nrpc++; // Only update latency on successful RPC. // This probably includes time needed for rexmits. u_int64_t now = getusec (); // prevent overflow, caused by time reversal if (now >= sent) { u_int64_t lat = now - sent; update_latency (NULL, l, lat); } else { warn << "*** Ignoring timewarp: sent " << sent << " > now " << now << "\n"; } } (realcb) (err); } // ----------------------------------------------------- long tcp_manager::doRPC (ptr<location> from, ptr<location> l, const rpc_program &prog, int procno, ptr<void> in, void *out, aclnt_cb cb, cbtmo_t cb_tmo, long fake_seqno /* = 0 */) { // hack to avoid limit on wrap()'s number of arguments RPC_delay_args *args = New RPC_delay_args (from, l, prog, procno, in, out, cb, NULL); if (chord_rpc_style == CHORD_RPC_SFSBT) { tcpconnect (l->saddr ().sin_addr, ntohs (l->saddr ().sin_port), wrap (this, &tcp_manager::doRPC_tcp_connect_cb, args)); } else { hostinfo *hi = lookup_host (l->address ()); if (hi->fd == -2) { //no connect initiated // weird: tcpconnect wants the address in NBO, and port in HBO hi->fd = -1; // signal pending connect tcpconnect (l->saddr ().sin_addr, ntohs (l->saddr ().sin_port), wrap (this, &tcp_manager::doRPC_tcp_connect_cb, args)); } else if (hi->fd == -1) { //connect pending, add to waiters hi->connect_waiters.push_back (args); } else if (hi->fd > 0) { //already connected send_RPC (args); } } return 0; } long tcp_manager::doRPC_dead (ptr<location> l, const rpc_program &prog, int procno, ptr<void> in, void *out, aclnt_cb cb, long fake_seqno /* = 0 */) { return doRPC (NULL, l, prog, procno, in, out, cb, NULL, fake_seqno); } void tcp_manager::remove_host (hostinfo *h) { // unnecessary SO_LINGER already set // tcp_abort (h->fd); if (chord_rpc_style == CHORD_RPC_SFST) { h->fd = -2; h->xp = NULL; while (h->connect_waiters.size ()) { RPC_delay_args *a = h->connect_waiters.pop_front (); a->cb (RPC_CANTSEND); delete a; } } } void tcp_manager::send_RPC (RPC_delay_args *args) { hostinfo *hi = lookup_host (args->l->address ()); if (!hi->xp) { delaycb (0, 0, wrap (this, &tcp_manager::send_RPC_ateofcb, args)); } else if (hi->xp->ateof()) { hostlru.remove (hi); hostlru.insert_tail (hi); args->l->set_alive (false); remove_host (hi); delaycb (0, 0, wrap (this, &tcp_manager::send_RPC_ateofcb, args)); } else { hi->orpc++; args->now = getusec (); ptr<aclnt> c = aclnt::alloc (hi->xp, args->prog); c->call (args->procno, args->in, args->out, wrap (this, &tcp_manager::doRPC_tcp_cleanup, c, args)); } } void tcp_manager::send_RPC_ateofcb (RPC_delay_args *args) { (args->cb) (RPC_CANTSEND); delete args; } void tcp_manager::doRPC_tcp_connect_cb (RPC_delay_args *args, int fd) { hostinfo *hi = lookup_host (args->l->address ()); if (fd < 0) { warn << "locationtable: connect failed: " << strerror (errno) << "\n"; (args->cb) (RPC_CANTSEND); args->l->set_alive (false); remove_host (hi); delete args; } else { struct linger li; li.l_onoff = 1; li.l_linger = 0; setsockopt (fd, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof (li)); tcp_nodelay (fd); make_async(fd); if (chord_rpc_style == CHORD_RPC_SFST) { hi->fd = fd; hi->xp = axprt_stream::alloc (fd); assert (hi->xp); send_RPC (args); while (hi->connect_waiters.size ()) send_RPC (hi->connect_waiters.pop_front ()); } else { ptr<axprt_stream> xp = axprt_stream::alloc (fd); assert (xp); ptr<aclnt> c = aclnt::alloc (xp, args->prog); assert (c); c->call (args->procno, args->in, args->out, wrap (this, &tcp_manager::doRPC_tcp_cleanup, c, args)); } } } void tcp_manager::doRPC_tcp_cleanup (ptr<aclnt> c, RPC_delay_args *args, clnt_stat err) { hostinfo *hi = lookup_host (args->l->address ()); u_int64_t diff; if (args->from && args->from->address ().hostname == args->l->address ().hostname) diff = 5000; else { u_int64_t now = getusec (); diff = now - args->now; if (diff > 5000000) warn << "long tcp latency to " << args->l->address ().hostname << ": " << diff << ", orpc " << hi->orpc << "\n"; } hi->orpc--; if (diff < 5000000) update_latency (NULL, args->l, diff); (*args->cb)(err); delete args; } void tcp_manager::stats () { char buf[1024]; rpc_manager::stats (); for (hostinfo *h = hosts.first (); h ; h = hosts.next (h)) { warnx << " host " << h->host << ": rpcs " << h->nrpc << ", orpcs " << h->orpc; sprintf (buf, ", lat %.1f, var %.1f\n", h->a_lat/1000, h->a_var/1000); warnx << buf; } } <|endoftext|>
<commit_before>#include "selfdrive/ui/replay/framereader.h" #include <assert.h> #include <unistd.h> #include <QDebug> static int ffmpeg_lockmgr_cb(void **arg, enum AVLockOp op) { std::mutex *mutex = (std::mutex *)*arg; switch (op) { case AV_LOCK_CREATE: mutex = new std::mutex(); break; case AV_LOCK_OBTAIN: mutex->lock(); break; case AV_LOCK_RELEASE: mutex->unlock(); case AV_LOCK_DESTROY: delete mutex; break; } return 0; } class AVInitializer { public: AVInitializer() { int ret = av_lockmgr_register(ffmpeg_lockmgr_cb); assert(ret >= 0); av_register_all(); avformat_network_init(); } ~AVInitializer() { avformat_network_deinit(); } }; static AVInitializer av_initializer; FrameReader::FrameReader(const std::string &url, QObject *parent) : url_(url), QObject(parent) { process_thread_ = QThread::create(&FrameReader::process, this); connect(process_thread_, &QThread::finished, process_thread_, &QThread::deleteLater); process_thread_->start(); } FrameReader::~FrameReader() { // wait until thread is finished. exit_ = true; process_thread_->wait(); cv_decode_.notify_all(); cv_frame_.notify_all(); if (decode_thread_.joinable()) { decode_thread_.join(); } // free all. for (auto &f : frames_) { av_free_packet(&f.pkt); if (f.data) { delete[] f.data; } } while (!buffer_pool.empty()) { delete[] buffer_pool.front(); buffer_pool.pop(); } av_frame_free(&frmRgb_); avcodec_close(pCodecCtx_); avcodec_free_context(&pCodecCtx_); avformat_close_input(&pFormatCtx_); sws_freeContext(sws_ctx_); } void FrameReader::process() { if (processFrames()) { decode_thread_ = std::thread(&FrameReader::decodeThread, this); } if (!exit_) { emit finished(); } } bool FrameReader::processFrames() { if (avformat_open_input(&pFormatCtx_, url_.c_str(), NULL, NULL) != 0) { qDebug() << "error loading " << url_.c_str(); return false; } avformat_find_stream_info(pFormatCtx_, NULL); av_dump_format(pFormatCtx_, 0, url_.c_str(), 0); auto pCodecCtxOrig = pFormatCtx_->streams[0]->codec; auto pCodec = avcodec_find_decoder(pCodecCtxOrig->codec_id); assert(pCodec); pCodecCtx_ = avcodec_alloc_context3(pCodec); int ret = avcodec_copy_context(pCodecCtx_, pCodecCtxOrig); assert(ret == 0); ret = avcodec_open2(pCodecCtx_, pCodec, NULL); assert(ret >= 0); width = pCodecCtxOrig->width; height = pCodecCtxOrig->height; sws_ctx_ = sws_getContext(width, height, AV_PIX_FMT_YUV420P, width, height, AV_PIX_FMT_BGR24, SWS_BILINEAR, NULL, NULL, NULL); assert(sws_ctx_); frmRgb_ = av_frame_alloc(); assert(frmRgb_); frames_.reserve(60 * 20); // 20fps, one minute do { Frame &frame = frames_.emplace_back(); if (av_read_frame(pFormatCtx_, &frame.pkt) < 0) { frames_.pop_back(); break; } } while (!exit_); valid_ = !exit_; return valid_; } uint8_t *FrameReader::get(int idx) { if (!valid_ || idx < 0 || idx >= frames_.size()) { return nullptr; } { std::unique_lock lk(mutex_); decode_idx_ = idx; cv_decode_.notify_one(); cv_frame_.wait(lk, [=] { return exit_ || frames_[idx].data || frames_[idx].failed; }); } return frames_[idx].data; } void FrameReader::decodeThread() { int idx = 0; while (!exit_) { const int from = std::max(idx, 0); const int to = std::min(idx + 20, (int)frames_.size()); for (int i = 0; i < frames_.size() && !exit_; ++i) { Frame &frame = frames_[i]; if (i >= from && i < to) { if (frame.data || frame.failed) continue; uint8_t *dat = decodeFrame(&frame.pkt); std::unique_lock lk(mutex_); frame.data = dat; frame.failed = !dat; cv_frame_.notify_all(); } else if (frame.data) { buffer_pool.push(frame.data); frame.data = nullptr; frame.failed = false; } } // sleep & wait std::unique_lock lk(mutex_); cv_decode_.wait(lk, [=] { return exit_ || decode_idx_ != -1; }); idx = decode_idx_; decode_idx_ = -1; } } uint8_t *FrameReader::decodeFrame(AVPacket *pkt) { int gotFrame; AVFrame *f = av_frame_alloc(); avcodec_decode_video2(pCodecCtx_, f, &gotFrame, pkt); uint8_t *dat = nullptr; if (gotFrame) { if (!buffer_pool.empty()) { dat = buffer_pool.front(); buffer_pool.pop(); } else { dat = new uint8_t[getRGBSize()]; } int ret = avpicture_fill((AVPicture *)frmRgb_, dat, AV_PIX_FMT_BGR24, f->width, f->height); assert(ret > 0); if (sws_scale(sws_ctx_, (const uint8_t **)f->data, f->linesize, 0, f->height, frmRgb_->data, frmRgb_->linesize) <= 0) { delete[] dat; dat = nullptr; } } av_frame_free(&f); return dat; } <commit_msg>FrameReader: use 'from' in std::min comparison (#21195)<commit_after>#include "selfdrive/ui/replay/framereader.h" #include <assert.h> #include <unistd.h> #include <QDebug> static int ffmpeg_lockmgr_cb(void **arg, enum AVLockOp op) { std::mutex *mutex = (std::mutex *)*arg; switch (op) { case AV_LOCK_CREATE: mutex = new std::mutex(); break; case AV_LOCK_OBTAIN: mutex->lock(); break; case AV_LOCK_RELEASE: mutex->unlock(); case AV_LOCK_DESTROY: delete mutex; break; } return 0; } class AVInitializer { public: AVInitializer() { int ret = av_lockmgr_register(ffmpeg_lockmgr_cb); assert(ret >= 0); av_register_all(); avformat_network_init(); } ~AVInitializer() { avformat_network_deinit(); } }; static AVInitializer av_initializer; FrameReader::FrameReader(const std::string &url, QObject *parent) : url_(url), QObject(parent) { process_thread_ = QThread::create(&FrameReader::process, this); connect(process_thread_, &QThread::finished, process_thread_, &QThread::deleteLater); process_thread_->start(); } FrameReader::~FrameReader() { // wait until thread is finished. exit_ = true; process_thread_->wait(); cv_decode_.notify_all(); cv_frame_.notify_all(); if (decode_thread_.joinable()) { decode_thread_.join(); } // free all. for (auto &f : frames_) { av_free_packet(&f.pkt); if (f.data) { delete[] f.data; } } while (!buffer_pool.empty()) { delete[] buffer_pool.front(); buffer_pool.pop(); } av_frame_free(&frmRgb_); avcodec_close(pCodecCtx_); avcodec_free_context(&pCodecCtx_); avformat_close_input(&pFormatCtx_); sws_freeContext(sws_ctx_); } void FrameReader::process() { if (processFrames()) { decode_thread_ = std::thread(&FrameReader::decodeThread, this); } if (!exit_) { emit finished(); } } bool FrameReader::processFrames() { if (avformat_open_input(&pFormatCtx_, url_.c_str(), NULL, NULL) != 0) { qDebug() << "error loading " << url_.c_str(); return false; } avformat_find_stream_info(pFormatCtx_, NULL); av_dump_format(pFormatCtx_, 0, url_.c_str(), 0); auto pCodecCtxOrig = pFormatCtx_->streams[0]->codec; auto pCodec = avcodec_find_decoder(pCodecCtxOrig->codec_id); assert(pCodec); pCodecCtx_ = avcodec_alloc_context3(pCodec); int ret = avcodec_copy_context(pCodecCtx_, pCodecCtxOrig); assert(ret == 0); ret = avcodec_open2(pCodecCtx_, pCodec, NULL); assert(ret >= 0); width = pCodecCtxOrig->width; height = pCodecCtxOrig->height; sws_ctx_ = sws_getContext(width, height, AV_PIX_FMT_YUV420P, width, height, AV_PIX_FMT_BGR24, SWS_BILINEAR, NULL, NULL, NULL); assert(sws_ctx_); frmRgb_ = av_frame_alloc(); assert(frmRgb_); frames_.reserve(60 * 20); // 20fps, one minute do { Frame &frame = frames_.emplace_back(); if (av_read_frame(pFormatCtx_, &frame.pkt) < 0) { frames_.pop_back(); break; } } while (!exit_); valid_ = !exit_; return valid_; } uint8_t *FrameReader::get(int idx) { if (!valid_ || idx < 0 || idx >= frames_.size()) { return nullptr; } { std::unique_lock lk(mutex_); decode_idx_ = idx; cv_decode_.notify_one(); cv_frame_.wait(lk, [=] { return exit_ || frames_[idx].data || frames_[idx].failed; }); } return frames_[idx].data; } void FrameReader::decodeThread() { int idx = 0; while (!exit_) { const int from = std::max(idx, 0); const int to = std::min(from + 20, (int)frames_.size()); for (int i = 0; i < frames_.size() && !exit_; ++i) { Frame &frame = frames_[i]; if (i >= from && i < to) { if (frame.data || frame.failed) continue; uint8_t *dat = decodeFrame(&frame.pkt); std::unique_lock lk(mutex_); frame.data = dat; frame.failed = !dat; cv_frame_.notify_all(); } else if (frame.data) { buffer_pool.push(frame.data); frame.data = nullptr; frame.failed = false; } } // sleep & wait std::unique_lock lk(mutex_); cv_decode_.wait(lk, [=] { return exit_ || decode_idx_ != -1; }); idx = decode_idx_; decode_idx_ = -1; } } uint8_t *FrameReader::decodeFrame(AVPacket *pkt) { int gotFrame; AVFrame *f = av_frame_alloc(); avcodec_decode_video2(pCodecCtx_, f, &gotFrame, pkt); uint8_t *dat = nullptr; if (gotFrame) { if (!buffer_pool.empty()) { dat = buffer_pool.front(); buffer_pool.pop(); } else { dat = new uint8_t[getRGBSize()]; } int ret = avpicture_fill((AVPicture *)frmRgb_, dat, AV_PIX_FMT_BGR24, f->width, f->height); assert(ret > 0); if (sws_scale(sws_ctx_, (const uint8_t **)f->data, f->linesize, 0, f->height, frmRgb_->data, frmRgb_->linesize) <= 0) { delete[] dat; dat = nullptr; } } av_frame_free(&f); return dat; } <|endoftext|>
<commit_before>#include "circle2d.hpp" #include "frea/constant.hpp" #include "frea/ulps.hpp" #include "segment2d.hpp" #include "aabb2d.hpp" #include "constant.hpp" namespace beat { namespace g2 { using frea::Square; Circle::Circle(const Vec2& c, const float r): center(c), radius(r) { D_Assert0(r >= 0); } Vec2 Circle::CircumscribingCenter(const Vec2& v0, const Vec2& v1, const Vec2& v2) { const Vec2 s0 = Square(v0), s1 = Square(v1), s2 = Square(v2); const float C = 2 * ((v0.y - v2.y) * (v0.x - v1.x) - (v0.y - v1.y) * (v0.x - v2.x)); if(std::abs(C) <= 1e-5f) throw NoValidCircle("Circle::CircumscribingCenter"); const float x = ((s0.x - s1.x + s0.y - s1.y) * (v0.y - v2.y) - (s0.x - s2.x + s0.y - s2.y) * (v0.y - v1.y)) / C; const float y = ((s0.x - s2.x + s0.y - s2.y) * (v0.x - v1.x) - (s0.x - s1.x + s0.y - s1.y) * (v0.x - v2.x)) / C; return {x, y}; } Circle Circle::FromEquationCoeff(const float l, const float m, const float n) { const Vec2 c{-l/2, -m/2}; const float r = std::sqrt(-n + Square(c.x) + Square(c.y)); return Circle{c, r}; } Circle Circle::Circumscribing(const Vec2& v0, const Vec2& v1, const Vec2& v2) { const Vec2 c = CircumscribingCenter(v0, v1, v2); return Circle{c, c.distance(v0)}; } Circle Circle::Encapsule(const AABB& a) { const float rd = std::sqrt(Square(a.width()) + Square(a.height()))/2; return Circle{a.bs_getCenter(), frea::ulps::Move(rd,64)}; } void Circle::distend(const float r) { radius *= r; } // 半径のみ倍率をかける Circle Circle::operator * (const float s) const { return Circle(center, radius*s); } Circle& Circle::operator += (const Vec2& ofs) { center += ofs; return *this; } std::ostream& operator << (std::ostream& os, const Circle& c) { return os << "Circle(2d) [ center: " << c.center << ", radius: " << c.radius << ']'; } float Circle::bs_getArea() const { AssertF("not implemented yet"); } float Circle::bs_getInertia() const { AssertF("not implemented yet"); } const Vec2& Circle::bs_getCenter() const { return center; } const Circle& Circle::bs_getBCircle() const { return *this; } AABB Circle::bs_getBBox() const { Vec2 d(radius); return AABB(center - d, center + d); } Circle Circle::operator * (const AMat32& m) const { auto& m2 = reinterpret_cast<const frea::AMat2&>(m); Vec2 tx(radius,0), ty(0,radius), ori(center); ori = ori.convertI<3,2>(1) * m; tx = tx * m2; ty = ty * m2; return Circle(ori, std::sqrt(std::max(tx.len_sq(), ty.len_sq()))); } Vec2 Circle::support(const Vec2& dir) const { return dir * radius + center; } bool Circle::hit(const Vec2& p) const { return center.dist_sq(p) <= Square(radius); } bool Circle::hit(const Circle& c) const { return center.dist_sq(c.center) <= Square(radius + c.radius); } bool Circle::hit(const Segment& s) const { const Vec2 np = s.nearest(center).first; return np.dist_sq(center) <= Square(radius); } using Mat34 = frea::Mat_t<float, 3, 4, false>; Circle Circle::CircumscribingM(const Vec2& v0, const Vec2& v1, const Vec2& v2) { Mat34 mat; const auto set = [&mat](const int n, const auto& v) { mat.m[n][0] = v.x; mat.m[n][1] = v.y; mat.m[n][2] = 1; mat.m[n][3] = -Square(v.x) -Square(v.y); }; set(0, v0); set(1, v1); set(2, v2); mat.rowReduce(1e-5f); return Circle::FromEquationCoeff(mat.m[0][3], mat.m[1][3], mat.m[2][3]); } void Circle::setBoundary(const IModel* p) { p->im_getBVolume(*this); } void Circle::appendBoundary(const IModel* p) { Circle c2; p->im_getBVolume(c2); Vec2 toC2 = c2.center - center; const float lensq = toC2.len_sq(); if(lensq >= ZEROVEC_LENGTH_SQ) { toC2 *= 1.0f / std::sqrt(lensq); const Vec2 tv(support(toC2) - c2.support(-toC2)); const float r_min = std::min(radius, c2.radius); if(tv.dot(toC2) < 0 || tv.len_sq() < frea::Square(r_min*2)) { // 新たな円を算出 const Vec2 tv0(center - toC2*radius), tv1(c2.center + toC2*c2.radius); radius = tv0.distance(tv1) * .5f; center = (tv0+tv1) * .5f; } else { // 円が内包されている if(radius < c2.radius) { radius = c2.radius; center = c2.center; } } } else { // 円の中心が同じ位置にある radius = std::max(c2.radius, radius); } } } } <commit_msg>Circle: appendBoundaryの修正<commit_after>#include "circle2d.hpp" #include "frea/constant.hpp" #include "frea/ulps.hpp" #include "segment2d.hpp" #include "aabb2d.hpp" #include "constant.hpp" namespace beat { namespace g2 { using frea::Square; Circle::Circle(const Vec2& c, const float r): center(c), radius(r) { D_Assert0(r >= 0); } Vec2 Circle::CircumscribingCenter(const Vec2& v0, const Vec2& v1, const Vec2& v2) { const Vec2 s0 = Square(v0), s1 = Square(v1), s2 = Square(v2); const float C = 2 * ((v0.y - v2.y) * (v0.x - v1.x) - (v0.y - v1.y) * (v0.x - v2.x)); if(std::abs(C) <= 1e-5f) throw NoValidCircle("Circle::CircumscribingCenter"); const float x = ((s0.x - s1.x + s0.y - s1.y) * (v0.y - v2.y) - (s0.x - s2.x + s0.y - s2.y) * (v0.y - v1.y)) / C; const float y = ((s0.x - s2.x + s0.y - s2.y) * (v0.x - v1.x) - (s0.x - s1.x + s0.y - s1.y) * (v0.x - v2.x)) / C; return {x, y}; } Circle Circle::FromEquationCoeff(const float l, const float m, const float n) { const Vec2 c{-l/2, -m/2}; const float r = std::sqrt(-n + Square(c.x) + Square(c.y)); return Circle{c, r}; } Circle Circle::Circumscribing(const Vec2& v0, const Vec2& v1, const Vec2& v2) { const Vec2 c = CircumscribingCenter(v0, v1, v2); return Circle{c, c.distance(v0)}; } Circle Circle::Encapsule(const AABB& a) { const float rd = std::sqrt(Square(a.width()) + Square(a.height()))/2; return Circle{a.bs_getCenter(), frea::ulps::Move(rd,64)}; } void Circle::distend(const float r) { radius *= r; } // 半径のみ倍率をかける Circle Circle::operator * (const float s) const { return Circle(center, radius*s); } Circle& Circle::operator += (const Vec2& ofs) { center += ofs; return *this; } std::ostream& operator << (std::ostream& os, const Circle& c) { return os << "Circle(2d) [ center: " << c.center << ", radius: " << c.radius << ']'; } float Circle::bs_getArea() const { AssertF("not implemented yet"); } float Circle::bs_getInertia() const { AssertF("not implemented yet"); } const Vec2& Circle::bs_getCenter() const { return center; } const Circle& Circle::bs_getBCircle() const { return *this; } AABB Circle::bs_getBBox() const { Vec2 d(radius); return AABB(center - d, center + d); } Circle Circle::operator * (const AMat32& m) const { auto& m2 = reinterpret_cast<const frea::AMat2&>(m); Vec2 tx(radius,0), ty(0,radius), ori(center); ori = ori.convertI<3,2>(1) * m; tx = tx * m2; ty = ty * m2; return Circle(ori, std::sqrt(std::max(tx.len_sq(), ty.len_sq()))); } Vec2 Circle::support(const Vec2& dir) const { return dir * radius + center; } bool Circle::hit(const Vec2& p) const { return center.dist_sq(p) <= Square(radius); } bool Circle::hit(const Circle& c) const { return center.dist_sq(c.center) <= Square(radius + c.radius); } bool Circle::hit(const Segment& s) const { const Vec2 np = s.nearest(center).first; return np.dist_sq(center) <= Square(radius); } using Mat34 = frea::Mat_t<float, 3, 4, false>; Circle Circle::CircumscribingM(const Vec2& v0, const Vec2& v1, const Vec2& v2) { Mat34 mat; const auto set = [&mat](const int n, const auto& v) { mat.m[n][0] = v.x; mat.m[n][1] = v.y; mat.m[n][2] = 1; mat.m[n][3] = -Square(v.x) -Square(v.y); }; set(0, v0); set(1, v1); set(2, v2); mat.rowReduce(1e-5f); return Circle::FromEquationCoeff(mat.m[0][3], mat.m[1][3], mat.m[2][3]); } void Circle::setBoundary(const IModel* p) { p->im_getBVolume(*this); } void Circle::appendBoundary(const IModel* p) { Circle c2; p->im_getBVolume(c2); Vec2 toC2 = c2.center - center; const float len = toC2.normalize(); if(len >= ZEROVEC_LENGTH) { const Vec2 p2 = c2.support(toC2); const Vec2 tv(p2 - support(toC2)); if(tv.dot(toC2) < 0) { // 円が内包されている return; } Vec2 p0 = support(-toC2), p1 = c2.support(-toC2); if(toC2.dot(p1) < toC2.dot(p0)) { std::swap(p0, p1); } center = (p0+p2) /2; radius = p0.distance(p2) + 1e-3f; } else { // 円の中心が同じ位置にある radius = std::max(c2.radius, radius) + len; } } } } <|endoftext|>
<commit_before>#include <iostream> #include <cerrno> #include <getopt.h> #include <unistd.h> #include <csignal> #include <openssl/ssl.h> #include "../utils/errno_exception.h" #include "../utils/file.h" #include "../utils/dir.h" #include "server_socket.h" #include "http_server.h" using namespace std; int https_server_port = 443; int http_server_port = 80; bool disable_http_redirect = false; bool disable_ssl = false; String pid_file = "tmp/pids/server.pid"; const SSL_METHOD *ssl_method = nullptr; SSL_CTX *ssl_ctx = nullptr; void parse_arguments(int argc, char *argv[]) { static struct option long_options[] = { { "help", no_argument, NULL, 'h' }, { "https-port", required_argument, NULL, 'p' }, { "http-port", required_argument, NULL, 'P' }, { "daemon", no_argument, NULL, 'd' }, { "pid", required_argument, NULL, 'f' }, { "no-ssl", no_argument, NULL, 's' }, { "no-http-redirect", no_argument, NULL, 'r' }, { 0, 0, 0, 0 } }; while (true) { opterr = 0; int opt = getopt_long(argc, argv, "hdsrp:P:", long_options, NULL); if (opt == -1) break; switch (opt) { case 'h': cout << "Usage: ./fasty [options]" << endl; cout << " -p, --https-port=port Runs the HTTPS server on the specified port." << endl; cout << " --http-port=port Runs the HTTP server on the specified port." << endl; cout << " Defaults: 443 and 80 when run as root, 5001 and 5000 otherwise." << endl << endl; cout << " --no-ssl Disable HTTPS." << endl; cout << " --no-http-redirect Disable HTTP to HTTPS redirection." << endl; cout << " -d, --daemon Run the server as a daemon." << endl; cout << " -P, --pid=pid Specified the PID file." << endl; cout << " Default: tmp/pids/server.pid" << endl; cout << endl; cout << " -h, --help Show this help message." << endl; exit(0); break; case 'd': { cout << "[ Running as a daemon ]" << endl; pid_t pid = fork(); if (pid < 0) exit(-1); else if (pid > 0) exit(0); // Exit from the parent close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); break; } case 'p': https_server_port = String(optarg).to_i(); break; case 'P': http_server_port = String(optarg).to_i(); break; case 'f': pid_file = String(optarg); break; case 'r': disable_http_redirect = true; break; case 's': disable_ssl = true; break; } } } void create_pid_file() { if (!Dir::exists(File::dirname(pid_file))) Dir::mkdir_p(File::dirname(pid_file), 0755); File f(pid_file, "w"); f.write(String("") + getpid()); f.close(); } void delete_pid_file() { File::remove(pid_file); } void signal_handler(int signal) { cout << "Terminating..." << endl; if (ssl_ctx) SSL_CTX_free(ssl_ctx); delete_pid_file(); exit(0); } #if ENABLE_HTTP2 /** * This callback method is called by OpenSSL when a client sends an ALPN * request with his supported methods. * The client methods are stored as a length-prefixed string array. * The server should put his supported methods (among the client ones) in @out. * * This is the only legitimate way to negotiate HTTP2 over TLS. */ int alpn_callback(SSL *s, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { for (unsigned int i = 0; i < inlen; i += in[i] + 1) { String protocol = String((const char *) &in[i + 1]).substr(0, in[i]); /* * Most draft implementations either declare HTTP2 with "h2-something" * or "HTTP-draft-something", where "h2" whill be the ufficial protocol * name. */ if (protocol.substr(0, 2) == "h2" || protocol.substr(0, 11) == "HTTP-draft-") { /* Report the protocol as a length prefixed array in @out */ *out = (unsigned char *) in + i + 1; *outlen = in[i]; /* Inform OpenSSL of the success */ return SSL_TLSEXT_ERR_OK; } } /* * Inform OpenSSL that a common protocol was not found (clients will fall * back to HTTP/1.1) */ return SSL_TLSEXT_ERR_NOACK; } #endif void init_openssl() { SSL_library_init(); OpenSSL_add_all_algorithms(); SSL_load_error_strings(); ssl_method = SSLv23_server_method(); ssl_ctx = SSL_CTX_new(ssl_method); SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL); SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2); SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_COMPRESSION); SSL_CTX_set_options(ssl_ctx, SSL_OP_SINGLE_DH_USE); SSL_CTX_set_options(ssl_ctx, SSL_OP_SINGLE_ECDH_USE); SSL_CTX_set_cipher_list(ssl_ctx, "ALL:!ADH:!LOW:!EXP:!MD5:!RC4:!DSS:!aNULL@STRENGTH"); #if ENABLE_HTTP2 SSL_CTX_set_alpn_select_cb(ssl_ctx, alpn_callback, nullptr); #endif if (!ssl_ctx) { cout << "Could not create SSL Context. Exiting..." << endl; exit(0); } if (!SSL_CTX_use_certificate_file(ssl_ctx, "server.crt", SSL_FILETYPE_PEM)) { cout << "Could not load Server Certificate file. Exiting..." << endl; exit(0); } if (!SSL_CTX_use_PrivateKey_file(ssl_ctx, "server.key", SSL_FILETYPE_PEM)) { cout << "Could not load Server Private Key file. Exiting..." << endl; exit(0); } } void http_redirect_loop(void *param) { try { ServerSocket s(http_server_port, false); cout << "Starting HTTP redirect server on port " << http_server_port << endl; while (true) { ClientSocket client = s.next(); if (!fork()) HttpServer::InitRedirectThread(client); } } catch (std::exception &e) { cout << e.what() << endl; } } int main(int argc, char *argv[]) { if (geteuid() != 0) { https_server_port = 5001; http_server_port = 5000; } parse_arguments(argc, argv); signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); init_openssl(); try { create_pid_file(); ServerSocket s(disable_ssl ? http_server_port : https_server_port, !disable_ssl); if (disable_ssl) cout << "Starting HTTP server on port " << http_server_port << endl; else cout << "Starting HTTPS server on port " << https_server_port << endl; if (!disable_ssl and !disable_http_redirect) { pthread_t tid; pthread_create(&tid, NULL, (void *(*)(void *)) &http_redirect_loop, nullptr); } while (true) { ClientSocket client = s.next(); if (!fork()) HttpServer::InitThread(client); } } catch (std::exception &e) { cout << e.what() << endl; } return 0; } <commit_msg>Compacted options with ORs. Disabled both SSLv2 and SSLv3.<commit_after>#include <iostream> #include <cerrno> #include <getopt.h> #include <unistd.h> #include <csignal> #include <openssl/ssl.h> #include "../utils/errno_exception.h" #include "../utils/file.h" #include "../utils/dir.h" #include "server_socket.h" #include "http_server.h" using namespace std; int https_server_port = 443; int http_server_port = 80; bool disable_http_redirect = false; bool disable_ssl = false; String pid_file = "tmp/pids/server.pid"; const SSL_METHOD *ssl_method = nullptr; SSL_CTX *ssl_ctx = nullptr; void parse_arguments(int argc, char *argv[]) { static struct option long_options[] = { { "help", no_argument, NULL, 'h' }, { "https-port", required_argument, NULL, 'p' }, { "http-port", required_argument, NULL, 'P' }, { "daemon", no_argument, NULL, 'd' }, { "pid", required_argument, NULL, 'f' }, { "no-ssl", no_argument, NULL, 's' }, { "no-http-redirect", no_argument, NULL, 'r' }, { 0, 0, 0, 0 } }; while (true) { opterr = 0; int opt = getopt_long(argc, argv, "hdsrp:P:", long_options, NULL); if (opt == -1) break; switch (opt) { case 'h': cout << "Usage: ./fasty [options]" << endl; cout << " -p, --https-port=port Runs the HTTPS server on the specified port." << endl; cout << " --http-port=port Runs the HTTP server on the specified port." << endl; cout << " Defaults: 443 and 80 when run as root, 5001 and 5000 otherwise." << endl << endl; cout << " --no-ssl Disable HTTPS." << endl; cout << " --no-http-redirect Disable HTTP to HTTPS redirection." << endl; cout << " -d, --daemon Run the server as a daemon." << endl; cout << " -P, --pid=pid Specified the PID file." << endl; cout << " Default: tmp/pids/server.pid" << endl; cout << endl; cout << " -h, --help Show this help message." << endl; exit(0); break; case 'd': { cout << "[ Running as a daemon ]" << endl; pid_t pid = fork(); if (pid < 0) exit(-1); else if (pid > 0) exit(0); // Exit from the parent close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); break; } case 'p': https_server_port = String(optarg).to_i(); break; case 'P': http_server_port = String(optarg).to_i(); break; case 'f': pid_file = String(optarg); break; case 'r': disable_http_redirect = true; break; case 's': disable_ssl = true; break; } } } void create_pid_file() { if (!Dir::exists(File::dirname(pid_file))) Dir::mkdir_p(File::dirname(pid_file), 0755); File f(pid_file, "w"); f.write(String("") + getpid()); f.close(); } void delete_pid_file() { File::remove(pid_file); } void signal_handler(int signal) { cout << "Terminating..." << endl; if (ssl_ctx) SSL_CTX_free(ssl_ctx); delete_pid_file(); exit(0); } #if ENABLE_HTTP2 /** * This callback method is called by OpenSSL when a client sends an ALPN * request with his supported methods. * The client methods are stored as a length-prefixed string array. * The server should put his supported methods (among the client ones) in @out. * * This is the only legitimate way to negotiate HTTP2 over TLS. */ int alpn_callback(SSL *s, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { for (unsigned int i = 0; i < inlen; i += in[i] + 1) { String protocol = String((const char *) &in[i + 1]).substr(0, in[i]); /* * Most draft implementations either declare HTTP2 with "h2-something" * or "HTTP-draft-something", where "h2" whill be the ufficial protocol * name. */ if (protocol.substr(0, 2) == "h2" || protocol.substr(0, 11) == "HTTP-draft-") { /* Report the protocol as a length prefixed array in @out */ *out = (unsigned char *) in + i + 1; *outlen = in[i]; /* Inform OpenSSL of the success */ return SSL_TLSEXT_ERR_OK; } } /* * Inform OpenSSL that a common protocol was not found (clients will fall * back to HTTP/1.1) */ return SSL_TLSEXT_ERR_NOACK; } #endif void init_openssl() { SSL_library_init(); OpenSSL_add_all_algorithms(); SSL_load_error_strings(); ssl_method = SSLv23_server_method(); ssl_ctx = SSL_CTX_new(ssl_method); SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL); SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION); SSL_CTX_set_options(ssl_ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE); SSL_CTX_set_cipher_list(ssl_ctx, "ALL:!ADH:!LOW:!EXP:!MD5:!RC4:!DSS:!aNULL@STRENGTH"); #if ENABLE_HTTP2 SSL_CTX_set_alpn_select_cb(ssl_ctx, alpn_callback, nullptr); #endif if (!ssl_ctx) { cout << "Could not create SSL Context. Exiting..." << endl; exit(0); } if (!SSL_CTX_use_certificate_file(ssl_ctx, "server.crt", SSL_FILETYPE_PEM)) { cout << "Could not load Server Certificate file. Exiting..." << endl; exit(0); } if (!SSL_CTX_use_PrivateKey_file(ssl_ctx, "server.key", SSL_FILETYPE_PEM)) { cout << "Could not load Server Private Key file. Exiting..." << endl; exit(0); } } void http_redirect_loop(void *param) { try { ServerSocket s(http_server_port, false); cout << "Starting HTTP redirect server on port " << http_server_port << endl; while (true) { ClientSocket client = s.next(); if (!fork()) HttpServer::InitRedirectThread(client); } } catch (std::exception &e) { cout << e.what() << endl; } } int main(int argc, char *argv[]) { if (geteuid() != 0) { https_server_port = 5001; http_server_port = 5000; } parse_arguments(argc, argv); signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); init_openssl(); try { create_pid_file(); ServerSocket s(disable_ssl ? http_server_port : https_server_port, !disable_ssl); if (disable_ssl) cout << "Starting HTTP server on port " << http_server_port << endl; else cout << "Starting HTTPS server on port " << https_server_port << endl; if (!disable_ssl and !disable_http_redirect) { pthread_t tid; pthread_create(&tid, NULL, (void *(*)(void *)) &http_redirect_loop, nullptr); } while (true) { ClientSocket client = s.next(); if (!fork()) HttpServer::InitThread(client); } } catch (std::exception &e) { cout << e.what() << endl; } return 0; } <|endoftext|>
<commit_before>//===- lib/Driver/Targets.cpp - Linker Targets ----------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// /// Concrete instances of the Target interface. /// //===----------------------------------------------------------------------===// #include "lld/Driver/Target.h" #include "lld/ReaderWriter/ReaderArchive.h" #include "lld/ReaderWriter/ReaderELF.h" #include "lld/ReaderWriter/ReaderYAML.h" #include "lld/ReaderWriter/WriterELF.h" #include "lld/ReaderWriter/WriterYAML.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/raw_ostream.h" #include <set> using namespace lld; class X86LinuxTarget final : public Target { public: X86LinuxTarget(const LinkerOptions &lo) : Target(lo), _woe(lo._entrySymbol) { _readerELF.reset(createReaderELF(_roe, _roa)); _readerYAML.reset(createReaderYAML(_roy)); _writer.reset(createWriterELF(_woe)); _writerYAML.reset(createWriterYAML(_woy)); } virtual ErrorOr<lld::Reader&> getReader(const LinkerInput &input) { auto kind = input.getKind(); if (!kind) return error_code(kind); if (*kind == InputKind::YAML) return *_readerYAML; if (*kind == InputKind::Object) return *_readerELF; return llvm::make_error_code(llvm::errc::invalid_argument); } virtual ErrorOr<lld::Writer&> getWriter() { return _options._outputYAML ? *_writerYAML : *_writer; } private: lld::ReaderOptionsELF _roe; lld::ReaderOptionsArchive _roa; struct : lld::ReaderOptionsYAML { virtual Reference::Kind kindFromString(StringRef kindName) const { int k; if (kindName.getAsInteger(0, k)) k = 0; return k; } } _roy; struct WOpts : lld::WriterOptionsELF { WOpts(StringRef entry) { _endianness = llvm::support::little; _is64Bit = false; _type = llvm::ELF::ET_EXEC; _machine = llvm::ELF::EM_386; _entryPoint = entry; } } _woe; struct WYOpts : lld::WriterOptionsYAML { virtual StringRef kindToString(Reference::Kind k) const { std::string str; llvm::raw_string_ostream rso(str); rso << (unsigned)k; rso.flush(); return *_strings.insert(str).first; } mutable std::set<std::string> _strings; } _woy; std::unique_ptr<lld::Reader> _readerELF, _readerYAML; std::unique_ptr<lld::Writer> _writer, _writerYAML; }; class X86_64LinuxTarget final : public Target { public: X86_64LinuxTarget(const LinkerOptions &lo) : Target(lo), _woe(lo._entrySymbol) { _readerELF.reset(createReaderELF(_roe, _roa)); _readerYAML.reset(createReaderYAML(_roy)); _writer.reset(createWriterELF(_woe)); _writerYAML.reset(createWriterYAML(_woy)); } virtual ErrorOr<lld::Reader&> getReader(const LinkerInput &input) { auto kind = input.getKind(); if (!kind) return error_code(kind); if (*kind == InputKind::YAML) return *_readerYAML; if (*kind == InputKind::Object) return *_readerELF; return llvm::make_error_code(llvm::errc::invalid_argument); } virtual ErrorOr<lld::Writer&> getWriter() { return _options._outputYAML ? *_writerYAML : *_writer; } private: lld::ReaderOptionsELF _roe; lld::ReaderOptionsArchive _roa; struct : lld::ReaderOptionsYAML { virtual Reference::Kind kindFromString(StringRef kindName) const { int k; if (kindName.getAsInteger(0, k)) k = 0; return k; } } _roy; struct WOpts : lld::WriterOptionsELF { WOpts(StringRef entry) { _endianness = llvm::support::little; _is64Bit = true; _type = llvm::ELF::ET_EXEC; _machine = llvm::ELF::EM_X86_64; _entryPoint = entry; } } _woe; struct WYOpts : lld::WriterOptionsYAML { virtual StringRef kindToString(Reference::Kind k) const { std::string str; llvm::raw_string_ostream rso(str); rso << (unsigned)k; rso.flush(); return *_strings.insert(str).first; } mutable std::set<std::string> _strings; } _woy; std::unique_ptr<lld::Reader> _readerELF, _readerYAML; std::unique_ptr<lld::Writer> _writer, _writerYAML; }; std::unique_ptr<Target> Target::create(const LinkerOptions &lo) { llvm::Triple t(lo._target); if (t.getOS() == llvm::Triple::Linux && t.getArch() == llvm::Triple::x86) return std::unique_ptr<Target>(new X86LinuxTarget(lo)); else if (t.getOS() == llvm::Triple::Linux && t.getArch() == llvm::Triple::x86_64) return std::unique_ptr<Target>(new X86_64LinuxTarget(lo)); return std::unique_ptr<Target>(); } <commit_msg>add hexagon target to lld<commit_after>//===- lib/Driver/Targets.cpp - Linker Targets ----------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// /// Concrete instances of the Target interface. /// //===----------------------------------------------------------------------===// #include "lld/Driver/Target.h" #include "lld/ReaderWriter/ReaderArchive.h" #include "lld/ReaderWriter/ReaderELF.h" #include "lld/ReaderWriter/ReaderYAML.h" #include "lld/ReaderWriter/WriterELF.h" #include "lld/ReaderWriter/WriterYAML.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/raw_ostream.h" #include <set> using namespace lld; class X86LinuxTarget final : public Target { public: X86LinuxTarget(const LinkerOptions &lo) : Target(lo), _woe(lo._entrySymbol) { _readerELF.reset(createReaderELF(_roe, _roa)); _readerYAML.reset(createReaderYAML(_roy)); _writer.reset(createWriterELF(_woe)); _writerYAML.reset(createWriterYAML(_woy)); } virtual ErrorOr<lld::Reader&> getReader(const LinkerInput &input) { auto kind = input.getKind(); if (!kind) return error_code(kind); if (*kind == InputKind::YAML) return *_readerYAML; if (*kind == InputKind::Object) return *_readerELF; return llvm::make_error_code(llvm::errc::invalid_argument); } virtual ErrorOr<lld::Writer&> getWriter() { return _options._outputYAML ? *_writerYAML : *_writer; } private: lld::ReaderOptionsELF _roe; lld::ReaderOptionsArchive _roa; struct : lld::ReaderOptionsYAML { virtual Reference::Kind kindFromString(StringRef kindName) const { int k; if (kindName.getAsInteger(0, k)) k = 0; return k; } } _roy; struct WOpts : lld::WriterOptionsELF { WOpts(StringRef entry) { _endianness = llvm::support::little; _is64Bit = false; _type = llvm::ELF::ET_EXEC; _machine = llvm::ELF::EM_386; _entryPoint = entry; } } _woe; struct WYOpts : lld::WriterOptionsYAML { virtual StringRef kindToString(Reference::Kind k) const { std::string str; llvm::raw_string_ostream rso(str); rso << (unsigned)k; rso.flush(); return *_strings.insert(str).first; } mutable std::set<std::string> _strings; } _woy; std::unique_ptr<lld::Reader> _readerELF, _readerYAML; std::unique_ptr<lld::Writer> _writer, _writerYAML; }; class X86_64LinuxTarget final : public Target { public: X86_64LinuxTarget(const LinkerOptions &lo) : Target(lo), _woe(lo._entrySymbol) { _readerELF.reset(createReaderELF(_roe, _roa)); _readerYAML.reset(createReaderYAML(_roy)); _writer.reset(createWriterELF(_woe)); _writerYAML.reset(createWriterYAML(_woy)); } virtual ErrorOr<lld::Reader&> getReader(const LinkerInput &input) { auto kind = input.getKind(); if (!kind) return error_code(kind); if (*kind == InputKind::YAML) return *_readerYAML; if (*kind == InputKind::Object) return *_readerELF; return llvm::make_error_code(llvm::errc::invalid_argument); } virtual ErrorOr<lld::Writer&> getWriter() { return _options._outputYAML ? *_writerYAML : *_writer; } private: lld::ReaderOptionsELF _roe; lld::ReaderOptionsArchive _roa; struct : lld::ReaderOptionsYAML { virtual Reference::Kind kindFromString(StringRef kindName) const { int k; if (kindName.getAsInteger(0, k)) k = 0; return k; } } _roy; struct WOpts : lld::WriterOptionsELF { WOpts(StringRef entry) { _endianness = llvm::support::little; _is64Bit = true; _type = llvm::ELF::ET_EXEC; _machine = llvm::ELF::EM_X86_64; _entryPoint = entry; } } _woe; struct WYOpts : lld::WriterOptionsYAML { virtual StringRef kindToString(Reference::Kind k) const { std::string str; llvm::raw_string_ostream rso(str); rso << (unsigned)k; rso.flush(); return *_strings.insert(str).first; } mutable std::set<std::string> _strings; } _woy; std::unique_ptr<lld::Reader> _readerELF, _readerYAML; std::unique_ptr<lld::Writer> _writer, _writerYAML; }; class HexagonTarget final : public Target { public: HexagonTarget(const LinkerOptions &lo) : Target(lo), _woe(lo._entrySymbol) { _readerELF.reset(createReaderELF(_roe, _roa)); _readerYAML.reset(createReaderYAML(_roy)); _writer.reset(createWriterELF(_woe)); _writerYAML.reset(createWriterYAML(_woy)); } virtual ErrorOr<lld::Reader&> getReader(const LinkerInput &input) { auto kind = input.getKind(); if (!kind) return error_code(kind); if (*kind == InputKind::YAML) return *_readerYAML; if (*kind == InputKind::Object) return *_readerELF; return llvm::make_error_code(llvm::errc::invalid_argument); } virtual ErrorOr<lld::Writer&> getWriter() { return _options._outputYAML ? *_writerYAML : *_writer; } private: lld::ReaderOptionsELF _roe; lld::ReaderOptionsArchive _roa; struct : lld::ReaderOptionsYAML { virtual Reference::Kind kindFromString(StringRef kindName) const { int k; if (kindName.getAsInteger(0, k)) k = 0; return k; } } _roy; struct WOpts : lld::WriterOptionsELF { WOpts(StringRef entry) { _endianness = llvm::support::little; _is64Bit = false; _type = llvm::ELF::ET_EXEC; _machine = llvm::ELF::EM_HEXAGON; _entryPoint = entry; } } _woe; struct WYOpts : lld::WriterOptionsYAML { virtual StringRef kindToString(Reference::Kind k) const { std::string str; llvm::raw_string_ostream rso(str); rso << (unsigned)k; rso.flush(); return *_strings.insert(str).first; } mutable std::set<std::string> _strings; } _woy; std::unique_ptr<lld::Reader> _readerELF, _readerYAML; std::unique_ptr<lld::Writer> _writer, _writerYAML; }; std::unique_ptr<Target> Target::create(const LinkerOptions &lo) { llvm::Triple t(lo._target); if (t.getOS() == llvm::Triple::Linux && t.getArch() == llvm::Triple::x86) return std::unique_ptr<Target>(new X86LinuxTarget(lo)); else if (t.getOS() == llvm::Triple::Linux && t.getArch() == llvm::Triple::x86_64) return std::unique_ptr<Target>(new X86_64LinuxTarget(lo)); else if (t.getArch() == llvm::Triple::hexagon) return std::unique_ptr<Target>(new HexagonTarget(lo)); return std::unique_ptr<Target>(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkFixedArrayTest2.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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include "itkFixedArray.h" #include <time.h> int itkFixedArrayTest2(int, char* [] ) { // Define the number of elements in the array const unsigned int nelements = 10000000L; // Define the number of runs used for timing const unsigned int nrun = 10; // Declare a simple timer clock_t t; typedef itk::FixedArray<double,2> ArrayType; // Declare an array of nelements FixedArray // and add a small margin to play with pointers // but not map outside the allocated memory ArrayType * vec = new ArrayType[nelements+8]; // Fill it up with zeros memset(vec,0,(nelements+8)*sizeof(ArrayType)); // Display the alignment of the array std::cout << "Initial alignment: " << (((int)vec)& 7) << "\n"; // Start a simple experiment t = clock(); double acc1 = 0.0; for (unsigned int i=0;i<nrun;++i) { for (unsigned int j=0;j<nelements;++j) { acc1 += vec[j][0]; } } // Get the final timing and display it t=clock() - t; const double time1 = (t*1000.0) / CLOCKS_PER_SEC; std::cout << "Initial execution time: " << time1 << "ms\n"; // We now emulate an 8 bytes aligned array // Cast the pointer to char to play with bytes char * p = reinterpret_cast<char*>( vec ); // Move the char pointer until is aligned on 8 bytes while ( ( (int)p ) % 8 ) { ++p; } // Cast the 8 bytes aligned pointer back to the original type ArrayType * vec2 = reinterpret_cast<ArrayType*>( p ); // Make sure the new pointer is well aligned by // displaying the alignment std::cout << "New alignment: " << (((int)vec2)& 7) << "\n"; // Start the simple experiment on the 8 byte aligned array t = clock(); double acc2 = 0.0; for (unsigned int i=0;i<nrun;++i) { for (unsigned int j=0;j<nelements;++j) { acc2+=vec2[j][0]; } } // Get the final timing and display it t = clock() - t; const double time2 = (t*1000.0) / CLOCKS_PER_SEC; std::cout << "Execution time: " << time2 << "ms\n"; // Free up the memory delete [] vec; std::cout << "Performance ratio = " << 100.0 * (time1-time2)/time2 << "%" << std::endl; // Make sure we do something with the sums otherwise everything // could be optimized away by the compiler if( acc1+acc2 == 0.0 ) { return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>COMP: Adding #include for <memory> in order to get declaration of memset().<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkFixedArrayTest2.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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include "itkFixedArray.h" #include <time.h> #include <memory> int itkFixedArrayTest2(int, char* [] ) { // Define the number of elements in the array const unsigned int nelements = 10000000L; // Define the number of runs used for timing const unsigned int nrun = 10; // Declare a simple timer clock_t t; typedef itk::FixedArray<double,2> ArrayType; // Declare an array of nelements FixedArray // and add a small margin to play with pointers // but not map outside the allocated memory ArrayType * vec = new ArrayType[nelements+8]; // Fill it up with zeros memset(vec,0,(nelements+8)*sizeof(ArrayType)); // Display the alignment of the array std::cout << "Initial alignment: " << (((int)vec)& 7) << "\n"; // Start a simple experiment t = clock(); double acc1 = 0.0; for (unsigned int i=0;i<nrun;++i) { for (unsigned int j=0;j<nelements;++j) { acc1 += vec[j][0]; } } // Get the final timing and display it t=clock() - t; const double time1 = (t*1000.0) / CLOCKS_PER_SEC; std::cout << "Initial execution time: " << time1 << "ms\n"; // We now emulate an 8 bytes aligned array // Cast the pointer to char to play with bytes char * p = reinterpret_cast<char*>( vec ); // Move the char pointer until is aligned on 8 bytes while ( ( (int)p ) % 8 ) { ++p; } // Cast the 8 bytes aligned pointer back to the original type ArrayType * vec2 = reinterpret_cast<ArrayType*>( p ); // Make sure the new pointer is well aligned by // displaying the alignment std::cout << "New alignment: " << (((int)vec2)& 7) << "\n"; // Start the simple experiment on the 8 byte aligned array t = clock(); double acc2 = 0.0; for (unsigned int i=0;i<nrun;++i) { for (unsigned int j=0;j<nelements;++j) { acc2+=vec2[j][0]; } } // Get the final timing and display it t = clock() - t; const double time2 = (t*1000.0) / CLOCKS_PER_SEC; std::cout << "Execution time: " << time2 << "ms\n"; // Free up the memory delete [] vec; std::cout << "Performance ratio = " << 100.0 * (time1-time2)/time2 << "%" << std::endl; // Make sure we do something with the sums otherwise everything // could be optimized away by the compiler if( acc1+acc2 == 0.0 ) { return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdlib.h> #if defined(OS_WIN) #include <windows.h> #endif #include "base/debug/trace_event.h" #include "base/message_loop.h" #include "base/rand_util.h" #include "base/string_number_conversions.h" #include "base/stringprintf.h" #include "base/threading/platform_thread.h" #include "base/win/scoped_com_initializer.h" #include "build/build_config.h" #include "content/common/gpu/gpu_config.h" #include "content/gpu/gpu_child_thread.h" #include "content/gpu/gpu_info_collector.h" #include "content/gpu/gpu_process.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" #include "crypto/hmac.h" #include "ui/gl/gl_surface.h" #include "ui/gl/gl_switches.h" #if defined(OS_WIN) #include "content/common/gpu/media/dxva_video_decode_accelerator.h" #include "sandbox/win/src/sandbox.h" #elif defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) #include "content/common/gpu/media/omx_video_decode_accelerator.h" #elif defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY) #include "content/common/gpu/media/vaapi_video_decode_accelerator.h" #endif #if defined(USE_X11) #include "ui/base/x/x11_util.h" #endif #if defined(OS_LINUX) #include "content/public/common/sandbox_init.h" #endif namespace { void WarmUpSandbox(const content::GPUInfo&, bool); void CollectGraphicsInfo(content::GPUInfo*); } // Main function for starting the Gpu process. int GpuMain(const content::MainFunctionParams& parameters) { TRACE_EVENT0("gpu", "GpuMain"); base::Time start_time = base::Time::Now(); const CommandLine& command_line = parameters.command_line; if (command_line.HasSwitch(switches::kGpuStartupDialog)) { ChildProcess::WaitForDebugger("Gpu"); } if (!command_line.HasSwitch(switches::kSingleProcess)) { #if defined(OS_WIN) // Prevent Windows from displaying a modal dialog on failures like not being // able to load a DLL. SetErrorMode( SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); #elif defined(USE_X11) ui::SetDefaultX11ErrorHandlers(); #endif } // Initialization of the OpenGL bindings may fail, in which case we // will need to tear down this process. However, we can not do so // safely until the IPC channel is set up, because the detection of // early return of a child process is implemented using an IPC // channel error. If the IPC channel is not fully set up between the // browser and GPU process, and the GPU process crashes or exits // early, the browser process will never detect it. For this reason // we defer tearing down the GPU process until receiving the // GpuMsg_Initialize message from the browser. bool dead_on_arrival = false; content::GPUInfo gpu_info; // Get vendor_id, device_id, driver_version from browser process through // commandline switches. DCHECK(command_line.HasSwitch(switches::kGpuVendorID) && command_line.HasSwitch(switches::kGpuDeviceID) && command_line.HasSwitch(switches::kGpuDriverVersion)); bool success = base::HexStringToInt( command_line.GetSwitchValueASCII(switches::kGpuVendorID), reinterpret_cast<int*>(&(gpu_info.gpu.vendor_id))); DCHECK(success); success = base::HexStringToInt( command_line.GetSwitchValueASCII(switches::kGpuDeviceID), reinterpret_cast<int*>(&(gpu_info.gpu.device_id))); DCHECK(success); gpu_info.driver_vendor = command_line.GetSwitchValueASCII(switches::kGpuDriverVendor); gpu_info.driver_version = command_line.GetSwitchValueASCII(switches::kGpuDriverVersion); content::GetContentClient()->SetGpuInfo(gpu_info); // We need to track that information for the WarmUpSandbox function. bool initialized_gl_context = false; // Load and initialize the GL implementation and locate the GL entry points. if (gfx::GLSurface::InitializeOneOff()) { #if defined(OS_LINUX) // We collect full GPU info on demand in Win/Mac, i.e., when about:gpu // page opens. This is because we can make blacklist decisions based on // preliminary GPU info. // However, on Linux, we may not have enough info for blacklisting. if (!gpu_info.gpu.vendor_id || !gpu_info.gpu.device_id || gpu_info.driver_vendor.empty() || gpu_info.driver_version.empty()) { CollectGraphicsInfo(&gpu_info); // We know that CollectGraphicsInfo will initialize a GLContext. initialized_gl_context = true; } #if !defined(OS_CHROMEOS) if (gpu_info.gpu.vendor_id == 0x10de && // NVIDIA gpu_info.driver_vendor == "NVIDIA") { base::ThreadRestrictions::AssertIOAllowed(); if (access("/dev/nvidiactl", R_OK) != 0) { VLOG(1) << "NVIDIA device file /dev/nvidiactl access denied"; gpu_info.gpu_accessible = false; dead_on_arrival = true; } } #endif // OS_CHROMEOS #endif // OS_LINUX } else { VLOG(1) << "gfx::GLSurface::InitializeOneOff failed"; gpu_info.gpu_accessible = false; gpu_info.finalized = true; dead_on_arrival = true; } { const bool should_initialize_gl_context = !initialized_gl_context && !dead_on_arrival; // Warm up the current process before enabling the sandbox. WarmUpSandbox(gpu_info, should_initialize_gl_context); } #if defined(OS_LINUX) { TRACE_EVENT0("gpu", "Initialize sandbox"); bool do_init_sandbox = true; #if defined(OS_CHROMEOS) && defined(NDEBUG) // On Chrome OS and when not on a debug build, initialize // the GPU process' sandbox only for Intel GPUs. do_init_sandbox = gpu_info.gpu.vendor_id == 0x8086; // Intel GPU. #endif if (do_init_sandbox) { content::InitializeSandbox(); } } #endif #if defined(OS_WIN) { TRACE_EVENT0("gpu", "Lower token"); // For windows, if the target_services interface is not zero, the process // is sandboxed and we must call LowerToken() before rendering untrusted // content. sandbox::TargetServices* target_services = parameters.sandbox_info->target_services; if (target_services) target_services->LowerToken(); } #endif MessageLoop::Type message_loop_type = MessageLoop::TYPE_IO; #if defined(OS_WIN) // Unless we're running on desktop GL, we don't need a UI message // loop, so avoid its use to work around apparent problems with some // third-party software. if (command_line.HasSwitch(switches::kUseGL) && command_line.GetSwitchValueASCII(switches::kUseGL) == gfx::kGLImplementationDesktopName) { message_loop_type = MessageLoop::TYPE_UI; } #elif defined(OS_LINUX) message_loop_type = MessageLoop::TYPE_DEFAULT; #endif MessageLoop main_message_loop(message_loop_type); base::PlatformThread::SetName("CrGpuMain"); GpuProcess gpu_process; GpuChildThread* child_thread = new GpuChildThread(dead_on_arrival, gpu_info); child_thread->Init(start_time); gpu_process.set_main_thread(child_thread); { TRACE_EVENT0("gpu", "Run Message Loop"); main_message_loop.Run(); } child_thread->StopWatchdog(); return 0; } namespace { void CreateDummyGlContext() { scoped_refptr<gfx::GLSurface> surface( gfx::GLSurface::CreateOffscreenGLSurface(false, gfx::Size(1, 1))); if (!surface.get()) { VLOG(1) << "gfx::GLSurface::CreateOffscreenGLSurface failed"; return; } // On Linux, this is needed to make sure /dev/nvidiactl has // been opened and its descriptor cached. scoped_refptr<gfx::GLContext> context( gfx::GLContext::CreateGLContext(NULL, surface, gfx::PreferDiscreteGpu)); if (!context.get()) { VLOG(1) << "gfx::GLContext::CreateGLContext failed"; return; } // Similarly, this is needed for /dev/nvidia0. if (context->MakeCurrent(surface)) { context->ReleaseCurrent(surface.get()); } else { VLOG(1) << "gfx::GLContext::MakeCurrent failed"; } } void WarmUpSandbox(const content::GPUInfo& gpu_info, bool should_initialize_gl_context) { { TRACE_EVENT0("gpu", "Warm up rand"); // Warm up the random subsystem, which needs to be done pre-sandbox on all // platforms. (void) base::RandUint64(); } { TRACE_EVENT0("gpu", "Warm up HMAC"); // Warm up the crypto subsystem, which needs to done pre-sandbox on all // platforms. crypto::HMAC hmac(crypto::HMAC::SHA256); unsigned char key = '\0'; bool ret = hmac.Init(&key, sizeof(key)); (void) ret; } #if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) OmxVideoDecodeAccelerator::PreSandboxInitialization(); #elif defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY) VaapiVideoDecodeAccelerator::PreSandboxInitialization(); #endif #if defined(OS_LINUX) if (gpu_info.gpu.vendor_id == 0x10de && // NVIDIA gpu_info.driver_vendor == "NVIDIA" && should_initialize_gl_context) { // We need this on Nvidia to pre-open /dev/nvidiactl and /dev/nvidia0. CreateDummyGlContext(); } #endif { TRACE_EVENT0("gpu", "Initialize COM"); base::win::ScopedCOMInitializer com_initializer; } #if defined(OS_WIN) { TRACE_EVENT0("gpu", "Preload setupapi.dll"); // Preload this DLL because the sandbox prevents it from loading. LoadLibrary(L"setupapi.dll"); } { TRACE_EVENT0("gpu", "Initialize DXVA"); // Initialize H/W video decoding stuff which fails in the sandbox. DXVAVideoDecodeAccelerator::PreSandboxInitialization(); } #endif } void CollectGraphicsInfo(content::GPUInfo* gpu_info) { if (!gpu_info_collector::CollectGraphicsInfo(gpu_info)) VLOG(1) << "gpu_info_collector::CollectGraphicsInfo failed"; content::GetContentClient()->SetGpuInfo(*gpu_info); } } // namespace. <commit_msg>GPU: warm-up Nvidia driver on Linux for Optimus cards.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdlib.h> #if defined(OS_WIN) #include <windows.h> #endif #include "base/debug/trace_event.h" #include "base/message_loop.h" #include "base/rand_util.h" #include "base/string_number_conversions.h" #include "base/stringprintf.h" #include "base/threading/platform_thread.h" #include "base/win/scoped_com_initializer.h" #include "build/build_config.h" #include "content/common/gpu/gpu_config.h" #include "content/gpu/gpu_child_thread.h" #include "content/gpu/gpu_info_collector.h" #include "content/gpu/gpu_process.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" #include "crypto/hmac.h" #include "ui/gl/gl_surface.h" #include "ui/gl/gl_switches.h" #if defined(OS_WIN) #include "content/common/gpu/media/dxva_video_decode_accelerator.h" #include "sandbox/win/src/sandbox.h" #elif defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) #include "content/common/gpu/media/omx_video_decode_accelerator.h" #elif defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY) #include "content/common/gpu/media/vaapi_video_decode_accelerator.h" #endif #if defined(USE_X11) #include "ui/base/x/x11_util.h" #endif #if defined(OS_LINUX) #include "content/public/common/sandbox_init.h" #endif namespace { void WarmUpSandbox(const content::GPUInfo&, bool); void CollectGraphicsInfo(content::GPUInfo*); } // Main function for starting the Gpu process. int GpuMain(const content::MainFunctionParams& parameters) { TRACE_EVENT0("gpu", "GpuMain"); base::Time start_time = base::Time::Now(); const CommandLine& command_line = parameters.command_line; if (command_line.HasSwitch(switches::kGpuStartupDialog)) { ChildProcess::WaitForDebugger("Gpu"); } if (!command_line.HasSwitch(switches::kSingleProcess)) { #if defined(OS_WIN) // Prevent Windows from displaying a modal dialog on failures like not being // able to load a DLL. SetErrorMode( SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); #elif defined(USE_X11) ui::SetDefaultX11ErrorHandlers(); #endif } // Initialization of the OpenGL bindings may fail, in which case we // will need to tear down this process. However, we can not do so // safely until the IPC channel is set up, because the detection of // early return of a child process is implemented using an IPC // channel error. If the IPC channel is not fully set up between the // browser and GPU process, and the GPU process crashes or exits // early, the browser process will never detect it. For this reason // we defer tearing down the GPU process until receiving the // GpuMsg_Initialize message from the browser. bool dead_on_arrival = false; content::GPUInfo gpu_info; // Get vendor_id, device_id, driver_version from browser process through // commandline switches. DCHECK(command_line.HasSwitch(switches::kGpuVendorID) && command_line.HasSwitch(switches::kGpuDeviceID) && command_line.HasSwitch(switches::kGpuDriverVersion)); bool success = base::HexStringToInt( command_line.GetSwitchValueASCII(switches::kGpuVendorID), reinterpret_cast<int*>(&(gpu_info.gpu.vendor_id))); DCHECK(success); success = base::HexStringToInt( command_line.GetSwitchValueASCII(switches::kGpuDeviceID), reinterpret_cast<int*>(&(gpu_info.gpu.device_id))); DCHECK(success); gpu_info.driver_vendor = command_line.GetSwitchValueASCII(switches::kGpuDriverVendor); gpu_info.driver_version = command_line.GetSwitchValueASCII(switches::kGpuDriverVersion); content::GetContentClient()->SetGpuInfo(gpu_info); // We need to track that information for the WarmUpSandbox function. bool initialized_gl_context = false; // Load and initialize the GL implementation and locate the GL entry points. if (gfx::GLSurface::InitializeOneOff()) { #if defined(OS_LINUX) // We collect full GPU info on demand in Win/Mac, i.e., when about:gpu // page opens. This is because we can make blacklist decisions based on // preliminary GPU info. // However, on Linux, we may not have enough info for blacklisting. if (!gpu_info.gpu.vendor_id || !gpu_info.gpu.device_id || gpu_info.driver_vendor.empty() || gpu_info.driver_version.empty()) { CollectGraphicsInfo(&gpu_info); // We know that CollectGraphicsInfo will initialize a GLContext. initialized_gl_context = true; } #if !defined(OS_CHROMEOS) if (gpu_info.gpu.vendor_id == 0x10de && // NVIDIA gpu_info.driver_vendor == "NVIDIA") { base::ThreadRestrictions::AssertIOAllowed(); if (access("/dev/nvidiactl", R_OK) != 0) { VLOG(1) << "NVIDIA device file /dev/nvidiactl access denied"; gpu_info.gpu_accessible = false; dead_on_arrival = true; } } #endif // OS_CHROMEOS #endif // OS_LINUX } else { VLOG(1) << "gfx::GLSurface::InitializeOneOff failed"; gpu_info.gpu_accessible = false; gpu_info.finalized = true; dead_on_arrival = true; } { const bool should_initialize_gl_context = !initialized_gl_context && !dead_on_arrival; // Warm up the current process before enabling the sandbox. WarmUpSandbox(gpu_info, should_initialize_gl_context); } #if defined(OS_LINUX) { TRACE_EVENT0("gpu", "Initialize sandbox"); bool do_init_sandbox = true; #if defined(OS_CHROMEOS) && defined(NDEBUG) // On Chrome OS and when not on a debug build, initialize // the GPU process' sandbox only for Intel GPUs. do_init_sandbox = gpu_info.gpu.vendor_id == 0x8086; // Intel GPU. #endif if (do_init_sandbox) { content::InitializeSandbox(); } } #endif #if defined(OS_WIN) { TRACE_EVENT0("gpu", "Lower token"); // For windows, if the target_services interface is not zero, the process // is sandboxed and we must call LowerToken() before rendering untrusted // content. sandbox::TargetServices* target_services = parameters.sandbox_info->target_services; if (target_services) target_services->LowerToken(); } #endif MessageLoop::Type message_loop_type = MessageLoop::TYPE_IO; #if defined(OS_WIN) // Unless we're running on desktop GL, we don't need a UI message // loop, so avoid its use to work around apparent problems with some // third-party software. if (command_line.HasSwitch(switches::kUseGL) && command_line.GetSwitchValueASCII(switches::kUseGL) == gfx::kGLImplementationDesktopName) { message_loop_type = MessageLoop::TYPE_UI; } #elif defined(OS_LINUX) message_loop_type = MessageLoop::TYPE_DEFAULT; #endif MessageLoop main_message_loop(message_loop_type); base::PlatformThread::SetName("CrGpuMain"); GpuProcess gpu_process; GpuChildThread* child_thread = new GpuChildThread(dead_on_arrival, gpu_info); child_thread->Init(start_time); gpu_process.set_main_thread(child_thread); { TRACE_EVENT0("gpu", "Run Message Loop"); main_message_loop.Run(); } child_thread->StopWatchdog(); return 0; } namespace { void CreateDummyGlContext() { scoped_refptr<gfx::GLSurface> surface( gfx::GLSurface::CreateOffscreenGLSurface(false, gfx::Size(1, 1))); if (!surface.get()) { VLOG(1) << "gfx::GLSurface::CreateOffscreenGLSurface failed"; return; } // On Linux, this is needed to make sure /dev/nvidiactl has // been opened and its descriptor cached. scoped_refptr<gfx::GLContext> context( gfx::GLContext::CreateGLContext(NULL, surface, gfx::PreferDiscreteGpu)); if (!context.get()) { VLOG(1) << "gfx::GLContext::CreateGLContext failed"; return; } // Similarly, this is needed for /dev/nvidia0. if (context->MakeCurrent(surface)) { context->ReleaseCurrent(surface.get()); } else { VLOG(1) << "gfx::GLContext::MakeCurrent failed"; } } void WarmUpSandbox(const content::GPUInfo& gpu_info, bool should_initialize_gl_context) { { TRACE_EVENT0("gpu", "Warm up rand"); // Warm up the random subsystem, which needs to be done pre-sandbox on all // platforms. (void) base::RandUint64(); } { TRACE_EVENT0("gpu", "Warm up HMAC"); // Warm up the crypto subsystem, which needs to done pre-sandbox on all // platforms. crypto::HMAC hmac(crypto::HMAC::SHA256); unsigned char key = '\0'; bool ret = hmac.Init(&key, sizeof(key)); (void) ret; } #if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) OmxVideoDecodeAccelerator::PreSandboxInitialization(); #elif defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY) VaapiVideoDecodeAccelerator::PreSandboxInitialization(); #endif #if defined(OS_LINUX) // We special case Optimus since the vendor_id we see may not be Nvidia. bool uses_nvidia_driver = (gpu_info.gpu.vendor_id == 0x10de && // NVIDIA. gpu_info.driver_vendor == "NVIDIA") || gpu_info.optimus; if (uses_nvidia_driver && should_initialize_gl_context) { // We need this on Nvidia to pre-open /dev/nvidiactl and /dev/nvidia0. CreateDummyGlContext(); } #endif { TRACE_EVENT0("gpu", "Initialize COM"); base::win::ScopedCOMInitializer com_initializer; } #if defined(OS_WIN) { TRACE_EVENT0("gpu", "Preload setupapi.dll"); // Preload this DLL because the sandbox prevents it from loading. LoadLibrary(L"setupapi.dll"); } { TRACE_EVENT0("gpu", "Initialize DXVA"); // Initialize H/W video decoding stuff which fails in the sandbox. DXVAVideoDecodeAccelerator::PreSandboxInitialization(); } #endif } void CollectGraphicsInfo(content::GPUInfo* gpu_info) { if (!gpu_info_collector::CollectGraphicsInfo(gpu_info)) VLOG(1) << "gpu_info_collector::CollectGraphicsInfo failed"; content::GetContentClient()->SetGpuInfo(*gpu_info); } } // namespace. <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_ERR_ELEMENTWISE_ERROR_CHECKER_HPP #define STAN_MATH_PRIM_ERR_ELEMENTWISE_ERROR_CHECKER_HPP #include <stan/math/prim/err/throw_domain_error.hpp> #include <stan/math/prim/fun/get.hpp> #include <stan/math/prim/fun/size.hpp> #include <stan/math/prim/fun/value_of_rec.hpp> #include <stan/math/prim/meta/is_eigen.hpp> #include <stan/math/prim/meta/is_var_matrix.hpp> #include <stan/math/prim/meta/is_vector.hpp> #include <stan/math/prim/meta/is_stan_scalar.hpp> #include <string> #include <sstream> #include <vector> namespace stan { namespace math { namespace internal { /** Apply an error check to a container, signal failure with `false`. * Apply a predicate like is_positive to the double underlying every scalar in a * container, producing true if the predicate holds everywhere and `false` if it * fails anywhere. * @tparam F type of predicate */ template <typename F> class Iser { const F& is_good; public: /** * @param is_good predicate to check, must accept doubles and produce bools */ explicit Iser(const F& is_good) : is_good(is_good) {} /** * Check the scalar. * @tparam T type of scalar * @param x scalar * @return `false` if the scalar fails the error check */ template <typename T, typename = require_stan_scalar_t<T>> bool is(const T& x) { return is_good(value_of_rec_rec(x)); } /** * Check all the scalars inside the container. * @tparam T type of scalar * @param x container * @return `false` if any of the scalars fail the error check */ template <typename T, typename = require_not_stan_scalar_t<T>, typename = void> bool is(const T& x) { for (size_t i = 0; i < stan::math::size(x); ++i) if (!is(stan::get(x, i))) return false; return true; } }; /** * No-op. */ inline void pipe_in(std::stringstream& ss) {} /** * Pipes given arguments into a stringstream. Integral arguments (indices) are * increased by 1 before. * * @tparam Arg0 type of the first argument * @tparam Args types of remaining arguments * @param ss stringstream to pipe arguments in * @param arg0 the first argument * @param args remining arguments */ template <typename Arg0, typename... Args> inline void pipe_in(std::stringstream& ss, Arg0 arg0, const Args... args) { if (std::is_integral<Arg0>::value) { ss << arg0 + 1; } else { ss << arg0; } pipe_in(ss, args...); } } // namespace internal /** * Check that the predicate holds for the value of `x`, working elementwise on * containers. If `x` is a scalar, check the double underlying the scalar. If * `x` is a container, check each element inside `x`, recursively. * @tparam F type of predicate * @tparam T type of `x` * @tparam Indexings types of `indexings` * @param is_good predicate to check, must accept doubles and produce bools * @param function function name (for error messages) * @param name variable name (for error messages) * @param x variable to check, can be a scalar, a container of scalars, a * container of containers of scalars, etc * @param must_be message describing what the value should be * @param indexings any additional indexing to print. Intended for internal use * in `elementwise_check` only. * @throws `std::domain_error` if `is_good` returns `false` for the value * of any element in `x` */ template <typename F, typename T, typename... Indexings, require_stan_scalar_t<T>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { if (unlikely(!is_good(value_of_rec(x)))) { std::stringstream ss{}; ss << function << ": " << name; internal::pipe_in(ss, indexings...); ss << "is " << x << ", but must be " << must_be << "!"; throw std::domain_error(ss.str()); } } template <typename F, typename T, typename... Indexings, require_eigen_t<T>* = nullptr, std::enable_if_t<static_cast<bool>(Eigen::internal::traits<T>::Flags&( Eigen::LinearAccessBit | Eigen::DirectAccessBit))>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { for (size_t i = 0; i < x.size(); i++) { auto scal = value_of_rec(x.coeff(i)); if (unlikely(!is_good(scal))) { std::stringstream ss{}; ss << function << ": " << name; internal::pipe_in(ss, indexings...); if (is_eigen_vector<T>::value) { ss << "[" << i + 1 << "] is " << scal << ", but must be " << must_be << "!"; } else if (Eigen::internal::traits<T>::Flags & Eigen::RowMajorBit) { ss << "[" << i / x.rows() + 1 << ", " << i % x.rows() + 1 << "] is " << scal << ", but must be " << must_be << "!"; } else { ss << "[" << i % x.cols() + 1 << ", " << i / x.cols() + 1 << "] is " << scal << ", but must be " << must_be << "!"; } throw std::domain_error(ss.str()); } } } template < typename F, typename T, typename... Indexings, require_eigen_t<T>* = nullptr, std::enable_if_t<!(Eigen::internal::traits<T>::Flags & (Eigen::LinearAccessBit | Eigen::DirectAccessBit)) && !(Eigen::internal::traits<T>::Flags & Eigen::RowMajorBit)>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { for (size_t i = 0; i < x.rows(); i++) { for (size_t j = 0; j < x.cols(); j++) { auto scal = value_of_rec(x.coeff(i, j)); if (unlikely(!is_good(scal))) { std::stringstream ss{}; ss << function << ": " << name; internal::pipe_in(ss, indexings...); ss << "[" << i + 1 << ", " << j + 1 << "] is " << scal << ", but must be " << must_be << "!"; throw std::domain_error(ss.str()); } } } } template < typename F, typename T, typename... Indexings, require_eigen_t<T>* = nullptr, std::enable_if_t<!(Eigen::internal::traits<T>::Flags & (Eigen::LinearAccessBit | Eigen::DirectAccessBit)) && static_cast<bool>(Eigen::internal::traits<T>::Flags & Eigen::RowMajorBit)>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { for (size_t j = 0; j < x.cols(); j++) { for (size_t i = 0; i < x.rows(); i++) { auto scal = value_of_rec(x.coeff(i, j)); if (unlikely(!is_good(scal))) { std::stringstream ss{}; ss << function << ": " << name; internal::pipe_in(ss, indexings...); ss << "[" << i + 1 << ", " << j + 1 << "] is " << scal << ", but must be " << must_be << "!"; throw std::domain_error(ss.str()); } } } } template <typename F, typename T, typename... Indexings, require_std_vector_t<T>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { for (size_t j = 0; j < x.size(); j++) { elementwise_check(is_good, function, name, x[j], must_be, indexings..., "[", j, "]"); } } template <typename F, typename T, typename... Indexings, require_var_matrix_t<T>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { elementwise_check(is_good, function, name, x.val(), must_be, indexings...); } /** * Check that the predicate holds for the value of `x`, working elementwise on * containers. If `x` is a scalar, check the double underlying the scalar. If * `x` is a container, check each element inside `x`, recursively. * @tparam F type of predicate * @tparam T type of `x` * @param is_good predicate to check, must accept doubles and produce bools * @param x variable to check, can be a scalar, a container of scalars, a * container of containers of scalars, etc * @return `false` if any of the scalars fail the error check */ template <typename F, typename T> inline bool elementwise_is(const F& is_good, const T& x) { return internal::Iser<F>{is_good}.is(x); } } // namespace math } // namespace stan #endif <commit_msg>fix typo<commit_after>#ifndef STAN_MATH_PRIM_ERR_ELEMENTWISE_ERROR_CHECKER_HPP #define STAN_MATH_PRIM_ERR_ELEMENTWISE_ERROR_CHECKER_HPP #include <stan/math/prim/err/throw_domain_error.hpp> #include <stan/math/prim/fun/get.hpp> #include <stan/math/prim/fun/size.hpp> #include <stan/math/prim/fun/value_of_rec.hpp> #include <stan/math/prim/meta/is_eigen.hpp> #include <stan/math/prim/meta/is_var_matrix.hpp> #include <stan/math/prim/meta/is_vector.hpp> #include <stan/math/prim/meta/is_stan_scalar.hpp> #include <string> #include <sstream> #include <vector> namespace stan { namespace math { namespace internal { /** Apply an error check to a container, signal failure with `false`. * Apply a predicate like is_positive to the double underlying every scalar in a * container, producing true if the predicate holds everywhere and `false` if it * fails anywhere. * @tparam F type of predicate */ template <typename F> class Iser { const F& is_good; public: /** * @param is_good predicate to check, must accept doubles and produce bools */ explicit Iser(const F& is_good) : is_good(is_good) {} /** * Check the scalar. * @tparam T type of scalar * @param x scalar * @return `false` if the scalar fails the error check */ template <typename T, typename = require_stan_scalar_t<T>> bool is(const T& x) { return is_good(value_of_rec(x)); } /** * Check all the scalars inside the container. * @tparam T type of scalar * @param x container * @return `false` if any of the scalars fail the error check */ template <typename T, typename = require_not_stan_scalar_t<T>, typename = void> bool is(const T& x) { for (size_t i = 0; i < stan::math::size(x); ++i) if (!is(stan::get(x, i))) return false; return true; } }; /** * No-op. */ inline void pipe_in(std::stringstream& ss) {} /** * Pipes given arguments into a stringstream. Integral arguments (indices) are * increased by 1 before. * * @tparam Arg0 type of the first argument * @tparam Args types of remaining arguments * @param ss stringstream to pipe arguments in * @param arg0 the first argument * @param args remining arguments */ template <typename Arg0, typename... Args> inline void pipe_in(std::stringstream& ss, Arg0 arg0, const Args... args) { if (std::is_integral<Arg0>::value) { ss << arg0 + 1; } else { ss << arg0; } pipe_in(ss, args...); } } // namespace internal /** * Check that the predicate holds for the value of `x`, working elementwise on * containers. If `x` is a scalar, check the double underlying the scalar. If * `x` is a container, check each element inside `x`, recursively. * @tparam F type of predicate * @tparam T type of `x` * @tparam Indexings types of `indexings` * @param is_good predicate to check, must accept doubles and produce bools * @param function function name (for error messages) * @param name variable name (for error messages) * @param x variable to check, can be a scalar, a container of scalars, a * container of containers of scalars, etc * @param must_be message describing what the value should be * @param indexings any additional indexing to print. Intended for internal use * in `elementwise_check` only. * @throws `std::domain_error` if `is_good` returns `false` for the value * of any element in `x` */ template <typename F, typename T, typename... Indexings, require_stan_scalar_t<T>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { if (unlikely(!is_good(value_of_rec(x)))) { std::stringstream ss{}; ss << function << ": " << name; internal::pipe_in(ss, indexings...); ss << "is " << x << ", but must be " << must_be << "!"; throw std::domain_error(ss.str()); } } template <typename F, typename T, typename... Indexings, require_eigen_t<T>* = nullptr, std::enable_if_t<static_cast<bool>(Eigen::internal::traits<T>::Flags&( Eigen::LinearAccessBit | Eigen::DirectAccessBit))>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { for (size_t i = 0; i < x.size(); i++) { auto scal = value_of_rec(x.coeff(i)); if (unlikely(!is_good(scal))) { std::stringstream ss{}; ss << function << ": " << name; internal::pipe_in(ss, indexings...); if (is_eigen_vector<T>::value) { ss << "[" << i + 1 << "] is " << scal << ", but must be " << must_be << "!"; } else if (Eigen::internal::traits<T>::Flags & Eigen::RowMajorBit) { ss << "[" << i / x.rows() + 1 << ", " << i % x.rows() + 1 << "] is " << scal << ", but must be " << must_be << "!"; } else { ss << "[" << i % x.cols() + 1 << ", " << i / x.cols() + 1 << "] is " << scal << ", but must be " << must_be << "!"; } throw std::domain_error(ss.str()); } } } template < typename F, typename T, typename... Indexings, require_eigen_t<T>* = nullptr, std::enable_if_t<!(Eigen::internal::traits<T>::Flags & (Eigen::LinearAccessBit | Eigen::DirectAccessBit)) && !(Eigen::internal::traits<T>::Flags & Eigen::RowMajorBit)>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { for (size_t i = 0; i < x.rows(); i++) { for (size_t j = 0; j < x.cols(); j++) { auto scal = value_of_rec(x.coeff(i, j)); if (unlikely(!is_good(scal))) { std::stringstream ss{}; ss << function << ": " << name; internal::pipe_in(ss, indexings...); ss << "[" << i + 1 << ", " << j + 1 << "] is " << scal << ", but must be " << must_be << "!"; throw std::domain_error(ss.str()); } } } } template < typename F, typename T, typename... Indexings, require_eigen_t<T>* = nullptr, std::enable_if_t<!(Eigen::internal::traits<T>::Flags & (Eigen::LinearAccessBit | Eigen::DirectAccessBit)) && static_cast<bool>(Eigen::internal::traits<T>::Flags & Eigen::RowMajorBit)>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { for (size_t j = 0; j < x.cols(); j++) { for (size_t i = 0; i < x.rows(); i++) { auto scal = value_of_rec(x.coeff(i, j)); if (unlikely(!is_good(scal))) { std::stringstream ss{}; ss << function << ": " << name; internal::pipe_in(ss, indexings...); ss << "[" << i + 1 << ", " << j + 1 << "] is " << scal << ", but must be " << must_be << "!"; throw std::domain_error(ss.str()); } } } } template <typename F, typename T, typename... Indexings, require_std_vector_t<T>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { for (size_t j = 0; j < x.size(); j++) { elementwise_check(is_good, function, name, x[j], must_be, indexings..., "[", j, "]"); } } template <typename F, typename T, typename... Indexings, require_var_matrix_t<T>* = nullptr> inline void elementwise_check(const F& is_good, const char* function, const char* name, const T& x, const char* must_be, const Indexings... indexings) { elementwise_check(is_good, function, name, x.val(), must_be, indexings...); } /** * Check that the predicate holds for the value of `x`, working elementwise on * containers. If `x` is a scalar, check the double underlying the scalar. If * `x` is a container, check each element inside `x`, recursively. * @tparam F type of predicate * @tparam T type of `x` * @param is_good predicate to check, must accept doubles and produce bools * @param x variable to check, can be a scalar, a container of scalars, a * container of containers of scalars, etc * @return `false` if any of the scalars fail the error check */ template <typename F, typename T> inline bool elementwise_is(const F& is_good, const T& x) { return internal::Iser<F>{is_good}.is(x); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include "BAVersusScreen.h" #include "BAGlobal.h" #include "ABGeometry.h" #include "BACharAssets.h" #include "BAGameAssets.h" #define VSSCREEN_MILLIS_SINCE(MILLIS) (float)(millis() - MILLIS) #define VSSCREEN_ANIMATIONTIME 500.0f BAGamesCommand showVersusScreenWithPlayerAndEnemy(BACharacterData player, BACharacterData enemy){ // store info unsigned long startTime = millis(); int player1AppearAfter = 100; int player2AppearAfter = 300; // Show player rect ABRect startRect = ABRectMake(-48,0,48,64); ABRect endRect = ABRectMake(167,0,32,64); //VS Rect int vsAppearsAfter = 600; ABRect vsRectStart = ABRectMake(0,-32,128,128); ABRect vsRectEnd = ABRectMake(64,32, 1,1); // main loop while(true){ if (!arduboy.nextFrame()) continue; arduboy.clear(); // update input globalInput.updateInput(); // get time unsigned int deltatime = VSSCREEN_MILLIS_SINCE(startTime); // draw player 1 if (deltatime> player1AppearAfter){ arduboy.drawBitmap(12, 32, outlineAssetForCharacter(player.characterID), 32, 32, WHITE); arduboy.setCursor(12,10); arduboy.print(player.name); } // draw enemy if (deltatime> player2AppearAfter){ arduboy.drawBitmap(86, 32, outlineAssetForCharacter(enemy.characterID), 32, 32, WHITE); arduboy.setCursor(86,10); arduboy.print(enemy.name); } // Draw appear player rect // clac progress deltatime = deltatime%5000; // this repeats the animation every 5 seconds float progress = (float)deltatime/(float)VSSCREEN_ANIMATIONTIME; progress = (progress > 1.0f)?1.0f:progress; ABRect animationRect = animateRectToRect(startRect, endRect, progress); arduboy.fillRect(animationRect.origin.x, animationRect.origin.y, animationRect.size.width, animationRect.size.height, WHITE); // draw VS if (deltatime > vsAppearsAfter){ progress = (float)(deltatime - vsAppearsAfter)/300.0f; progress = (progress > 1.0f)?1.0f:progress; animationRect = animateRectToRect(vsRectStart, vsRectEnd, progress); arduboy.fillRect(animationRect.origin.x, animationRect.origin.y, animationRect.size.width, animationRect.size.height, WHITE); arduboy.drawBitmap(48, 16, BAGameAsset_VS, 32, 32, WHITE); } // Get Input if(globalInput.pressed(A_BUTTON)){ playSoundSuccess(); return BAGamesCommandNext; } if(globalInput.pressed(B_BUTTON)){ return BAGamesCommandBack; } arduboy.display(); } return BAGamesCommandErr; } <commit_msg>fixed button mapping on versus screen<commit_after>#include "BAVersusScreen.h" #include "BAGlobal.h" #include "ABGeometry.h" #include "BACharAssets.h" #include "BAGameAssets.h" #define VSSCREEN_MILLIS_SINCE(MILLIS) (float)(millis() - MILLIS) #define VSSCREEN_ANIMATIONTIME 500.0f BAGamesCommand showVersusScreenWithPlayerAndEnemy(BACharacterData player, BACharacterData enemy){ // store info unsigned long startTime = millis(); int player1AppearAfter = 100; int player2AppearAfter = 300; // Show player rect ABRect startRect = ABRectMake(-48,0,48,64); ABRect endRect = ABRectMake(167,0,32,64); //VS Rect int vsAppearsAfter = 600; ABRect vsRectStart = ABRectMake(0,-32,128,128); ABRect vsRectEnd = ABRectMake(64,32, 1,1); // main loop while(true){ if (!arduboy.nextFrame()) continue; arduboy.clear(); // update input globalInput.updateInput(); // get time unsigned int deltatime = VSSCREEN_MILLIS_SINCE(startTime); // draw player 1 if (deltatime> player1AppearAfter){ arduboy.drawBitmap(12, 32, outlineAssetForCharacter(player.characterID), 32, 32, WHITE); arduboy.setCursor(12,10); arduboy.print(player.name); } // draw enemy if (deltatime> player2AppearAfter){ arduboy.drawBitmap(86, 32, outlineAssetForCharacter(enemy.characterID), 32, 32, WHITE); arduboy.setCursor(86,10); arduboy.print(enemy.name); } // Draw appear player rect // clac progress deltatime = deltatime%5000; // this repeats the animation every 5 seconds float progress = (float)deltatime/(float)VSSCREEN_ANIMATIONTIME; progress = (progress > 1.0f)?1.0f:progress; ABRect animationRect = animateRectToRect(startRect, endRect, progress); arduboy.fillRect(animationRect.origin.x, animationRect.origin.y, animationRect.size.width, animationRect.size.height, WHITE); // draw VS if (deltatime > vsAppearsAfter){ progress = (float)(deltatime - vsAppearsAfter)/300.0f; progress = (progress > 1.0f)?1.0f:progress; animationRect = animateRectToRect(vsRectStart, vsRectEnd, progress); arduboy.fillRect(animationRect.origin.x, animationRect.origin.y, animationRect.size.width, animationRect.size.height, WHITE); arduboy.drawBitmap(48, 16, BAGameAsset_VS, 32, 32, WHITE); } // Get Input if(globalInput.pressed(B_BUTTON)){ playSoundSuccess(); return BAGamesCommandNext; } if(globalInput.pressed(A_BUTTON)){ playSoundBack(); return BAGamesCommandBack; } arduboy.display(); } return BAGamesCommandErr; } <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "benchmark/benchmark.h" #include "experimental/ModelBuilder/MemRefUtils.h" #include "experimental/ModelBuilder/ModelBuilder.h" #include "experimental/ModelBuilder/ModelRunner.h" using namespace mlir; // NOLINT // Helper method to construct an affine map. static SmallVector<AffineMap, 3> makeColumnMajorMatmulMaps(ModelBuilder &mb) { AffineExpr m, n, k; bindDims(mb.getContext(), m, n, k); SmallVector<AffineMap, 3> results; results.push_back(AffineMap::get(3, 0, {k, n}, mb.getContext())); results.push_back(AffineMap::get(3, 0, {m, k}, mb.getContext())); results.push_back(AffineMap::get(3, 0, {n, m}, mb.getContext())); return results; } // Helper method to build a matrix-matrix column-major multiplication function // using the vector dialect and that runs ITERS times to amortize any calling // overhead. template <unsigned M, unsigned N, unsigned K, unsigned ITERS> void buildMatMat(ModelBuilder &mb, StringLiteral fn) { auto f32 = mb.f32; auto mkVectorType = mb.getVectorType({M, K}, f32); auto typeA = mb.getMemRefType({}, mkVectorType); auto knVectorType = mb.getVectorType({K, N}, f32); auto typeB = mb.getMemRefType({}, knVectorType); auto mnVectorType = mb.getVectorType({M, N}, f32); auto typeC = mb.getMemRefType({}, mnVectorType); auto f = mb.makeFunction( fn, {}, {typeA, typeB, typeC}, MLIRFuncOpConfig().setEmitCInterface(true).setPreferAvx512(true)); OpBuilder b(&f.getBody()); ScopedContext scope(b, f.getLoc()); // Build the following accesses: // affine_map<(m, n, k) -> (k, m)>, // affine_map<(m, n, k) -> (n, k)>, // affine_map<(m, n, k) -> (n, m)> SmallVector<AffineMap, 4> accesses = makeColumnMajorMatmulMaps(mb); // Build the following iterator types: // iterator_types = ["parallel", "parallel", "reduction"] SmallVector<Attribute, 4> iterator_types; iterator_types.push_back(mb.getStringAttr("parallel")); iterator_types.push_back(mb.getStringAttr("parallel")); iterator_types.push_back(mb.getStringAttr("reduction")); // Loop ITERS times over the kernel to reduce the JIT's overhead. StdIndexedValue A(f.getArgument(0)), B(f.getArgument(1)), C(f.getArgument(2)); loopNestBuilder(std_constant_index(0), std_constant_index(ITERS), std_constant_index(1), [&](Value) { // Compute C += A x B, in column-major form, with LLVM // matrix intrinsics. C() = (vector_contract(A(), B(), C(), mb.getAffineMapArrayAttr(accesses), mb.getArrayAttr(iterator_types))); }); std_ret(); } // Benchmark method. template <unsigned M, unsigned N, unsigned K, bool MeasureBuild, bool LowerToLLVMMatrixIntrinsics> void BM_MxMColMajorVectors(benchmark::State &state) { constexpr unsigned NumMxMPerIteration = 1000; state.counters["NumMxM/Iter"] = NumMxMPerIteration; // Column major vector types. using TypeLHS = Vector2D<K, M, float>; using TypeRHS = Vector2D<N, K, float>; using TypeRES = Vector2D<N, M, float>; // Prepare arguments beforehand. auto oneInit = [](unsigned idx, TypeLHS *ptr) { float *p = reinterpret_cast<float *>(ptr + idx); for (unsigned i = 0; i < M * N; ++i) p[i] = 1.0f; }; auto incInit = [](unsigned idx, TypeRHS *ptr) { float *p = reinterpret_cast<float *>(ptr + idx); for (unsigned i = 0; i < M * N; ++i) p[i] = 1.0f + i; }; auto zeroInit = [](unsigned idx, TypeRES *ptr) { float *p = reinterpret_cast<float *>(ptr + idx); for (unsigned i = 0; i < M * N; ++i) p[i] = 0.0f; }; auto A = makeInitializedStridedMemRefDescriptor<TypeLHS, 1>({1}, oneInit); auto B = makeInitializedStridedMemRefDescriptor<TypeRHS, 1>({1}, incInit); auto C = makeInitializedStridedMemRefDescriptor<TypeRES, 1>({1}, zeroInit); StringLiteral funcName = "matmult_column_major"; vector::VectorTransformsOptions vectorTransformsOptions{ LowerToLLVMMatrixIntrinsics ? vector::VectorContractLowering::Matmul : vector::VectorContractLowering::FMA}; CompilationOptions compilationOptions{/*llvmOptLevel=*/3, /*llcOptLevel=*/3, vectorTransformsOptions}; if (MeasureBuild) { // If this is a build-time benchmark, build, compile, and execute // the function inside the timed loop, building a fresh new function // in each iteration to get the full JIT time (keep I == 1 here). for (auto _ : state) { ModelBuilder builder; buildMatMat<M, N, K, 1>(builder, funcName); ModelRunner runner(builder.getModuleRef()); runner.compile(compilationOptions); auto err = runner.invoke(funcName, A, B, C); if (err) llvm_unreachable("Error compiling/running function."); } } else { // If this is a run-time benchmark, build, compile, and execute // the function once outside the timed loop, then continue running // the same function inside the loop to focus on actual runtime // (set I == NumIterations here to amortize calling overhead). ModelBuilder builder; buildMatMat<M, N, K, NumMxMPerIteration>(builder, funcName); ModelRunner runner(builder.getModuleRef()); runner.compile(compilationOptions); auto err = runner.invoke(funcName, A, B, C); if (err) llvm_unreachable("Error compiling/running function."); for (auto _ : state) { auto err_run = runner.invoke(funcName, A, B, C); if (err_run) llvm_unreachable("Error running function."); } } } // // Benchmark drivers (build). // #define BENCHMARK_MATMUL_COLUMN_MAJOR(SZ_M, SZ_N, SZ_K) \ BENCHMARK_TEMPLATE(BM_MxMColMajorVectors, SZ_M, SZ_N, SZ_K, true, false); \ BENCHMARK_TEMPLATE(BM_MxMColMajorVectors, SZ_M, SZ_N, SZ_K, true, true); \ BENCHMARK_TEMPLATE(BM_MxMColMajorVectors, SZ_M, SZ_N, SZ_K, false, false); \ BENCHMARK_TEMPLATE(BM_MxMColMajorVectors, SZ_M, SZ_N, SZ_K, false, true); BENCHMARK_MATMUL_COLUMN_MAJOR(1, 1, 1); BENCHMARK_MATMUL_COLUMN_MAJOR(2, 2, 2); BENCHMARK_MATMUL_COLUMN_MAJOR(4, 4, 4); BENCHMARK_MATMUL_COLUMN_MAJOR(8, 8, 8); BENCHMARK_MATMUL_COLUMN_MAJOR(16, 16, 16); <commit_msg>Update Model builder benchmark to match MLIR changes.<commit_after>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "benchmark/benchmark.h" #include "experimental/ModelBuilder/MemRefUtils.h" #include "experimental/ModelBuilder/ModelBuilder.h" #include "experimental/ModelBuilder/ModelRunner.h" using namespace mlir; // NOLINT // Helper method to construct an affine map. static SmallVector<AffineMap, 3> makeColumnMajorMatmulMaps(ModelBuilder &mb) { AffineExpr m, n, k; bindDims(mb.getContext(), m, n, k); SmallVector<AffineMap, 3> results; results.push_back(AffineMap::get(3, 0, {k, n}, mb.getContext())); results.push_back(AffineMap::get(3, 0, {m, k}, mb.getContext())); results.push_back(AffineMap::get(3, 0, {n, m}, mb.getContext())); return results; } // Helper method to build a matrix-matrix column-major multiplication function // using the vector dialect and that runs ITERS times to amortize any calling // overhead. template <unsigned M, unsigned N, unsigned K, unsigned ITERS> void buildMatMat(ModelBuilder &mb, StringLiteral fn) { auto f32 = mb.f32; auto mkVectorType = mb.getVectorType({M, K}, f32); auto typeA = mb.getMemRefType({}, mkVectorType); auto knVectorType = mb.getVectorType({K, N}, f32); auto typeB = mb.getMemRefType({}, knVectorType); auto mnVectorType = mb.getVectorType({M, N}, f32); auto typeC = mb.getMemRefType({}, mnVectorType); auto f = mb.makeFunction( fn, {}, {typeA, typeB, typeC}, MLIRFuncOpConfig().setEmitCInterface(true).setPreferAvx512(true)); OpBuilder b(&f.getBody()); ScopedContext scope(b, f.getLoc()); // Build the following accesses: // affine_map<(m, n, k) -> (k, m)>, // affine_map<(m, n, k) -> (n, k)>, // affine_map<(m, n, k) -> (n, m)> SmallVector<AffineMap, 4> accesses = makeColumnMajorMatmulMaps(mb); // Build the following iterator types: // iterator_types = ["parallel", "parallel", "reduction"] SmallVector<Attribute, 4> iterator_types; iterator_types.push_back(mb.getStringAttr("parallel")); iterator_types.push_back(mb.getStringAttr("parallel")); iterator_types.push_back(mb.getStringAttr("reduction")); // Loop ITERS times over the kernel to reduce the JIT's overhead. StdIndexedValue A(f.getArgument(0)), B(f.getArgument(1)), C(f.getArgument(2)); loopNestBuilder(std_constant_index(0), std_constant_index(ITERS), std_constant_index(1), [&](Value) { // Compute C += A x B, in column-major form, with LLVM // matrix intrinsics. C() = (vector_contract(A(), B(), C(), mb.getAffineMapArrayAttr(accesses), mb.getArrayAttr(iterator_types))); }); std_ret(); } // Benchmark method. template <unsigned M, unsigned N, unsigned K, bool MeasureBuild, bool LowerToLLVMMatrixIntrinsics> void BM_MxMColMajorVectors(benchmark::State &state) { constexpr unsigned NumMxMPerIteration = 1000; state.counters["NumMxM/Iter"] = NumMxMPerIteration; // Column major vector types. using TypeLHS = Vector2D<K, M, float>; using TypeRHS = Vector2D<N, K, float>; using TypeRES = Vector2D<N, M, float>; // Prepare arguments beforehand. auto oneInit = [](unsigned idx, TypeLHS *ptr) { float *p = reinterpret_cast<float *>(ptr + idx); for (unsigned i = 0; i < M * N; ++i) p[i] = 1.0f; }; auto incInit = [](unsigned idx, TypeRHS *ptr) { float *p = reinterpret_cast<float *>(ptr + idx); for (unsigned i = 0; i < M * N; ++i) p[i] = 1.0f + i; }; auto zeroInit = [](unsigned idx, TypeRES *ptr) { float *p = reinterpret_cast<float *>(ptr + idx); for (unsigned i = 0; i < M * N; ++i) p[i] = 0.0f; }; auto A = makeInitializedStridedMemRefDescriptor<TypeLHS, 1>({1}, oneInit); auto B = makeInitializedStridedMemRefDescriptor<TypeRHS, 1>({1}, incInit); auto C = makeInitializedStridedMemRefDescriptor<TypeRES, 1>({1}, zeroInit); StringLiteral funcName = "matmult_column_major"; vector::VectorTransformsOptions vectorTransformsOptions{ LowerToLLVMMatrixIntrinsics ? vector::VectorContractLowering::Matmul : vector::VectorContractLowering::Dot}; CompilationOptions compilationOptions{/*llvmOptLevel=*/3, /*llcOptLevel=*/3, vectorTransformsOptions}; if (MeasureBuild) { // If this is a build-time benchmark, build, compile, and execute // the function inside the timed loop, building a fresh new function // in each iteration to get the full JIT time (keep I == 1 here). for (auto _ : state) { ModelBuilder builder; buildMatMat<M, N, K, 1>(builder, funcName); ModelRunner runner(builder.getModuleRef()); runner.compile(compilationOptions); auto err = runner.invoke(funcName, A, B, C); if (err) llvm_unreachable("Error compiling/running function."); } } else { // If this is a run-time benchmark, build, compile, and execute // the function once outside the timed loop, then continue running // the same function inside the loop to focus on actual runtime // (set I == NumIterations here to amortize calling overhead). ModelBuilder builder; buildMatMat<M, N, K, NumMxMPerIteration>(builder, funcName); ModelRunner runner(builder.getModuleRef()); runner.compile(compilationOptions); auto err = runner.invoke(funcName, A, B, C); if (err) llvm_unreachable("Error compiling/running function."); for (auto _ : state) { auto err_run = runner.invoke(funcName, A, B, C); if (err_run) llvm_unreachable("Error running function."); } } } // // Benchmark drivers (build). // #define BENCHMARK_MATMUL_COLUMN_MAJOR(SZ_M, SZ_N, SZ_K) \ BENCHMARK_TEMPLATE(BM_MxMColMajorVectors, SZ_M, SZ_N, SZ_K, true, false); \ BENCHMARK_TEMPLATE(BM_MxMColMajorVectors, SZ_M, SZ_N, SZ_K, true, true); \ BENCHMARK_TEMPLATE(BM_MxMColMajorVectors, SZ_M, SZ_N, SZ_K, false, false); \ BENCHMARK_TEMPLATE(BM_MxMColMajorVectors, SZ_M, SZ_N, SZ_K, false, true); BENCHMARK_MATMUL_COLUMN_MAJOR(1, 1, 1); BENCHMARK_MATMUL_COLUMN_MAJOR(2, 2, 2); BENCHMARK_MATMUL_COLUMN_MAJOR(4, 4, 4); BENCHMARK_MATMUL_COLUMN_MAJOR(8, 8, 8); BENCHMARK_MATMUL_COLUMN_MAJOR(16, 16, 16); <|endoftext|>
<commit_before>#include "CVolumeSceneObject.h" #include <ionWindow.h> #include "CProgramContext.h" CVolumeSceneObject::SControl::SControl() : Mode(0), SliceAxis(1.f, 0.f, 0.f), LocalRange(0.2f), MinimumAlpha(0.1f), EmphasisLocation(0.5f), AlphaIntensity(1.f), StepSize(100.f), DebugLevel(0), UseShading(0) {} CVolumeSceneObject::CVolumeSceneObject() : Cube(0), Shader(0), SceneManager(CApplication::Get().GetSceneManager()) { setCullingEnabled(false); // Setup volume cube Cube = new CMesh(); CMesh::SMeshBuffer * Mesh = new CMesh::SMeshBuffer(); Mesh->Vertices.resize(24); Mesh->Vertices[0].Position = SVector3f(-0.5, -0.5, -0.5); Mesh->Vertices[1].Position = SVector3f(-0.5, 0.5, -0.5); Mesh->Vertices[2].Position = SVector3f( 0.5, 0.5, -0.5); Mesh->Vertices[3].Position = SVector3f( 0.5, -0.5, -0.5); Mesh->Vertices[0].Color = SColorf(0, 0, 0); Mesh->Vertices[1].Color = SColorf(0, 1, 0); Mesh->Vertices[2].Color = SColorf(1, 1, 0); Mesh->Vertices[3].Color = SColorf(1, 0, 0); Mesh->Vertices[4].Position = SVector3f( 0.5, -0.5, -0.5); Mesh->Vertices[5].Position = SVector3f( 0.5, 0.5, -0.5); Mesh->Vertices[6].Position = SVector3f( 0.5, 0.5, 0.5); Mesh->Vertices[7].Position = SVector3f( 0.5, -0.5, 0.5); Mesh->Vertices[4].Color = SColorf(1, 0, 0); Mesh->Vertices[5].Color = SColorf(1, 1, 0); Mesh->Vertices[6].Color = SColorf(1, 1, 1); Mesh->Vertices[7].Color = SColorf(1, 0, 1); Mesh->Vertices[8].Position = SVector3f( 0.5, -0.5, 0.5); Mesh->Vertices[9].Position = SVector3f( 0.5, 0.5, 0.5); Mesh->Vertices[10].Position = SVector3f(-0.5, 0.5, 0.5); Mesh->Vertices[11].Position = SVector3f(-0.5, -0.5, 0.5); Mesh->Vertices[8].Color = SColorf(1, 0, 1); Mesh->Vertices[9].Color = SColorf(1, 1, 1); Mesh->Vertices[10].Color = SColorf(0, 1, 1); Mesh->Vertices[11].Color = SColorf(0, 0, 1); Mesh->Vertices[12].Position = SVector3f(-0.5, -0.5, 0.5); Mesh->Vertices[13].Position = SVector3f(-0.5, 0.5, 0.5); Mesh->Vertices[14].Position = SVector3f(-0.5, 0.5, -0.5); Mesh->Vertices[15].Position = SVector3f(-0.5, -0.5, -0.5); Mesh->Vertices[12].Color = SColorf(0, 0, 1); Mesh->Vertices[13].Color = SColorf(0, 1, 1); Mesh->Vertices[14].Color = SColorf(0, 1, 0); Mesh->Vertices[15].Color = SColorf(0, 0, 0); Mesh->Vertices[16].Position = SVector3f(-0.5, 0.5, -0.5); Mesh->Vertices[17].Position = SVector3f(-0.5, 0.5, 0.5); Mesh->Vertices[18].Position = SVector3f( 0.5, 0.5, 0.5); Mesh->Vertices[19].Position = SVector3f( 0.5, 0.5, -0.5); Mesh->Vertices[16].Color = SColorf(0, 1, 0); Mesh->Vertices[17].Color = SColorf(0, 1, 1); Mesh->Vertices[18].Color = SColorf(1, 1, 1); Mesh->Vertices[19].Color = SColorf(1, 1, 0); Mesh->Vertices[20].Position = SVector3f( 0.5, -0.5, -0.5); Mesh->Vertices[21].Position = SVector3f( 0.5, -0.5, 0.5); Mesh->Vertices[22].Position = SVector3f(-0.5, -0.5, 0.5); Mesh->Vertices[23].Position = SVector3f(-0.5, -0.5, -0.5); Mesh->Vertices[20].Color = SColorf(1, 0, 0); Mesh->Vertices[21].Color = SColorf(1, 0, 1); Mesh->Vertices[22].Color = SColorf(0, 0, 1); Mesh->Vertices[23].Color = SColorf(0, 0, 0); Mesh->Triangles.resize(12); for (int i = 0; i < 6; ++ i) { Mesh->Vertices[4*i + 0].TextureCoordinates = SVector2f(0, 1); Mesh->Vertices[4*i + 1].TextureCoordinates = SVector2f(0, 0); Mesh->Vertices[4*i + 2].TextureCoordinates = SVector2f(1, 0); Mesh->Vertices[4*i + 3].TextureCoordinates = SVector2f(1, 1); Mesh->Triangles[2*i].Indices[0] = 4*i + 0; Mesh->Triangles[2*i].Indices[1] = 4*i + 1; Mesh->Triangles[2*i].Indices[2] = 4*i + 2; Mesh->Triangles[2*i+1].Indices[0] = 4*i + 0; Mesh->Triangles[2*i+1].Indices[1] = 4*i + 2; Mesh->Triangles[2*i+1].Indices[2] = 4*i + 3; } Cube->MeshBuffers.push_back(Mesh); Cube->calculateNormalsPerFace(); Cube->updateBuffers(); Shader = CProgramContext::Get().Shaders.Volume; } bool CVolumeSceneObject::draw(IScene const * const Scene, sharedPtr<IRenderPass> Pass, bool const CullingEnabled) { if (! ISceneObject::draw(Scene, Pass, CullingEnabled)) return false; // Check data syncing if (Cube->MeshBuffers[0]->PositionBuffer.isDirty()) Cube->MeshBuffers[0]->PositionBuffer.syncData(); if (Cube->MeshBuffers[0]->ColorBuffer.isDirty()) Cube->MeshBuffers[0]->ColorBuffer.syncData(); if (Cube->MeshBuffers[0]->IndexBuffer.isDirty()) Cube->MeshBuffers[0]->IndexBuffer.syncData(); glEnable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glCullFace(GL_BACK); { if (Shader) { CShaderContext Context(* Shader); // Attributes Context.bindBufferObject("aColor", Cube->MeshBuffers[0]->ColorBuffer.getHandle(), 3); Context.bindBufferObject("aPosition", Cube->MeshBuffers[0]->PositionBuffer.getHandle(), 3); Context.bindIndexBufferObject(Cube->MeshBuffers[0]->IndexBuffer.getHandle()); // Matrices Context.uniform("uModelMatrix", Transformation.getGLMMat4()); Context.uniform("uInvModelMatrix", glm::inverse(Transformation.getGLMMat4())); Context.uniform("uProjMatrix", SceneManager.getActiveCamera()->GetProjectionMatrix()); Context.uniform("uViewMatrix", SceneManager.getActiveCamera()->GetViewMatrix()); // Volume texture glEnable(GL_TEXTURE_3D); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_3D, VolumeHandle); Context.uniform("uVolumeData", 0); // Scene depth glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, CApplication::Get().GetSceneManager().getSceneDepthTexture()->getTextureHandle()); Context.uniform("uDepthTexture", 1); // Control parameters Context.uniform("uAlphaIntensity", Control.AlphaIntensity); Context.uniform("uHighlightMode", Control.Mode); Context.uniform("uSliceAxis", Control.SliceAxis); Context.uniform("uLocalRange", Control.LocalRange); Context.uniform("uMinimumAlpha", Control.MinimumAlpha); Context.uniform("uEmphasisLocation", Control.EmphasisLocation); Context.uniform("uStepSize", 1.f / Control.StepSize); Context.uniform("uDebugLevel", Control.DebugLevel); Context.uniform("uUseShading", Control.UseShading); // Camera position for determining front face Context.uniform("uCameraPosition", SceneManager.getActiveCamera()->getPosition()); if (Control.UseShading != 1) Context.uniform("uLightPosition", SceneManager.getActiveCamera()->getPosition()); else Context.uniform("uLightPosition", CProgramContext::Get().Scene.OrbitCamera->getPosition()); // Transparency glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Draw glDrawElements(GL_TRIANGLES, Cube->MeshBuffers[0]->IndexBuffer.getElements().size(), GL_UNSIGNED_INT, 0); // Unbind textures glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_3D, 0); // OpenGL state glDisable(GL_BLEND); glDisable(GL_TEXTURE_3D); glDisable(GL_TEXTURE_2D); } } glDisable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); return true; } <commit_msg>+ Made volume back/front face culling more robust<commit_after>#include "CVolumeSceneObject.h" #include <ionWindow.h> #include "CProgramContext.h" CVolumeSceneObject::SControl::SControl() : Mode(0), SliceAxis(1.f, 0.f, 0.f), LocalRange(0.2f), MinimumAlpha(0.1f), EmphasisLocation(0.5f), AlphaIntensity(1.f), StepSize(100.f), DebugLevel(0), UseShading(0) {} CVolumeSceneObject::CVolumeSceneObject() : Cube(0), Shader(0), SceneManager(CApplication::Get().GetSceneManager()) { setCullingEnabled(false); // Setup volume cube Cube = new CMesh(); CMesh::SMeshBuffer * Mesh = new CMesh::SMeshBuffer(); Mesh->Vertices.resize(24); Mesh->Vertices[0].Position = SVector3f(-0.5, -0.5, -0.5); Mesh->Vertices[1].Position = SVector3f(-0.5, 0.5, -0.5); Mesh->Vertices[2].Position = SVector3f( 0.5, 0.5, -0.5); Mesh->Vertices[3].Position = SVector3f( 0.5, -0.5, -0.5); Mesh->Vertices[0].Color = SColorf(0, 0, 0); Mesh->Vertices[1].Color = SColorf(0, 1, 0); Mesh->Vertices[2].Color = SColorf(1, 1, 0); Mesh->Vertices[3].Color = SColorf(1, 0, 0); Mesh->Vertices[4].Position = SVector3f( 0.5, -0.5, -0.5); Mesh->Vertices[5].Position = SVector3f( 0.5, 0.5, -0.5); Mesh->Vertices[6].Position = SVector3f( 0.5, 0.5, 0.5); Mesh->Vertices[7].Position = SVector3f( 0.5, -0.5, 0.5); Mesh->Vertices[4].Color = SColorf(1, 0, 0); Mesh->Vertices[5].Color = SColorf(1, 1, 0); Mesh->Vertices[6].Color = SColorf(1, 1, 1); Mesh->Vertices[7].Color = SColorf(1, 0, 1); Mesh->Vertices[8].Position = SVector3f( 0.5, -0.5, 0.5); Mesh->Vertices[9].Position = SVector3f( 0.5, 0.5, 0.5); Mesh->Vertices[10].Position = SVector3f(-0.5, 0.5, 0.5); Mesh->Vertices[11].Position = SVector3f(-0.5, -0.5, 0.5); Mesh->Vertices[8].Color = SColorf(1, 0, 1); Mesh->Vertices[9].Color = SColorf(1, 1, 1); Mesh->Vertices[10].Color = SColorf(0, 1, 1); Mesh->Vertices[11].Color = SColorf(0, 0, 1); Mesh->Vertices[12].Position = SVector3f(-0.5, -0.5, 0.5); Mesh->Vertices[13].Position = SVector3f(-0.5, 0.5, 0.5); Mesh->Vertices[14].Position = SVector3f(-0.5, 0.5, -0.5); Mesh->Vertices[15].Position = SVector3f(-0.5, -0.5, -0.5); Mesh->Vertices[12].Color = SColorf(0, 0, 1); Mesh->Vertices[13].Color = SColorf(0, 1, 1); Mesh->Vertices[14].Color = SColorf(0, 1, 0); Mesh->Vertices[15].Color = SColorf(0, 0, 0); Mesh->Vertices[16].Position = SVector3f(-0.5, 0.5, -0.5); Mesh->Vertices[17].Position = SVector3f(-0.5, 0.5, 0.5); Mesh->Vertices[18].Position = SVector3f( 0.5, 0.5, 0.5); Mesh->Vertices[19].Position = SVector3f( 0.5, 0.5, -0.5); Mesh->Vertices[16].Color = SColorf(0, 1, 0); Mesh->Vertices[17].Color = SColorf(0, 1, 1); Mesh->Vertices[18].Color = SColorf(1, 1, 1); Mesh->Vertices[19].Color = SColorf(1, 1, 0); Mesh->Vertices[20].Position = SVector3f( 0.5, -0.5, -0.5); Mesh->Vertices[21].Position = SVector3f( 0.5, -0.5, 0.5); Mesh->Vertices[22].Position = SVector3f(-0.5, -0.5, 0.5); Mesh->Vertices[23].Position = SVector3f(-0.5, -0.5, -0.5); Mesh->Vertices[20].Color = SColorf(1, 0, 0); Mesh->Vertices[21].Color = SColorf(1, 0, 1); Mesh->Vertices[22].Color = SColorf(0, 0, 1); Mesh->Vertices[23].Color = SColorf(0, 0, 0); Mesh->Triangles.resize(12); for (int i = 0; i < 6; ++ i) { Mesh->Vertices[4*i + 0].TextureCoordinates = SVector2f(0, 1); Mesh->Vertices[4*i + 1].TextureCoordinates = SVector2f(0, 0); Mesh->Vertices[4*i + 2].TextureCoordinates = SVector2f(1, 0); Mesh->Vertices[4*i + 3].TextureCoordinates = SVector2f(1, 1); Mesh->Triangles[2*i].Indices[0] = 4*i + 0; Mesh->Triangles[2*i].Indices[1] = 4*i + 1; Mesh->Triangles[2*i].Indices[2] = 4*i + 2; Mesh->Triangles[2*i+1].Indices[0] = 4*i + 0; Mesh->Triangles[2*i+1].Indices[1] = 4*i + 2; Mesh->Triangles[2*i+1].Indices[2] = 4*i + 3; } Cube->MeshBuffers.push_back(Mesh); Cube->calculateNormalsPerFace(); Cube->updateBuffers(); Shader = CProgramContext::Get().Shaders.Volume; } bool CVolumeSceneObject::draw(IScene const * const Scene, sharedPtr<IRenderPass> Pass, bool const CullingEnabled) { if (! ISceneObject::draw(Scene, Pass, CullingEnabled)) return false; // Check data syncing if (Cube->MeshBuffers[0]->PositionBuffer.isDirty()) Cube->MeshBuffers[0]->PositionBuffer.syncData(); if (Cube->MeshBuffers[0]->ColorBuffer.isDirty()) Cube->MeshBuffers[0]->ColorBuffer.syncData(); if (Cube->MeshBuffers[0]->IndexBuffer.isDirty()) Cube->MeshBuffers[0]->IndexBuffer.syncData(); glEnable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); int Inversions = 0; if (Scale.X < 0) Inversions ++; if (Scale.Y < 0) Inversions ++; if (Scale.Z < 0) Inversions ++; if (Inversions % 2) glCullFace(GL_BACK); else glCullFace(GL_FRONT); { if (Shader) { CShaderContext Context(* Shader); // Attributes Context.bindBufferObject("aColor", Cube->MeshBuffers[0]->ColorBuffer.getHandle(), 3); Context.bindBufferObject("aPosition", Cube->MeshBuffers[0]->PositionBuffer.getHandle(), 3); Context.bindIndexBufferObject(Cube->MeshBuffers[0]->IndexBuffer.getHandle()); // Matrices Context.uniform("uModelMatrix", Transformation.getGLMMat4()); Context.uniform("uInvModelMatrix", glm::inverse(Transformation.getGLMMat4())); Context.uniform("uProjMatrix", SceneManager.getActiveCamera()->GetProjectionMatrix()); Context.uniform("uViewMatrix", SceneManager.getActiveCamera()->GetViewMatrix()); // Volume texture glEnable(GL_TEXTURE_3D); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_3D, VolumeHandle); Context.uniform("uVolumeData", 0); // Scene depth glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, CApplication::Get().GetSceneManager().getSceneDepthTexture()->getTextureHandle()); Context.uniform("uDepthTexture", 1); // Control parameters Context.uniform("uAlphaIntensity", Control.AlphaIntensity); Context.uniform("uHighlightMode", Control.Mode); Context.uniform("uSliceAxis", Control.SliceAxis); Context.uniform("uLocalRange", Control.LocalRange); Context.uniform("uMinimumAlpha", Control.MinimumAlpha); Context.uniform("uEmphasisLocation", Control.EmphasisLocation); Context.uniform("uStepSize", 1.f / Control.StepSize); Context.uniform("uDebugLevel", Control.DebugLevel); Context.uniform("uUseShading", Control.UseShading); // Camera position for determining front face Context.uniform("uCameraPosition", SceneManager.getActiveCamera()->getPosition()); if (Control.UseShading != 1) Context.uniform("uLightPosition", SceneManager.getActiveCamera()->getPosition()); else Context.uniform("uLightPosition", CProgramContext::Get().Scene.OrbitCamera->getPosition()); // Transparency glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Draw glDrawElements(GL_TRIANGLES, Cube->MeshBuffers[0]->IndexBuffer.getElements().size(), GL_UNSIGNED_INT, 0); // Unbind textures glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_3D, 0); // OpenGL state glDisable(GL_BLEND); glDisable(GL_TEXTURE_3D); glDisable(GL_TEXTURE_2D); } } glDisable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); return true; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuzoom.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: ihi $ $Date: 2007-11-26 14:35:33 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "fuzoom.hxx" #include <svx/svxids.hrc> #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef _SFXVIEWFRM_HXX #include <sfx2/viewfrm.hxx> #endif #include "app.hrc" #ifndef _SVDPAGV_HXX //autogen #include <svx/svdpagv.hxx> #endif #ifndef SD_FRAMW_VIEW_HXX #include "FrameView.hxx" #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif #include "drawdoc.hxx" #include "zoomlist.hxx" namespace sd { USHORT SidArrayZoom[] = { SID_ATTR_ZOOM, SID_ZOOM_OUT, SID_ZOOM_IN, 0 }; TYPEINIT1( FuZoom, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuZoom::FuZoom( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq), bVisible(FALSE), bStartDrag(FALSE) { } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuZoom::~FuZoom() { if (bVisible) { // Hide ZoomRect mpViewShell->DrawMarkRect(aZoomRect); bVisible = FALSE; bStartDrag = FALSE; } } FunctionReference FuZoom::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuZoom( pViewSh, pWin, pView, pDoc, rReq ) ); return xFunc; } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL FuZoom::MouseButtonDown(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); mpWindow->CaptureMouse(); bStartDrag = TRUE; aBeginPosPix = rMEvt.GetPosPixel(); aBeginPos = mpWindow->PixelToLogic(aBeginPosPix); return TRUE; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL FuZoom::MouseMove(const MouseEvent& rMEvt) { if (bStartDrag) { if (bVisible) { mpViewShell->DrawMarkRect(aZoomRect); } Point aPosPix = rMEvt.GetPosPixel(); ForceScroll(aPosPix); aEndPos = mpWindow->PixelToLogic(aPosPix); aBeginPos = mpWindow->PixelToLogic(aBeginPosPix); if (nSlotId == SID_ZOOM_PANNING) { // Panning Point aScroll = aBeginPos - aEndPos; // #i2237# // removed old stuff here which still forced zoom to be // %BRUSH_SIZE which is outdated now if (aScroll.X() != 0 || aScroll.Y() != 0) { Size aWorkSize = mpView->GetWorkArea().GetSize(); Size aPageSize = mpView->GetSdrPageView()->GetPage()->GetSize(); aScroll.X() /= aWorkSize.Width() / aPageSize.Width(); aScroll.Y() /= aWorkSize.Height() / aPageSize.Height(); mpViewShell->Scroll(aScroll.X(), aScroll.Y()); aBeginPosPix = aPosPix; } } else { Rectangle aRect(aBeginPos, aEndPos); aZoomRect = aRect; aZoomRect.Justify(); mpViewShell->DrawMarkRect(aZoomRect); } bVisible = TRUE; } return bStartDrag; } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL FuZoom::MouseButtonUp(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); if (bVisible) { // Hide ZoomRect mpViewShell->DrawMarkRect(aZoomRect); bVisible = FALSE; } Point aPosPix = rMEvt.GetPosPixel(); if(SID_ZOOM_PANNING != nSlotId) { // Zoom Size aZoomSizePixel = mpWindow->LogicToPixel(aZoomRect).GetSize(); ULONG nTol = DRGPIX + DRGPIX; if ( aZoomSizePixel.Width() < (long) nTol && aZoomSizePixel.Height() < (long) nTol ) { // Klick auf der Stelle: Zoomfaktor verdoppeln Point aPos = mpWindow->PixelToLogic(aPosPix); Size aSize = mpWindow->PixelToLogic(mpWindow->GetOutputSizePixel()); aSize.Width() /= 2; aSize.Height() /= 2; aPos.X() -= aSize.Width() / 2; aPos.Y() -= aSize.Height() / 2; aZoomRect.SetPos(aPos); aZoomRect.SetSize(aSize); } mpViewShell->SetZoomRect(aZoomRect); } Rectangle aVisAreaWin = mpWindow->PixelToLogic(Rectangle(Point(0,0), mpWindow->GetOutputSizePixel())); mpViewShell->GetZoomList()->InsertZoomRect(aVisAreaWin); bStartDrag = FALSE; mpWindow->ReleaseMouse(); mpViewShell->Cancel(); return TRUE; } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuZoom::Activate() { aPtr = mpWindow->GetPointer(); if (nSlotId == SID_ZOOM_PANNING) { mpWindow->SetPointer(Pointer(POINTER_HAND)); } else { mpWindow->SetPointer(Pointer(POINTER_MAGNIFY)); } } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuZoom::Deactivate() { mpWindow->SetPointer( aPtr ); mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArrayZoom ); } } // end of namespace sd <commit_msg>INTEGRATION: CWS changefileheader (1.12.100); FILE MERGED 2008/04/01 15:34:55 thb 1.12.100.3: #i85898# Stripping all external header guards 2008/04/01 12:38:58 thb 1.12.100.2: #i85898# Stripping all external header guards 2008/03/31 13:58:07 rt 1.12.100.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuzoom.cxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "fuzoom.hxx" #include <svx/svxids.hrc> #include <sfx2/bindings.hxx> #include <sfx2/viewfrm.hxx> #include "app.hrc" #include <svx/svdpagv.hxx> #ifndef SD_FRAMW_VIEW_HXX #include "FrameView.hxx" #endif #include "ViewShell.hxx" #include "View.hxx" #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif #include "drawdoc.hxx" #include "zoomlist.hxx" namespace sd { USHORT SidArrayZoom[] = { SID_ATTR_ZOOM, SID_ZOOM_OUT, SID_ZOOM_IN, 0 }; TYPEINIT1( FuZoom, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuZoom::FuZoom( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq), bVisible(FALSE), bStartDrag(FALSE) { } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuZoom::~FuZoom() { if (bVisible) { // Hide ZoomRect mpViewShell->DrawMarkRect(aZoomRect); bVisible = FALSE; bStartDrag = FALSE; } } FunctionReference FuZoom::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuZoom( pViewSh, pWin, pView, pDoc, rReq ) ); return xFunc; } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL FuZoom::MouseButtonDown(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); mpWindow->CaptureMouse(); bStartDrag = TRUE; aBeginPosPix = rMEvt.GetPosPixel(); aBeginPos = mpWindow->PixelToLogic(aBeginPosPix); return TRUE; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL FuZoom::MouseMove(const MouseEvent& rMEvt) { if (bStartDrag) { if (bVisible) { mpViewShell->DrawMarkRect(aZoomRect); } Point aPosPix = rMEvt.GetPosPixel(); ForceScroll(aPosPix); aEndPos = mpWindow->PixelToLogic(aPosPix); aBeginPos = mpWindow->PixelToLogic(aBeginPosPix); if (nSlotId == SID_ZOOM_PANNING) { // Panning Point aScroll = aBeginPos - aEndPos; // #i2237# // removed old stuff here which still forced zoom to be // %BRUSH_SIZE which is outdated now if (aScroll.X() != 0 || aScroll.Y() != 0) { Size aWorkSize = mpView->GetWorkArea().GetSize(); Size aPageSize = mpView->GetSdrPageView()->GetPage()->GetSize(); aScroll.X() /= aWorkSize.Width() / aPageSize.Width(); aScroll.Y() /= aWorkSize.Height() / aPageSize.Height(); mpViewShell->Scroll(aScroll.X(), aScroll.Y()); aBeginPosPix = aPosPix; } } else { Rectangle aRect(aBeginPos, aEndPos); aZoomRect = aRect; aZoomRect.Justify(); mpViewShell->DrawMarkRect(aZoomRect); } bVisible = TRUE; } return bStartDrag; } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL FuZoom::MouseButtonUp(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); if (bVisible) { // Hide ZoomRect mpViewShell->DrawMarkRect(aZoomRect); bVisible = FALSE; } Point aPosPix = rMEvt.GetPosPixel(); if(SID_ZOOM_PANNING != nSlotId) { // Zoom Size aZoomSizePixel = mpWindow->LogicToPixel(aZoomRect).GetSize(); ULONG nTol = DRGPIX + DRGPIX; if ( aZoomSizePixel.Width() < (long) nTol && aZoomSizePixel.Height() < (long) nTol ) { // Klick auf der Stelle: Zoomfaktor verdoppeln Point aPos = mpWindow->PixelToLogic(aPosPix); Size aSize = mpWindow->PixelToLogic(mpWindow->GetOutputSizePixel()); aSize.Width() /= 2; aSize.Height() /= 2; aPos.X() -= aSize.Width() / 2; aPos.Y() -= aSize.Height() / 2; aZoomRect.SetPos(aPos); aZoomRect.SetSize(aSize); } mpViewShell->SetZoomRect(aZoomRect); } Rectangle aVisAreaWin = mpWindow->PixelToLogic(Rectangle(Point(0,0), mpWindow->GetOutputSizePixel())); mpViewShell->GetZoomList()->InsertZoomRect(aVisAreaWin); bStartDrag = FALSE; mpWindow->ReleaseMouse(); mpViewShell->Cancel(); return TRUE; } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuZoom::Activate() { aPtr = mpWindow->GetPointer(); if (nSlotId == SID_ZOOM_PANNING) { mpWindow->SetPointer(Pointer(POINTER_HAND)); } else { mpWindow->SetPointer(Pointer(POINTER_MAGNIFY)); } } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuZoom::Deactivate() { mpWindow->SetPointer( aPtr ); mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArrayZoom ); } } // end of namespace sd <|endoftext|>
<commit_before>/** @file main.cc * * Driver file for testing LCC * * @author Nishant Mehta (niche) */ // example for running program via fx-run on no.cc.gatech.edu: // fx-run mnist_lcc /scratch/niche/fastlib-stl/build/bin/mnist_lcc --lambda=0.05, --data_dir=/scratch/niche/fastlib-stl/contrib/niche/discriminative_sparse_coding/mnist --digit1=4, --digit2=9, --n_iterations=1, --n_atoms=50, #include <fastlib/fastlib.h> #include <armadillo> #include "lcc.h" using namespace arma; using namespace std; int main(int argc, char* argv[]) { fx_module* root = fx_init(argc, argv, NULL); double lambda = fx_param_double_req(NULL, "lambda"); // if using fx-run, one could just leave results_dir blank const char* results_dir = fx_param_str(NULL, "results_dir", ""); const char* data_dir = fx_param_str_req(NULL, "data_dir"); const char* initial_dictionary_fullpath = fx_param_str(NULL, "initial_dictionary", ""); u32 digit_1 = fx_param_int_req(NULL, "digit1"); u32 digit_2 = fx_param_int_req(NULL, "digit2"); u32 n_iterations = fx_param_int_req(NULL, "n_iterations"); u32 n_atoms = fx_param_int_req(NULL, "n_atoms"); // Load Data char* data_filename = (char*) malloc(320 * sizeof(char)); sprintf(data_filename, "%s/train%d.arm", data_dir, digit_1); mat X_neg; X_neg.load(data_filename); u32 n_neg_points = X_neg.n_cols; sprintf(data_filename, "%s/train%d.arm", data_dir, digit_2); mat X_pos; X_pos.load(data_filename); u32 n_pos_points = X_pos.n_cols; free(data_filename); mat X = join_rows(X_neg, X_pos); u32 n_points = X.n_cols; // normalize each column of data for(u32 i = 0; i < n_points; i++) { X.col(i) /= norm(X.col(i), 2); } // create a labels vector, NOT so that we can use it for LCC, but so we can save the labels for easy discriminative training upon exit of this program vec y = vec(n_points); y.subvec(0, n_neg_points - 1).fill(-1); y.subvec(n_neg_points, n_points - 1).fill(1); // run LCC LocalCoordinateCoding lcc; lcc.Init(X, n_atoms, lambda); if(strlen(initial_dictionary_fullpath) == 0) { lcc.DataDependentRandomInitDictionary(); } else { mat initial_D; initial_D.load(initial_dictionary_fullpath); if(initial_D.n_cols != n_atoms) { fprintf(stderr, "Error: The specified initial dictionary to load has %d atoms, but the learned dictionary was specified to have %d atoms! Exiting..\n", initial_D.n_cols, n_atoms); return EXIT_FAILURE; } if(initial_D.n_rows != X.n_rows) { fprintf(stderr, "Error: The specified initial dictionary to load has %d dimensions, but the specified data has %d dimensions! Exiting..\n", initial_D.n_rows, X.n_rows); return EXIT_FAILURE; } lcc.SetDictionary(initial_D); } wall_clock timer; timer.tic(); lcc.DoLCC(n_iterations); double n_secs = timer.toc(); cout << "took " << n_secs << " seconds" << endl; mat learned_D; lcc.GetDictionary(learned_D); mat learned_V; lcc.GetCoding(learned_V); if(strlen(results_dir) == 0) { learned_D.save("D.dat", raw_ascii); learned_V.save("V.dat", raw_ascii); y.save("y.dat", raw_ascii); } else { char* data_fullpath = (char*) malloc(320 * sizeof(char)); sprintf(data_fullpath, "%s/D.dat", results_dir); learned_D.save(data_fullpath, raw_ascii); sprintf(data_fullpath, "%s/V.dat", results_dir); learned_V.save(data_fullpath, raw_ascii); sprintf(data_fullpath, "%s/y.dat", results_dir); y.save(data_fullpath, raw_ascii); free(data_fullpath); } fx_done(root); } <commit_msg>switched two usages of fx_param_int_req to fx_param_double_req since the latter allows the use of scientific notation<commit_after>/** @file main.cc * * Driver file for testing LCC * * @author Nishant Mehta (niche) */ // example for running program via fx-run on no.cc.gatech.edu: // fx-run mnist_lcc /scratch/niche/fastlib-stl/build/bin/mnist_lcc --lambda=0.05, --data_dir=/scratch/niche/fastlib-stl/contrib/niche/discriminative_sparse_coding/mnist --digit1=4, --digit2=9, --n_iterations=1, --n_atoms=50, #include <fastlib/fastlib.h> #include <armadillo> #include "lcc.h" using namespace arma; using namespace std; int main(int argc, char* argv[]) { fx_module* root = fx_init(argc, argv, NULL); double lambda = fx_param_double_req(NULL, "lambda"); // if using fx-run, one could just leave results_dir blank const char* results_dir = fx_param_str(NULL, "results_dir", ""); const char* data_dir = fx_param_str_req(NULL, "data_dir"); const char* initial_dictionary_fullpath = fx_param_str(NULL, "initial_dictionary", ""); u32 digit_1 = fx_param_int_req(NULL, "digit1"); u32 digit_2 = fx_param_int_req(NULL, "digit2"); u32 n_iterations = (u32) fx_param_double_req(NULL, "n_iterations"); u32 n_atoms = (u32) fx_param_double_req(NULL, "n_atoms"); // Load Data char* data_filename = (char*) malloc(320 * sizeof(char)); sprintf(data_filename, "%s/train%d.arm", data_dir, digit_1); mat X_neg; X_neg.load(data_filename); u32 n_neg_points = X_neg.n_cols; sprintf(data_filename, "%s/train%d.arm", data_dir, digit_2); mat X_pos; X_pos.load(data_filename); u32 n_pos_points = X_pos.n_cols; free(data_filename); mat X = join_rows(X_neg, X_pos); u32 n_points = X.n_cols; // normalize each column of data for(u32 i = 0; i < n_points; i++) { X.col(i) /= norm(X.col(i), 2); } // create a labels vector, NOT so that we can use it for LCC, but so we can save the labels for easy discriminative training upon exit of this program vec y = vec(n_points); y.subvec(0, n_neg_points - 1).fill(-1); y.subvec(n_neg_points, n_points - 1).fill(1); // run LCC LocalCoordinateCoding lcc; lcc.Init(X, n_atoms, lambda); if(strlen(initial_dictionary_fullpath) == 0) { lcc.DataDependentRandomInitDictionary(); } else { mat initial_D; initial_D.load(initial_dictionary_fullpath); if(initial_D.n_cols != n_atoms) { fprintf(stderr, "Error: The specified initial dictionary to load has %d atoms, but the learned dictionary was specified to have %d atoms! Exiting..\n", initial_D.n_cols, n_atoms); return EXIT_FAILURE; } if(initial_D.n_rows != X.n_rows) { fprintf(stderr, "Error: The specified initial dictionary to load has %d dimensions, but the specified data has %d dimensions! Exiting..\n", initial_D.n_rows, X.n_rows); return EXIT_FAILURE; } lcc.SetDictionary(initial_D); } wall_clock timer; timer.tic(); lcc.DoLCC(n_iterations); double n_secs = timer.toc(); cout << "took " << n_secs << " seconds" << endl; mat learned_D; lcc.GetDictionary(learned_D); mat learned_V; lcc.GetCoding(learned_V); if(strlen(results_dir) == 0) { learned_D.save("D.dat", raw_ascii); learned_V.save("V.dat", raw_ascii); y.save("y.dat", raw_ascii); } else { char* data_fullpath = (char*) malloc(320 * sizeof(char)); sprintf(data_fullpath, "%s/D.dat", results_dir); learned_D.save(data_fullpath, raw_ascii); sprintf(data_fullpath, "%s/V.dat", results_dir); learned_V.save(data_fullpath, raw_ascii); sprintf(data_fullpath, "%s/y.dat", results_dir); y.save(data_fullpath, raw_ascii); free(data_fullpath); } fx_done(root); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_RIGHT_TRI_HPP #define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_RIGHT_TRI_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/mdivide_left_tri.hpp> #include <stan/math/prim/mat/fun/transpose.hpp> #include <stan/math/prim/mat/err/check_multiplicable.hpp> #include <stan/math/prim/mat/err/check_square.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <boost/math/tools/promotion.hpp> namespace stan { namespace math { /** * Returns the solution of the system Ax=b when A is triangular * @param A Triangular matrix. Specify upper or lower with TriView * being Eigen::Upper or Eigen::Lower. * @param b Right hand side matrix or vector. * @return x = b A^-1, solution of the linear system. * @throws std::domain_error if A is not square or the rows of b don't * match the size of A. */ template <int TriView, typename T1, typename T2, int R1, int C1, int R2, int C2> inline Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, R1, C2> mdivide_right_tri(const Eigen::Matrix<T1, R1, C1> &b, const Eigen::Matrix<T2, R2, C2> &A) { check_square("mdivide_right_tri", "A", A); check_multiplicable("mdivide_right_tri", "b", b, "A", A); // FIXME: This is nice and general but requires some extra memory // and copying. if (TriView == Eigen::Lower) { return transpose( mdivide_left_tri<Eigen::Upper>(transpose(A), transpose(b))); } else if (TriView == Eigen::Upper) { return transpose( mdivide_left_tri<Eigen::Lower>(transpose(A), transpose(b))); } domain_error("mdivide_left_tri", "triangular view must be Eigen::Lower or Eigen::Upper", "", ""); } } // namespace math } // namespace stan #endif <commit_msg>avoid copying<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_RIGHT_TRI_HPP #define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_RIGHT_TRI_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/mdivide_left_tri.hpp> #include <stan/math/prim/mat/fun/transpose.hpp> #include <stan/math/prim/mat/err/check_multiplicable.hpp> #include <stan/math/prim/mat/err/check_square.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <boost/math/tools/promotion.hpp> namespace stan { namespace math { /** * Returns the solution of the system Ax=b when A is triangular * @param A Triangular matrix. Specify upper or lower with TriView * being Eigen::Upper or Eigen::Lower. * @param b Right hand side matrix or vector. * @return x = b A^-1, solution of the linear system. * @throws std::domain_error if A is not square or the rows of b don't * match the size of A. */ template <int TriView, typename T1, typename T2, int R1, int C1, int R2, int C2> inline Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, R1, C2> mdivide_right_tri(const Eigen::Matrix<T1, R1, C1> &b, const Eigen::Matrix<T2, R2, C2> &A) { check_square("mdivide_right_tri", "A", A); check_multiplicable("mdivide_right_tri", "b", b, "A", A); return promote_common<Eigen::Matrix<T1, R1, C1>, Eigen::Matrix<T2, R1, C1> >( A) .template triangularView<TriView>() .transpose() .solve( promote_common<Eigen::Matrix<T1, R2, C2>, Eigen::Matrix<T2, R2, C2> >( b) .transpose()) .transpose(); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: present.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2006-10-06 09:52:59 $ * * 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 _SD_PRESENT_HXX_ #define _SD_PRESENT_HXX_ #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _FIELD_HXX //autogen #include <vcl/field.hxx> #endif class SfxItemSet; class List; /************************************************************************* |* Dialog zum Festlegen von Optionen und Starten der Praesentation \************************************************************************/ class SdStartPresentationDlg : public ModalDialog { private: FixedLine aGrpRange; RadioButton aRbtAll; RadioButton aRbtAtDia; RadioButton aRbtCustomshow; ListBox aLbDias; ListBox aLbCustomshow; FixedLine aGrpKind; RadioButton aRbtStandard; RadioButton aRbtWindow; RadioButton aRbtAuto; // FixedText aFtPause; TimeField aTmfPause; CheckBox aCbxAutoLogo; FixedLine aGrpOptions; CheckBox aCbxManuel; CheckBox aCbxMousepointer; CheckBox aCbxPen; CheckBox aCbxNavigator; CheckBox aCbxAnimationAllowed; CheckBox aCbxChangePage; CheckBox aCbxAlwaysOnTop; FixedLine maGrpMonitor; FixedText maFtMonitor; ListBox maLBMonitor; OKButton aBtnOK; CancelButton aBtnCancel; HelpButton aBtnHelp; List* pCustomShowList; const SfxItemSet& rOutAttrs; sal_Int32 mnMonitors; String msPrimaryMonitor; String msMonitor; String msAllMonitors; DECL_LINK( ChangeRangeHdl, void * ); DECL_LINK( ClickWindowPresentationHdl, void * ); DECL_LINK( ChangePauseHdl, void * ); void InitMonitorSettings(); public: SdStartPresentationDlg( Window* pWindow, const SfxItemSet& rInAttrs, List& rPageNames, List* pCSList ); void GetAttr( SfxItemSet& rOutAttrs ); }; #endif // _SD_PRESENT_HXX_ <commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.16); FILE MERGED 2006/11/22 12:42:05 cl 1.5.16.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: present.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:46:52 $ * * 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 _SD_PRESENT_HXX_ #define _SD_PRESENT_HXX_ #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _FIELD_HXX //autogen #include <vcl/field.hxx> #endif class SfxItemSet; class List; /************************************************************************* |* Dialog zum Festlegen von Optionen und Starten der Praesentation \************************************************************************/ class SdStartPresentationDlg : public ModalDialog { private: FixedLine aGrpRange; RadioButton aRbtAll; RadioButton aRbtAtDia; RadioButton aRbtCustomshow; ListBox aLbDias; ListBox aLbCustomshow; FixedLine aGrpKind; RadioButton aRbtStandard; RadioButton aRbtWindow; RadioButton aRbtAuto; TimeField aTmfPause; CheckBox aCbxAutoLogo; FixedLine aGrpOptions; CheckBox aCbxManuel; CheckBox aCbxMousepointer; CheckBox aCbxPen; CheckBox aCbxNavigator; CheckBox aCbxAnimationAllowed; CheckBox aCbxChangePage; CheckBox aCbxAlwaysOnTop; FixedLine maGrpMonitor; FixedText maFtMonitor; ListBox maLBMonitor; OKButton aBtnOK; CancelButton aBtnCancel; HelpButton aBtnHelp; List* pCustomShowList; const SfxItemSet& rOutAttrs; sal_Int32 mnMonitors; String msPrimaryMonitor; String msMonitor; String msAllMonitors; DECL_LINK( ChangeRangeHdl, void * ); DECL_LINK( ClickWindowPresentationHdl, void * ); DECL_LINK( ChangePauseHdl, void * ); void InitMonitorSettings(); public: SdStartPresentationDlg( Window* pWindow, const SfxItemSet& rInAttrs, List& rPageNames, List* pCSList ); void GetAttr( SfxItemSet& rOutAttrs ); }; #endif // _SD_PRESENT_HXX_ <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ScrollbarThemeWin.h" #include "GraphicsContext.h" #include "PlatformMouseEvent.h" #include "Scrollbar.h" #include "SoftLinking.h" // Generic state constants #define TS_NORMAL 1 #define TS_HOVER 2 #define TS_ACTIVE 3 #define TS_DISABLED 4 #define SP_BUTTON 1 #define SP_THUMBHOR 2 #define SP_THUMBVERT 3 #define SP_TRACKSTARTHOR 4 #define SP_TRACKENDHOR 5 #define SP_TRACKSTARTVERT 6 #define SP_TRACKENDVERT 7 #define SP_GRIPPERHOR 8 #define SP_GRIPPERVERT 9 #define TS_UP_BUTTON 0 #define TS_DOWN_BUTTON 4 #define TS_LEFT_BUTTON 8 #define TS_RIGHT_BUTTON 12 #define TS_UP_BUTTON_HOVER 17 #define TS_DOWN_BUTTON_HOVER 18 #define TS_LEFT_BUTTON_HOVER 19 #define TS_RIGHT_BUTTON_HOVER 20 using namespace std; namespace WebCore { static HANDLE scrollbarTheme; static bool haveTheme; static bool runningVista; // FIXME: Refactor the soft-linking code so that it can be shared with RenderThemeWin SOFT_LINK_LIBRARY(uxtheme) SOFT_LINK(uxtheme, OpenThemeData, HANDLE, WINAPI, (HWND hwnd, LPCWSTR pszClassList), (hwnd, pszClassList)) SOFT_LINK(uxtheme, CloseThemeData, HRESULT, WINAPI, (HANDLE hTheme), (hTheme)) SOFT_LINK(uxtheme, DrawThemeBackground, HRESULT, WINAPI, (HANDLE hTheme, HDC hdc, int iPartId, int iStateId, const RECT* pRect, const RECT* pClipRect), (hTheme, hdc, iPartId, iStateId, pRect, pClipRect)) SOFT_LINK(uxtheme, IsThemeActive, BOOL, WINAPI, (), ()) SOFT_LINK(uxtheme, IsThemeBackgroundPartiallyTransparent, BOOL, WINAPI, (HANDLE hTheme, int iPartId, int iStateId), (hTheme, iPartId, iStateId)) static bool isRunningOnVistaOrLater() { static bool os = false; static bool initialized = false; if (!initialized) { OSVERSIONINFOEX vi = {sizeof(vi), 0}; GetVersionEx((OSVERSIONINFO*)&vi); // NOTE: This does not work under a debugger - Vista shims Visual Studio, // making it believe it is xpsp2, which is inherited by debugged applications os = vi.dwMajorVersion >= 6; initialized = true; } return os; } static void checkAndInitScrollbarTheme() { if (uxthemeLibrary() && !scrollbarTheme) scrollbarTheme = OpenThemeData(0, L"Scrollbar"); haveTheme = scrollbarTheme && IsThemeActive(); } #if !USE(SAFARI_THEME) ScrollbarTheme* ScrollbarTheme::nativeTheme() { static SafariThemeWin winTheme; return &winTheme; } #endif ScrollbarThemeWin::ScrollbarThemeWin() { static bool initialized; if (!initialized) { initialized = true; checkAndInitScrollbarTheme(); runningVista = isRunningOnVistaOrLater(); } } ScrollbarThemeWin::~ScrollbarThemeWin() { } int ScrollbarThemeWin::scrollbarThickness(ScrollbarControlSize) { static int thickness; if (!thickness) thickness = ::GetSystemMetrics(SM_CXVSCROLL); return thickness; } void ScrollbarThemeWin::themeChanged() { if (haveTheme) CloseThemeData(scrollbarTheme); } bool ScrollbarThemeWin::invalidateOnMouseEnterExit() { return runningVista; } bool ScrollbarThemeWin::hasThumb(Scrollbar* scrollbar) { return thumbLength(scrollbar) > 0; } IntRect ScrollbarThemeWin::backButtonRect(Scrollbar* scrollbar, ScrollbarPart part, bool) { // Windows just has single arrows. if (part == BackButtonEndPart) return IntRect(); // Our desired rect is essentially 17x17. // Our actual rect will shrink to half the available space when // we have < 34 pixels left. This allows the scrollbar // to scale down and function even at tiny sizes. int thickness = scrollbarThickness(); if (scrollbar->orientation() == HorizontalScrollbar) return IntRect(scrollbar->x(), scrollbar->y(), scrollbar->width() < 2 * thickness ? scrollbar->width() / 2 : thickness, thickness); return IntRect(scrollbar->x(), scrollbar->y(), thickness, scrollbar->height() < 2 * thickness ? scrollbar->height() / 2 : thickness); } IntRect ScrollbarThemeWin::forwardButtonRect(Scrollbar* scrollbar, ScrollbarPart part, bool) { // Windows just has single arrows. if (part == ForwardButtonStartPart) return IntRect(); // Our desired rect is essentially 17x17. // Our actual rect will shrink to half the available space when // we have < 34 pixels left. This allows the scrollbar // to scale down and function even at tiny sizes. int thickness = scrollbarThickness(); if (scrollbar->orientation() == HorizontalScrollbar) { int w = scrollbar->width() < 2 * thickness ? scrollbar->width() / 2 : thickness; return IntRect(scrollbar->x() + scrollbar->width() - w, scrollbar->y(), w, thickness); } int h = scrollbar->height() < 2 * thickness ? scrollbar->height() / 2 : thickness; return IntRect(scrollbar->x(), scrollbar->y() + scrollbar->height() - h, thickness, h); } IntRect ScrollbarThemeWin::trackRect(Scrollbar* scrollbar, bool) { int thickness = scrollbarThickness(); if (scrollbar->orientation() == HorizontalScrollbar) { if (scrollbar->width() < 2 * thickness) return IntRect(); return IntRect(scrollbar->x() + thickness, scrollbar->y(), scrollbar->width() - 2 * thickness, thickness); } if (scrollbar->height() < 2 * thickness) return IntRect(); return IntRect(scrollbar->x(), scrollbar->y() + thickness, thickness, scrollbar->height() - 2 * thickness); } void ScrollbarThemeWin::paintTrack(GraphicsContext* context, Scrollbar* scrollbar, const IntRect& rect, ScrollbarPart partType) { checkAndInitScrollbarTheme(); bool start = partType == BackTrackPart; int part; if (scrollbar->orientation() == HorizontalScrollbar) part = start ? SP_TRACKSTARTHOR : SP_TRACKENDHOR; else part = start ? SP_TRACKSTARTVERT : SP_TRACKENDVERT; int state; if (!scrollbar->enabled()) state = TS_DISABLED; else if ((scrollbar->hoveredPart() == BackTrackPart && start) || (scrollbar->hoveredPart() == ForwardTrackPart && !start)) state = (scrollbar->pressedPart() == scrollbar->hoveredPart() ? TS_ACTIVE : TS_HOVER); else state = TS_NORMAL; bool alphaBlend = false; if (scrollbarTheme) alphaBlend = IsThemeBackgroundPartiallyTransparent(scrollbarTheme, part, state); HDC hdc = context->getWindowsContext(rect, alphaBlend); RECT themeRect(rect); if (scrollbarTheme) DrawThemeBackground(scrollbarTheme, hdc, part, state, &themeRect, 0); else { DWORD color3DFace = ::GetSysColor(COLOR_3DFACE); DWORD colorScrollbar = ::GetSysColor(COLOR_SCROLLBAR); DWORD colorWindow = ::GetSysColor(COLOR_WINDOW); if ((color3DFace != colorScrollbar) && (colorWindow != colorScrollbar)) ::FillRect(hdc, &themeRect, HBRUSH(COLOR_SCROLLBAR+1)); else { static WORD patternBits[8] = { 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55 }; HBITMAP patternBitmap = ::CreateBitmap(8, 8, 1, 1, patternBits); HBRUSH brush = ::CreatePatternBrush(patternBitmap); SaveDC(hdc); ::SetTextColor(hdc, ::GetSysColor(COLOR_3DHILIGHT)); ::SetBkColor(hdc, ::GetSysColor(COLOR_3DFACE)); ::SetBrushOrgEx(hdc, rect.x(), rect.y(), NULL); ::SelectObject(hdc, brush); ::FillRect(hdc, &themeRect, brush); ::RestoreDC(hdc, -1); ::DeleteObject(brush); ::DeleteObject(patternBitmap); } } context->releaseWindowsContext(hdc, rect, alphaBlend); } void ScrollbarThemeWin::paintButton(GraphicsContext* context, Scrollbar* scrollbar, const IntRect& rect, ScrollbarPart part) { checkAndInitScrollbarTheme(); bool start = (part == BackButtonStartPart); int xpState = 0; int classicState = 0; if (scrollbar->orientation() == HorizontalScrollbar) xpState = start ? TS_LEFT_BUTTON : TS_RIGHT_BUTTON; else xpState = start ? TS_UP_BUTTON : TS_DOWN_BUTTON; classicState = xpState / 4; if (!scrollbar->enabled()) { xpState += TS_DISABLED; classicState |= DFCS_INACTIVE; } else if ((scrollbar->hoveredPart() == BackButtonStartPart && start) || (scrollbar->hoveredPart() == ForwardButtonEndPart && !start)) { if (scrollbar->pressedPart() == scrollbar->hoveredPart()) { xpState += TS_ACTIVE; classicState |= DFCS_PUSHED | DFCS_FLAT; } else xpState += TS_HOVER; } else { if (scrollbar->hoveredPart() == NoPart || !runningVista) xpState += TS_NORMAL; else { if (scrollbar->orientation() == HorizontalScrollbar) xpState = start ? TS_LEFT_BUTTON_HOVER : TS_RIGHT_BUTTON_HOVER; else xpState = start ? TS_UP_BUTTON_HOVER : TS_DOWN_BUTTON_HOVER; } } bool alphaBlend = false; if (scrollbarTheme) alphaBlend = IsThemeBackgroundPartiallyTransparent(scrollbarTheme, SP_BUTTON, xpState); HDC hdc = context->getWindowsContext(rect, alphaBlend); RECT themeRect(rect); if (scrollbarTheme) DrawThemeBackground(scrollbarTheme, hdc, SP_BUTTON, xpState, &themeRect, 0); else ::DrawFrameControl(hdc, &themeRect, DFC_SCROLL, classicState); context->releaseWindowsContext(hdc, rect, alphaBlend); } static IntRect gripperRect(int thickness, const IntRect& thumbRect) { // Center in the thumb. int gripperThickness = thickness / 2; return IntRect(thumbRect.x() + (thumbRect.width() - gripperThickness) / 2, thumbRect.y() + (thumbRect.height() - gripperThickness) / 2, gripperThickness, gripperThickness); } static void paintGripper(Scrollbar* scrollbar, HDC hdc, const IntRect& rect) { if (!scrollbarTheme) return; // Classic look has no gripper. int state; if (!scrollbar->enabled()) state = TS_DISABLED; else if (scrollbar->pressedPart() == ThumbPart) state = TS_ACTIVE; // Thumb always stays active once pressed. else if (scrollbar->hoveredPart() == ThumbPart) state = TS_HOVER; else state = TS_NORMAL; RECT themeRect(rect); DrawThemeBackground(scrollbarTheme, hdc, scrollbar->orientation() == HorizontalScrollbar ? SP_GRIPPERHOR : SP_GRIPPERVERT, state, &themeRect, 0); } void ScrollbarThemeWin::paintThumb(GraphicsContext* context, Scrollbar* scrollbar, const IntRect& rect) { checkAndInitScrollbarTheme(); int state; if (!scrollbar->enabled()) state = TS_DISABLED; else if (scrollbar->pressedPart() == ThumbPart) state = TS_ACTIVE; // Thumb always stays active once pressed. else if (scrollbar->hoveredPart() == ThumbPart) state = TS_HOVER; else state = TS_NORMAL; bool alphaBlend = false; if (scrollbarTheme) alphaBlend = IsThemeBackgroundPartiallyTransparent(scrollbarTheme, scrollbar->orientation() == HorizontalScrollbar ? SP_THUMBHOR : SP_THUMBVERT, state); HDC hdc = context->getWindowsContext(rect, alphaBlend); RECT themeRect(rect); if (scrollbarTheme) { DrawThemeBackground(scrollbarTheme, hdc, scrollbar->orientation() == HorizontalScrollbar ? SP_THUMBHOR : SP_THUMBVERT, state, &themeRect, 0); paintGripper(scrollbar, hdc, gripperRect(scrollbarThickness(), rect)); } else ::DrawEdge(hdc, &themeRect, EDGE_RAISED, BF_RECT | BF_MIDDLE); context->releaseWindowsContext(hdc, rect, alphaBlend); } bool ScrollbarThemeWin::shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent& evt) { return evt.shiftKey() && evt.button() == LeftButton; } } <commit_msg>Fix Windows bustage.<commit_after>/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ScrollbarThemeWin.h" #include "GraphicsContext.h" #include "PlatformMouseEvent.h" #include "Scrollbar.h" #include "SoftLinking.h" // Generic state constants #define TS_NORMAL 1 #define TS_HOVER 2 #define TS_ACTIVE 3 #define TS_DISABLED 4 #define SP_BUTTON 1 #define SP_THUMBHOR 2 #define SP_THUMBVERT 3 #define SP_TRACKSTARTHOR 4 #define SP_TRACKENDHOR 5 #define SP_TRACKSTARTVERT 6 #define SP_TRACKENDVERT 7 #define SP_GRIPPERHOR 8 #define SP_GRIPPERVERT 9 #define TS_UP_BUTTON 0 #define TS_DOWN_BUTTON 4 #define TS_LEFT_BUTTON 8 #define TS_RIGHT_BUTTON 12 #define TS_UP_BUTTON_HOVER 17 #define TS_DOWN_BUTTON_HOVER 18 #define TS_LEFT_BUTTON_HOVER 19 #define TS_RIGHT_BUTTON_HOVER 20 using namespace std; namespace WebCore { static HANDLE scrollbarTheme; static bool haveTheme; static bool runningVista; // FIXME: Refactor the soft-linking code so that it can be shared with RenderThemeWin SOFT_LINK_LIBRARY(uxtheme) SOFT_LINK(uxtheme, OpenThemeData, HANDLE, WINAPI, (HWND hwnd, LPCWSTR pszClassList), (hwnd, pszClassList)) SOFT_LINK(uxtheme, CloseThemeData, HRESULT, WINAPI, (HANDLE hTheme), (hTheme)) SOFT_LINK(uxtheme, DrawThemeBackground, HRESULT, WINAPI, (HANDLE hTheme, HDC hdc, int iPartId, int iStateId, const RECT* pRect, const RECT* pClipRect), (hTheme, hdc, iPartId, iStateId, pRect, pClipRect)) SOFT_LINK(uxtheme, IsThemeActive, BOOL, WINAPI, (), ()) SOFT_LINK(uxtheme, IsThemeBackgroundPartiallyTransparent, BOOL, WINAPI, (HANDLE hTheme, int iPartId, int iStateId), (hTheme, iPartId, iStateId)) static bool isRunningOnVistaOrLater() { static bool os = false; static bool initialized = false; if (!initialized) { OSVERSIONINFOEX vi = {sizeof(vi), 0}; GetVersionEx((OSVERSIONINFO*)&vi); // NOTE: This does not work under a debugger - Vista shims Visual Studio, // making it believe it is xpsp2, which is inherited by debugged applications os = vi.dwMajorVersion >= 6; initialized = true; } return os; } static void checkAndInitScrollbarTheme() { if (uxthemeLibrary() && !scrollbarTheme) scrollbarTheme = OpenThemeData(0, L"Scrollbar"); haveTheme = scrollbarTheme && IsThemeActive(); } #if !USE(SAFARI_THEME) ScrollbarTheme* ScrollbarTheme::nativeTheme() { static SafariThemeWin winTheme; return &winTheme; } #endif ScrollbarThemeWin::ScrollbarThemeWin() { static bool initialized; if (!initialized) { initialized = true; checkAndInitScrollbarTheme(); runningVista = isRunningOnVistaOrLater(); } } ScrollbarThemeWin::~ScrollbarThemeWin() { } int ScrollbarThemeWin::scrollbarThickness(ScrollbarControlSize) { static int thickness; if (!thickness) thickness = ::GetSystemMetrics(SM_CXVSCROLL); return thickness; } void ScrollbarThemeWin::themeChanged() { if (haveTheme) CloseThemeData(scrollbarTheme); } bool ScrollbarThemeWin::invalidateOnMouseEnterExit() { return runningVista; } bool ScrollbarThemeWin::hasThumb(Scrollbar* scrollbar) { return thumbLength(scrollbar) > 0; } IntRect ScrollbarThemeWin::backButtonRect(Scrollbar* scrollbar, ScrollbarPart part, bool) { // Windows just has single arrows. if (part == BackButtonEndPart) return IntRect(); // Our desired rect is essentially 17x17. // Our actual rect will shrink to half the available space when // we have < 34 pixels left. This allows the scrollbar // to scale down and function even at tiny sizes. int thickness = scrollbarThickness(); if (scrollbar->orientation() == HorizontalScrollbar) return IntRect(scrollbar->x(), scrollbar->y(), scrollbar->width() < 2 * thickness ? scrollbar->width() / 2 : thickness, thickness); return IntRect(scrollbar->x(), scrollbar->y(), thickness, scrollbar->height() < 2 * thickness ? scrollbar->height() / 2 : thickness); } IntRect ScrollbarThemeWin::forwardButtonRect(Scrollbar* scrollbar, ScrollbarPart part, bool) { // Windows just has single arrows. if (part == ForwardButtonStartPart) return IntRect(); // Our desired rect is essentially 17x17. // Our actual rect will shrink to half the available space when // we have < 34 pixels left. This allows the scrollbar // to scale down and function even at tiny sizes. int thickness = scrollbarThickness(); if (scrollbar->orientation() == HorizontalScrollbar) { int w = scrollbar->width() < 2 * thickness ? scrollbar->width() / 2 : thickness; return IntRect(scrollbar->x() + scrollbar->width() - w, scrollbar->y(), w, thickness); } int h = scrollbar->height() < 2 * thickness ? scrollbar->height() / 2 : thickness; return IntRect(scrollbar->x(), scrollbar->y() + scrollbar->height() - h, thickness, h); } IntRect ScrollbarThemeWin::trackRect(Scrollbar* scrollbar, bool) { int thickness = scrollbarThickness(); if (scrollbar->orientation() == HorizontalScrollbar) { if (scrollbar->width() < 2 * thickness) return IntRect(); return IntRect(scrollbar->x() + thickness, scrollbar->y(), scrollbar->width() - 2 * thickness, thickness); } if (scrollbar->height() < 2 * thickness) return IntRect(); return IntRect(scrollbar->x(), scrollbar->y() + thickness, thickness, scrollbar->height() - 2 * thickness); } void ScrollbarThemeWin::paintTrackPiece(GraphicsContext* context, Scrollbar* scrollbar, const IntRect& rect, ScrollbarPart partType) { checkAndInitScrollbarTheme(); bool start = partType == BackTrackPart; int part; if (scrollbar->orientation() == HorizontalScrollbar) part = start ? SP_TRACKSTARTHOR : SP_TRACKENDHOR; else part = start ? SP_TRACKSTARTVERT : SP_TRACKENDVERT; int state; if (!scrollbar->enabled()) state = TS_DISABLED; else if ((scrollbar->hoveredPart() == BackTrackPart && start) || (scrollbar->hoveredPart() == ForwardTrackPart && !start)) state = (scrollbar->pressedPart() == scrollbar->hoveredPart() ? TS_ACTIVE : TS_HOVER); else state = TS_NORMAL; bool alphaBlend = false; if (scrollbarTheme) alphaBlend = IsThemeBackgroundPartiallyTransparent(scrollbarTheme, part, state); HDC hdc = context->getWindowsContext(rect, alphaBlend); RECT themeRect(rect); if (scrollbarTheme) DrawThemeBackground(scrollbarTheme, hdc, part, state, &themeRect, 0); else { DWORD color3DFace = ::GetSysColor(COLOR_3DFACE); DWORD colorScrollbar = ::GetSysColor(COLOR_SCROLLBAR); DWORD colorWindow = ::GetSysColor(COLOR_WINDOW); if ((color3DFace != colorScrollbar) && (colorWindow != colorScrollbar)) ::FillRect(hdc, &themeRect, HBRUSH(COLOR_SCROLLBAR+1)); else { static WORD patternBits[8] = { 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55 }; HBITMAP patternBitmap = ::CreateBitmap(8, 8, 1, 1, patternBits); HBRUSH brush = ::CreatePatternBrush(patternBitmap); SaveDC(hdc); ::SetTextColor(hdc, ::GetSysColor(COLOR_3DHILIGHT)); ::SetBkColor(hdc, ::GetSysColor(COLOR_3DFACE)); ::SetBrushOrgEx(hdc, rect.x(), rect.y(), NULL); ::SelectObject(hdc, brush); ::FillRect(hdc, &themeRect, brush); ::RestoreDC(hdc, -1); ::DeleteObject(brush); ::DeleteObject(patternBitmap); } } context->releaseWindowsContext(hdc, rect, alphaBlend); } void ScrollbarThemeWin::paintButton(GraphicsContext* context, Scrollbar* scrollbar, const IntRect& rect, ScrollbarPart part) { checkAndInitScrollbarTheme(); bool start = (part == BackButtonStartPart); int xpState = 0; int classicState = 0; if (scrollbar->orientation() == HorizontalScrollbar) xpState = start ? TS_LEFT_BUTTON : TS_RIGHT_BUTTON; else xpState = start ? TS_UP_BUTTON : TS_DOWN_BUTTON; classicState = xpState / 4; if (!scrollbar->enabled()) { xpState += TS_DISABLED; classicState |= DFCS_INACTIVE; } else if ((scrollbar->hoveredPart() == BackButtonStartPart && start) || (scrollbar->hoveredPart() == ForwardButtonEndPart && !start)) { if (scrollbar->pressedPart() == scrollbar->hoveredPart()) { xpState += TS_ACTIVE; classicState |= DFCS_PUSHED | DFCS_FLAT; } else xpState += TS_HOVER; } else { if (scrollbar->hoveredPart() == NoPart || !runningVista) xpState += TS_NORMAL; else { if (scrollbar->orientation() == HorizontalScrollbar) xpState = start ? TS_LEFT_BUTTON_HOVER : TS_RIGHT_BUTTON_HOVER; else xpState = start ? TS_UP_BUTTON_HOVER : TS_DOWN_BUTTON_HOVER; } } bool alphaBlend = false; if (scrollbarTheme) alphaBlend = IsThemeBackgroundPartiallyTransparent(scrollbarTheme, SP_BUTTON, xpState); HDC hdc = context->getWindowsContext(rect, alphaBlend); RECT themeRect(rect); if (scrollbarTheme) DrawThemeBackground(scrollbarTheme, hdc, SP_BUTTON, xpState, &themeRect, 0); else ::DrawFrameControl(hdc, &themeRect, DFC_SCROLL, classicState); context->releaseWindowsContext(hdc, rect, alphaBlend); } static IntRect gripperRect(int thickness, const IntRect& thumbRect) { // Center in the thumb. int gripperThickness = thickness / 2; return IntRect(thumbRect.x() + (thumbRect.width() - gripperThickness) / 2, thumbRect.y() + (thumbRect.height() - gripperThickness) / 2, gripperThickness, gripperThickness); } static void paintGripper(Scrollbar* scrollbar, HDC hdc, const IntRect& rect) { if (!scrollbarTheme) return; // Classic look has no gripper. int state; if (!scrollbar->enabled()) state = TS_DISABLED; else if (scrollbar->pressedPart() == ThumbPart) state = TS_ACTIVE; // Thumb always stays active once pressed. else if (scrollbar->hoveredPart() == ThumbPart) state = TS_HOVER; else state = TS_NORMAL; RECT themeRect(rect); DrawThemeBackground(scrollbarTheme, hdc, scrollbar->orientation() == HorizontalScrollbar ? SP_GRIPPERHOR : SP_GRIPPERVERT, state, &themeRect, 0); } void ScrollbarThemeWin::paintThumb(GraphicsContext* context, Scrollbar* scrollbar, const IntRect& rect) { checkAndInitScrollbarTheme(); int state; if (!scrollbar->enabled()) state = TS_DISABLED; else if (scrollbar->pressedPart() == ThumbPart) state = TS_ACTIVE; // Thumb always stays active once pressed. else if (scrollbar->hoveredPart() == ThumbPart) state = TS_HOVER; else state = TS_NORMAL; bool alphaBlend = false; if (scrollbarTheme) alphaBlend = IsThemeBackgroundPartiallyTransparent(scrollbarTheme, scrollbar->orientation() == HorizontalScrollbar ? SP_THUMBHOR : SP_THUMBVERT, state); HDC hdc = context->getWindowsContext(rect, alphaBlend); RECT themeRect(rect); if (scrollbarTheme) { DrawThemeBackground(scrollbarTheme, hdc, scrollbar->orientation() == HorizontalScrollbar ? SP_THUMBHOR : SP_THUMBVERT, state, &themeRect, 0); paintGripper(scrollbar, hdc, gripperRect(scrollbarThickness(), rect)); } else ::DrawEdge(hdc, &themeRect, EDGE_RAISED, BF_RECT | BF_MIDDLE); context->releaseWindowsContext(hdc, rect, alphaBlend); } bool ScrollbarThemeWin::shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent& evt) { return evt.shiftKey() && evt.button() == LeftButton; } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_PROB_STD_NORMAL_LPDF_HPP #define STAN_MATH_PRIM_SCAL_PROB_STD_NORMAL_LPDF_HPP #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <stan/math/prim/scal/meta/length.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <boost/random/normal_distribution.hpp> #include <boost/random/variate_generator.hpp> #include <cmath> #include <string> namespace stan { namespace math { /** * The log of the normal density for the specified scalar(s) given * a mean of 0 and a standard deviation of 1. y can be either * a scalar or a vector. * * <p>The result log probability is defined to be the sum of the * log probabilities for each observation. * @tparam T_y Underlying type of scalar in sequence. * @param y (Sequence of) scalar(s). * @return The log of the product of the densities. * @throw std::domain_error if any scalar is nan. */ template <bool propto, typename T_y> typename return_type<T_y>::type std_normal_lpdf(const T_y& y) { static const std::string function = "std_normal_lpdf"; typedef typename stan::partials_return_type<T_y>::type T_partials_return; using std::log; using stan::is_constant_struct; if (!(stan::length(y))) return 0.0; T_partials_return logp(0.0); check_not_nan(function, "Random variable", y); if (!include_summand<propto, T_y>::value) return 0.0; operands_and_partials<T_y> ops_partials(y); scalar_seq_view<T_y> y_vec(y); for (size_t n = 0; n < length(y); n++) { const T_partials_return y_dbl = value_of(y_vec[n]); static double NEGATIVE_HALF = -0.5; if (include_summand<propto>::value) logp += NEG_LOG_SQRT_TWO_PI; if (include_summand<propto, T_y>::value) logp += NEGATIVE_HALF * y_dbl * y_dbl; if (!is_constant_struct<T_y>::value) ops_partials.edge1_.partials_[n] -= y_dbl; } return ops_partials.build(logp); } template <typename T_y> inline typename return_type<T_y>::type std_normal_lpdf(const T_y& y) { return std_normal_lpdf<false>(y); } } } #endif <commit_msg>Removed unnecessary include of std::log<commit_after>#ifndef STAN_MATH_PRIM_SCAL_PROB_STD_NORMAL_LPDF_HPP #define STAN_MATH_PRIM_SCAL_PROB_STD_NORMAL_LPDF_HPP #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/length.hpp> #include <boost/random/normal_distribution.hpp> #include <boost/random/variate_generator.hpp> #include <string> namespace stan { namespace math { /** * The log of the normal density for the specified scalar(s) given * a mean of 0 and a standard deviation of 1. y can be either * a scalar or a vector. * * <p>The result log probability is defined to be the sum of the * log probabilities for each observation. * @tparam T_y Underlying type of scalar in sequence. * @param y (Sequence of) scalar(s). * @return The log of the product of the densities. * @throw std::domain_error if any scalar is nan. */ template <bool propto, typename T_y> typename return_type<T_y>::type std_normal_lpdf(const T_y& y) { static const std::string function = "std_normal_lpdf"; typedef typename stan::partials_return_type<T_y>::type T_partials_return; using stan::is_constant_struct; if (!(stan::length(y))) return 0.0; T_partials_return logp(0.0); check_not_nan(function, "Random variable", y); if (!include_summand<propto, T_y>::value) return 0.0; operands_and_partials<T_y> ops_partials(y); scalar_seq_view<T_y> y_vec(y); for (size_t n = 0; n < length(y); n++) { const T_partials_return y_dbl = value_of(y_vec[n]); static double NEGATIVE_HALF = -0.5; if (include_summand<propto>::value) logp += NEG_LOG_SQRT_TWO_PI; if (include_summand<propto, T_y>::value) logp += NEGATIVE_HALF * y_dbl * y_dbl; if (!is_constant_struct<T_y>::value) ops_partials.edge1_.partials_[n] -= y_dbl; } return ops_partials.build(logp); } template <typename T_y> inline typename return_type<T_y>::type std_normal_lpdf(const T_y& y) { return std_normal_lpdf<false>(y); } } } #endif <|endoftext|>
<commit_before>#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" #include "transaction.h" #include "internal/operations/post_operation.h" #include "internal/operations/put_operation.h" #include "internal/operations/erase_operation.h" #include "dummy_values.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { TEST_CLASS(DataStoreApiTest) { public: TEST_METHOD(pushOperationsToTransaction) { Transaction sut; std::shared_ptr<Internal::IOperation> postOp = std::make_shared<Internal::PostOperation>(0, task1); sut.push(postOp); Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size()); std::shared_ptr<Internal::IOperation> putOp = std::make_shared<Internal::PutOperation>(0, task2); sut.push(putOp); Assert::AreEqual(boost::lexical_cast<size_t>(2), sut.operationsQueue.size()); std::shared_ptr<Internal::IOperation> eraseOp = std::make_shared<Internal::EraseOperation>(0); sut.push(eraseOp); Assert::AreEqual(boost::lexical_cast<size_t>(3), sut.operationsQueue.size()); } TEST_METHOD(transactionRollback) { Transaction sut; std::shared_ptr<Internal::IOperation> postOp = std::make_shared<Internal::PostOperation>(0, task1); sut.push(postOp); std::shared_ptr<Internal::IOperation> putOp = std::make_shared<Internal::PutOperation>(0, task2); sut.push(putOp); std::shared_ptr<Internal::IOperation> eraseOp = std::make_shared<Internal::EraseOperation>(0); sut.push(eraseOp); Assert::AreEqual(boost::lexical_cast<size_t>(3), sut.operationsQueue.size()); sut.rollback(); Assert::AreEqual(boost::lexical_cast<size_t>(0), sut.operationsQueue.size()); } TEST_METHOD(constructTransactionWithDataStoreBegin) { Transaction& sut(DataStore::get().begin()); Assert::IsTrue(DataStore::get().transactionStack.size() == 1); DataStore::get().post(0, task1); Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size()); DataStore::get().put(0, task2); Assert::AreEqual(boost::lexical_cast<size_t>(2), sut.operationsQueue.size()); DataStore::get().erase(0); Assert::AreEqual(boost::lexical_cast<size_t>(3), sut.operationsQueue.size()); sut.commit(); } TEST_METHOD(commitTransaction) { Transaction& sut(DataStore::get().begin()); DataStore::get().post(0, task1); DataStore::get().post(1, task2); DataStore::get().erase(0); sut.commit(); int size = DataStore::get().getAllTask().size(); Assert::AreEqual(1, size); } }; } // namespace UnitTests } // namespace DataStore } // namespace You <commit_msg>Remove unnecessary assert statement from test<commit_after>#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" #include "transaction.h" #include "internal/operations/post_operation.h" #include "internal/operations/put_operation.h" #include "internal/operations/erase_operation.h" #include "dummy_values.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { TEST_CLASS(DataStoreApiTest) { public: TEST_METHOD(pushOperationsToTransaction) { Transaction sut; std::shared_ptr<Internal::IOperation> postOp = std::make_shared<Internal::PostOperation>(0, task1); sut.push(postOp); Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size()); std::shared_ptr<Internal::IOperation> putOp = std::make_shared<Internal::PutOperation>(0, task2); sut.push(putOp); Assert::AreEqual(boost::lexical_cast<size_t>(2), sut.operationsQueue.size()); std::shared_ptr<Internal::IOperation> eraseOp = std::make_shared<Internal::EraseOperation>(0); sut.push(eraseOp); Assert::AreEqual(boost::lexical_cast<size_t>(3), sut.operationsQueue.size()); } TEST_METHOD(transactionRollback) { Transaction sut; std::shared_ptr<Internal::IOperation> postOp = std::make_shared<Internal::PostOperation>(0, task1); sut.push(postOp); std::shared_ptr<Internal::IOperation> putOp = std::make_shared<Internal::PutOperation>(0, task2); sut.push(putOp); std::shared_ptr<Internal::IOperation> eraseOp = std::make_shared<Internal::EraseOperation>(0); sut.push(eraseOp); Assert::AreEqual(boost::lexical_cast<size_t>(3), sut.operationsQueue.size()); sut.rollback(); Assert::AreEqual(boost::lexical_cast<size_t>(0), sut.operationsQueue.size()); } TEST_METHOD(constructTransactionWithDataStoreBegin) { Transaction& sut(DataStore::get().begin()); DataStore::get().post(0, task1); Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size()); DataStore::get().put(0, task2); Assert::AreEqual(boost::lexical_cast<size_t>(2), sut.operationsQueue.size()); DataStore::get().erase(0); Assert::AreEqual(boost::lexical_cast<size_t>(3), sut.operationsQueue.size()); sut.commit(); } TEST_METHOD(commitTransaction) { Transaction& sut(DataStore::get().begin()); DataStore::get().post(0, task1); DataStore::get().post(1, task2); DataStore::get().erase(0); sut.commit(); int size = DataStore::get().getAllTask().size(); Assert::AreEqual(1, size); } }; } // namespace UnitTests } // namespace DataStore } // namespace You <|endoftext|>
<commit_before>/* * Copyright 2011 DataStax * * 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 "php_pdo_cassandra.hpp" #include "php_pdo_cassandra_int.hpp" /** {{{ static int pdo_cassandra_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC) */ static int pdo_cassandra_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); pdo_cassandra_db_handle *H = static_cast <pdo_cassandra_db_handle *>(S->H); try { if (!H->transport->isOpen()) { H->transport->open(); } std::string q = stmt->active_query_string; S->result.reset (new CqlResult); H->client->execute_cql_query(*S->result.get (), q, (H->compression ? Compression::GZIP : Compression::NONE)); S->has_iterator = 0; stmt->row_count = S->result.get()->rows.size (); return 1; } catch (NotFoundException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_NOT_FOUND, "%s", e.what()); } catch (InvalidRequestException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_INVALID_REQUEST, "%s", e.why.c_str()); } catch (UnavailableException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_UNAVAILABLE, "%s", e.what()); } catch (TimedOutException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_TIMED_OUT, "%s", e.what()); } catch (AuthenticationException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_AUTHENTICATION_ERROR, "%s", e.why.c_str()); } catch (AuthorizationException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_AUTHORIZATION_ERROR, "%s", e.why.c_str()); } catch (SchemaDisagreementException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_SCHEMA_DISAGREEMENT, "%s", e.what()); } catch (TTransportException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_TRANSPORT_ERROR, "%s", e.what()); } catch (TException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_GENERAL_ERROR, "%s", e.what()); } catch (std::exception &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_GENERAL_ERROR, "%s", e.what()); } return 0; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori, long offset TSRMLS_DC) */ static int pdo_cassandra_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori, long offset TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); if (!S->has_iterator) { S->it = S->result.get()->rows.begin (); S->has_iterator = 1; stmt->column_count = (*S->it).columns.size (); } else { S->it++; } if (S->it == S->result.get()->rows.end ()) { // Iterated all rows, reset the iterator S->has_iterator = 0; return 0; } return 1; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_describe(pdo_stmt_t *stmt, int colno TSRMLS_DC) */ static int pdo_cassandra_stmt_describe(pdo_stmt_t *stmt, int colno TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); if (colno < 0 || (colno >= 0 && (static_cast <size_t>(colno) >= (*S->it).columns.size ()))) { return 0; } if (!(*S->it).columns[colno].name.size ()) { return 0; } stmt->columns[colno].name = estrdup (const_cast <char *> ((*S->it).columns[colno].name.c_str ())); stmt->columns[colno].namelen = (*S->it).columns[colno].name.size (); stmt->columns[colno].maxlen = -1; stmt->columns[colno].precision = 0; stmt->columns[colno].param_type = PDO_PARAM_STR; return 1; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_get_column(pdo_stmt_t *stmt, int colno, char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC) */ static int pdo_cassandra_stmt_get_column(pdo_stmt_t *stmt, int colno, char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); if (colno < 0 || (colno >= 0 && (static_cast <size_t>(colno) >= (*S->it).columns.size ()))) { return 0; } *ptr = const_cast <char *> ((*S->it).columns[colno].value.c_str ()); *len = (*S->it).columns[colno].value.size(); *caller_frees = 0; return 1; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_get_column_meta(pdo_stmt_t *stmt, long colno, zval *return_value TSRMLS_DC) */ static int pdo_cassandra_stmt_get_column_meta(pdo_stmt_t *stmt, long colno, zval *return_value TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); if (colno < 0 || (colno >= 0 && (static_cast <size_t>(colno) >= (*S->it).columns.size ()))) { return FAILURE; } array_init(return_value); add_assoc_string(return_value, "native_type", "string", 1); return SUCCESS; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_cursor_closer(pdo_stmt_t *stmt TSRMLS_DC) */ static int pdo_cassandra_stmt_cursor_close(pdo_stmt_t *stmt TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); S->has_iterator = 0; return 1; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC) */ static int pdo_cassandra_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC) { if (stmt->driver_data) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); S->result.reset(); delete S; stmt->driver_data = NULL; } return 1; } /* }}} */ struct pdo_stmt_methods cassandra_stmt_methods = { pdo_cassandra_stmt_dtor, pdo_cassandra_stmt_execute, pdo_cassandra_stmt_fetch, pdo_cassandra_stmt_describe, pdo_cassandra_stmt_get_column, NULL, /* param_hook */ NULL, /* set_attr */ NULL, /* get_attr */ pdo_cassandra_stmt_get_column_meta, NULL, /* next_rowset */ pdo_cassandra_stmt_cursor_close }; /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ <commit_msg>Fix indentation<commit_after>/* * Copyright 2011 DataStax * * 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 "php_pdo_cassandra.hpp" #include "php_pdo_cassandra_int.hpp" /** {{{ static int pdo_cassandra_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC) */ static int pdo_cassandra_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); pdo_cassandra_db_handle *H = static_cast <pdo_cassandra_db_handle *>(S->H); try { if (!H->transport->isOpen()) { H->transport->open(); } std::string q = stmt->active_query_string; S->result.reset (new CqlResult); H->client->execute_cql_query(*S->result.get (), q, (H->compression ? Compression::GZIP : Compression::NONE)); S->has_iterator = 0; stmt->row_count = S->result.get()->rows.size (); return 1; } catch (NotFoundException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_NOT_FOUND, "%s", e.what()); } catch (InvalidRequestException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_INVALID_REQUEST, "%s", e.why.c_str()); } catch (UnavailableException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_UNAVAILABLE, "%s", e.what()); } catch (TimedOutException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_TIMED_OUT, "%s", e.what()); } catch (AuthenticationException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_AUTHENTICATION_ERROR, "%s", e.why.c_str()); } catch (AuthorizationException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_AUTHORIZATION_ERROR, "%s", e.why.c_str()); } catch (SchemaDisagreementException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_SCHEMA_DISAGREEMENT, "%s", e.what()); } catch (TTransportException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_TRANSPORT_ERROR, "%s", e.what()); } catch (TException &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_GENERAL_ERROR, "%s", e.what()); } catch (std::exception &e) { pdo_cassandra_error(stmt->dbh, PDO_CASSANDRA_GENERAL_ERROR, "%s", e.what()); } return 0; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori, long offset TSRMLS_DC) */ static int pdo_cassandra_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori, long offset TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); if (!S->has_iterator) { S->it = S->result.get()->rows.begin (); S->has_iterator = 1; stmt->column_count = (*S->it).columns.size (); } else { S->it++; } if (S->it == S->result.get()->rows.end ()) { // Iterated all rows, reset the iterator S->has_iterator = 0; return 0; } return 1; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_describe(pdo_stmt_t *stmt, int colno TSRMLS_DC) */ static int pdo_cassandra_stmt_describe(pdo_stmt_t *stmt, int colno TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); if (colno < 0 || (colno >= 0 && (static_cast <size_t>(colno) >= (*S->it).columns.size ()))) { return 0; } if (!(*S->it).columns[colno].name.size ()) { return 0; } stmt->columns[colno].name = estrdup (const_cast <char *> ((*S->it).columns[colno].name.c_str ())); stmt->columns[colno].namelen = (*S->it).columns[colno].name.size (); stmt->columns[colno].maxlen = -1; stmt->columns[colno].precision = 0; stmt->columns[colno].param_type = PDO_PARAM_STR; return 1; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_get_column(pdo_stmt_t *stmt, int colno, char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC) */ static int pdo_cassandra_stmt_get_column(pdo_stmt_t *stmt, int colno, char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); if (colno < 0 || (colno >= 0 && (static_cast <size_t>(colno) >= (*S->it).columns.size ()))) { return 0; } *ptr = const_cast <char *> ((*S->it).columns[colno].value.c_str ()); *len = (*S->it).columns[colno].value.size(); *caller_frees = 0; return 1; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_get_column_meta(pdo_stmt_t *stmt, long colno, zval *return_value TSRMLS_DC) */ static int pdo_cassandra_stmt_get_column_meta(pdo_stmt_t *stmt, long colno, zval *return_value TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); if (colno < 0 || (colno >= 0 && (static_cast <size_t>(colno) >= (*S->it).columns.size ()))) { return FAILURE; } array_init(return_value); add_assoc_string(return_value, "native_type", "string", 1); return SUCCESS; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_cursor_closer(pdo_stmt_t *stmt TSRMLS_DC) */ static int pdo_cassandra_stmt_cursor_close(pdo_stmt_t *stmt TSRMLS_DC) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); S->has_iterator = 0; return 1; } /* }}} */ /** {{{ static int pdo_cassandra_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC) */ static int pdo_cassandra_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC) { if (stmt->driver_data) { pdo_cassandra_stmt *S = static_cast <pdo_cassandra_stmt *>(stmt->driver_data); S->result.reset(); delete S; stmt->driver_data = NULL; } return 1; } /* }}} */ struct pdo_stmt_methods cassandra_stmt_methods = { pdo_cassandra_stmt_dtor, pdo_cassandra_stmt_execute, pdo_cassandra_stmt_fetch, pdo_cassandra_stmt_describe, pdo_cassandra_stmt_get_column, NULL, /* param_hook */ NULL, /* set_attr */ NULL, /* get_attr */ pdo_cassandra_stmt_get_column_meta, NULL, /* next_rowset */ pdo_cassandra_stmt_cursor_close }; /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ <|endoftext|>
<commit_before> /* Copyright (c) 2007, Arvid Norberg 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 author 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 <boost/bind.hpp> #include "libtorrent/invariant_check.hpp" #include "libtorrent/connection_queue.hpp" #include "libtorrent/socket.hpp" namespace libtorrent { connection_queue::connection_queue(io_service& ios): m_next_ticket(0) , m_num_connecting(0) , m_half_open_limit(0) , m_abort(false) , m_timer(ios) #ifndef NDEBUG , m_in_timeout_function(false) #endif { #ifdef TORRENT_CONNECTION_LOGGING m_log.open("connection_queue.log"); #endif } int connection_queue::free_slots() const { mutex_t::scoped_lock l(m_mutex); return m_half_open_limit == 0 ? (std::numeric_limits<int>::max)() : m_half_open_limit - m_queue.size(); } void connection_queue::enqueue(boost::function<void(int)> const& on_connect , boost::function<void()> const& on_timeout , time_duration timeout, int priority) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; TORRENT_ASSERT(priority >= 0); TORRENT_ASSERT(priority < 2); entry* e = 0; switch (priority) { case 0: m_queue.push_back(entry()); e = &m_queue.back(); break; case 1: m_queue.push_front(entry()); e = &m_queue.front(); break; } e->priority = priority; e->on_connect = on_connect; e->on_timeout = on_timeout; e->ticket = m_next_ticket; e->timeout = timeout; ++m_next_ticket; try_connect(); } void connection_queue::done(int ticket) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::ticket, _1) == ticket); if (i == m_queue.end()) { // this might not be here in case on_timeout calls remove return; } if (i->connecting) --m_num_connecting; m_queue.erase(i); try_connect(); } void connection_queue::close() { error_code ec; mutex_t::scoped_lock l(m_mutex); m_timer.cancel(ec); m_abort = true; // make a copy of the list to go through, so // that connections removing themseleves won't // interfere with the iteration std::list<entry> closing_entries = m_queue; // we don't want to call the timeout callback while we're locked // since that is a recepie for dead-locks l.unlock(); for (std::list<entry>::iterator i = closing_entries.begin() , end(closing_entries.end()); i != end; ++i) { try { i->on_timeout(); } catch (std::exception&) {} } } void connection_queue::limit(int limit) { TORRENT_ASSERT(limit >= 0); m_half_open_limit = limit; } int connection_queue::limit() const { return m_half_open_limit; } #ifndef NDEBUG void connection_queue::check_invariant() const { int num_connecting = 0; for (std::list<entry>::const_iterator i = m_queue.begin(); i != m_queue.end(); ++i) { if (i->connecting) ++num_connecting; } TORRENT_ASSERT(num_connecting == m_num_connecting); } #endif void connection_queue::try_connect() { INVARIANT_CHECK; #ifdef TORRENT_CONNECTION_LOGGING m_log << log_time() << " " << free_slots() << std::endl; #endif if (m_abort) return; if (m_num_connecting >= m_half_open_limit && m_half_open_limit > 0) return; if (m_queue.empty()) { error_code ec; m_timer.cancel(ec); return; } std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::connecting, _1) == false); while (i != m_queue.end()) { TORRENT_ASSERT(i->connecting == false); ptime expire = time_now() + i->timeout; if (m_num_connecting == 0) { error_code ec; m_timer.expires_at(expire, ec); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } i->connecting = true; ++m_num_connecting; i->expires = expire; INVARIANT_CHECK; entry& ent = *i; ++i; #ifndef BOOST_NO_EXCEPTIONS try { #endif ent.on_connect(ent.ticket); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception&) {} #endif #ifdef TORRENT_CONNECTION_LOGGING m_log << log_time() << " " << free_slots() << std::endl; #endif if (m_num_connecting >= m_half_open_limit && m_half_open_limit > 0) break; i = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false); } } #ifndef NDEBUG struct function_guard { function_guard(bool& v): val(v) { TORRENT_ASSERT(!val); val = true; } ~function_guard() { val = false; } bool& val; }; #endif void connection_queue::on_timeout(error_code const& e) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; #ifndef NDEBUG function_guard guard_(m_in_timeout_function); #endif TORRENT_ASSERT(!e || e == asio::error::operation_aborted); if (e) return; ptime next_expire = max_time(); ptime now = time_now(); std::list<entry> timed_out; for (std::list<entry>::iterator i = m_queue.begin(); !m_queue.empty() && i != m_queue.end();) { if (i->connecting && i->expires < now) { std::list<entry>::iterator j = i; ++i; timed_out.splice(timed_out.end(), m_queue, j, i); --m_num_connecting; continue; } if (i->expires < next_expire) next_expire = i->expires; ++i; } // we don't want to call the timeout callback while we're locked // since that is a recepie for dead-locks l.unlock(); for (std::list<entry>::iterator i = timed_out.begin() , end(timed_out.end()); i != end; ++i) { try { i->on_timeout(); } catch (std::exception&) {} } l.lock(); if (next_expire < max_time()) { error_code ec; m_timer.expires_at(next_expire, ec); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } try_connect(); } } <commit_msg>fix connection_queue::close<commit_after> /* Copyright (c) 2007, Arvid Norberg 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 author 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 <boost/bind.hpp> #include "libtorrent/invariant_check.hpp" #include "libtorrent/connection_queue.hpp" #include "libtorrent/socket.hpp" namespace libtorrent { connection_queue::connection_queue(io_service& ios): m_next_ticket(0) , m_num_connecting(0) , m_half_open_limit(0) , m_abort(false) , m_timer(ios) #ifndef NDEBUG , m_in_timeout_function(false) #endif { #ifdef TORRENT_CONNECTION_LOGGING m_log.open("connection_queue.log"); #endif } int connection_queue::free_slots() const { mutex_t::scoped_lock l(m_mutex); return m_half_open_limit == 0 ? (std::numeric_limits<int>::max)() : m_half_open_limit - m_queue.size(); } void connection_queue::enqueue(boost::function<void(int)> const& on_connect , boost::function<void()> const& on_timeout , time_duration timeout, int priority) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; TORRENT_ASSERT(priority >= 0); TORRENT_ASSERT(priority < 2); entry* e = 0; switch (priority) { case 0: m_queue.push_back(entry()); e = &m_queue.back(); break; case 1: m_queue.push_front(entry()); e = &m_queue.front(); break; } e->priority = priority; e->on_connect = on_connect; e->on_timeout = on_timeout; e->ticket = m_next_ticket; e->timeout = timeout; ++m_next_ticket; try_connect(); } void connection_queue::done(int ticket) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::ticket, _1) == ticket); if (i == m_queue.end()) { // this might not be here in case on_timeout calls remove return; } if (i->connecting) --m_num_connecting; m_queue.erase(i); try_connect(); } void connection_queue::close() { error_code ec; mutex_t::scoped_lock l(m_mutex); m_timer.cancel(ec); m_abort = true; while (!m_queue.empty()) { // we don't want to call the timeout callback while we're locked // since that is a recepie for dead-locks l.unlock(); try { m_queue.front().on_timeout(); } catch (std::exception&) {} l.lock(); m_queue.pop_front(); } } void connection_queue::limit(int limit) { TORRENT_ASSERT(limit >= 0); m_half_open_limit = limit; } int connection_queue::limit() const { return m_half_open_limit; } #ifndef NDEBUG void connection_queue::check_invariant() const { int num_connecting = 0; for (std::list<entry>::const_iterator i = m_queue.begin(); i != m_queue.end(); ++i) { if (i->connecting) ++num_connecting; } TORRENT_ASSERT(num_connecting == m_num_connecting); } #endif void connection_queue::try_connect() { INVARIANT_CHECK; #ifdef TORRENT_CONNECTION_LOGGING m_log << log_time() << " " << free_slots() << std::endl; #endif if (m_abort) return; if (m_num_connecting >= m_half_open_limit && m_half_open_limit > 0) return; if (m_queue.empty()) { error_code ec; m_timer.cancel(ec); return; } std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::connecting, _1) == false); while (i != m_queue.end()) { TORRENT_ASSERT(i->connecting == false); ptime expire = time_now() + i->timeout; if (m_num_connecting == 0) { error_code ec; m_timer.expires_at(expire, ec); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } i->connecting = true; ++m_num_connecting; i->expires = expire; INVARIANT_CHECK; entry& ent = *i; ++i; #ifndef BOOST_NO_EXCEPTIONS try { #endif ent.on_connect(ent.ticket); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception&) {} #endif #ifdef TORRENT_CONNECTION_LOGGING m_log << log_time() << " " << free_slots() << std::endl; #endif if (m_num_connecting >= m_half_open_limit && m_half_open_limit > 0) break; i = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false); } } #ifndef NDEBUG struct function_guard { function_guard(bool& v): val(v) { TORRENT_ASSERT(!val); val = true; } ~function_guard() { val = false; } bool& val; }; #endif void connection_queue::on_timeout(error_code const& e) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; #ifndef NDEBUG function_guard guard_(m_in_timeout_function); #endif TORRENT_ASSERT(!e || e == asio::error::operation_aborted); if (e) return; ptime next_expire = max_time(); ptime now = time_now(); std::list<entry> timed_out; for (std::list<entry>::iterator i = m_queue.begin(); !m_queue.empty() && i != m_queue.end();) { if (i->connecting && i->expires < now) { std::list<entry>::iterator j = i; ++i; timed_out.splice(timed_out.end(), m_queue, j, i); --m_num_connecting; continue; } if (i->expires < next_expire) next_expire = i->expires; ++i; } // we don't want to call the timeout callback while we're locked // since that is a recepie for dead-locks l.unlock(); for (std::list<entry>::iterator i = timed_out.begin() , end(timed_out.end()); i != end; ++i) { try { i->on_timeout(); } catch (std::exception&) {} } l.lock(); if (next_expire < max_time()) { error_code ec; m_timer.expires_at(next_expire, ec); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } try_connect(); } } <|endoftext|>
<commit_before> /* Copyright (c) 2007, Arvid Norberg 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 author 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 <boost/bind.hpp> #include "libtorrent/invariant_check.hpp" #include "libtorrent/connection_queue.hpp" #include "libtorrent/socket.hpp" namespace libtorrent { connection_queue::connection_queue(io_service& ios): m_next_ticket(0) , m_num_connecting(0) , m_half_open_limit(0) , m_abort(false) , m_timer(ios) #ifndef NDEBUG , m_in_timeout_function(false) #endif { #ifdef TORRENT_CONNECTION_LOGGING m_log.open("connection_queue.log"); #endif } int connection_queue::free_slots() const { mutex_t::scoped_lock l(m_mutex); return m_half_open_limit == 0 ? (std::numeric_limits<int>::max)() : m_half_open_limit - m_queue.size(); } void connection_queue::enqueue(boost::function<void(int)> const& on_connect , boost::function<void()> const& on_timeout , time_duration timeout, int priority) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; TORRENT_ASSERT(priority >= 0); TORRENT_ASSERT(priority < 2); entry* e = 0; switch (priority) { case 0: m_queue.push_back(entry()); e = &m_queue.back(); break; case 1: m_queue.push_front(entry()); e = &m_queue.front(); break; } e->priority = priority; e->on_connect = on_connect; e->on_timeout = on_timeout; e->ticket = m_next_ticket; e->timeout = timeout; ++m_next_ticket; try_connect(); } void connection_queue::done(int ticket) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::ticket, _1) == ticket); if (i == m_queue.end()) { // this might not be here in case on_timeout calls remove return; } if (i->connecting) --m_num_connecting; m_queue.erase(i); try_connect(); } void connection_queue::close() { error_code ec; mutex_t::scoped_lock l(m_mutex); m_timer.cancel(ec); m_abort = true; while (!m_queue.empty()) { // we don't want to call the timeout callback while we're locked // since that is a recepie for dead-locks entry e = m_queue.front(); m_queue.pop_front(); l.unlock(); try { e.on_timeout(); } catch (std::exception&) {} l.lock(); } } void connection_queue::limit(int limit) { TORRENT_ASSERT(limit >= 0); m_half_open_limit = limit; } int connection_queue::limit() const { return m_half_open_limit; } #ifndef NDEBUG void connection_queue::check_invariant() const { int num_connecting = 0; for (std::list<entry>::const_iterator i = m_queue.begin(); i != m_queue.end(); ++i) { if (i->connecting) ++num_connecting; } TORRENT_ASSERT(num_connecting == m_num_connecting); } #endif void connection_queue::try_connect() { INVARIANT_CHECK; #ifdef TORRENT_CONNECTION_LOGGING m_log << log_time() << " " << free_slots() << std::endl; #endif if (m_abort) return; if (m_num_connecting >= m_half_open_limit && m_half_open_limit > 0) return; if (m_queue.empty()) { error_code ec; m_timer.cancel(ec); return; } std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::connecting, _1) == false); while (i != m_queue.end()) { TORRENT_ASSERT(i->connecting == false); ptime expire = time_now() + i->timeout; if (m_num_connecting == 0) { error_code ec; m_timer.expires_at(expire, ec); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } i->connecting = true; ++m_num_connecting; i->expires = expire; INVARIANT_CHECK; entry& ent = *i; ++i; #ifndef BOOST_NO_EXCEPTIONS try { #endif ent.on_connect(ent.ticket); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception&) {} #endif #ifdef TORRENT_CONNECTION_LOGGING m_log << log_time() << " " << free_slots() << std::endl; #endif if (m_num_connecting >= m_half_open_limit && m_half_open_limit > 0) break; i = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false); } } #ifndef NDEBUG struct function_guard { function_guard(bool& v): val(v) { TORRENT_ASSERT(!val); val = true; } ~function_guard() { val = false; } bool& val; }; #endif void connection_queue::on_timeout(error_code const& e) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; #ifndef NDEBUG function_guard guard_(m_in_timeout_function); #endif TORRENT_ASSERT(!e || e == asio::error::operation_aborted); if (e) return; ptime next_expire = max_time(); ptime now = time_now(); std::list<entry> timed_out; for (std::list<entry>::iterator i = m_queue.begin(); !m_queue.empty() && i != m_queue.end();) { if (i->connecting && i->expires < now) { std::list<entry>::iterator j = i; ++i; timed_out.splice(timed_out.end(), m_queue, j, i); --m_num_connecting; continue; } if (i->expires < next_expire) next_expire = i->expires; ++i; } // we don't want to call the timeout callback while we're locked // since that is a recepie for dead-locks l.unlock(); for (std::list<entry>::iterator i = timed_out.begin() , end(timed_out.end()); i != end; ++i) { try { i->on_timeout(); } catch (std::exception&) {} } l.lock(); if (next_expire < max_time()) { error_code ec; m_timer.expires_at(next_expire, ec); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } try_connect(); } } <commit_msg>fix for connection_queue::close() to maintain the correct m_num_connecting counter<commit_after> /* Copyright (c) 2007, Arvid Norberg 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 author 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 <boost/bind.hpp> #include "libtorrent/invariant_check.hpp" #include "libtorrent/connection_queue.hpp" #include "libtorrent/socket.hpp" namespace libtorrent { connection_queue::connection_queue(io_service& ios): m_next_ticket(0) , m_num_connecting(0) , m_half_open_limit(0) , m_abort(false) , m_timer(ios) #ifndef NDEBUG , m_in_timeout_function(false) #endif { #ifdef TORRENT_CONNECTION_LOGGING m_log.open("connection_queue.log"); #endif } int connection_queue::free_slots() const { mutex_t::scoped_lock l(m_mutex); return m_half_open_limit == 0 ? (std::numeric_limits<int>::max)() : m_half_open_limit - m_queue.size(); } void connection_queue::enqueue(boost::function<void(int)> const& on_connect , boost::function<void()> const& on_timeout , time_duration timeout, int priority) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; TORRENT_ASSERT(priority >= 0); TORRENT_ASSERT(priority < 2); entry* e = 0; switch (priority) { case 0: m_queue.push_back(entry()); e = &m_queue.back(); break; case 1: m_queue.push_front(entry()); e = &m_queue.front(); break; } e->priority = priority; e->on_connect = on_connect; e->on_timeout = on_timeout; e->ticket = m_next_ticket; e->timeout = timeout; ++m_next_ticket; try_connect(); } void connection_queue::done(int ticket) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::ticket, _1) == ticket); if (i == m_queue.end()) { // this might not be here in case on_timeout calls remove return; } if (i->connecting) --m_num_connecting; m_queue.erase(i); try_connect(); } void connection_queue::close() { error_code ec; mutex_t::scoped_lock l(m_mutex); m_timer.cancel(ec); m_abort = true; while (!m_queue.empty()) { // we don't want to call the timeout callback while we're locked // since that is a recepie for dead-locks entry e = m_queue.front(); m_queue.pop_front(); if (e.connecting) --m_num_connecting; l.unlock(); try { e.on_timeout(); } catch (std::exception&) {} l.lock(); } } void connection_queue::limit(int limit) { TORRENT_ASSERT(limit >= 0); m_half_open_limit = limit; } int connection_queue::limit() const { return m_half_open_limit; } #ifndef NDEBUG void connection_queue::check_invariant() const { int num_connecting = 0; for (std::list<entry>::const_iterator i = m_queue.begin(); i != m_queue.end(); ++i) { if (i->connecting) ++num_connecting; } TORRENT_ASSERT(num_connecting == m_num_connecting); } #endif void connection_queue::try_connect() { INVARIANT_CHECK; #ifdef TORRENT_CONNECTION_LOGGING m_log << log_time() << " " << free_slots() << std::endl; #endif if (m_abort) return; if (m_num_connecting >= m_half_open_limit && m_half_open_limit > 0) return; if (m_queue.empty()) { error_code ec; m_timer.cancel(ec); return; } std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::connecting, _1) == false); while (i != m_queue.end()) { TORRENT_ASSERT(i->connecting == false); ptime expire = time_now() + i->timeout; if (m_num_connecting == 0) { error_code ec; m_timer.expires_at(expire, ec); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } i->connecting = true; ++m_num_connecting; i->expires = expire; INVARIANT_CHECK; entry& ent = *i; ++i; #ifndef BOOST_NO_EXCEPTIONS try { #endif ent.on_connect(ent.ticket); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception&) {} #endif #ifdef TORRENT_CONNECTION_LOGGING m_log << log_time() << " " << free_slots() << std::endl; #endif if (m_num_connecting >= m_half_open_limit && m_half_open_limit > 0) break; i = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false); } } #ifndef NDEBUG struct function_guard { function_guard(bool& v): val(v) { TORRENT_ASSERT(!val); val = true; } ~function_guard() { val = false; } bool& val; }; #endif void connection_queue::on_timeout(error_code const& e) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; #ifndef NDEBUG function_guard guard_(m_in_timeout_function); #endif TORRENT_ASSERT(!e || e == asio::error::operation_aborted); if (e) return; ptime next_expire = max_time(); ptime now = time_now(); std::list<entry> timed_out; for (std::list<entry>::iterator i = m_queue.begin(); !m_queue.empty() && i != m_queue.end();) { if (i->connecting && i->expires < now) { std::list<entry>::iterator j = i; ++i; timed_out.splice(timed_out.end(), m_queue, j, i); --m_num_connecting; continue; } if (i->expires < next_expire) next_expire = i->expires; ++i; } // we don't want to call the timeout callback while we're locked // since that is a recepie for dead-locks l.unlock(); for (std::list<entry>::iterator i = timed_out.begin() , end(timed_out.end()); i != end; ++i) { try { i->on_timeout(); } catch (std::exception&) {} } l.lock(); if (next_expire < max_time()) { error_code ec; m_timer.expires_at(next_expire, ec); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } try_connect(); } } <|endoftext|>
<commit_before>/* * openni_face_detection.cpp * * Created on: 22 Sep 2012 * Author: Aitor Aldoma */ #include "pcl/recognition/face_detection/rf_face_detector_trainer.h" #include "pcl/apps/face_detection/openni_frame_source.h" #include "pcl/apps/face_detection/face_detection_apps_utils.h" #include <pcl/console/parse.h> #include <pcl/features/integral_image_normal.h> void run(pcl::RFFaceDetectorTrainer & fdrf, bool heat_map = false, bool show_votes = false) { OpenNIFrameSource::OpenNIFrameSource camera; OpenNIFrameSource::PointCloudPtr scene_vis; pcl::visualization::PCLVisualizer vis ("Face dection"); vis.addCoordinateSystem (0.1); //keyboard callback to stop getting frames and finalize application boost::function<void(const pcl::visualization::KeyboardEvent&)> keyboard_cb = boost::bind (&OpenNIFrameSource::OpenNIFrameSource::onKeyboardEvent, &camera, _1); vis.registerKeyboardCallback (keyboard_cb); while (camera.isActive ()) { scene_vis = camera.snap (); typename pcl::PointCloud<pcl::PointXYZ>::Ptr scene (new pcl::PointCloud<pcl::PointXYZ> ()); pcl::copyPointCloud (*scene_vis, *scene); fdrf.setInputCloud (scene); if (heat_map) { pcl::PointCloud<pcl::PointXYZI>::Ptr intensity_cloud (new pcl::PointCloud<pcl::PointXYZI>); fdrf.setFaceHeatMapCloud (intensity_cloud); } { pcl::ScopeTime t ("Detect faces..."); fdrf.detectFaces (); } pcl::visualization::PointCloudColorHandlerRGBField<OpenNIFrameSource::PointT> handler_keypoints (scene_vis); vis.addPointCloud < OpenNIFrameSource::PointT > (scene_vis, handler_keypoints, "scene_cloud"); if (heat_map) { pcl::PointCloud<pcl::PointXYZI>::Ptr intensity_cloud (new pcl::PointCloud<pcl::PointXYZI>); fdrf.getFaceHeatMap (intensity_cloud); pcl::visualization::PointCloudColorHandlerGenericField < pcl::PointXYZI > handler_keypoints (intensity_cloud, "intensity"); vis.addPointCloud < pcl::PointXYZI > (intensity_cloud, handler_keypoints, "heat_map"); } if (show_votes) { //display votes_ pcl::PointCloud<pcl::PointXYZ>::Ptr votes_cloud (new pcl::PointCloud<pcl::PointXYZ> ()); fdrf.getVotes (votes_cloud); pcl::visualization::PointCloudColorHandlerCustom < pcl::PointXYZ > handler_votes (votes_cloud, 255, 0, 0); vis.addPointCloud < pcl::PointXYZ > (votes_cloud, handler_votes, "votes_cloud"); vis.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 14, "votes_cloud"); vis.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, 0.5, "votes_cloud"); vis.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, 0.75, "votes_cloud"); } std::vector<Eigen::VectorXf> heads; fdrf.getDetectedFaces (heads); face_detection_apps_utils::displayHeads (heads, vis); vis.setRepresentationToSurfaceForAllActors (); vis.spinOnce (); vis.removeAllPointClouds (); vis.removeAllShapes (); } } //./bin/pcl_openni_face_detector -face_threshold 0.99 -max_variance 2400 -min_votes_size 300 -stride_sw 4 -heat_map 0 -show_votes 1 -pose_refinement 1 -icp_iterations 5 -model_path face_model.pcd -forest_fn forest.txt int main(int argc, char ** argv) { int STRIDE_SW = 4; int use_normals = 0; float trans_max_variance = 1600.f; int min_votes_size = 300; float face_threshold = 0.99f; int heat_map = 1; int show_votes = 0; int pose_refinement_ = 0; int icp_iterations = 5; std::string forest_fn = "../data/forests/forest.txt"; std::string model_path_ = "../data/ply_models/face.pcd"; pcl::console::parse_argument (argc, argv, "-forest_fn", forest_fn); pcl::console::parse_argument (argc, argv, "-max_variance", trans_max_variance); pcl::console::parse_argument (argc, argv, "-min_votes_size", min_votes_size); pcl::console::parse_argument (argc, argv, "-use_normals", use_normals); pcl::console::parse_argument (argc, argv, "-face_threshold", face_threshold); pcl::console::parse_argument (argc, argv, "-stride_sw", STRIDE_SW); pcl::console::parse_argument (argc, argv, "-heat_map", heat_map); pcl::console::parse_argument (argc, argv, "-show_votes", show_votes); pcl::console::parse_argument (argc, argv, "-pose_refinement", pose_refinement_); pcl::console::parse_argument (argc, argv, "-model_path", model_path_); pcl::console::parse_argument (argc, argv, "-icp_iterations", icp_iterations); pcl::RFFaceDetectorTrainer fdrf; fdrf.setForestFilename (forest_fn); fdrf.setWSize (80); fdrf.setUseNormals (static_cast<bool> (use_normals)); fdrf.setWStride (STRIDE_SW); fdrf.setLeavesFaceMaxVariance (trans_max_variance); fdrf.setLeavesFaceThreshold (face_threshold); fdrf.setFaceMinVotes (min_votes_size); if (pose_refinement_) { fdrf.setPoseRefinement (true, icp_iterations); fdrf.setModelPath (model_path_); } //load forest from file and pass it to the detector std::filebuf fb; fb.open (forest_fn.c_str (), std::ios::in); std::istream os (&fb); typedef pcl::face_detection::RFTreeNode<pcl::face_detection::FeatureType> NodeType; pcl::DecisionForest<NodeType> forest; forest.deserialize (os); fb.close (); fdrf.setForest (forest); run (fdrf, heat_map, show_votes); } <commit_msg>Yet another typename out of place... copy paste is evil.<commit_after>/* * openni_face_detection.cpp * * Created on: 22 Sep 2012 * Author: Aitor Aldoma */ #include "pcl/recognition/face_detection/rf_face_detector_trainer.h" #include "pcl/apps/face_detection/openni_frame_source.h" #include "pcl/apps/face_detection/face_detection_apps_utils.h" #include <pcl/console/parse.h> #include <pcl/features/integral_image_normal.h> void run(pcl::RFFaceDetectorTrainer & fdrf, bool heat_map = false, bool show_votes = false) { OpenNIFrameSource::OpenNIFrameSource camera; OpenNIFrameSource::PointCloudPtr scene_vis; pcl::visualization::PCLVisualizer vis ("Face dection"); vis.addCoordinateSystem (0.1); //keyboard callback to stop getting frames and finalize application boost::function<void(const pcl::visualization::KeyboardEvent&)> keyboard_cb = boost::bind (&OpenNIFrameSource::OpenNIFrameSource::onKeyboardEvent, &camera, _1); vis.registerKeyboardCallback (keyboard_cb); while (camera.isActive ()) { scene_vis = camera.snap (); pcl::PointCloud<pcl::PointXYZ>::Ptr scene (new pcl::PointCloud<pcl::PointXYZ> ()); pcl::copyPointCloud (*scene_vis, *scene); fdrf.setInputCloud (scene); if (heat_map) { pcl::PointCloud<pcl::PointXYZI>::Ptr intensity_cloud (new pcl::PointCloud<pcl::PointXYZI>); fdrf.setFaceHeatMapCloud (intensity_cloud); } { pcl::ScopeTime t ("Detect faces..."); fdrf.detectFaces (); } pcl::visualization::PointCloudColorHandlerRGBField<OpenNIFrameSource::PointT> handler_keypoints (scene_vis); vis.addPointCloud < OpenNIFrameSource::PointT > (scene_vis, handler_keypoints, "scene_cloud"); if (heat_map) { pcl::PointCloud<pcl::PointXYZI>::Ptr intensity_cloud (new pcl::PointCloud<pcl::PointXYZI>); fdrf.getFaceHeatMap (intensity_cloud); pcl::visualization::PointCloudColorHandlerGenericField < pcl::PointXYZI > handler_keypoints (intensity_cloud, "intensity"); vis.addPointCloud < pcl::PointXYZI > (intensity_cloud, handler_keypoints, "heat_map"); } if (show_votes) { //display votes_ pcl::PointCloud<pcl::PointXYZ>::Ptr votes_cloud (new pcl::PointCloud<pcl::PointXYZ> ()); fdrf.getVotes (votes_cloud); pcl::visualization::PointCloudColorHandlerCustom < pcl::PointXYZ > handler_votes (votes_cloud, 255, 0, 0); vis.addPointCloud < pcl::PointXYZ > (votes_cloud, handler_votes, "votes_cloud"); vis.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 14, "votes_cloud"); vis.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, 0.5, "votes_cloud"); vis.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, 0.75, "votes_cloud"); } std::vector<Eigen::VectorXf> heads; fdrf.getDetectedFaces (heads); face_detection_apps_utils::displayHeads (heads, vis); vis.setRepresentationToSurfaceForAllActors (); vis.spinOnce (); vis.removeAllPointClouds (); vis.removeAllShapes (); } } //./bin/pcl_openni_face_detector -face_threshold 0.99 -max_variance 2400 -min_votes_size 300 -stride_sw 4 -heat_map 0 -show_votes 1 -pose_refinement 1 -icp_iterations 5 -model_path face_model.pcd -forest_fn forest.txt int main(int argc, char ** argv) { int STRIDE_SW = 4; int use_normals = 0; float trans_max_variance = 1600.f; int min_votes_size = 300; float face_threshold = 0.99f; int heat_map = 1; int show_votes = 0; int pose_refinement_ = 0; int icp_iterations = 5; std::string forest_fn = "../data/forests/forest.txt"; std::string model_path_ = "../data/ply_models/face.pcd"; pcl::console::parse_argument (argc, argv, "-forest_fn", forest_fn); pcl::console::parse_argument (argc, argv, "-max_variance", trans_max_variance); pcl::console::parse_argument (argc, argv, "-min_votes_size", min_votes_size); pcl::console::parse_argument (argc, argv, "-use_normals", use_normals); pcl::console::parse_argument (argc, argv, "-face_threshold", face_threshold); pcl::console::parse_argument (argc, argv, "-stride_sw", STRIDE_SW); pcl::console::parse_argument (argc, argv, "-heat_map", heat_map); pcl::console::parse_argument (argc, argv, "-show_votes", show_votes); pcl::console::parse_argument (argc, argv, "-pose_refinement", pose_refinement_); pcl::console::parse_argument (argc, argv, "-model_path", model_path_); pcl::console::parse_argument (argc, argv, "-icp_iterations", icp_iterations); pcl::RFFaceDetectorTrainer fdrf; fdrf.setForestFilename (forest_fn); fdrf.setWSize (80); fdrf.setUseNormals (static_cast<bool> (use_normals)); fdrf.setWStride (STRIDE_SW); fdrf.setLeavesFaceMaxVariance (trans_max_variance); fdrf.setLeavesFaceThreshold (face_threshold); fdrf.setFaceMinVotes (min_votes_size); if (pose_refinement_) { fdrf.setPoseRefinement (true, icp_iterations); fdrf.setModelPath (model_path_); } //load forest from file and pass it to the detector std::filebuf fb; fb.open (forest_fn.c_str (), std::ios::in); std::istream os (&fb); typedef pcl::face_detection::RFTreeNode<pcl::face_detection::FeatureType> NodeType; pcl::DecisionForest<NodeType> forest; forest.deserialize (os); fb.close (); fdrf.setForest (forest); run (fdrf, heat_map, show_votes); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "RocksDBTransactionState.h" #include "Aql/QueryCache.h" #include "Basics/Exceptions.h" #include "Cache/CacheManagerFeature.h" #include "Cache/Manager.h" #include "Cache/Transaction.h" #include "Logger/Logger.h" #include "RestServer/TransactionManagerFeature.h" #include "RocksDBEngine/RocksDBCollection.h" #include "RocksDBEngine/RocksDBCommon.h" #include "RocksDBEngine/RocksDBCounterManager.h" #include "RocksDBEngine/RocksDBEngine.h" #include "RocksDBEngine/RocksDBLogValue.h" #include "RocksDBEngine/RocksDBTransactionCollection.h" #include "StorageEngine/EngineSelectorFeature.h" #include "StorageEngine/StorageEngine.h" #include "StorageEngine/TransactionCollection.h" #include "Transaction/Methods.h" #include "VocBase/LogicalCollection.h" #include "VocBase/TransactionManager.h" #include "VocBase/modes.h" #include "VocBase/ticks.h" #include <rocksdb/db.h> #include <rocksdb/options.h> #include <rocksdb/status.h> #include <rocksdb/utilities/optimistic_transaction_db.h> #include <rocksdb/utilities/transaction.h> using namespace arangodb; // for the RocksDB engine we do not need any additional data struct RocksDBTransactionData final : public TransactionData {}; RocksDBSavePoint::RocksDBSavePoint(rocksdb::Transaction* trx) : RocksDBSavePoint(trx, false) {} RocksDBSavePoint::RocksDBSavePoint(rocksdb::Transaction* trx, bool handled) : _trx(trx), _handled(handled) { TRI_ASSERT(trx != nullptr); if (!_handled) { _trx->SetSavePoint(); } } RocksDBSavePoint::~RocksDBSavePoint() { if (!_handled) { rollback(); } } void RocksDBSavePoint::commit() { // note: _handled may already be true here _handled = true; // this will prevent the rollback } void RocksDBSavePoint::rollback() { TRI_ASSERT(!_handled); _trx->RollbackToSavePoint(); _handled = true; // in order to not roll back again by accident } /// @brief transaction type RocksDBTransactionState::RocksDBTransactionState( TRI_vocbase_t* vocbase, uint64_t maxTransSize, bool intermediateTransactionEnabled, uint64_t intermediateTransactionSize, uint64_t intermediateTransactionNumber) : TransactionState(vocbase), _rocksReadOptions(), _cacheTx(nullptr), _transactionSize(0), _maxTransactionSize(maxTransSize), _intermediateTransactionSize(intermediateTransactionSize), _intermediateTransactionNumber(intermediateTransactionNumber), _numInserts(0), _numUpdates(0), _numRemoves(0), _intermediateTransactionEnabled(intermediateTransactionEnabled) {} /// @brief free a transaction container RocksDBTransactionState::~RocksDBTransactionState() { if (_cacheTx != nullptr) { // note: endTransaction() will delete _cacheTrx! CacheManagerFeature::MANAGER->endTransaction(_cacheTx); _cacheTx = nullptr; } } /// @brief start a transaction Result RocksDBTransactionState::beginTransaction(transaction::Hints hints) { LOG_TRX(this, _nestingLevel) << "beginning " << AccessMode::typeString(_type) << " transaction"; Result result = useCollections(_nestingLevel); if (result.ok()) { // all valid if (_nestingLevel == 0) { updateStatus(transaction::Status::RUNNING); } } else { // something is wrong if (_nestingLevel == 0) { updateStatus(transaction::Status::ABORTED); } // free what we have got so far unuseCollections(_nestingLevel); return result; } if (_nestingLevel == 0) { // get a new id _id = TRI_NewTickServer(); // register a protector auto data = std::make_unique<RocksDBTransactionData>(); // intentionally empty TransactionManagerFeature::MANAGER->registerTransaction(_id, std::move(data)); TRI_ASSERT(_rocksTransaction == nullptr); TRI_ASSERT(_cacheTx == nullptr); // start cache transaction _cacheTx = CacheManagerFeature::MANAGER->beginTransaction(isReadOnlyTransaction()); // start rocks transaction StorageEngine* engine = EngineSelectorFeature::ENGINE; rocksdb::TransactionDB* db = static_cast<RocksDBEngine*>(engine)->db(); _rocksTransaction.reset(db->BeginTransaction( _rocksWriteOptions, rocksdb::TransactionOptions())); _rocksTransaction->SetSnapshot(); _rocksReadOptions.snapshot = _rocksTransaction->GetSnapshot(); RocksDBLogValue header = RocksDBLogValue::BeginTransaction(_vocbase->id(), _id); _rocksTransaction->PutLogData(header.slice()); } else { TRI_ASSERT(_status == transaction::Status::RUNNING); } return result; } /// @brief commit a transaction Result RocksDBTransactionState::commitTransaction( transaction::Methods* activeTrx) { LOG_TRX(this, _nestingLevel) << "committing " << AccessMode::typeString(_type) << " transaction"; TRI_ASSERT(_status == transaction::Status::RUNNING); TRI_IF_FAILURE("TransactionWriteCommitMarker") { return Result(TRI_ERROR_DEBUG); } arangodb::Result result; if (_nestingLevel == 0) { if (_rocksTransaction != nullptr) { // set wait for sync flag if required if (waitForSync()) { _rocksWriteOptions.sync = true; _rocksTransaction->SetWriteOptions(_rocksWriteOptions); } rocksdb::SequenceNumber prevSeq = rocksutils::globalRocksDB()->GetLatestSequenceNumber(); // TODO wait for response on github issue to see how we can use the // sequence number result = rocksutils::convertStatus(_rocksTransaction->Commit()); rocksdb::SequenceNumber latestSeq = rocksutils::globalRocksDB()->GetLatestSequenceNumber(); if (prevSeq+1 != latestSeq) { LOG_TOPIC(INFO, Logger::DEVEL) << "Commits slipped between commits"; } if (!result.ok()) { abortTransaction(activeTrx); return result; } if (_cacheTx != nullptr) { // note: endTransaction() will delete _cacheTx! CacheManagerFeature::MANAGER->endTransaction(_cacheTx); _cacheTx = nullptr; } rocksdb::Snapshot const* snap = this->_rocksReadOptions.snapshot; TRI_ASSERT(snap != nullptr); for (auto& trxCollection : _collections) { RocksDBTransactionCollection* collection = static_cast<RocksDBTransactionCollection*>(trxCollection); int64_t adjustment = collection->numInserts() - collection->numRemoves(); if (collection->numInserts() != 0 || collection->numRemoves() != 0 || collection->revision() != 0) { RocksDBCollection* coll = static_cast<RocksDBCollection*>( trxCollection->collection()->getPhysical()); coll->adjustNumberDocuments(adjustment); coll->setRevision(collection->revision()); RocksDBEngine* engine = static_cast<RocksDBEngine*>(EngineSelectorFeature::ENGINE); RocksDBCounterManager::CounterAdjustment update( latestSeq, collection->numInserts(), collection->numRemoves(), collection->revision()); engine->counterManager()->updateCounter(coll->objectId(), update); } } _rocksTransaction.reset(); } updateStatus(transaction::Status::COMMITTED); } unuseCollections(_nestingLevel); return result; } /// @brief abort and rollback a transaction Result RocksDBTransactionState::abortTransaction( transaction::Methods* activeTrx) { LOG_TRX(this, _nestingLevel) << "aborting " << AccessMode::typeString(_type) << " transaction"; TRI_ASSERT(_status == transaction::Status::RUNNING); Result result; if (_nestingLevel == 0) { if (_rocksTransaction != nullptr) { rocksdb::Status status = _rocksTransaction->Rollback(); result = rocksutils::convertStatus(status); _rocksTransaction.reset(); } if (_cacheTx != nullptr) { // note: endTransaction() will delete _cacheTx! CacheManagerFeature::MANAGER->endTransaction(_cacheTx); _cacheTx = nullptr; } updateStatus(transaction::Status::ABORTED); if (hasOperations()) { // must clean up the query cache because the transaction // may have queried something via AQL that is now rolled back clearQueryCache(); } } unuseCollections(_nestingLevel); return result; } /// @brief add an operation for a transaction collection RocksDBOperationResult RocksDBTransactionState::addOperation( TRI_voc_cid_t cid, TRI_voc_rid_t revisionId, TRI_voc_document_operation_e operationType, uint64_t operationSize, uint64_t keySize) { RocksDBOperationResult res; uint64_t newSize = _transactionSize + operationSize + keySize; if (_maxTransactionSize < newSize) { // we hit the transaction size limit std::string message = "aborting transaction because maximal transaction size limit of " + std::to_string(_maxTransactionSize) + " bytes is reached"; res.reset(TRI_ERROR_RESOURCE_LIMIT, message); return res; } auto collection = static_cast<RocksDBTransactionCollection*>(findCollection(cid)); if (collection == nullptr) { std::string message = "collection '" + std::to_string(cid) + "' not found in transaction state"; THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, message); } // should not fail or fail with exception collection->addOperation(operationType, operationSize, revisionId); // clear the query cache for this collection if (arangodb::aql::QueryCache::instance()->mayBeActive()) { arangodb::aql::QueryCache::instance()->invalidate( _vocbase, collection->collectionName()); } switch (operationType) { case TRI_VOC_DOCUMENT_OPERATION_UNKNOWN: break; case TRI_VOC_DOCUMENT_OPERATION_INSERT: ++_numInserts; break; case TRI_VOC_DOCUMENT_OPERATION_UPDATE: case TRI_VOC_DOCUMENT_OPERATION_REPLACE: ++_numUpdates; break; case TRI_VOC_DOCUMENT_OPERATION_REMOVE: ++_numRemoves; break; } _transactionSize = newSize; auto numOperations = _numInserts + _numUpdates + _numRemoves; // signal if intermediate commit is required // this will be done if intermediate transactions are enabled // and either the "number of operations" or the "transaction size" // has reached the limit if (_intermediateTransactionEnabled && (_intermediateTransactionNumber <= numOperations || _intermediateTransactionSize <= newSize)) { res.commitRequired(true); } return res; } uint64_t RocksDBTransactionState::sequenceNumber() const { return static_cast<uint64_t>( _rocksTransaction->GetSnapshot()->GetSequenceNumber()); } void RocksDBTransactionState::reset() { // only reset when already commited TRI_ASSERT(_status == transaction::Status::COMMITTED); // reset count _transactionSize = 0; _numInserts = 0; _numUpdates = 0; _numRemoves = 0; unuseCollections(_nestingLevel); for (auto it = _collections.rbegin(); it != _collections.rend(); ++it) { (static_cast<RocksDBTransactionCollection*>(*it))->resetCounts(); } _nestingLevel = 0; updateStatus(transaction::Status::CREATED); // start new transaction beginTransaction(transaction::Hints()); } <commit_msg>change log level for debugging<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "RocksDBTransactionState.h" #include "Aql/QueryCache.h" #include "Basics/Exceptions.h" #include "Cache/CacheManagerFeature.h" #include "Cache/Manager.h" #include "Cache/Transaction.h" #include "Logger/Logger.h" #include "RestServer/TransactionManagerFeature.h" #include "RocksDBEngine/RocksDBCollection.h" #include "RocksDBEngine/RocksDBCommon.h" #include "RocksDBEngine/RocksDBCounterManager.h" #include "RocksDBEngine/RocksDBEngine.h" #include "RocksDBEngine/RocksDBLogValue.h" #include "RocksDBEngine/RocksDBTransactionCollection.h" #include "StorageEngine/EngineSelectorFeature.h" #include "StorageEngine/StorageEngine.h" #include "StorageEngine/TransactionCollection.h" #include "Transaction/Methods.h" #include "VocBase/LogicalCollection.h" #include "VocBase/TransactionManager.h" #include "VocBase/modes.h" #include "VocBase/ticks.h" #include <rocksdb/db.h> #include <rocksdb/options.h> #include <rocksdb/status.h> #include <rocksdb/utilities/optimistic_transaction_db.h> #include <rocksdb/utilities/transaction.h> using namespace arangodb; // for the RocksDB engine we do not need any additional data struct RocksDBTransactionData final : public TransactionData {}; RocksDBSavePoint::RocksDBSavePoint(rocksdb::Transaction* trx) : RocksDBSavePoint(trx, false) {} RocksDBSavePoint::RocksDBSavePoint(rocksdb::Transaction* trx, bool handled) : _trx(trx), _handled(handled) { TRI_ASSERT(trx != nullptr); if (!_handled) { _trx->SetSavePoint(); } } RocksDBSavePoint::~RocksDBSavePoint() { if (!_handled) { rollback(); } } void RocksDBSavePoint::commit() { // note: _handled may already be true here _handled = true; // this will prevent the rollback } void RocksDBSavePoint::rollback() { TRI_ASSERT(!_handled); _trx->RollbackToSavePoint(); _handled = true; // in order to not roll back again by accident } /// @brief transaction type RocksDBTransactionState::RocksDBTransactionState( TRI_vocbase_t* vocbase, uint64_t maxTransSize, bool intermediateTransactionEnabled, uint64_t intermediateTransactionSize, uint64_t intermediateTransactionNumber) : TransactionState(vocbase), _rocksReadOptions(), _cacheTx(nullptr), _transactionSize(0), _maxTransactionSize(maxTransSize), _intermediateTransactionSize(intermediateTransactionSize), _intermediateTransactionNumber(intermediateTransactionNumber), _numInserts(0), _numUpdates(0), _numRemoves(0), _intermediateTransactionEnabled(intermediateTransactionEnabled) {} /// @brief free a transaction container RocksDBTransactionState::~RocksDBTransactionState() { if (_cacheTx != nullptr) { // note: endTransaction() will delete _cacheTrx! CacheManagerFeature::MANAGER->endTransaction(_cacheTx); _cacheTx = nullptr; } } /// @brief start a transaction Result RocksDBTransactionState::beginTransaction(transaction::Hints hints) { LOG_TRX(this, _nestingLevel) << "beginning " << AccessMode::typeString(_type) << " transaction"; Result result = useCollections(_nestingLevel); if (result.ok()) { // all valid if (_nestingLevel == 0) { updateStatus(transaction::Status::RUNNING); } } else { // something is wrong if (_nestingLevel == 0) { updateStatus(transaction::Status::ABORTED); } // free what we have got so far unuseCollections(_nestingLevel); return result; } if (_nestingLevel == 0) { // get a new id _id = TRI_NewTickServer(); // register a protector auto data = std::make_unique<RocksDBTransactionData>(); // intentionally empty TransactionManagerFeature::MANAGER->registerTransaction(_id, std::move(data)); TRI_ASSERT(_rocksTransaction == nullptr); TRI_ASSERT(_cacheTx == nullptr); // start cache transaction _cacheTx = CacheManagerFeature::MANAGER->beginTransaction(isReadOnlyTransaction()); // start rocks transaction StorageEngine* engine = EngineSelectorFeature::ENGINE; rocksdb::TransactionDB* db = static_cast<RocksDBEngine*>(engine)->db(); _rocksTransaction.reset(db->BeginTransaction( _rocksWriteOptions, rocksdb::TransactionOptions())); _rocksTransaction->SetSnapshot(); _rocksReadOptions.snapshot = _rocksTransaction->GetSnapshot(); RocksDBLogValue header = RocksDBLogValue::BeginTransaction(_vocbase->id(), _id); _rocksTransaction->PutLogData(header.slice()); } else { TRI_ASSERT(_status == transaction::Status::RUNNING); } return result; } /// @brief commit a transaction Result RocksDBTransactionState::commitTransaction( transaction::Methods* activeTrx) { LOG_TRX(this, _nestingLevel) << "committing " << AccessMode::typeString(_type) << " transaction"; TRI_ASSERT(_status == transaction::Status::RUNNING); TRI_IF_FAILURE("TransactionWriteCommitMarker") { return Result(TRI_ERROR_DEBUG); } arangodb::Result result; if (_nestingLevel == 0) { if (_rocksTransaction != nullptr) { // set wait for sync flag if required if (waitForSync()) { _rocksWriteOptions.sync = true; _rocksTransaction->SetWriteOptions(_rocksWriteOptions); } rocksdb::SequenceNumber prevSeq = rocksutils::globalRocksDB()->GetLatestSequenceNumber(); // TODO wait for response on github issue to see how we can use the // sequence number result = rocksutils::convertStatus(_rocksTransaction->Commit()); rocksdb::SequenceNumber latestSeq = rocksutils::globalRocksDB()->GetLatestSequenceNumber(); #ifdef ARANGODB_ENABLE_MAINTAINER_MODE if (prevSeq + 1 != latestSeq) { LOG_TOPIC(FATAL, Logger::FIXME) << "commits slipped between commits"; } #endif if (!result.ok()) { abortTransaction(activeTrx); return result; } if (_cacheTx != nullptr) { // note: endTransaction() will delete _cacheTx! CacheManagerFeature::MANAGER->endTransaction(_cacheTx); _cacheTx = nullptr; } rocksdb::Snapshot const* snap = this->_rocksReadOptions.snapshot; TRI_ASSERT(snap != nullptr); for (auto& trxCollection : _collections) { RocksDBTransactionCollection* collection = static_cast<RocksDBTransactionCollection*>(trxCollection); int64_t adjustment = collection->numInserts() - collection->numRemoves(); if (collection->numInserts() != 0 || collection->numRemoves() != 0 || collection->revision() != 0) { RocksDBCollection* coll = static_cast<RocksDBCollection*>( trxCollection->collection()->getPhysical()); coll->adjustNumberDocuments(adjustment); coll->setRevision(collection->revision()); RocksDBEngine* engine = static_cast<RocksDBEngine*>(EngineSelectorFeature::ENGINE); RocksDBCounterManager::CounterAdjustment update( latestSeq, collection->numInserts(), collection->numRemoves(), collection->revision()); engine->counterManager()->updateCounter(coll->objectId(), update); } } _rocksTransaction.reset(); } updateStatus(transaction::Status::COMMITTED); } unuseCollections(_nestingLevel); return result; } /// @brief abort and rollback a transaction Result RocksDBTransactionState::abortTransaction( transaction::Methods* activeTrx) { LOG_TRX(this, _nestingLevel) << "aborting " << AccessMode::typeString(_type) << " transaction"; TRI_ASSERT(_status == transaction::Status::RUNNING); Result result; if (_nestingLevel == 0) { if (_rocksTransaction != nullptr) { rocksdb::Status status = _rocksTransaction->Rollback(); result = rocksutils::convertStatus(status); _rocksTransaction.reset(); } if (_cacheTx != nullptr) { // note: endTransaction() will delete _cacheTx! CacheManagerFeature::MANAGER->endTransaction(_cacheTx); _cacheTx = nullptr; } updateStatus(transaction::Status::ABORTED); if (hasOperations()) { // must clean up the query cache because the transaction // may have queried something via AQL that is now rolled back clearQueryCache(); } } unuseCollections(_nestingLevel); return result; } /// @brief add an operation for a transaction collection RocksDBOperationResult RocksDBTransactionState::addOperation( TRI_voc_cid_t cid, TRI_voc_rid_t revisionId, TRI_voc_document_operation_e operationType, uint64_t operationSize, uint64_t keySize) { RocksDBOperationResult res; uint64_t newSize = _transactionSize + operationSize + keySize; if (_maxTransactionSize < newSize) { // we hit the transaction size limit std::string message = "aborting transaction because maximal transaction size limit of " + std::to_string(_maxTransactionSize) + " bytes is reached"; res.reset(TRI_ERROR_RESOURCE_LIMIT, message); return res; } auto collection = static_cast<RocksDBTransactionCollection*>(findCollection(cid)); if (collection == nullptr) { std::string message = "collection '" + std::to_string(cid) + "' not found in transaction state"; THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, message); } // should not fail or fail with exception collection->addOperation(operationType, operationSize, revisionId); // clear the query cache for this collection if (arangodb::aql::QueryCache::instance()->mayBeActive()) { arangodb::aql::QueryCache::instance()->invalidate( _vocbase, collection->collectionName()); } switch (operationType) { case TRI_VOC_DOCUMENT_OPERATION_UNKNOWN: break; case TRI_VOC_DOCUMENT_OPERATION_INSERT: ++_numInserts; break; case TRI_VOC_DOCUMENT_OPERATION_UPDATE: case TRI_VOC_DOCUMENT_OPERATION_REPLACE: ++_numUpdates; break; case TRI_VOC_DOCUMENT_OPERATION_REMOVE: ++_numRemoves; break; } _transactionSize = newSize; auto numOperations = _numInserts + _numUpdates + _numRemoves; // signal if intermediate commit is required // this will be done if intermediate transactions are enabled // and either the "number of operations" or the "transaction size" // has reached the limit if (_intermediateTransactionEnabled && (_intermediateTransactionNumber <= numOperations || _intermediateTransactionSize <= newSize)) { res.commitRequired(true); } return res; } uint64_t RocksDBTransactionState::sequenceNumber() const { return static_cast<uint64_t>( _rocksTransaction->GetSnapshot()->GetSequenceNumber()); } void RocksDBTransactionState::reset() { // only reset when already commited TRI_ASSERT(_status == transaction::Status::COMMITTED); // reset count _transactionSize = 0; _numInserts = 0; _numUpdates = 0; _numRemoves = 0; unuseCollections(_nestingLevel); for (auto it = _collections.rbegin(); it != _collections.rend(); ++it) { (static_cast<RocksDBTransactionCollection*>(*it))->resetCounts(); } _nestingLevel = 0; updateStatus(transaction::Status::CREATED); // start new transaction beginTransaction(transaction::Hints()); } <|endoftext|>
<commit_before>/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkImageInfoPriv.h" #include "SkSafeMath.h" #include "SkReadBuffer.h" #include "SkWriteBuffer.h" int SkColorTypeBytesPerPixel(SkColorType ct) { switch (ct) { case kUnknown_SkColorType: return 0; case kAlpha_8_SkColorType: return 1; case kRGB_565_SkColorType: return 2; case kARGB_4444_SkColorType: return 2; case kRGBA_8888_SkColorType: return 4; case kBGRA_8888_SkColorType: return 4; case kRGB_888x_SkColorType: return 4; case kRGBA_1010102_SkColorType: return 4; case kRGB_101010x_SkColorType: return 4; case kGray_8_SkColorType: return 1; case kRGBA_F16_SkColorType: return 8; } return 0; } // These values must be constant over revisions, though they can be renamed to reflect if/when // they are deprecated. enum Stored_SkColorType { kUnknown_Stored_SkColorType = 0, kAlpha_8_Stored_SkColorType = 1, kRGB_565_Stored_SkColorType = 2, kARGB_4444_Stored_SkColorType = 3, kRGBA_8888_Stored_SkColorType = 4, kBGRA_8888_Stored_SkColorType = 5, kIndex_8_Stored_SkColorType_DEPRECATED = 6, kGray_8_Stored_SkColorType = 7, kRGBA_F16_Stored_SkColorType = 8, kRGB_888x_Stored_SkColorType = 9, kRGBA_1010102_Stored_SkColorType = 10, kRGB_101010x_Stored_SkColorType = 11, }; bool SkColorTypeIsAlwaysOpaque(SkColorType ct) { return !(kAlpha_SkColorTypeComponentFlag & SkColorTypeComponentFlags(ct)); } /////////////////////////////////////////////////////////////////////////////////////////////////// int SkImageInfo::bytesPerPixel() const { return SkColorTypeBytesPerPixel(fColorType); } int SkImageInfo::shiftPerPixel() const { return SkColorTypeShiftPerPixel(fColorType); } size_t SkImageInfo::computeOffset(int x, int y, size_t rowBytes) const { SkASSERT((unsigned)x < (unsigned)this->width()); SkASSERT((unsigned)y < (unsigned)this->height()); return SkColorTypeComputeOffset(this->colorType(), x, y, rowBytes); } size_t SkImageInfo::computeByteSize(size_t rowBytes) const { if (0 == this->height()) { return 0; } SkSafeMath safe; size_t bytes = safe.add(safe.mul(safe.addInt(this->height(), -1), rowBytes), safe.mul(this->width(), this->bytesPerPixel())); return safe ? bytes : SIZE_MAX; } SkImageInfo SkImageInfo::MakeS32(int width, int height, SkAlphaType at) { return SkImageInfo(width, height, kN32_SkColorType, at, SkColorSpace::MakeSRGB()); } bool SkColorTypeValidateAlphaType(SkColorType colorType, SkAlphaType alphaType, SkAlphaType* canonical) { switch (colorType) { case kUnknown_SkColorType: alphaType = kUnknown_SkAlphaType; break; case kAlpha_8_SkColorType: if (kUnpremul_SkAlphaType == alphaType) { alphaType = kPremul_SkAlphaType; } // fall-through case kARGB_4444_SkColorType: case kRGBA_8888_SkColorType: case kBGRA_8888_SkColorType: case kRGBA_1010102_SkColorType: case kRGBA_F16_SkColorType: if (kUnknown_SkAlphaType == alphaType) { return false; } break; case kGray_8_SkColorType: case kRGB_565_SkColorType: case kRGB_888x_SkColorType: case kRGB_101010x_SkColorType: alphaType = kOpaque_SkAlphaType; break; default: return false; } if (canonical) { *canonical = alphaType; } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// #include "SkReadPixelsRec.h" bool SkReadPixelsRec::trim(int srcWidth, int srcHeight) { if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) { return false; } if (0 >= fInfo.width() || 0 >= fInfo.height()) { return false; } int x = fX; int y = fY; SkIRect srcR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height()); if (!srcR.intersect(0, 0, srcWidth, srcHeight)) { return false; } // if x or y are negative, then we have to adjust pixels if (x > 0) { x = 0; } if (y > 0) { y = 0; } // here x,y are either 0 or negative // we negate and add them so UBSAN (pointer-overflow) doesn't get confused. fPixels = ((char*)fPixels + -y*fRowBytes + -x*fInfo.bytesPerPixel()); // the intersect may have shrunk info's logical size fInfo = fInfo.makeWH(srcR.width(), srcR.height()); fX = srcR.x(); fY = srcR.y(); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// #include "SkWritePixelsRec.h" bool SkWritePixelsRec::trim(int dstWidth, int dstHeight) { if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) { return false; } if (0 >= fInfo.width() || 0 >= fInfo.height()) { return false; } int x = fX; int y = fY; SkIRect dstR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height()); if (!dstR.intersect(0, 0, dstWidth, dstHeight)) { return false; } // if x or y are negative, then we have to adjust pixels if (x > 0) { x = 0; } if (y > 0) { y = 0; } // here x,y are either 0 or negative // we negate and add them so UBSAN (pointer-overflow) doesn't get confused. fPixels = ((const char*)fPixels + -y*fRowBytes + -x*fInfo.bytesPerPixel()); // the intersect may have shrunk info's logical size fInfo = fInfo.makeWH(dstR.width(), dstR.height()); fX = dstR.x(); fY = dstR.y(); return true; } <commit_msg>remove unused enum<commit_after>/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkImageInfoPriv.h" #include "SkSafeMath.h" #include "SkReadBuffer.h" #include "SkWriteBuffer.h" int SkColorTypeBytesPerPixel(SkColorType ct) { switch (ct) { case kUnknown_SkColorType: return 0; case kAlpha_8_SkColorType: return 1; case kRGB_565_SkColorType: return 2; case kARGB_4444_SkColorType: return 2; case kRGBA_8888_SkColorType: return 4; case kBGRA_8888_SkColorType: return 4; case kRGB_888x_SkColorType: return 4; case kRGBA_1010102_SkColorType: return 4; case kRGB_101010x_SkColorType: return 4; case kGray_8_SkColorType: return 1; case kRGBA_F16_SkColorType: return 8; } return 0; } bool SkColorTypeIsAlwaysOpaque(SkColorType ct) { return !(kAlpha_SkColorTypeComponentFlag & SkColorTypeComponentFlags(ct)); } /////////////////////////////////////////////////////////////////////////////////////////////////// int SkImageInfo::bytesPerPixel() const { return SkColorTypeBytesPerPixel(fColorType); } int SkImageInfo::shiftPerPixel() const { return SkColorTypeShiftPerPixel(fColorType); } size_t SkImageInfo::computeOffset(int x, int y, size_t rowBytes) const { SkASSERT((unsigned)x < (unsigned)this->width()); SkASSERT((unsigned)y < (unsigned)this->height()); return SkColorTypeComputeOffset(this->colorType(), x, y, rowBytes); } size_t SkImageInfo::computeByteSize(size_t rowBytes) const { if (0 == this->height()) { return 0; } SkSafeMath safe; size_t bytes = safe.add(safe.mul(safe.addInt(this->height(), -1), rowBytes), safe.mul(this->width(), this->bytesPerPixel())); return safe ? bytes : SIZE_MAX; } SkImageInfo SkImageInfo::MakeS32(int width, int height, SkAlphaType at) { return SkImageInfo(width, height, kN32_SkColorType, at, SkColorSpace::MakeSRGB()); } bool SkColorTypeValidateAlphaType(SkColorType colorType, SkAlphaType alphaType, SkAlphaType* canonical) { switch (colorType) { case kUnknown_SkColorType: alphaType = kUnknown_SkAlphaType; break; case kAlpha_8_SkColorType: if (kUnpremul_SkAlphaType == alphaType) { alphaType = kPremul_SkAlphaType; } // fall-through case kARGB_4444_SkColorType: case kRGBA_8888_SkColorType: case kBGRA_8888_SkColorType: case kRGBA_1010102_SkColorType: case kRGBA_F16_SkColorType: if (kUnknown_SkAlphaType == alphaType) { return false; } break; case kGray_8_SkColorType: case kRGB_565_SkColorType: case kRGB_888x_SkColorType: case kRGB_101010x_SkColorType: alphaType = kOpaque_SkAlphaType; break; default: return false; } if (canonical) { *canonical = alphaType; } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// #include "SkReadPixelsRec.h" bool SkReadPixelsRec::trim(int srcWidth, int srcHeight) { if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) { return false; } if (0 >= fInfo.width() || 0 >= fInfo.height()) { return false; } int x = fX; int y = fY; SkIRect srcR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height()); if (!srcR.intersect(0, 0, srcWidth, srcHeight)) { return false; } // if x or y are negative, then we have to adjust pixels if (x > 0) { x = 0; } if (y > 0) { y = 0; } // here x,y are either 0 or negative // we negate and add them so UBSAN (pointer-overflow) doesn't get confused. fPixels = ((char*)fPixels + -y*fRowBytes + -x*fInfo.bytesPerPixel()); // the intersect may have shrunk info's logical size fInfo = fInfo.makeWH(srcR.width(), srcR.height()); fX = srcR.x(); fY = srcR.y(); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// #include "SkWritePixelsRec.h" bool SkWritePixelsRec::trim(int dstWidth, int dstHeight) { if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) { return false; } if (0 >= fInfo.width() || 0 >= fInfo.height()) { return false; } int x = fX; int y = fY; SkIRect dstR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height()); if (!dstR.intersect(0, 0, dstWidth, dstHeight)) { return false; } // if x or y are negative, then we have to adjust pixels if (x > 0) { x = 0; } if (y > 0) { y = 0; } // here x,y are either 0 or negative // we negate and add them so UBSAN (pointer-overflow) doesn't get confused. fPixels = ((const char*)fPixels + -y*fRowBytes + -x*fInfo.bytesPerPixel()); // the intersect may have shrunk info's logical size fInfo = fInfo.makeWH(dstR.width(), dstR.height()); fX = dstR.x(); fY = dstR.y(); return true; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems, * University of Southern California * Jan Issac (jan.issac@gmail.com) * Manuel Wuthrich (manuel.wuthrich@gmail.com) * * * * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * @date 11/5/2014 * @author Jan Issac (jan.issac@gmail.com) * Max-Planck-Institute for Intelligent Systems, * University of Southern California */ #ifndef FL__FILTER__GAUSSIAN__UNSCENTED_TRANSFORM_HPP #define FL__FILTER__GAUSSIAN__UNSCENTED_TRANSFORM_HPP #include <fast_filtering/utils/traits.hpp> #include <fast_filtering/distributions/gaussian.hpp> #include <fast_filtering/filtering_library/filter/gaussian/point_set_transform.hpp> namespace fl { // Forward declarations template <typename PointSetGaussian_, typename Gaussian_> class UnscentedTransform; /** * */ template <typename PointSetGaussian_, typename Gaussian_> struct Traits<UnscentedTransform<PointSetGaussian_, Gaussian_>> { typedef typename Traits<PointSetGaussian_>::Point Point; typedef typename Traits<PointSetGaussian_>::Weight Weight; typedef typename ff::Traits< typename Traits<PointSetGaussian_>::Base >::Operator Operator; enum { NumberOfPoints = IsFixed<Point::RowsAtCompileTime>() ? 2 * Point::RowsAtCompileTime + 1 : Eigen::Dynamic }; }; /** * This is the Unscented Transform used in the Unscented Kalman Filter * \cite wan2000unscented. It implememnts the PointSetTransform interface. * * \copydetails PointSetTransform */ template <typename PointSetGaussian_, typename Gaussian_ = PointSetGaussian_> class UnscentedTransform: public PointSetTransform<PointSetGaussian_, Gaussian_> { public: typedef UnscentedTransform<PointSetGaussian_, Gaussian_> This; typedef typename Traits<This>::Point Point; typedef typename Traits<This>::Weight Weight; typedef typename Traits<This>::Operator Operator; public: /** * Creates a UnscentedTransform * * @param alpha UT Scaling parameter alpha (distance to the mean) * @param beta UT Scaling parameter beta (2.0 is optimal for Gaussian) * @param kappa UT Scaling parameter kappa (higher order parameter) */ UnscentedTransform(double alpha = 1., double beta = 2., double kappa = 0.) : alpha_(alpha), beta_(beta), kappa_(kappa) { /** * \internal * * assert the implication: * isFixed(TransformNumberOfPoints) AND isFixed(PointSetNumberOfPoints) * => TransformNumberOfPoints EQUAL PointSetNumberOfPoints */ enum { TransformNumberOfPoints = Traits<This>::NumberOfPoints, PointSetNumberOfPoints = Traits<PointSetGaussian_>::NumberOfPoints }; static_assert(!(IsFixed<TransformNumberOfPoints>() && IsFixed<PointSetNumberOfPoints>()) || (TransformNumberOfPoints == PointSetNumberOfPoints), "Incompatible number of points of the specified" " fixed-size PointSetGaussian"); } /** * \copydoc PointSetTransform::forward(const Moments_&, * PointSetGaussian_&) const * * \throws WrongSizeException * \throws ResizingFixedSizeEntityException */ virtual void forward(const Gaussian_& gaussian, PointSetGaussian_& transform) const { forward(gaussian, gaussian.Dimension(), 0, transform); } /** * \copydoc PointSetTransform::forward(const Moments_&, * size_t, * size_t, * PointSetGaussian_&) const * * \throws WrongSizeException * \throws ResizingFixedSizeEntityException */ virtual void forward(const Gaussian_& gaussian, size_t global_rank, size_t rank_offset, PointSetGaussian_& transform) const { const double dim = double(global_rank); /** * \internal * A PointSetGaussian with a fixed number of points must have the * correct number of points which is required by this transform */ if (IsFixed<Traits<PointSetGaussian_>::NumberOfPoints>() && Traits<PointSetGaussian_>::NumberOfPoints != number_of_points(dim)) { BOOST_THROW_EXCEPTION( WrongSizeException("Incompatible number of points of the" " specified fixed-size PointSetGaussian")); } transform.resize(number_of_points(dim)); Operator covarianceSqr = gaussian.SquareRoot(); covarianceSqr *= gamma_factor(dim); Point point_shift; const Point& mean = gaussian.Mean(); const Weight weight_0{weight_mean_0(dim), weight_cov_0(dim)}; const Weight weight_i{weight_mean_i(dim), weight_cov_i(dim)}; transform.point(0, mean, weight_0); // use squential loops to enable loop unrolling const size_t start_1 = 1; const size_t limit_1 = start_1 + rank_offset; const size_t start_2 = limit_1; const size_t limit_2 = start_2 + gaussian.Dimension(); const size_t start_3 = limit_2; const size_t limit_3 = global_rank; for (size_t i = start_1; i < limit_1; ++i) { transform.point(i, mean, weight_i); transform.point(global_rank + i, mean, weight_i); } for (size_t i = start_2; i < limit_2; ++i) { point_shift = covarianceSqr.col(i - (rank_offset + 1)); transform.point(i, mean + point_shift, weight_i); transform.point(global_rank + i, mean - point_shift, weight_i); } for (size_t i = start_3; i <= limit_3; ++i) { transform.point(i, mean, weight_i); transform.point(global_rank + i, mean, weight_i); } } /** * @return Number of points generated by this transform * * @param global_rank Dimension of the Gaussian */ static constexpr size_t number_of_points(size_t global_rank) { return 2 * global_rank + 1; } public: /** \cond INTERNAL */ /** * @return First mean weight * * @param dim Dimension of the Gaussian */ double weight_mean_0(double dim) const { return lambda_scalar(dim) / (dim + lambda_scalar(dim)); } /** * @return First covariance weight * * @param dim Dimension of the Gaussian */ double weight_cov_0(double dim) const { return weight_mean_0(dim) + (1 - alpha_ * alpha_ + beta_); } /** * @return i-th mean weight * * @param dimension Dimension of the Gaussian */ double weight_mean_i(double dim) const { return 1. / (2. * (dim + lambda_scalar(dim))); } /** * @return i-th covariance weight * * @param dimension Dimension of the Gaussian */ double weight_cov_i(double dim) const { return weight_mean_i(dim); } /** * @param dim Dimension of the Gaussian */ double lambda_scalar(double dim) const { return alpha_ * alpha_ * (dim + kappa_) - dim; } /** * @param dim Dimension of the Gaussian */ double gamma_factor(double dim) const { return std::sqrt(dim + lambda_scalar(dim)); } /** \endcond */ protected: /** \cond INTERNAL */ double alpha_; double beta_; double kappa_; /** \endcond */ }; } #endif <commit_msg>Updated unscented transform<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems, * University of Southern California * Jan Issac (jan.issac\gmail.com) * Manuel Wuthrich (manuel.wuthrich\gmail.com) * * * * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * \date 11/5/2014 * \author Jan Issac (jan.issac\gmail.com) * Max-Planck-Institute for Intelligent Systems, * University of Southern California */ #ifndef FL__FILTER__GAUSSIAN__UNSCENTED_TRANSFORM_HPP #define FL__FILTER__GAUSSIAN__UNSCENTED_TRANSFORM_HPP #include <fast_filtering/utils/traits.hpp> #include <fast_filtering/distributions/gaussian.hpp> #include <fast_filtering/filtering_library/filter/gaussian/point_set_transform.hpp> namespace fl { /** * This is the Unscented Transform used in the Unscented Kalman Filter * \cite wan2000unscented. It implememnts the PointSetTransform interface. * * \copydetails PointSetTransform */ class UnscentedTransform : public PointSetTransform<UnscentedTransform> { public: /** * Creates a UnscentedTransform * * \param alpha UT Scaling parameter alpha (distance to the mean) * \param beta UT Scaling parameter beta (2.0 is optimal for Gaussian) * \param kappa UT Scaling parameter kappa (higher order parameter) */ UnscentedTransform(double alpha = 1., double beta = 2., double kappa = 0.) : PointSetTransform<UnscentedTransform>(this), alpha_(alpha), beta_(beta), kappa_(kappa) { } /** * \copydoc PointSetTransform::forward(const Gaussian&, * PointSetGaussian&) const * * \throws WrongSizeException * \throws ResizingFixedSizeEntityException */ template <typename Gaussian_, typename PointSetGaussian_> void forward(const Gaussian_& gaussian, PointSetGaussian_& point_set) const { forward(gaussian, gaussian.Dimension(), 0, point_set); } /** * \copydoc PointSetTransform::forward(const Gaussian&, * size_t global_dimension, * size_t dimension_offset, * PointSetGaussian&) const * * \throws WrongSizeException * \throws ResizingFixedSizeEntityException */ template <typename Gaussian_, typename PointSetGaussian_> void forward(const Gaussian_& gaussian, size_t global_dimension, size_t dimension_offset, PointSetGaussian_& point_set) const { typedef typename Traits<PointSetGaussian_>::Point Point; typedef typename Traits<PointSetGaussian_>::Weight Weight; const double dim = double(global_dimension); const size_t point_count = number_of_points(dim); /** * \internal * * \remark * A PointSetGaussian with a fixed number of points must have the * correct number of points which is required by this transform */ if (IsFixed<Traits<PointSetGaussian_>::NumberOfPoints>() && Traits<PointSetGaussian_>::NumberOfPoints != point_count) { BOOST_THROW_EXCEPTION( WrongSizeException("Incompatible number of points of the" " specified fixed-size PointSetGaussian")); } // will resize of transform size is different from point count. point_set.resize(point_count); auto covariance_sqrt = gaussian.SquareRoot(); covariance_sqrt *= gamma_factor(dim); Point point_shift; const Point& mean = gaussian.Mean(); // set the first point point_set.point(0, mean, Weight{weight_mean_0(dim), weight_cov_0(dim)}); // compute the remaining points Weight weight_i{weight_mean_i(dim), weight_cov_i(dim)}; // use squential loops to enable loop unrolling const size_t start_1 = 1; const size_t limit_1 = start_1 + dimension_offset; const size_t limit_2 = limit_1 + gaussian.Dimension(); const size_t limit_3 = global_dimension; for (size_t i = start_1; i < limit_1; ++i) { point_set.point(i, mean, weight_i); point_set.point(global_dimension + i, mean, weight_i); } for (size_t i = limit_1; i < limit_2; ++i) { point_shift = covariance_sqrt.col(i - dimension_offset - 1); point_set.point(i, mean + point_shift, weight_i); point_set.point(global_dimension + i, mean - point_shift, weight_i); } for (size_t i = limit_2; i <= limit_3; ++i) { point_set.point(i, mean, weight_i); point_set.point(global_dimension + i, mean, weight_i); } } /** * \return Number of points generated by this transform * * \param dimension Dimension of the Gaussian */ static constexpr size_t number_of_points(int dimension) { return (dimension != Eigen::Dynamic) ? 2 * dimension + 1 : 0; } public: /** \cond INTERNAL */ /** * \return First mean weight * * \param dim Dimension of the Gaussian */ double weight_mean_0(double dim) const { return lambda_scalar(dim) / (dim + lambda_scalar(dim)); } /** * \return First covariance weight * * \param dim Dimension of the Gaussian */ double weight_cov_0(double dim) const { return weight_mean_0(dim) + (1 - alpha_ * alpha_ + beta_); } /** * \return i-th mean weight * * \param dimension Dimension of the Gaussian */ double weight_mean_i(double dim) const { return 1. / (2. * (dim + lambda_scalar(dim))); } /** * \return i-th covariance weight * * \param dimension Dimension of the Gaussian */ double weight_cov_i(double dim) const { return weight_mean_i(dim); } /** * \param dim Dimension of the Gaussian */ double lambda_scalar(double dim) const { return alpha_ * alpha_ * (dim + kappa_) - dim; } /** * \param dim Dimension of the Gaussian */ double gamma_factor(double dim) const { return std::sqrt(dim + lambda_scalar(dim)); } /** \endcond */ protected: /** \cond INTERNAL */ double alpha_; double beta_; double kappa_; /** \endcond */ }; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pe_iface.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-07-31 16:10:01 $ * * 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 ADC_UIDL_PE_IFACE_HXX #define ADC_UIDL_PE_IFACE_HXX // USED SERVICES // BASE CLASSES #include <s2_luidl/parsenv2.hxx> #include <s2_luidl/pestate.hxx> // COMPONENTS // PARAMETERS namespace ary { namespace idl { class Interface; } } namespace csi { namespace uidl { class PE_Function; class PE_Attribute; class PE_Type; class PE_Interface : public UnoIDL_PE, public ParseEnvState { public: PE_Interface(); virtual ~PE_Interface(); virtual void EstablishContacts( UnoIDL_PE * io_pParentPE, ary::n22::Repository & io_rRepository, TokenProcessing_Result & o_rResult ); virtual void ProcessToken( const Token & i_rToken ); virtual void Process_MetaType( const TokMetaType & i_rToken ); virtual void Process_Identifier( const TokIdentifier & i_rToken ); virtual void Process_Punctuation( const TokPunctuation & i_rToken ); virtual void Process_NameSeparator(); virtual void Process_BuiltInType( const TokBuiltInType & i_rToken ); virtual void Process_TypeModifier( const TokTypeModifier & i_rToken ); virtual void Process_Stereotype( const TokStereotype & i_rToken ); virtual void Process_Default(); private: enum E_State /// @ATTENTION Do not change existing values (except of e_STATES_MAX) !!! Else array-indices will break. { e_none = 0, need_uik, uik, need_ident, ident, need_interface, need_name, wait_for_base, in_base, // in header, after ":" need_curlbr_open, e_std, in_function, in_attribute, need_finish, in_base_interface, // in body, after "interface" e_STATES_MAX }; enum E_TokenType /// @ATTENTION Do not change existing values (except of tt_MAX) !!! Else array-indices will break. { tt_metatype = 0, tt_identifier = 1, tt_punctuation = 2, tt_startoftype = 3, tt_stereotype = 4, tt_MAX }; typedef void (PE_Interface::*F_TOK)(const char *); void On_need_uik_MetaType(const char * i_sText); void On_uik_Identifier(const char * i_sText); void On_uik_Punctuation(const char * i_sText); void On_need_ident_MetaType(const char * i_sText); void On_ident_Identifier(const char * i_sText); void On_ident_Punctuation(const char * i_sText); void On_need_interface_MetaType(const char * i_sText); void On_need_name_Identifer(const char * i_sText); void On_wait_for_base_Punctuation(const char * i_sText); void On_need_curlbr_open_Punctuation(const char * i_sText); void On_std_Metatype(const char * i_sText); void On_std_Punctuation(const char * i_sText); void On_std_Stereotype(const char * i_sText); void On_std_GotoFunction(const char * i_sText); void On_std_GotoAttribute(const char * i_sText); void On_std_GotoBaseInterface(const char * i_sText); void On_need_finish_Punctuation(const char * i_sText); void On_Default(const char * i_sText); void CallHandler( const char * i_sTokenText, E_TokenType i_eTokenType ); virtual void InitData(); virtual void TransferData(); virtual void ReceiveData(); virtual UnoIDL_PE & MyPE(); void store_Interface(); // DATA static F_TOK aDispatcher[e_STATES_MAX][tt_MAX]; E_State eState; String sData_Name; bool bIsPreDeclaration; ary::idl::Interface * pCurInterface; ary::idl::Ce_id nCurInterface; Dyn<PE_Function> pPE_Function; Dyn<PE_Attribute> pPE_Attribute; Dyn<PE_Type> pPE_Type; ary::idl::Type_id nCurParsed_Base; bool bOptionalMember; }; // IMPLEMENTATION } // namespace uidl } // namespace csi #endif <commit_msg>INTEGRATION: CWS adc18 (1.5.8); FILE MERGED 2007/10/18 15:23:22 np 1.5.8.1: #i81775#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pe_iface.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-11-02 17:16:18 $ * * 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 ADC_UIDL_PE_IFACE_HXX #define ADC_UIDL_PE_IFACE_HXX // USED SERVICES // BASE CLASSES #include <s2_luidl/parsenv2.hxx> #include <s2_luidl/pestate.hxx> // COMPONENTS // PARAMETERS namespace ary { namespace idl { class Interface; } } namespace csi { namespace uidl { class PE_Function; class PE_Attribute; class PE_Type; class PE_Interface : public UnoIDL_PE, public ParseEnvState { public: PE_Interface(); virtual ~PE_Interface(); virtual void EstablishContacts( UnoIDL_PE * io_pParentPE, ary::Repository & io_rRepository, TokenProcessing_Result & o_rResult ); virtual void ProcessToken( const Token & i_rToken ); virtual void Process_MetaType( const TokMetaType & i_rToken ); virtual void Process_Identifier( const TokIdentifier & i_rToken ); virtual void Process_Punctuation( const TokPunctuation & i_rToken ); virtual void Process_NameSeparator(); virtual void Process_BuiltInType( const TokBuiltInType & i_rToken ); virtual void Process_TypeModifier( const TokTypeModifier & i_rToken ); virtual void Process_Stereotype( const TokStereotype & i_rToken ); virtual void Process_Default(); private: enum E_State /// @ATTENTION Do not change existing values (except of e_STATES_MAX) !!! Else array-indices will break. { e_none = 0, need_uik, uik, need_ident, ident, need_interface, need_name, wait_for_base, in_base, // in header, after ":" need_curlbr_open, e_std, in_function, in_attribute, need_finish, in_base_interface, // in body, after "interface" e_STATES_MAX }; enum E_TokenType /// @ATTENTION Do not change existing values (except of tt_MAX) !!! Else array-indices will break. { tt_metatype = 0, tt_identifier = 1, tt_punctuation = 2, tt_startoftype = 3, tt_stereotype = 4, tt_MAX }; typedef void (PE_Interface::*F_TOK)(const char *); void On_need_uik_MetaType(const char * i_sText); void On_uik_Identifier(const char * i_sText); void On_uik_Punctuation(const char * i_sText); void On_need_ident_MetaType(const char * i_sText); void On_ident_Identifier(const char * i_sText); void On_ident_Punctuation(const char * i_sText); void On_need_interface_MetaType(const char * i_sText); void On_need_name_Identifer(const char * i_sText); void On_wait_for_base_Punctuation(const char * i_sText); void On_need_curlbr_open_Punctuation(const char * i_sText); void On_std_Metatype(const char * i_sText); void On_std_Punctuation(const char * i_sText); void On_std_Stereotype(const char * i_sText); void On_std_GotoFunction(const char * i_sText); void On_std_GotoAttribute(const char * i_sText); void On_std_GotoBaseInterface(const char * i_sText); void On_need_finish_Punctuation(const char * i_sText); void On_Default(const char * i_sText); void CallHandler( const char * i_sTokenText, E_TokenType i_eTokenType ); virtual void InitData(); virtual void TransferData(); virtual void ReceiveData(); virtual UnoIDL_PE & MyPE(); void store_Interface(); // DATA static F_TOK aDispatcher[e_STATES_MAX][tt_MAX]; E_State eState; String sData_Name; bool bIsPreDeclaration; ary::idl::Interface * pCurInterface; ary::idl::Ce_id nCurInterface; Dyn<PE_Function> pPE_Function; Dyn<PE_Attribute> pPE_Attribute; Dyn<PE_Type> pPE_Type; ary::idl::Type_id nCurParsed_Base; bool bOptionalMember; }; // IMPLEMENTATION } // namespace uidl } // namespace csi #endif <|endoftext|>
<commit_before>#include <btBulletDynamicsCommon.h> #include "../Physics/GlmConversion.hpp" #include "RigidBody.hpp" namespace Component { RigidBody::~RigidBody() { Destroy(); } Json::Value RigidBody::Save() const { Json::Value component; component["mass"] = mass; component["friction"] = friction; component["rollingFriction"] = rollingFriction; component["kinematic"] = kinematic; return component; } bool RigidBody::IsKinematic() const { return kinematic; } float RigidBody::GetFriction() const { return friction; } float RigidBody::GetRollingFriction() const { return rollingFriction; } float RigidBody::GetSpinningFriction() const { return spinningFriction; } btRigidBody* RigidBody::GetBulletRigidBody() { return rigidBody; } void RigidBody::NewBulletRigidBody(float mass) { Destroy(); this->mass = mass; // Motion states inform us of movement caused by physics so that we can // deal with those changes as needed. btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0))); // Bullet treats zero mass as infinite, resulting in immovable objects. btRigidBody::btRigidBodyConstructionInfo constructionInfo(mass, motionState, nullptr, btVector3(0, 0, 0)); rigidBody = new btRigidBody(constructionInfo); rigidBody->setUserPointer(this); } void RigidBody::Destroy() { if (rigidBody) { delete rigidBody->getMotionState(); delete rigidBody; } } glm::vec3 RigidBody::GetPosition() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getOrigin()); } void RigidBody::SetPosition(const glm::vec3& pos) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->setWorldTransform(trans); } } glm::quat RigidBody::GetOrientation() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getRotation()); } void RigidBody::SetOrientation(const glm::quat& rotation) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->setWorldTransform(trans); } } float RigidBody::GetMass() { return mass; } void RigidBody::SetMass(float mass) { // Bullet provides a method on the shape that we can use to calculate // inertia. btVector3 inertia; rigidBody->getCollisionShape()->calculateLocalInertia(mass, inertia); rigidBody->setMassProps(mass, inertia); this->mass = mass; } void RigidBody::SetFriction(float friction) { rigidBody->setFriction(friction); this->friction = friction; } void RigidBody::SetRollingFriction(float friction) { rigidBody->setRollingFriction(friction); this->rollingFriction = friction; } void RigidBody::SetSpinningFriction(float friction) { rigidBody->setSpinningFriction(friction); this->spinningFriction = friction; } void RigidBody::MakeKinematic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = true; } void RigidBody::MakeDynamic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = false; } bool RigidBody::GetForceTransformSync() const { return forceTransformSync; } void RigidBody::SetForceTransformSync(bool sync) { forceTransformSync = sync; } } <commit_msg>Save spinning friction to JSON.<commit_after>#include <btBulletDynamicsCommon.h> #include "../Physics/GlmConversion.hpp" #include "RigidBody.hpp" namespace Component { RigidBody::~RigidBody() { Destroy(); } Json::Value RigidBody::Save() const { Json::Value component; component["mass"] = mass; component["friction"] = friction; component["rollingFriction"] = rollingFriction; component["spinningFriction"] = spinningFriction; component["kinematic"] = kinematic; return component; } bool RigidBody::IsKinematic() const { return kinematic; } float RigidBody::GetFriction() const { return friction; } float RigidBody::GetRollingFriction() const { return rollingFriction; } float RigidBody::GetSpinningFriction() const { return spinningFriction; } btRigidBody* RigidBody::GetBulletRigidBody() { return rigidBody; } void RigidBody::NewBulletRigidBody(float mass) { Destroy(); this->mass = mass; // Motion states inform us of movement caused by physics so that we can // deal with those changes as needed. btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0))); // Bullet treats zero mass as infinite, resulting in immovable objects. btRigidBody::btRigidBodyConstructionInfo constructionInfo(mass, motionState, nullptr, btVector3(0, 0, 0)); rigidBody = new btRigidBody(constructionInfo); rigidBody->setUserPointer(this); } void RigidBody::Destroy() { if (rigidBody) { delete rigidBody->getMotionState(); delete rigidBody; } } glm::vec3 RigidBody::GetPosition() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getOrigin()); } void RigidBody::SetPosition(const glm::vec3& pos) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->setWorldTransform(trans); } } glm::quat RigidBody::GetOrientation() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getRotation()); } void RigidBody::SetOrientation(const glm::quat& rotation) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->setWorldTransform(trans); } } float RigidBody::GetMass() { return mass; } void RigidBody::SetMass(float mass) { // Bullet provides a method on the shape that we can use to calculate // inertia. btVector3 inertia; rigidBody->getCollisionShape()->calculateLocalInertia(mass, inertia); rigidBody->setMassProps(mass, inertia); this->mass = mass; } void RigidBody::SetFriction(float friction) { rigidBody->setFriction(friction); this->friction = friction; } void RigidBody::SetRollingFriction(float friction) { rigidBody->setRollingFriction(friction); this->rollingFriction = friction; } void RigidBody::SetSpinningFriction(float friction) { rigidBody->setSpinningFriction(friction); this->spinningFriction = friction; } void RigidBody::MakeKinematic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = true; } void RigidBody::MakeDynamic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = false; } bool RigidBody::GetForceTransformSync() const { return forceTransformSync; } void RigidBody::SetForceTransformSync(bool sync) { forceTransformSync = sync; } } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "stdafx.h" #include "common/ExtManager.h" #include "rubyext/WebView.h" #include <common/RhodesApp.h> #include "MainWindow.h" extern CMainWindow& getAppWindow(); //#define IDM_NAVIGATE 40022 //#define IDM_EXECUTEJS 40033 //#define IDM_STOPNAVIGATE 40034 //#define IDM_ZOOMPAGE 40035 //#define IDM_ZOOMTEXT 40036 extern "C" HWND getMainWnd(); extern "C" HINSTANCE rho_wmimpl_get_appinstance(); extern "C" void rho_sys_app_exit(); extern "C" WCHAR* rho_wmimpl_get_configfilepath(); namespace rho { namespace common { IMPLEMENT_LOGCLASS(CExtManager, "ExtManager"); void CExtManager::registerExtension(const String& strName, IRhoExtension* pExt) { m_hashExtensions.put(strName, pExt); } IRhoExtension* CExtManager::getExtByName(const String& strName) { return m_hashExtensions.get(strName); } CRhoExtData CExtManager::makeExtData() { CRhoExtData oData; oData.m_hWnd = getMainWnd(); oData.m_hInstance = rho_wmimpl_get_appinstance(); oData.m_hBrowserWnd = getAppWindow().getWebKitEngine()->GetHTMLWND(); oData.m_iTabIndex = rho_webview_active_tab(); return oData; } void CExtManager::onSetPropertiesData( const wchar_t* pPropID, const wchar_t* pData) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { (it->second)->onSetPropertiesData( pPropID, pData, makeExtData() ); } } void CExtManager::onUnhandledProperty( const wchar_t* pModuleName, const wchar_t* pName, const wchar_t* pValue, const CRhoExtData& oExtData ) { rho::common::IRhoExtension* pExt = getExtByName( rho::common::convertToStringA(pModuleName) ); if (pExt) pExt->onSetProperty( pName, pValue, oExtData ); } void CExtManager::onBeforeNavigate(const wchar_t* szUrlBeingNavigatedTo) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { (it->second)->onBeforeNavigate( szUrlBeingNavigatedTo, makeExtData() ); } } void CExtManager::onNavigateComplete(const wchar_t* szUrlBeingNavigatedTo) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { (it->second)->onNavigateComplete( szUrlBeingNavigatedTo, makeExtData() ); } } void CExtManager::onDocumentComplete(const wchar_t* szUrlOfDocument) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { (it->second)->onNavigateComplete( szUrlOfDocument, makeExtData() ); } } void CExtManager::close() { m_hashExtensions.clear(); } void CExtManager::executeRubyCallback( const char* szCallback, const char* szCallbackBody, const char* szCallbackData, bool bWaitForResponse) { RHODESAPP().callCallbackWithData(szCallback, szCallbackBody, szCallbackData, bWaitForResponse ); } void CExtManager::navigate(const wchar_t* szUrl) { ::PostMessage( getMainWnd(), WM_COMMAND, IDM_NAVIGATE, (LPARAM)_wcsdup(szUrl) ); } bool CExtManager::existsJavascript(const wchar_t* szJSFunction) { #ifndef RHODES_EMULATOR return getAppWindow().getWebKitEngine()->isExistJavascript(szJSFunction, rho_webview_active_tab()); #else return true; #endif } void CExtManager::executeJavascript(const wchar_t* szJSFunction) { ::PostMessage( getMainWnd(), WM_COMMAND, IDM_EXECUTEJS, (LPARAM)_wcsdup(szJSFunction) ); } StringW CExtManager::getCurrentUrl() { return convertToStringW(RHODESAPP().getCurrentUrl(rho_webview_active_tab())); } void CExtManager::historyForward() { rho_webview_navigate_forward(); } void CExtManager::historyBack() { rho_webview_navigate_back(); } void CExtManager::refreshPage(bool bFromCache) { rho_webview_refresh(rho_webview_active_tab()); } void CExtManager::stopNavigate() { ::PostMessage( getMainWnd(), WM_COMMAND, IDM_STOPNAVIGATE, (LPARAM)rho_webview_active_tab() ); } void CExtManager::quitApp() { rho_sys_app_exit(); } void CExtManager::minimizeApp() { ::ShowWindow(getMainWnd(), SW_MINIMIZE ); } void CExtManager::restoreApp() { ::ShowWindow(getMainWnd(), SW_RESTORE ); } void CExtManager::resizeBrowserWindow(RECT rc) { ::MoveWindow( getMainWnd(), rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, TRUE ); } void CExtManager::zoomPage(float fZoom) { ::PostMessage( getMainWnd(), WM_COMMAND, IDM_ZOOMPAGE, (LPARAM)fZoom ); } void CExtManager::zoomText(int nZoom) { ::PostMessage( getMainWnd(), WM_COMMAND, IDM_ZOOMTEXT, (LPARAM)nZoom ); } int CExtManager::getTextZoom() //Enum (0 to 4) { #ifndef RHODES_EMULATOR return getAppWindow().getWebKitEngine()->GetTextZoomOnTab(rho_webview_active_tab()); #else return 2; #endif } StringW CExtManager::getConfigPath() { return rho_wmimpl_get_configfilepath(); } StringW CExtManager::getPageTitle(UINT iTab) { #ifndef RHODES_EMULATOR wchar_t szBuf[1025]; szBuf[0]=0; getAppWindow().getWebKitEngine()->GetTitleOnTab( szBuf, 1024, iTab ); return szBuf ? szBuf : L""; #else return L""; #endif } extern "C" unsigned long rb_require(const char *fname); void CExtManager::requireRubyFile( const char* szFilePath ) { rb_require(szFilePath); } void CExtManager::rhoLog(int nSeverity, const char* szModule, const char* szMsg, const char* szFile, int nLine) { rhoPlainLog(szFile, nLine, nSeverity, szModule, szMsg); } bool CExtManager::onWndMsg(MSG& oMsg) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { if ( (it->second)->onWndMsg( oMsg ) ) return true; } return false; } long CExtManager::OnNavigateTimeout(const wchar_t* szUrlBeingNavigatedTo) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { long lRes = (it->second)->OnNavigateTimeout( szUrlBeingNavigatedTo, makeExtData() ); if ( lRes ) return lRes; } return 0; } long CExtManager::OnSIPState(bool bSIPState) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { long lRes = (it->second)->OnSIPState( bSIPState, makeExtData() ); if ( lRes ) return lRes; } return 0; } long CExtManager::OnAlertPopup(int nEnum, void* pData) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { long lRes = (it->second)->OnAlertPopup( nEnum, pData, makeExtData() ); if ( lRes ) return lRes; } return 0; } long CExtManager::OnNavigateError(const wchar_t* szUrlBeingNavigatedTo) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { long lRes = (it->second)->OnNavigateError( szUrlBeingNavigatedTo, makeExtData() ); if ( lRes ) return lRes; } return 0; } void CExtManager::OnAppActivate(bool bActivate) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { (it->second)->OnAppActivate( bActivate, makeExtData() ); } } } //namespace common } //namespace rho <commit_msg>win32: fix build<commit_after>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "stdafx.h" #include "common/ExtManager.h" #include "rubyext/WebView.h" #include <common/RhodesApp.h> #include "MainWindow.h" #include "common/app_build_capabilities.h" extern CMainWindow& getAppWindow(); //#define IDM_NAVIGATE 40022 //#define IDM_EXECUTEJS 40033 //#define IDM_STOPNAVIGATE 40034 //#define IDM_ZOOMPAGE 40035 //#define IDM_ZOOMTEXT 40036 extern "C" HWND getMainWnd(); extern "C" HINSTANCE rho_wmimpl_get_appinstance(); extern "C" void rho_sys_app_exit(); extern "C" WCHAR* rho_wmimpl_get_configfilepath(); namespace rho { namespace common { IMPLEMENT_LOGCLASS(CExtManager, "ExtManager"); void CExtManager::registerExtension(const String& strName, IRhoExtension* pExt) { m_hashExtensions.put(strName, pExt); } IRhoExtension* CExtManager::getExtByName(const String& strName) { return m_hashExtensions.get(strName); } CRhoExtData CExtManager::makeExtData() { CRhoExtData oData; oData.m_hWnd = getMainWnd(); oData.m_hInstance = rho_wmimpl_get_appinstance(); oData.m_hBrowserWnd = getAppWindow().getWebKitEngine()->GetHTMLWND(); oData.m_iTabIndex = rho_webview_active_tab(); return oData; } void CExtManager::onSetPropertiesData( const wchar_t* pPropID, const wchar_t* pData) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { (it->second)->onSetPropertiesData( pPropID, pData, makeExtData() ); } } void CExtManager::onUnhandledProperty( const wchar_t* pModuleName, const wchar_t* pName, const wchar_t* pValue, const CRhoExtData& oExtData ) { rho::common::IRhoExtension* pExt = getExtByName( rho::common::convertToStringA(pModuleName) ); if (pExt) pExt->onSetProperty( pName, pValue, oExtData ); } void CExtManager::onBeforeNavigate(const wchar_t* szUrlBeingNavigatedTo) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { (it->second)->onBeforeNavigate( szUrlBeingNavigatedTo, makeExtData() ); } } void CExtManager::onNavigateComplete(const wchar_t* szUrlBeingNavigatedTo) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { (it->second)->onNavigateComplete( szUrlBeingNavigatedTo, makeExtData() ); } } void CExtManager::onDocumentComplete(const wchar_t* szUrlOfDocument) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { (it->second)->onNavigateComplete( szUrlOfDocument, makeExtData() ); } } void CExtManager::close() { m_hashExtensions.clear(); } void CExtManager::executeRubyCallback( const char* szCallback, const char* szCallbackBody, const char* szCallbackData, bool bWaitForResponse) { RHODESAPP().callCallbackWithData(szCallback, szCallbackBody, szCallbackData, bWaitForResponse ); } void CExtManager::navigate(const wchar_t* szUrl) { ::PostMessage( getMainWnd(), WM_COMMAND, IDM_NAVIGATE, (LPARAM)_wcsdup(szUrl) ); } bool CExtManager::existsJavascript(const wchar_t* szJSFunction) { #ifndef RHODES_EMULATOR return getAppWindow().getWebKitEngine()->isExistJavascript(szJSFunction, rho_webview_active_tab()); #else return true; #endif } void CExtManager::executeJavascript(const wchar_t* szJSFunction) { ::PostMessage( getMainWnd(), WM_COMMAND, IDM_EXECUTEJS, (LPARAM)_wcsdup(szJSFunction) ); } StringW CExtManager::getCurrentUrl() { return convertToStringW(RHODESAPP().getCurrentUrl(rho_webview_active_tab())); } void CExtManager::historyForward() { rho_webview_navigate_forward(); } void CExtManager::historyBack() { rho_webview_navigate_back(); } void CExtManager::refreshPage(bool bFromCache) { rho_webview_refresh(rho_webview_active_tab()); } void CExtManager::stopNavigate() { ::PostMessage( getMainWnd(), WM_COMMAND, IDM_STOPNAVIGATE, (LPARAM)rho_webview_active_tab() ); } void CExtManager::quitApp() { rho_sys_app_exit(); } void CExtManager::minimizeApp() { ::ShowWindow(getMainWnd(), SW_MINIMIZE ); } void CExtManager::restoreApp() { ::ShowWindow(getMainWnd(), SW_RESTORE ); } void CExtManager::resizeBrowserWindow(RECT rc) { ::MoveWindow( getMainWnd(), rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, TRUE ); } void CExtManager::zoomPage(float fZoom) { ::PostMessage( getMainWnd(), WM_COMMAND, IDM_ZOOMPAGE, (LPARAM)fZoom ); } void CExtManager::zoomText(int nZoom) { ::PostMessage( getMainWnd(), WM_COMMAND, IDM_ZOOMTEXT, (LPARAM)nZoom ); } int CExtManager::getTextZoom() //Enum (0 to 4) { #ifndef RHODES_EMULATOR return getAppWindow().getWebKitEngine()->GetTextZoomOnTab(rho_webview_active_tab()); #else return 2; #endif } StringW CExtManager::getConfigPath() { #if defined(APP_BUILD_CAPABILITY_MOTOROLA) return rho_wmimpl_get_configfilepath(); #else return L""; #endif } StringW CExtManager::getPageTitle(UINT iTab) { #ifndef RHODES_EMULATOR wchar_t szBuf[1025]; szBuf[0]=0; getAppWindow().getWebKitEngine()->GetTitleOnTab( szBuf, 1024, iTab ); return szBuf ? szBuf : L""; #else return L""; #endif } extern "C" unsigned long rb_require(const char *fname); void CExtManager::requireRubyFile( const char* szFilePath ) { rb_require(szFilePath); } void CExtManager::rhoLog(int nSeverity, const char* szModule, const char* szMsg, const char* szFile, int nLine) { rhoPlainLog(szFile, nLine, nSeverity, szModule, szMsg); } bool CExtManager::onWndMsg(MSG& oMsg) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { if ( (it->second)->onWndMsg( oMsg ) ) return true; } return false; } long CExtManager::OnNavigateTimeout(const wchar_t* szUrlBeingNavigatedTo) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { long lRes = (it->second)->OnNavigateTimeout( szUrlBeingNavigatedTo, makeExtData() ); if ( lRes ) return lRes; } return 0; } long CExtManager::OnSIPState(bool bSIPState) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { long lRes = (it->second)->OnSIPState( bSIPState, makeExtData() ); if ( lRes ) return lRes; } return 0; } long CExtManager::OnAlertPopup(int nEnum, void* pData) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { long lRes = (it->second)->OnAlertPopup( nEnum, pData, makeExtData() ); if ( lRes ) return lRes; } return 0; } long CExtManager::OnNavigateError(const wchar_t* szUrlBeingNavigatedTo) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { long lRes = (it->second)->OnNavigateError( szUrlBeingNavigatedTo, makeExtData() ); if ( lRes ) return lRes; } return 0; } void CExtManager::OnAppActivate(bool bActivate) { for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it ) { (it->second)->OnAppActivate( bActivate, makeExtData() ); } } } //namespace common } //namespace rho <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" #ident "Copyright (c) 2011 Tokutek Inc. All rights reserved." #ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it." #include <config.h> #include <toku_pthread.h> #include "kibbutz.h" #include "includes.h" // A Kibbutz is a collection of workers and some work to do. struct todo { void (*f)(void *extra); void *extra; struct todo *next; struct todo *prev; }; struct kid { struct kibbutz *k; }; struct kibbutz { toku_mutex_t mutex; toku_cond_t cond; bool please_shutdown; struct todo *head, *tail; // head is the next thing to do. int n_workers; pthread_t *workers; // an array of n_workers struct kid *ids; // pass this in when creating a worker so it knows who it is. }; static void *work_on_kibbutz (void *); KIBBUTZ toku_kibbutz_create (int n_workers) { KIBBUTZ XMALLOC(k); toku_mutex_init(&k->mutex, NULL); toku_cond_init(&k->cond, NULL); k->please_shutdown = false; k->head = NULL; k->tail = NULL; k->n_workers = n_workers; XMALLOC_N(n_workers, k->workers); XMALLOC_N(n_workers, k->ids); for (int i=0; i<n_workers; i++) { k->ids[i].k = k; int r = toku_pthread_create(&k->workers[i], NULL, work_on_kibbutz, &k->ids[i]); assert(r==0); } return k; } static void klock (KIBBUTZ k) { toku_mutex_lock(&k->mutex); } static void kunlock (KIBBUTZ k) { toku_mutex_unlock(&k->mutex); } static void kwait (KIBBUTZ k) { toku_cond_wait(&k->cond, &k->mutex); } static void ksignal (KIBBUTZ k) { toku_cond_signal(&k->cond); } // // pops the tail of the kibbutz off the list and works on it // Note that in toku_kibbutz_enq, items are enqueued at the head, // making the work be done in FIFO order. This is necessary // to avoid deadlocks in flusher threads. // static void *work_on_kibbutz (void *kidv) { struct kid *CAST_FROM_VOIDP(kid, kidv); KIBBUTZ k = kid->k; klock(k); while (1) { while (k->tail) { struct todo *item = k->tail; k->tail = item->prev; if (k->tail==NULL) { k->head=NULL; } else { // if there are other things to do, then wake up the next guy, if there is one. ksignal(k); } kunlock(k); item->f(item->extra); toku_free(item); klock(k); // if there's another item on k->head, then we'll just go grab it now, without waiting for a signal. } if (k->please_shutdown) { // Don't follow this unless the work is all done, so that when we set please_shutdown, all the work finishes before any threads quit. ksignal(k); // must wake up anyone else who is waiting, so they can shut down. kunlock(k); return NULL; } // There is no work to do and it's not time to shutdown, so wait. kwait(k); } } // // adds work to the head of the kibbutz // Note that in work_on_kibbutz, items are popped off the tail for work, // making the work be done in FIFO order. This is necessary // to avoid deadlocks in flusher threads. // void toku_kibbutz_enq (KIBBUTZ k, void (*f)(void*), void *extra) { struct todo *XMALLOC(td); td->f = f; td->extra = extra; klock(k); assert(!k->please_shutdown); td->next = k->head; td->prev = NULL; if (k->head) { assert(k->head->prev == NULL); k->head->prev = td; } k->head = td; if (k->tail==NULL) k->tail = td; ksignal(k); kunlock(k); } void toku_kibbutz_destroy (KIBBUTZ k) // Effect: wait for all the enqueued work to finish, and then destroy the kibbutz. // Note: It is an error for to perform kibbutz_enq operations after this is called. { klock(k); assert(!k->please_shutdown); k->please_shutdown = true; ksignal(k); // must wake everyone up to tell them to shutdown. kunlock(k); for (int i=0; i<k->n_workers; i++) { void *result; int r = toku_pthread_join(k->workers[i], &result); assert(r==0); assert(result==NULL); } toku_free(k->workers); toku_free(k->ids); toku_cond_destroy(&k->cond); toku_mutex_destroy(&k->mutex); toku_free(k); } <commit_msg>refs #5507 clear kibbutz mutex<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" #ident "Copyright (c) 2011 Tokutek Inc. All rights reserved." #ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it." #include <config.h> #include <toku_pthread.h> #include "kibbutz.h" #include "includes.h" // A Kibbutz is a collection of workers and some work to do. struct todo { void (*f)(void *extra); void *extra; struct todo *next; struct todo *prev; }; struct kid { struct kibbutz *k; }; struct kibbutz { toku_mutex_t mutex; toku_cond_t cond; bool please_shutdown; struct todo *head, *tail; // head is the next thing to do. int n_workers; pthread_t *workers; // an array of n_workers struct kid *ids; // pass this in when creating a worker so it knows who it is. }; static void *work_on_kibbutz (void *); KIBBUTZ toku_kibbutz_create (int n_workers) { KIBBUTZ XCALLOC(k); toku_mutex_init(&k->mutex, NULL); toku_cond_init(&k->cond, NULL); k->please_shutdown = false; k->head = NULL; k->tail = NULL; k->n_workers = n_workers; XMALLOC_N(n_workers, k->workers); XMALLOC_N(n_workers, k->ids); for (int i=0; i<n_workers; i++) { k->ids[i].k = k; int r = toku_pthread_create(&k->workers[i], NULL, work_on_kibbutz, &k->ids[i]); assert(r==0); } return k; } static void klock (KIBBUTZ k) { toku_mutex_lock(&k->mutex); } static void kunlock (KIBBUTZ k) { toku_mutex_unlock(&k->mutex); } static void kwait (KIBBUTZ k) { toku_cond_wait(&k->cond, &k->mutex); } static void ksignal (KIBBUTZ k) { toku_cond_signal(&k->cond); } // // pops the tail of the kibbutz off the list and works on it // Note that in toku_kibbutz_enq, items are enqueued at the head, // making the work be done in FIFO order. This is necessary // to avoid deadlocks in flusher threads. // static void *work_on_kibbutz (void *kidv) { struct kid *CAST_FROM_VOIDP(kid, kidv); KIBBUTZ k = kid->k; klock(k); while (1) { while (k->tail) { struct todo *item = k->tail; k->tail = item->prev; if (k->tail==NULL) { k->head=NULL; } else { // if there are other things to do, then wake up the next guy, if there is one. ksignal(k); } kunlock(k); item->f(item->extra); toku_free(item); klock(k); // if there's another item on k->head, then we'll just go grab it now, without waiting for a signal. } if (k->please_shutdown) { // Don't follow this unless the work is all done, so that when we set please_shutdown, all the work finishes before any threads quit. ksignal(k); // must wake up anyone else who is waiting, so they can shut down. kunlock(k); return NULL; } // There is no work to do and it's not time to shutdown, so wait. kwait(k); } } // // adds work to the head of the kibbutz // Note that in work_on_kibbutz, items are popped off the tail for work, // making the work be done in FIFO order. This is necessary // to avoid deadlocks in flusher threads. // void toku_kibbutz_enq (KIBBUTZ k, void (*f)(void*), void *extra) { struct todo *XMALLOC(td); td->f = f; td->extra = extra; klock(k); assert(!k->please_shutdown); td->next = k->head; td->prev = NULL; if (k->head) { assert(k->head->prev == NULL); k->head->prev = td; } k->head = td; if (k->tail==NULL) k->tail = td; ksignal(k); kunlock(k); } void toku_kibbutz_destroy (KIBBUTZ k) // Effect: wait for all the enqueued work to finish, and then destroy the kibbutz. // Note: It is an error for to perform kibbutz_enq operations after this is called. { klock(k); assert(!k->please_shutdown); k->please_shutdown = true; ksignal(k); // must wake everyone up to tell them to shutdown. kunlock(k); for (int i=0; i<k->n_workers; i++) { void *result; int r = toku_pthread_join(k->workers[i], &result); assert(r==0); assert(result==NULL); } toku_free(k->workers); toku_free(k->ids); toku_cond_destroy(&k->cond); toku_mutex_destroy(&k->mutex); toku_free(k); } <|endoftext|>
<commit_before>/* * Copyright (c) 2003 Jeremy Stribling (strib@mit.edu) * Thomer M. Gil (thomer@csail.mit.edu) * Massachusetts Institute of Technology * * 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. * * * See the HOWTO in eventgenerators/churneventgenerator.h . */ #include "churneventgenerator.h" #include "p2psim/eventqueue.h" #include "p2psim/network.h" #include "events/p2pevent.h" #include "events/simevent.h" #include <math.h> #include <time.h> #include <list> #include <stdlib.h> #include <iostream> #include "observers/datastoreobserver.h" using namespace std; ChurnEventGenerator::ChurnEventGenerator(Args *args) { if( (*args)["wkn"] == "" ) { _wkn_string = "1"; _wkn = 1; } else { _wkn_string = (*args)["wkn"]; _wkn = args->nget<IPAddress>("wkn", 1, 10); } _lifemean = args->nget( "lifemean", 3600000, 10 ); //0 means no failure _deathmean = args->nget( "deathmean", _lifemean, 10 ); //0 means no failure _lookupmean = args->nget( "lookupmean", 3600000, 10 ); _alpha = args->fget("alpha",1.0); _beta = args->nget("beta",1800000,10); _pareto = args->nget("pareto",0,10); _uniform = args->nget("uniform",0,10); if (_pareto && _uniform) abort(); if( (*args)["exittime"] == "" ) { _exittime_string = "200000"; _exittime = 200000; } else { _exittime_string = (*args)["exittime"]; _exittime = args->nget( "exittime", 200000, 10 ); } Node::set_collect_stat_time(args->nget("stattime",0,10)); _ipkeys = args->nget("ipkeys", 0, 10); _datakeys = args->nget("datakeys", 0, 10); _ips = NULL; EventQueue::Instance()->registerObserver(this); } void ChurnEventGenerator::run() { // first register the exit event vector<string> simargs; simargs.push_back( _exittime_string ); simargs.push_back( "exit" ); SimEvent *se = New SimEvent( &simargs ); add_event( se ); // start all nodes at a random time between 1 and n (except the wkn, who // starts at 1) vector<IPAddress> *_ips = Network::Instance()->getallfirstips(); IPAddress ip = 0; for(u_int xxx = 0; xxx < _ips->size(); xxx++){ ip = (*_ips)[xxx]; Args *a = New Args(); (*a)["wellknown"] = _wkn_string; (*a)["first"] = _wkn_string; //a hack u_int jointime; if( ip == _wkn ) { jointime = 1; } else { // add one to the mod factor because typical 2^n network sizes // make really bad mod factors jointime = (random()%(_ips->size()+1)) + 1; } if( now() + jointime < _exittime ) { P2PEvent *e = New P2PEvent(now() + jointime, ip, "join", a); add_event(e); } else { delete a; a = NULL; } // also schedule their first lookup a = New Args(); Time tolookup = next_exponential( _lookupmean ); (*a)["key"] = get_lookup_key(); if( _lookupmean > 0 && now() + jointime + tolookup < _exittime ) { P2PEvent *e = New P2PEvent(now() + jointime + tolookup, ip, "lookup", a); add_event(e); } else { delete a; } } EventQueue::Instance()->go(); } void ChurnEventGenerator::kick(Observed *o, ObserverInfo *oi) { assert( oi ); Event *ev = (Event *) oi; assert( ev ); if( ev->name() != "P2PEvent" ) { // not a p2p event, so we don't care return; } P2PEvent *p2p_observed = (P2PEvent *) ev; assert( p2p_observed ); Args *a = New Args(); IPAddress ip = p2p_observed->node->first_ip(); if( p2p_observed->type == "join" ) { // the wellknown can't crash (***TODO: fix this?***) also if lifemean is zero, this node won't die p2p_observed->node->record_join(); if (( ip != _wkn ) && ( _lifemean > 0)) { // pick a time for this node to die Time todie = 0; while (!todie) { if (_uniform) todie = next_uniform(_lifemean); else if (_pareto) todie = next_pareto(_alpha,_beta); else todie = next_exponential( _lifemean ); } if( now() + todie < _exittime ) { P2PEvent *e = New P2PEvent(now() + todie, ip, "crash", a); add_event(e); } } else { delete a; } } else if( p2p_observed->type == "crash" ) { p2p_observed->node->record_crash(); // pick a time for the node to rejoin Time tojoin = 0; while (!tojoin) { if (_uniform) tojoin = next_uniform(_deathmean); else if (_pareto) tojoin = next_pareto(_alpha,_beta); else tojoin = next_exponential( _deathmean ); } (*a)["wellknown"] = _wkn_string; //cout << now() << ": joining " << ip << " in " << tojoin << " ms" << endl; if( now() + tojoin < _exittime ) { P2PEvent *e = New P2PEvent(now() + tojoin, ip, "join", a); add_event(e); } else { delete a; } } else if( p2p_observed->type == "lookup" ) { // pick a time for the next lookup Time tolookup = next_exponential( _lookupmean ); (*a)["key"] = get_lookup_key(); string tmptmp = (*a)["key"]; if( now() + tolookup < _exittime ) { // cout << now() << ": Scheduling lookup to " << ip << " in " << tolookup // << " for " << (*a)["key"] << endl; P2PEvent *e = New P2PEvent(now() + tolookup, ip, "lookup", a); add_event(e); } else { delete a; } } else { delete a; } } Time ChurnEventGenerator::next_uniform(u_int mean) { //time is uniformly distributed between 0.1*mean and 1.9*mean double x = ( (double)random() / (double)(RAND_MAX) ); Time rt = (Time)((0.1+1.8*x)*mean); return rt; } Time ChurnEventGenerator::next_pareto(double a, u_int b) { double x = ( (double)random() / (double)(RAND_MAX) ); double xx = exp(log(1 - x)/a); Time rt = (Time) ((double)b/xx); //printf("CHEESE %llu %.3f\n",rt,xx); return rt; } Time ChurnEventGenerator::next_exponential( u_int mean ) { assert( mean > 0 ); double x = ( (double)random() / (double)(RAND_MAX) ); u_int rt = (u_int) ((-(mean*1.0))*log( 1 - x )); return (Time) rt; } string ChurnEventGenerator::get_lookup_key() { if (_datakeys) { DataItem vd = DataStoreObserver::Instance(NULL)->get_random_item(); char buf[10]; sprintf (buf, "%llX", vd.key); return string (buf); } if((!_ips) || Network::Instance()->changed()) { _ips = Network::Instance()->getallfirstips(); } if(_ipkeys){ // for Kelips, use only keys equal to live IP addresses. for(int iters = 0; iters < 50; iters++){ IPAddress ip = (*_ips)[random() % _ips->size()]; IPAddress currip = Network::Instance()->first2currip(ip); if(Network::Instance()->alive(currip)){ char buf[10]; sprintf(buf, "%x", currip); return string(buf); } } assert(0); } // look up random 64-bit keys char buffer[20]; // random() returns only 31 random bits. // so we need three to ensure all 64 bits are random. unsigned long long a = random(); unsigned long long b = random(); unsigned long long c = random(); unsigned long long x = (a << 48) ^ (b << 24) ^ (c >> 4); sprintf(buffer, "%llX", x); return string(buffer); } <commit_msg>assertion in this file won't fire...<commit_after>/* * Copyright (c) 2003 Jeremy Stribling (strib@mit.edu) * Thomer M. Gil (thomer@csail.mit.edu) * Massachusetts Institute of Technology * * 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. * * * See the HOWTO in eventgenerators/churneventgenerator.h . */ #include "churneventgenerator.h" #include "p2psim/eventqueue.h" #include "p2psim/network.h" #include "events/p2pevent.h" #include "events/simevent.h" #include <math.h> #include <time.h> #include <list> #include <stdlib.h> #include <iostream> #include "observers/datastoreobserver.h" using namespace std; ChurnEventGenerator::ChurnEventGenerator(Args *args) { if( (*args)["wkn"] == "" ) { _wkn_string = "1"; _wkn = 1; } else { _wkn_string = (*args)["wkn"]; _wkn = args->nget<IPAddress>("wkn", 1, 10); } _lifemean = args->nget( "lifemean", 3600000, 10 ); //0 means no failure _deathmean = args->nget( "deathmean", _lifemean, 10 ); //0 means no failure _lookupmean = args->nget( "lookupmean", 3600000, 10 ); _alpha = args->fget("alpha",1.0); _beta = args->nget("beta",1800000,10); _pareto = args->nget("pareto",0,10); _uniform = args->nget("uniform",0,10); if (_pareto && _uniform) abort(); if( (*args)["exittime"] == "" ) { _exittime_string = "200000"; _exittime = 200000; } else { _exittime_string = (*args)["exittime"]; _exittime = args->nget( "exittime", 200000, 10 ); } Node::set_collect_stat_time(args->nget("stattime",0,10)); _ipkeys = args->nget("ipkeys", 0, 10); _datakeys = args->nget("datakeys", 0, 10); _ips = NULL; EventQueue::Instance()->registerObserver(this); } void ChurnEventGenerator::run() { // first register the exit event vector<string> simargs; simargs.push_back( _exittime_string ); simargs.push_back( "exit" ); SimEvent *se = New SimEvent( &simargs ); add_event( se ); // start all nodes at a random time between 1 and n (except the wkn, who // starts at 1) vector<IPAddress> *_ips = Network::Instance()->getallfirstips(); IPAddress ip = 0; for(u_int xxx = 0; xxx < _ips->size(); xxx++){ ip = (*_ips)[xxx]; Args *a = New Args(); (*a)["wellknown"] = _wkn_string; (*a)["first"] = _wkn_string; //a hack u_int jointime; if( ip == _wkn ) { jointime = 1; } else { // add one to the mod factor because typical 2^n network sizes // make really bad mod factors jointime = (random()%(_ips->size()+1)) + 1; } if( now() + jointime < _exittime ) { P2PEvent *e = New P2PEvent(now() + jointime, ip, "join", a); add_event(e); } else { delete a; a = NULL; } // also schedule their first lookup a = New Args(); Time tolookup = next_exponential( _lookupmean ); string s = get_lookup_key(); (*a)["key"] = s; if( _lookupmean > 0 && now() + jointime + tolookup < _exittime ) { P2PEvent *e = New P2PEvent(now() + jointime + tolookup, ip, "lookup", a); add_event(e); } else { delete a; } } EventQueue::Instance()->go(); } void ChurnEventGenerator::kick(Observed *o, ObserverInfo *oi) { assert( oi ); Event *ev = (Event *) oi; assert( ev ); if( ev->name() != "P2PEvent" ) { // not a p2p event, so we don't care return; } P2PEvent *p2p_observed = (P2PEvent *) ev; assert( p2p_observed ); Args *a = New Args(); IPAddress ip = p2p_observed->node->first_ip(); if( p2p_observed->type == "join" ) { // the wellknown can't crash (***TODO: fix this?***) also if lifemean is zero, this node won't die p2p_observed->node->record_join(); if (( ip != _wkn ) && ( _lifemean > 0)) { // pick a time for this node to die Time todie = 0; while (!todie) { if (_uniform) todie = next_uniform(_lifemean); else if (_pareto) todie = next_pareto(_alpha,_beta); else todie = next_exponential( _lifemean ); } if( now() + todie < _exittime ) { P2PEvent *e = New P2PEvent(now() + todie, ip, "crash", a); add_event(e); } } else { delete a; } } else if( p2p_observed->type == "crash" ) { p2p_observed->node->record_crash(); // pick a time for the node to rejoin Time tojoin = 0; while (!tojoin) { if (_uniform) tojoin = next_uniform(_deathmean); else if (_pareto) tojoin = next_pareto(_alpha,_beta); else tojoin = next_exponential( _deathmean ); } (*a)["wellknown"] = _wkn_string; //cout << now() << ": joining " << ip << " in " << tojoin << " ms" << endl; if( now() + tojoin < _exittime ) { P2PEvent *e = New P2PEvent(now() + tojoin, ip, "join", a); add_event(e); } else { delete a; } } else if( p2p_observed->type == "lookup" ) { // pick a time for the next lookup Time tolookup = next_exponential( _lookupmean ); string s = get_lookup_key(); (*a)["key"] = s; if( now() + tolookup < _exittime ) { // cout << now() << ": Scheduling lookup to " << ip << " in " << tolookup // << " for " << (*a)["key"] << endl; P2PEvent *e = New P2PEvent(now() + tolookup, ip, "lookup", a); add_event(e); } else { delete a; } } else { delete a; } } Time ChurnEventGenerator::next_uniform(u_int mean) { //time is uniformly distributed between 0.1*mean and 1.9*mean double x = ( (double)random() / (double)(RAND_MAX) ); Time rt = (Time)((0.1+1.8*x)*mean); return rt; } Time ChurnEventGenerator::next_pareto(double a, u_int b) { double x = ( (double)random() / (double)(RAND_MAX) ); double xx = exp(log(1 - x)/a); Time rt = (Time) ((double)b/xx); //printf("CHEESE %llu %.3f\n",rt,xx); return rt; } Time ChurnEventGenerator::next_exponential( u_int mean ) { assert( mean > 0 ); double x = ( (double)random() / (double)(RAND_MAX) ); u_int rt = (u_int) ((-(mean*1.0))*log( 1 - x )); return (Time) rt; } string ChurnEventGenerator::get_lookup_key() { if (_datakeys) { DataItem vd = DataStoreObserver::Instance(NULL)->get_random_item(); char buf[10]; sprintf (buf, "%llX", vd.key); return string (buf); } if((!_ips) || Network::Instance()->changed()) { _ips = Network::Instance()->getallfirstips(); } if(_ipkeys){ // for Kelips, use only keys equal to live IP addresses. for(int iters = 0; iters < 50; iters++){ IPAddress ip = (*_ips)[random() % _ips->size()]; IPAddress currip = Network::Instance()->first2currip(ip); if(Network::Instance()->alive(currip)){ char buf[10]; sprintf(buf, "%x", currip); return string(buf); } } assert(0);//XXX wierd; assertion wont' fire } // look up random 64-bit keys char buffer[20]; // random() returns only 31 random bits. // so we need three to ensure all 64 bits are random. unsigned long long a = random(); unsigned long long b = random(); unsigned long long c = random(); unsigned long long x = (a << 48) ^ (b << 24) ^ (c >> 4); sprintf(buffer, "%llX", x); return string(buffer); } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// /* Copyright (c) 2014, 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 Oak Ridge National Laboratory 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_FunctionSpace.hpp * \author Stuart R. Slattery * \brief Function space. */ //---------------------------------------------------------------------------// #ifndef DTK_FUNCTIONSPACE_HPP #define DTK_FUNCTIONSPACE_HPP #include "DTK_EntitySet.hpp" #include "DTK_EntityLocalMap.hpp" #include "DTK_EntityShapeFunction.hpp" #include <Teuchos_RCP.hpp> #include <Thyra_SpmdVectorSpaceBase.hpp> namespace DataTransferKit { //---------------------------------------------------------------------------// /*! \class FunctionSpace \brief Space of a function. FunctionSpace binds the functional support of a field to a parallel vector space. */ //---------------------------------------------------------------------------// class FunctionSpace { public: /*! * \brief Constructor. */ FunctionSpace( const Teuchos::RCP<const Thyra::SpmdVectorSpaceBase<double> > vector_space, const Teuchos::RCP<EntitySet>& entity_set, const Teuchos::RCP<EntityLocalMap>& local_map = Teuchos::null, const Teuchos::RCP<EntityShapeFunction>& shape_function = Teuchos::null ); /*! * \brief Destructor. */ ~FunctionSpace(); /*! * \brief Get the entity set over which the fields are defined. */ Teuchos::RCP<EntitySet> entitySet() const; /*! * \brief Get the reference frame for entities supporting the function. */ Teuchos::RCP<EntityLocalMap> entityLocalMap() const; /*! * \brief Get the shape function for entities supporting the function. */ Teuchos::RCP<EntityShapeFunction> entityShapeFunction() const; /*! * \brief Get the parallel vector space under the DOFs. */ Teuchos::RCP<const Thyra::SpmdVectorSpaceBase<double> > vectorSpace() const; private: // The vector space under the DOFs. Teuchos::RCP<const Thyra::SpmdVectorSpaceBase<double> > d_vector_space; // The entity set over which the function space is constructed. Teuchos::RCP<EntitySet> d_entity_set; // The reference frame for entities in the set. Teuchos::RCP<EntityLocalMap> d_local_map; // The shape function for the entities in the set. Teuchos::RCP<EntityShapeFunction> d_shape_function; }; //---------------------------------------------------------------------------// } // end namespace DataTransferKit //---------------------------------------------------------------------------// #endif // end DTK_FUNCTIONSPACE_HPP //---------------------------------------------------------------------------// // end DTK_FunctionSpace.hpp //---------------------------------------------------------------------------// <commit_msg>updating local DOF id api in function space<commit_after>//---------------------------------------------------------------------------// /* Copyright (c) 2014, 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 Oak Ridge National Laboratory 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_FunctionSpace.hpp * \author Stuart R. Slattery * \brief Function space. */ //---------------------------------------------------------------------------// #ifndef DTK_FUNCTIONSPACE_HPP #define DTK_FUNCTIONSPACE_HPP #include "DTK_EntitySet.hpp" #include "DTK_EntityLocalMap.hpp" #include "DTK_EntityShapeFunction.hpp" #include <Teuchos_RCP.hpp> #include <Tpetra_Map.hpp> namespace DataTransferKit { //---------------------------------------------------------------------------// /*! \class FunctionSpace \brief Space of a function. FunctionSpace binds the functional support of a field to a parallel vector space. */ //---------------------------------------------------------------------------// class FunctionSpace { public: /*! * \brief Constructor. */ FunctionSpace( const Teuchos::ArrayView<const std::size_t> local_dof_ids, const Teuchos::RCP<EntitySet>& entity_set, const Teuchos::RCP<EntityLocalMap>& local_map = Teuchos::null, const Teuchos::RCP<EntityShapeFunction>& shape_function = Teuchos::null ); /*! * \brief Destructor. */ ~FunctionSpace(); /*! * \brief Get the entity set over which the fields are defined. */ Teuchos::RCP<EntitySet> entitySet() const; /*! * \brief Get the local map for entities supporting the function. */ Teuchos::RCP<EntityLocalMap> localMap() const; /*! * \brief Get the shape function for entities supporting the function. */ Teuchos::RCP<EntityShapeFunction> shapeFunction() const; /*! * \brief Get the parallel map under the DOFs. */ Teuchos::RCP<const Tpetra::Map<int,std::size_t> > dofMap() const; private: // The entity set over which the function space is constructed. Teuchos::RCP<EntitySet> d_entity_set; // The reference frame for entities in the set. Teuchos::RCP<EntityLocalMap> d_local_map; // The shape function for the entities in the set. Teuchos::RCP<EntityShapeFunction> d_shape_function; // A parallel map under the DOFs. Teuchos::RCP<const Tpetra::Map<int,std::size_t> > d_dof_map; }; //---------------------------------------------------------------------------// } // end namespace DataTransferKit //---------------------------------------------------------------------------// #endif // end DTK_FUNCTIONSPACE_HPP //---------------------------------------------------------------------------// // end DTK_FunctionSpace.hpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>#include "suzanne.h" //@todo COMMENT! //@todo refactor "suzanne" test model loader into a real model loader // // CONSTRUCTORS //////////////////////////////////////////////////////////////// // Suzanne::Suzanne() { model = loadObj( QString("table.obj") ); } Suzanne::Suzanne( QString path ) { model = loadObj( path ); } Suzanne::~Suzanne() { this->teardownGL(); } // // INTERFACE IMPLEMENTATIONS /////////////////////////////////////////////////// // void Suzanne::initializeGL() { initializeOpenGLFunctions(); // Create the Shader for suzanne to use program = new QOpenGLShaderProgram(); program->addShaderFromSourceFile( QOpenGLShader::Vertex, ":/shaders/simple.vs" ); program->addShaderFromSourceFile( QOpenGLShader::Fragment, ":/shaders/simple.fs" ); program->link(); program->bind(); // Cache the Uniform Locations modelWorld = program->uniformLocation( "model_to_world" ); worldEye = program->uniformLocation( "world_to_eye" ); eyeClip = program->uniformLocation( "eye_to_clip" ); // Create a Vertex Buffer Object (vbo) vbo.create(); vbo.bind(); vbo.setUsagePattern( QOpenGLBuffer::StaticDraw ); vbo.allocate( model, numVertices * sizeof( model[0] ) ); // Create a Vertex Array Object (vao) vao.create(); vao.bind(); program->enableAttributeArray( 0 ); program->enableAttributeArray( 1 ); program->setAttributeBuffer( 0, GL_FLOAT, Vertex::positionOffset(), Vertex::PositionTupleSize, Vertex::stride() ); program->setAttributeBuffer( 1, GL_FLOAT, Vertex::colorOffset(), Vertex::ColorTupleSize, Vertex::stride() ); // Release all (order matters) vao.release(); vbo.release(); program->release(); } void Suzanne::paintGL( Camera3D& camera, QMatrix4x4& projection ) { glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glDepthMask( GL_TRUE ); glEnable( GL_CULL_FACE ); program->bind(); program->setUniformValue( worldEye, camera.toMatrix() ); program->setUniformValue( eyeClip, projection ); vao.bind(); program->setUniformValue( modelWorld, transform.toMatrix() ); glDrawArrays( GL_TRIANGLES, 0, numVertices ); vao.release(); program->release(); } void Suzanne::teardownGL() { vao.destroy(); vbo.destroy(); delete program; } // // MODEL LOADING /////////////////////////////////////////////////////////////// // Vertex* Suzanne::loadObj( QString path ) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile( path.toStdString(), aiProcess_GenSmoothNormals | aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType ); qDebug() << "After importer"; aiMesh* mesh = scene->mMeshes[0]; qDebug() << "After mesh"; numVertices = mesh->mNumFaces * 3; Vertex* geometry = new Vertex[ numVertices ]; qDebug() << "After Vertex declr"; int counter = 0; for( unsigned int i = 0; i < mesh->mNumFaces; i++ ) { const aiFace& face = mesh->mFaces[i]; qDebug() << "After aiFace declr"; for( unsigned int j = 0; j < 3; j++ ) { qDebug() << "Before aiVector3D"; qDebug() << mesh->mNumVertices; qDebug() << "Qt wtf"; qDebug() << face.mNumIndices; aiVector3D pos = mesh->mVertices[ face.mIndices[j] ]; qDebug() << "After aiVector3D"; QVector3D position( pos.x, pos.y, pos.z) ; QVector3D color( 255.0f, 165.0f, 0.0f ); qDebug() << "before geometry"; geometry[counter] = Vertex( position, color ); counter++; qDebug() << "After geometry"; } } geometry -= mesh->mNumFaces * 3; return geometry; }<commit_msg>removed debug output<commit_after>#include "suzanne.h" //@todo COMMENT! //@todo refactor "suzanne" test model loader into a real model loader // // CONSTRUCTORS //////////////////////////////////////////////////////////////// // Suzanne::Suzanne() { model = loadObj( QString("table.obj") ); } Suzanne::Suzanne( QString path ) { model = loadObj( path ); } Suzanne::~Suzanne() { this->teardownGL(); } // // INTERFACE IMPLEMENTATIONS /////////////////////////////////////////////////// // void Suzanne::initializeGL() { initializeOpenGLFunctions(); // Create the Shader for suzanne to use program = new QOpenGLShaderProgram(); program->addShaderFromSourceFile( QOpenGLShader::Vertex, ":/shaders/simple.vs" ); program->addShaderFromSourceFile( QOpenGLShader::Fragment, ":/shaders/simple.fs" ); program->link(); program->bind(); // Cache the Uniform Locations modelWorld = program->uniformLocation( "model_to_world" ); worldEye = program->uniformLocation( "world_to_eye" ); eyeClip = program->uniformLocation( "eye_to_clip" ); // Create a Vertex Buffer Object (vbo) vbo.create(); vbo.bind(); vbo.setUsagePattern( QOpenGLBuffer::StaticDraw ); vbo.allocate( model, numVertices * sizeof( model[0] ) ); // Create a Vertex Array Object (vao) vao.create(); vao.bind(); program->enableAttributeArray( 0 ); program->enableAttributeArray( 1 ); program->setAttributeBuffer( 0, GL_FLOAT, Vertex::positionOffset(), Vertex::PositionTupleSize, Vertex::stride() ); program->setAttributeBuffer( 1, GL_FLOAT, Vertex::colorOffset(), Vertex::ColorTupleSize, Vertex::stride() ); // Release all (order matters) vao.release(); vbo.release(); program->release(); } void Suzanne::paintGL( Camera3D& camera, QMatrix4x4& projection ) { glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glDepthMask( GL_TRUE ); glEnable( GL_CULL_FACE ); program->bind(); program->setUniformValue( worldEye, camera.toMatrix() ); program->setUniformValue( eyeClip, projection ); vao.bind(); program->setUniformValue( modelWorld, transform.toMatrix() ); glDrawArrays( GL_TRIANGLES, 0, numVertices ); vao.release(); program->release(); } void Suzanne::teardownGL() { vao.destroy(); vbo.destroy(); delete program; } // // MODEL LOADING /////////////////////////////////////////////////////////////// // Vertex* Suzanne::loadObj( QString path ) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile( path.toStdString(), aiProcess_GenSmoothNormals | aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType ); aiMesh* mesh = scene->mMeshes[0]; numVertices = mesh->mNumFaces * 3; Vertex* geometry = new Vertex[ numVertices ]; int counter = 0; for( unsigned int i = 0; i < mesh->mNumFaces; i++ ) { const aiFace& face = mesh->mFaces[i]; for( unsigned int j = 0; j < 3; j++ ) { aiVector3D pos = mesh->mVertices[ face.mIndices[j] ]; QVector3D position( pos.x, pos.y, pos.z) ; QVector3D color( 255.0f, 165.0f, 0.0f ); geometry[counter] = Vertex( position, color ); counter++; } } geometry -= mesh->mNumFaces * 3; return geometry; }<|endoftext|>
<commit_before>/* * @file opencog/embodiment/Control/OperationalAvatarController/PsiFeelingUpdaterAgent.cc * * @author Zhenhua Cai <czhedu@gmail.com> * @date 2011-04-19 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <boost/tokenizer.hpp> #include <opencog/atomspace/SimpleTruthValue.h> #include <opencog/guile/SchemeEval.h> #include <lib/json_spirit/json_spirit.h> #include "OAC.h" #include "PsiFeelingUpdaterAgent.h" using namespace opencog::oac; PsiFeelingUpdaterAgent::~PsiFeelingUpdaterAgent() { #ifdef HAVE_ZMQ delete this->publisher; #endif } PsiFeelingUpdaterAgent::PsiFeelingUpdaterAgent(CogServer& cs) : Agent(cs) { this->cycleCount = 0; #ifdef HAVE_ZMQ this->publisher = NULL; #endif // Force the Agent initialize itself during its first cycle. this->forceInitNextCycle(); } #ifdef HAVE_ZMQ void PsiFeelingUpdaterAgent::publishUpdatedValue(Plaza & plaza, zmq::socket_t & publisher, const unsigned long timeStamp) { using namespace json_spirit; // Send the name of current mind agent which would be used as a filter key by subscribers std::string keyString = "PsiFeelingUpdaterAgent"; plaza.publishStringMore(publisher, keyString); // Pack time stamp and all the feeling values in json format Object jsonObj; // json_spirit::Object is of type std::vector< Pair > jsonObj.push_back( Pair("timestamp", (uint64_t) timeStamp) ); std::map <std::string, FeelingMeta>::iterator iFeeling; std::string feeling; double updatedValue; for ( iFeeling = feelingMetaMap.begin(); iFeeling != feelingMetaMap.end(); iFeeling ++ ) { feeling = iFeeling->first; updatedValue = iFeeling->second.updatedValue; jsonObj.push_back( Pair(feeling, updatedValue) ); }// for // Publish the data packed in json format std::string dataString = write_formatted(jsonObj); plaza.publishString(publisher, dataString); } #endif // HAVE_ZMQ void PsiFeelingUpdaterAgent::init() { logger().debug( "PsiFeelingUpdaterAgent::%s - Initializing the Agent [ cycle = %d ]", __FUNCTION__, this->cycleCount); // Get OAC OAC* oac = dynamic_cast<OAC*>(&_cogserver); OC_ASSERT(oac, "Did not get an OAC server"); // Get AtomSpace AtomSpace& atomSpace = oac->getAtomSpace(); // Get petId const std::string & petId = oac->getPet().getPetId(); // Get petHandle Handle petHandle = AtomSpaceUtil::getAgentHandle(atomSpace, petId); if ( petHandle == Handle::UNDEFINED ) { logger().warn("PsiFeelingUpdaterAgent::%s - Failed to get the handle to the pet ( id = '%s' ) [ cycle = %d ]", __FUNCTION__, petId.c_str(), this->cycleCount); return; } // Clear old feelingMetaMap; this->feelingMetaMap.clear(); // Get feeling names from the configuration file std::string feelingNames = config()["PSI_FEELINGS"]; // Process feelings one by one boost::tokenizer<> feelingNamesTok (feelingNames); std::string feeling, feelingUpdater; FeelingMeta feelingMeta; for ( boost::tokenizer<>::iterator iFeelingName = feelingNamesTok.begin(); iFeelingName != feelingNamesTok.end(); iFeelingName ++ ) { feeling = (*iFeelingName); feelingUpdater = feeling + "FeelingUpdater"; logger().debug( "PsiFeelingUpdaterAgent::%s - Searching the meta data of feeling '%s'.", __FUNCTION__, feeling.c_str()); // Get the corresponding EvaluationLink of the pet's feeling Handle evaluationLink = this->getFeelingEvaluationLink(&_cogserver, feeling, petHandle); if ( evaluationLink == Handle::UNDEFINED ) { logger().warn( "PsiFeelingUpdaterAgent::%s - Failed to get the EvaluationLink for feeling '%s'", __FUNCTION__, feeling.c_str()); continue; } // Insert the meta data of the feeling to feelingMetaMap feelingMeta.init(feelingUpdater, evaluationLink); feelingMetaMap[feeling] = feelingMeta; logger().debug( "PsiFeelingUpdaterAgent::%s - Store the meta data of feeling '%s' successfully.", __FUNCTION__, feeling.c_str()); }// for // Initialize ZeroMQ publisher and add it to the plaza #ifdef HAVE_ZMQ Plaza & plaza = oac->getPlaza(); this->publisher = new zmq::socket_t (plaza.getZmqContext(), ZMQ_PUB); this->publishEndPoint = "ipc://" + petId + ".PsiFeelingUpdaterAgent.ipc"; this->publisher->bind( this->publishEndPoint.c_str() ); plaza.addPublisher(this->publishEndPoint); #endif // Avoid initialize during next cycle this->bInitialized = true; } Handle PsiFeelingUpdaterAgent::getFeelingEvaluationLink(opencog::CogServer * server, const std::string feelingName, Handle petHandle) { // Get AtomSpace AtomSpace& atomSpace = server->getAtomSpace(); // Get the Handle to feeling (PredicateNode) Handle feelingPredicateHandle = atomSpace.getHandle(PREDICATE_NODE, feelingName); if (feelingPredicateHandle == Handle::UNDEFINED) { logger().warn("PsiFeelingUpdaterAgent::%s - Failed to find the PredicateNode for feeling '%s' [ cycle = %d ].", __FUNCTION__, feelingName.c_str(), this->cycleCount); return opencog::Handle::UNDEFINED; } // Get the Handle to ListLink that contains the pet handle std::vector<Handle> listLinkOutgoing; listLinkOutgoing.push_back(petHandle); Handle listLinkHandle = atomSpace.getHandle(LIST_LINK, listLinkOutgoing); if (listLinkHandle == Handle::UNDEFINED) { logger().warn( "PsiFeelingUpdaterAgent::%s - Failed to find the ListLink containing the pet ( id = '%s' ) [ cycle = %d ].", __FUNCTION__, atomSpace.getName(petHandle).c_str(), this->cycleCount); return opencog::Handle::UNDEFINED; } // Get the Handle to EvaluationLink holding the pet's feeling std::vector<Handle> evaluationLinkOutgoing; evaluationLinkOutgoing.push_back(feelingPredicateHandle); evaluationLinkOutgoing.push_back(listLinkHandle); Handle evaluationLinkHandle = atomSpace.getHandle(EVALUATION_LINK, evaluationLinkOutgoing); if (evaluationLinkHandle == Handle::UNDEFINED) { logger().warn( "PsiFeelingUpdaterAgent::%s - Failed to find the EvaluationLink holding the feling '%s' of the pet ( id = '%s' ) [ cycle = %d ].", __FUNCTION__, feelingName.c_str(), atomSpace.getName(petHandle).c_str(), this->cycleCount); return opencog::Handle::UNDEFINED; } return evaluationLinkHandle; } void PsiFeelingUpdaterAgent::runUpdaters() { logger().debug( "PsiFeelingUpdaterAgent::%s - Running feeling updaters (scheme scripts) [ cycle = %d ]", __FUNCTION__ , this->cycleCount); #if HAVE_GUILE // Get OAC OAC* oac = dynamic_cast<OAC*>(&_cogserver); OC_ASSERT(oac, "Did not get an OAC server"); // Get AtomSpace AtomSpace& atomSpace = oac->getAtomSpace(); // Initialize scheme evaluator SchemeEval* evaluator = new SchemeEval(); std::string scheme_expression, scheme_return_value; // Process feelings one by one std::map <std::string, FeelingMeta>::iterator iFeeling; std::string feeling, feelingUpdater; for ( iFeeling = feelingMetaMap.begin(); iFeeling != feelingMetaMap.end(); iFeeling ++ ) { feeling = iFeeling->first; feelingUpdater = iFeeling->second.updaterName; scheme_expression = "( " + feelingUpdater + " )"; // Run the Procedure that update feeling and get the updated value scheme_return_value = evaluator->eval(scheme_expression); if ( evaluator->eval_error() ) { logger().error( "PsiFeelingUpdaterAgent::%s - Failed to execute '%s'", __FUNCTION__, scheme_expression.c_str()); iFeeling->second.bUpdated = false; continue; } else { iFeeling->second.bUpdated = true; } // Store updated value to FeelingMeta.updatedValue // // Note: Don't use boost::lexical_cast as below, because SchemeEval will append // a '\n' to the end of the result (scheme_return_value), which will make // boost::lexical_cast throw exception // // iFeeling->second.updatedValue = boost::lexical_cast<double>(scheme_return_value); // iFeeling->second.updatedValue = atof( scheme_return_value.c_str() ); // TODO: Change the log level to fine, after testing logger().debug( "PsiFeelingUpdaterAgent::%s - The new level of feeling '%s' will be %f", __FUNCTION__, feeling.c_str(), iFeeling->second.updatedValue); }// for delete evaluator; #endif // HAVE_GUILE } void PsiFeelingUpdaterAgent::setUpdatedValues() { logger().debug( "PsiFeelingUpdaterAgent::%s - Setting updated feelings to AtomSpace [ cycle =%d ]", __FUNCTION__, this->cycleCount); // Get OAC OAC* oac = dynamic_cast<OAC*>(&_cogserver); OC_ASSERT(oac, "Did not get an OAC server"); // Get AtomSpace AtomSpace& atomSpace = oac->getAtomSpace(); // Process feelings one by one std::map <std::string, FeelingMeta>::iterator iFeeling; std::string feeling; double updatedValue; Handle evaluationLink; for ( iFeeling = feelingMetaMap.begin(); iFeeling != feelingMetaMap.end(); iFeeling ++ ) { if ( !iFeeling->second.bUpdated ) continue; feeling = iFeeling->first; evaluationLink = iFeeling->second.evaluationLink; updatedValue = iFeeling->second.updatedValue; // Set truth value of corresponding EvaluationLink TruthValuePtr stvFeeling = SimpleTruthValue::createTV(updatedValue, 1.0); atomSpace.setTV(evaluationLink, stvFeeling); // Reset bUpdated iFeeling->second.bUpdated = false; // TODO: Change the log level to fine, after testing logger().debug( "PsiFeelingUpdaterAgent::%s - Set the level of feeling '%s' to %f", __FUNCTION__, feeling.c_str(), updatedValue); }// for } void PsiFeelingUpdaterAgent::sendUpdatedValues() { logger().debug( "PsiFeelingUpdaterAgent::%s - Sending updated feelings to the virtual world where the pet lives [ cycle =%d ]", __FUNCTION__, this->cycleCount); // Get OAC OAC * oac = dynamic_cast<OAC *>(&_cogserver); // Get AtomSpace // AtomSpace & atomSpace = * ( oac->getAtomSpace() ); // Get petName const std::string & petName = oac->getPet().getName(); // Prepare the data to be sent std::map <std::string, FeelingMeta>::iterator iFeeling; std::map <std::string, float> feelingValueMap; std::string feeling; double updatedValue; for ( iFeeling = feelingMetaMap.begin(); iFeeling != feelingMetaMap.end(); iFeeling ++ ) { feeling = iFeeling->first; updatedValue = iFeeling->second.updatedValue; feelingValueMap[feeling] = updatedValue; }// for // Send updated feelings to the virtual world where the pet lives oac->getPAI().sendEmotionalFeelings(petName, feelingValueMap); } void PsiFeelingUpdaterAgent::run() { this->cycleCount ++; logger().debug( "PsiFeelingUpdaterAgent::%s - Executing run %d times", __FUNCTION__, this->cycleCount); // Initialize the Agent (feelingMetaMap etc) if ( !this->bInitialized ) this->init(); // Run feeling updaters (combo scripts) this->runUpdaters(); // Set updated values to AtomSpace this->setUpdatedValues(); // Send updated values to the virtual world where the pet lives this->sendUpdatedValues(); #ifdef HAVE_ZMQ // Publish updated modulator values via ZeroMQ OAC * oac = dynamic_cast<OAC *>(&_cogserver); unsigned long timeStamp = oac->getPAI().getLatestSimWorldTimestamp(); Plaza & plaza = oac->getPlaza(); this->publishUpdatedValue(plaza, *this->publisher, timeStamp); #endif } <commit_msg>Fix compiler warning<commit_after>/* * @file opencog/embodiment/Control/OperationalAvatarController/PsiFeelingUpdaterAgent.cc * * @author Zhenhua Cai <czhedu@gmail.com> * @date 2011-04-19 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <boost/tokenizer.hpp> #include <opencog/atomspace/SimpleTruthValue.h> #include <opencog/guile/SchemeEval.h> #include <lib/json_spirit/json_spirit.h> #include "OAC.h" #include "PsiFeelingUpdaterAgent.h" using namespace opencog::oac; PsiFeelingUpdaterAgent::~PsiFeelingUpdaterAgent() { #ifdef HAVE_ZMQ delete this->publisher; #endif } PsiFeelingUpdaterAgent::PsiFeelingUpdaterAgent(CogServer& cs) : Agent(cs) { this->cycleCount = 0; #ifdef HAVE_ZMQ this->publisher = NULL; #endif // Force the Agent initialize itself during its first cycle. this->forceInitNextCycle(); } #ifdef HAVE_ZMQ void PsiFeelingUpdaterAgent::publishUpdatedValue(Plaza & plaza, zmq::socket_t & publisher, const unsigned long timeStamp) { using namespace json_spirit; // Send the name of current mind agent which would be used as a filter key by subscribers std::string keyString = "PsiFeelingUpdaterAgent"; plaza.publishStringMore(publisher, keyString); // Pack time stamp and all the feeling values in json format Object jsonObj; // json_spirit::Object is of type std::vector< Pair > jsonObj.push_back( Pair("timestamp", (uint64_t) timeStamp) ); std::map <std::string, FeelingMeta>::iterator iFeeling; std::string feeling; double updatedValue; for ( iFeeling = feelingMetaMap.begin(); iFeeling != feelingMetaMap.end(); iFeeling ++ ) { feeling = iFeeling->first; updatedValue = iFeeling->second.updatedValue; jsonObj.push_back( Pair(feeling, updatedValue) ); }// for // Publish the data packed in json format std::string dataString = write_formatted(jsonObj); plaza.publishString(publisher, dataString); } #endif // HAVE_ZMQ void PsiFeelingUpdaterAgent::init() { logger().debug( "PsiFeelingUpdaterAgent::%s - Initializing the Agent [ cycle = %d ]", __FUNCTION__, this->cycleCount); // Get OAC OAC* oac = dynamic_cast<OAC*>(&_cogserver); OC_ASSERT(oac, "Did not get an OAC server"); // Get AtomSpace AtomSpace& atomSpace = oac->getAtomSpace(); // Get petId const std::string & petId = oac->getPet().getPetId(); // Get petHandle Handle petHandle = AtomSpaceUtil::getAgentHandle(atomSpace, petId); if ( petHandle == Handle::UNDEFINED ) { logger().warn("PsiFeelingUpdaterAgent::%s - Failed to get the handle to the pet ( id = '%s' ) [ cycle = %d ]", __FUNCTION__, petId.c_str(), this->cycleCount); return; } // Clear old feelingMetaMap; this->feelingMetaMap.clear(); // Get feeling names from the configuration file std::string feelingNames = config()["PSI_FEELINGS"]; // Process feelings one by one boost::tokenizer<> feelingNamesTok (feelingNames); std::string feeling, feelingUpdater; FeelingMeta feelingMeta; for ( boost::tokenizer<>::iterator iFeelingName = feelingNamesTok.begin(); iFeelingName != feelingNamesTok.end(); iFeelingName ++ ) { feeling = (*iFeelingName); feelingUpdater = feeling + "FeelingUpdater"; logger().debug( "PsiFeelingUpdaterAgent::%s - Searching the meta data of feeling '%s'.", __FUNCTION__, feeling.c_str()); // Get the corresponding EvaluationLink of the pet's feeling Handle evaluationLink = this->getFeelingEvaluationLink(&_cogserver, feeling, petHandle); if ( evaluationLink == Handle::UNDEFINED ) { logger().warn( "PsiFeelingUpdaterAgent::%s - Failed to get the EvaluationLink for feeling '%s'", __FUNCTION__, feeling.c_str()); continue; } // Insert the meta data of the feeling to feelingMetaMap feelingMeta.init(feelingUpdater, evaluationLink); feelingMetaMap[feeling] = feelingMeta; logger().debug( "PsiFeelingUpdaterAgent::%s - Store the meta data of feeling '%s' successfully.", __FUNCTION__, feeling.c_str()); }// for // Initialize ZeroMQ publisher and add it to the plaza #ifdef HAVE_ZMQ Plaza & plaza = oac->getPlaza(); this->publisher = new zmq::socket_t (plaza.getZmqContext(), ZMQ_PUB); this->publishEndPoint = "ipc://" + petId + ".PsiFeelingUpdaterAgent.ipc"; this->publisher->bind( this->publishEndPoint.c_str() ); plaza.addPublisher(this->publishEndPoint); #endif // Avoid initialize during next cycle this->bInitialized = true; } Handle PsiFeelingUpdaterAgent::getFeelingEvaluationLink(opencog::CogServer * server, const std::string feelingName, Handle petHandle) { // Get AtomSpace AtomSpace& atomSpace = server->getAtomSpace(); // Get the Handle to feeling (PredicateNode) Handle feelingPredicateHandle = atomSpace.getHandle(PREDICATE_NODE, feelingName); if (feelingPredicateHandle == Handle::UNDEFINED) { logger().warn("PsiFeelingUpdaterAgent::%s - Failed to find the PredicateNode for feeling '%s' [ cycle = %d ].", __FUNCTION__, feelingName.c_str(), this->cycleCount); return opencog::Handle::UNDEFINED; } // Get the Handle to ListLink that contains the pet handle std::vector<Handle> listLinkOutgoing; listLinkOutgoing.push_back(petHandle); Handle listLinkHandle = atomSpace.getHandle(LIST_LINK, listLinkOutgoing); if (listLinkHandle == Handle::UNDEFINED) { logger().warn( "PsiFeelingUpdaterAgent::%s - Failed to find the ListLink containing the pet ( id = '%s' ) [ cycle = %d ].", __FUNCTION__, atomSpace.getName(petHandle).c_str(), this->cycleCount); return opencog::Handle::UNDEFINED; } // Get the Handle to EvaluationLink holding the pet's feeling std::vector<Handle> evaluationLinkOutgoing; evaluationLinkOutgoing.push_back(feelingPredicateHandle); evaluationLinkOutgoing.push_back(listLinkHandle); Handle evaluationLinkHandle = atomSpace.getHandle(EVALUATION_LINK, evaluationLinkOutgoing); if (evaluationLinkHandle == Handle::UNDEFINED) { logger().warn( "PsiFeelingUpdaterAgent::%s - Failed to find the EvaluationLink holding the feling '%s' of the pet ( id = '%s' ) [ cycle = %d ].", __FUNCTION__, feelingName.c_str(), atomSpace.getName(petHandle).c_str(), this->cycleCount); return opencog::Handle::UNDEFINED; } return evaluationLinkHandle; } void PsiFeelingUpdaterAgent::runUpdaters() { logger().debug( "PsiFeelingUpdaterAgent::%s - Running feeling updaters (scheme scripts) [ cycle = %d ]", __FUNCTION__ , this->cycleCount); #if HAVE_GUILE // Get OAC OAC* oac = dynamic_cast<OAC*>(&_cogserver); OC_ASSERT(oac, "Did not get an OAC server"); // Initialize scheme evaluator SchemeEval* evaluator = new SchemeEval(); std::string scheme_expression, scheme_return_value; // Process feelings one by one std::map <std::string, FeelingMeta>::iterator iFeeling; std::string feeling, feelingUpdater; for ( iFeeling = feelingMetaMap.begin(); iFeeling != feelingMetaMap.end(); iFeeling ++ ) { feeling = iFeeling->first; feelingUpdater = iFeeling->second.updaterName; scheme_expression = "( " + feelingUpdater + " )"; // Run the Procedure that update feeling and get the updated value scheme_return_value = evaluator->eval(scheme_expression); if ( evaluator->eval_error() ) { logger().error( "PsiFeelingUpdaterAgent::%s - Failed to execute '%s'", __FUNCTION__, scheme_expression.c_str()); iFeeling->second.bUpdated = false; continue; } else { iFeeling->second.bUpdated = true; } // Store updated value to FeelingMeta.updatedValue // // Note: Don't use boost::lexical_cast as below, because SchemeEval will append // a '\n' to the end of the result (scheme_return_value), which will make // boost::lexical_cast throw exception // // iFeeling->second.updatedValue = boost::lexical_cast<double>(scheme_return_value); // iFeeling->second.updatedValue = atof( scheme_return_value.c_str() ); // TODO: Change the log level to fine, after testing logger().debug( "PsiFeelingUpdaterAgent::%s - The new level of feeling '%s' will be %f", __FUNCTION__, feeling.c_str(), iFeeling->second.updatedValue); }// for delete evaluator; #endif // HAVE_GUILE } void PsiFeelingUpdaterAgent::setUpdatedValues() { logger().debug( "PsiFeelingUpdaterAgent::%s - Setting updated feelings to AtomSpace [ cycle =%d ]", __FUNCTION__, this->cycleCount); // Get OAC OAC* oac = dynamic_cast<OAC*>(&_cogserver); OC_ASSERT(oac, "Did not get an OAC server"); // Get AtomSpace AtomSpace& atomSpace = oac->getAtomSpace(); // Process feelings one by one std::map <std::string, FeelingMeta>::iterator iFeeling; std::string feeling; double updatedValue; Handle evaluationLink; for ( iFeeling = feelingMetaMap.begin(); iFeeling != feelingMetaMap.end(); iFeeling ++ ) { if ( !iFeeling->second.bUpdated ) continue; feeling = iFeeling->first; evaluationLink = iFeeling->second.evaluationLink; updatedValue = iFeeling->second.updatedValue; // Set truth value of corresponding EvaluationLink TruthValuePtr stvFeeling = SimpleTruthValue::createTV(updatedValue, 1.0); atomSpace.setTV(evaluationLink, stvFeeling); // Reset bUpdated iFeeling->second.bUpdated = false; // TODO: Change the log level to fine, after testing logger().debug( "PsiFeelingUpdaterAgent::%s - Set the level of feeling '%s' to %f", __FUNCTION__, feeling.c_str(), updatedValue); }// for } void PsiFeelingUpdaterAgent::sendUpdatedValues() { logger().debug( "PsiFeelingUpdaterAgent::%s - Sending updated feelings to the virtual world where the pet lives [ cycle =%d ]", __FUNCTION__, this->cycleCount); // Get OAC OAC * oac = dynamic_cast<OAC *>(&_cogserver); // Get AtomSpace // AtomSpace & atomSpace = * ( oac->getAtomSpace() ); // Get petName const std::string & petName = oac->getPet().getName(); // Prepare the data to be sent std::map <std::string, FeelingMeta>::iterator iFeeling; std::map <std::string, float> feelingValueMap; std::string feeling; double updatedValue; for ( iFeeling = feelingMetaMap.begin(); iFeeling != feelingMetaMap.end(); iFeeling ++ ) { feeling = iFeeling->first; updatedValue = iFeeling->second.updatedValue; feelingValueMap[feeling] = updatedValue; }// for // Send updated feelings to the virtual world where the pet lives oac->getPAI().sendEmotionalFeelings(petName, feelingValueMap); } void PsiFeelingUpdaterAgent::run() { this->cycleCount ++; logger().debug( "PsiFeelingUpdaterAgent::%s - Executing run %d times", __FUNCTION__, this->cycleCount); // Initialize the Agent (feelingMetaMap etc) if ( !this->bInitialized ) this->init(); // Run feeling updaters (combo scripts) this->runUpdaters(); // Set updated values to AtomSpace this->setUpdatedValues(); // Send updated values to the virtual world where the pet lives this->sendUpdatedValues(); #ifdef HAVE_ZMQ // Publish updated modulator values via ZeroMQ OAC * oac = dynamic_cast<OAC *>(&_cogserver); unsigned long timeStamp = oac->getPAI().getLatestSimWorldTimestamp(); Plaza & plaza = oac->getPlaza(); this->publishUpdatedValue(plaza, *this->publisher, timeStamp); #endif } <|endoftext|>
<commit_before>//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an intepreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/ModuleProvider.h" #include "llvm/Bytecode/Reader.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/Target/TargetMachineImpls.h" #include "llvm/Target/TargetData.h" #include "Support/CommandLine.h" #include "Support/Debug.h" #include "Support/SystemUtils.h" using namespace llvm; namespace { cl::opt<std::string> InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); } static std::vector<std::string> makeStringVector(char * const *envp) { std::vector<std::string> rv; for (unsigned i = 0; envp[i]; ++i) rv.push_back(envp[i]); return rv; } static void *CreateArgv(ExecutionEngine *EE, const std::vector<std::string> &InputArgv) { if (EE->getTargetData().getPointerSize() == 8) { // 64 bit target? PointerTy *Result = new PointerTy[InputArgv.size()+1]; DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n"); for (unsigned i = 0; i < InputArgv.size(); ++i) { unsigned Size = InputArgv[i].size()+1; char *Dest = new char[Size]; DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n"); std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); Dest[Size-1] = 0; // Endian safe: Result[i] = (PointerTy)Dest; EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i), Type::LongTy); } Result[InputArgv.size()] = 0; return Result; } else { // 32 bit target? int *Result = new int[InputArgv.size()+1]; DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n"); for (unsigned i = 0; i < InputArgv.size(); ++i) { unsigned Size = InputArgv[i].size()+1; char *Dest = new char[Size]; DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n"); std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); Dest[Size-1] = 0; // Endian safe: Result[i] = (PointerTy)Dest; EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i), Type::IntTy); } Result[InputArgv.size()] = 0; // null terminate it return Result; } } //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { cl::ParseCommandLineOptions(argc, argv, " llvm interpreter & dynamic compiler\n"); // Load the bytecode... std::string ErrorMsg; ModuleProvider *MP = 0; try { MP = getBytecodeModuleProvider(InputFile); } catch (std::string &err) { std::cerr << "Error loading program '" << InputFile << "': " << err << "\n"; exit(1); } ExecutionEngine *EE = ExecutionEngine::create(MP, ForceInterpreter); assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?"); // If the user specifically requested an argv[0] to pass into the program, do // it now. if (!FakeArgv0.empty()) { InputFile = FakeArgv0; } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (InputFile.rfind(".bc") == InputFile.length() - 3) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *Fn = MP->getModule()->getMainFunction(); if (!Fn) { std::cerr << "'main' function not found in module.\n"; return -1; } std::vector<GenericValue> GVArgs; GenericValue GVArgc; GVArgc.IntVal = InputArgv.size(); GVArgs.push_back(GVArgc); // Arg #0 = argc. GVArgs.push_back(PTOGV(CreateArgv(EE, InputArgv))); // Arg #1 = argv. assert(((char **)GVTOP(GVArgs[1]))[0] && "argv[0] was null after CreateArgv"); std::vector<std::string> EnvVars = makeStringVector(envp); GVArgs.push_back(PTOGV(CreateArgv(EE, EnvVars))); // Arg #2 = envp. GenericValue Result = EE->runFunction(Fn, GVArgs); // If the program didn't explicitly call exit, call exit now, for the program. // This ensures that any atexit handlers get called correctly. Function *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy, Type::IntTy, 0); GVArgs.clear(); GVArgs.push_back(Result); EE->runFunction(Exit, GVArgs); std::cerr << "ERROR: exit(" << Result.IntVal << ") returned!\n"; abort(); } <commit_msg>Simplify code<commit_after>//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an intepreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/ModuleProvider.h" #include "llvm/Bytecode/Reader.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/Target/TargetMachineImpls.h" #include "llvm/Target/TargetData.h" #include "Support/CommandLine.h" #include "Support/Debug.h" #include "Support/SystemUtils.h" using namespace llvm; namespace { cl::opt<std::string> InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); } static void *CreateArgv(ExecutionEngine *EE, const std::vector<std::string> &InputArgv) { unsigned PtrSize = EE->getTargetData().getPointerSize(); char *Result = new char[(InputArgv.size()+1)*PtrSize]; DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n"); const Type *SBytePtr = PointerType::get(Type::SByteTy); for (unsigned i = 0; i != InputArgv.size(); ++i) { unsigned Size = InputArgv[i].size()+1; char *Dest = new char[Size]; DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n"); std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); Dest[Size-1] = 0; // Endian safe: Result[i] = (PointerTy)Dest; EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize), SBytePtr); } // Null terminate it EE->StoreValueToMemory(PTOGV(0), (GenericValue*)(Result+InputArgv.size()*PtrSize), SBytePtr); return Result; } //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { cl::ParseCommandLineOptions(argc, argv, " llvm interpreter & dynamic compiler\n"); // Load the bytecode... std::string ErrorMsg; ModuleProvider *MP = 0; try { MP = getBytecodeModuleProvider(InputFile); } catch (std::string &err) { std::cerr << "Error loading program '" << InputFile << "': " << err << "\n"; exit(1); } ExecutionEngine *EE = ExecutionEngine::create(MP, ForceInterpreter); assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?"); // If the user specifically requested an argv[0] to pass into the program, do // it now. if (!FakeArgv0.empty()) { InputFile = FakeArgv0; } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (InputFile.rfind(".bc") == InputFile.length() - 3) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *Fn = MP->getModule()->getMainFunction(); if (!Fn) { std::cerr << "'main' function not found in module.\n"; return -1; } std::vector<GenericValue> GVArgs; GenericValue GVArgc; GVArgc.IntVal = InputArgv.size(); GVArgs.push_back(GVArgc); // Arg #0 = argc. GVArgs.push_back(PTOGV(CreateArgv(EE, InputArgv))); // Arg #1 = argv. assert(((char **)GVTOP(GVArgs[1]))[0] && "argv[0] was null after CreateArgv"); std::vector<std::string> EnvVars; for (unsigned i = 0; envp[i]; ++i) EnvVars.push_back(envp[i]); GVArgs.push_back(PTOGV(CreateArgv(EE, EnvVars))); // Arg #2 = envp. GenericValue Result = EE->runFunction(Fn, GVArgs); // If the program didn't explicitly call exit, call exit now, for the program. // This ensures that any atexit handlers get called correctly. Function *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy, Type::IntTy, 0); GVArgs.clear(); GVArgs.push_back(Result); EE->runFunction(Exit, GVArgs); std::cerr << "ERROR: exit(" << Result.IntVal << ") returned!\n"; abort(); } <|endoftext|>
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file HexParser.cpp * @author Peter Schüller * * @brief HEX parser implementation */ #include "dlvhex/HexParser.hpp" #include "dlvhex/ProgramCtx.h" #include "dlvhex/HexGrammar.h" #include "dlvhex/HexGrammarPTToASTConverter.h" #include <boost/scope_exit.hpp> #include <fstream> #include <unistd.h> DLVHEX_NAMESPACE_BEGIN HexParser::HexParser(ProgramCtx& ctx): ctx(ctx) { // prepare ctx: we need an edb and a registry assert(ctx.registry != 0); if( ctx.edb == 0 ) { // create empty interpretation using this context's registry ctx.edb.reset(new Interpretation(ctx.registry)); } } HexParser::~HexParser() { } // parse from istream into ctx, using registry in ctx void HexParser::parse(std::istream& is) throw (SyntaxError) { // put whole input from stream into a string // (an alternative would be the boost::spirit::multi_pass iterator // but this can be done later when the parser is updated to Spirit V2) std::ostringstream buf; buf << is.rdbuf(); std::string input = buf.str(); HexGrammar grammar; typedef HexGrammarPTToASTConverter Converter; Converter::iterator_t it_begin(input.c_str(), input.c_str()+input.size()); Converter::iterator_t it_end; // parse ast boost::spirit::tree_parse_info<Converter::iterator_t, Converter::factory_t> info = boost::spirit::pt_parse<Converter::factory_t>( it_begin, it_end, grammar, boost::spirit::space_p); // successful parse? if( !info.full ) throw SyntaxError("Could not parse complete input!", info.stop.get_position().line, "TODO"); // if this is not ok, there is some bug and the following code will be incomplete assert(info.trees.size() == 1); // create dlvhex AST from spirit parser tree Converter converter(ctx); converter.convertPTToAST(*info.trees.begin()); } // parse from file into ctx, using registry in ctx void HexParser::parse(const std::string& filename) throw (SyntaxError) { std::ifstream ifs; ifs.open(filename.c_str()); if( !ifs.is_open() ) { char* ch = get_current_dir_name(); std::string cwd(ch); free(ch); throw SyntaxError("File '" + filename + "' could not be opened with cwd '" + cwd + "'"); } BOOST_SCOPE_EXIT((&ifs)) { ifs.close(); } BOOST_SCOPE_EXIT_END parse(ifs); } DLVHEX_NAMESPACE_END // Local Variables: // mode: C++ // End: #if 0 void HexParserDriver::parse(std::istream& is, Program& program, AtomSet& EDB) throw (SyntaxError) { // put whole input from stream into a string // (an alternative would be the boost::spirit::multi_pass iterator // but it was not possible to setup/simply did not compile) std::ostringstream buf; buf << is.rdbuf(); std::string input = buf.str(); HexGrammar grammar; typedef HexGrammarPTToASTConverter Converter; Converter::iterator_t it_begin(input.c_str(), input.c_str()+input.size()); Converter::iterator_t it_end; // parse ast boost::spirit::tree_parse_info<Converter::iterator_t, Converter::factory_t> info = boost::spirit::pt_parse<Converter::factory_t>( it_begin, it_end, grammar, boost::spirit::space_p); // successful parse? if( !info.full ) throw SyntaxError("Could not parse complete input!", info.stop.get_position().line, this->source); // if this is not ok, there is some bug and the following code will be incomplete assert(info.trees.size() == 1); // create dlvhex AST from spirit parser tree Converter converter; converter.convertPTToAST(*info.trees.begin(), program, EDB); } void HexParserDriver::parse(const std::string& file, Program &program, AtomSet& EDB) throw (SyntaxError) { this->source = file; std::ifstream ifs; ifs.open(this->source.c_str()); if (!ifs.is_open()) { throw SyntaxError("File " + this->source + " not found"); } parse(ifs, program, EDB); ifs.close(); } #endif <commit_msg>Use getcwd.<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file HexParser.cpp * @author Peter Schüller * * @brief HEX parser implementation */ #include "dlvhex/HexParser.hpp" #include "dlvhex/ProgramCtx.h" #include "dlvhex/HexGrammar.h" #include "dlvhex/HexGrammarPTToASTConverter.h" #include <boost/scope_exit.hpp> #include <fstream> #include <unistd.h> DLVHEX_NAMESPACE_BEGIN HexParser::HexParser(ProgramCtx& ctx): ctx(ctx) { // prepare ctx: we need an edb and a registry assert(ctx.registry != 0); if( ctx.edb == 0 ) { // create empty interpretation using this context's registry ctx.edb.reset(new Interpretation(ctx.registry)); } } HexParser::~HexParser() { } // parse from istream into ctx, using registry in ctx void HexParser::parse(std::istream& is) throw (SyntaxError) { // put whole input from stream into a string // (an alternative would be the boost::spirit::multi_pass iterator // but this can be done later when the parser is updated to Spirit V2) std::ostringstream buf; buf << is.rdbuf(); std::string input = buf.str(); HexGrammar grammar; typedef HexGrammarPTToASTConverter Converter; Converter::iterator_t it_begin(input.c_str(), input.c_str()+input.size()); Converter::iterator_t it_end; // parse ast boost::spirit::tree_parse_info<Converter::iterator_t, Converter::factory_t> info = boost::spirit::pt_parse<Converter::factory_t>( it_begin, it_end, grammar, boost::spirit::space_p); // successful parse? if( !info.full ) throw SyntaxError("Could not parse complete input!", info.stop.get_position().line, "TODO"); // if this is not ok, there is some bug and the following code will be incomplete assert(info.trees.size() == 1); // create dlvhex AST from spirit parser tree Converter converter(ctx); converter.convertPTToAST(*info.trees.begin()); } // parse from file into ctx, using registry in ctx void HexParser::parse(const std::string& filename) throw (SyntaxError) { std::ifstream ifs; ifs.open(filename.c_str()); if( !ifs.is_open() ) { char* ch = getcwd(NULL, 0); std::string cwd(ch); free(ch); throw SyntaxError("File '" + filename + "' could not be opened with cwd '" + cwd + "'"); } BOOST_SCOPE_EXIT((&ifs)) { ifs.close(); } BOOST_SCOPE_EXIT_END parse(ifs); } DLVHEX_NAMESPACE_END // Local Variables: // mode: C++ // End: #if 0 void HexParserDriver::parse(std::istream& is, Program& program, AtomSet& EDB) throw (SyntaxError) { // put whole input from stream into a string // (an alternative would be the boost::spirit::multi_pass iterator // but it was not possible to setup/simply did not compile) std::ostringstream buf; buf << is.rdbuf(); std::string input = buf.str(); HexGrammar grammar; typedef HexGrammarPTToASTConverter Converter; Converter::iterator_t it_begin(input.c_str(), input.c_str()+input.size()); Converter::iterator_t it_end; // parse ast boost::spirit::tree_parse_info<Converter::iterator_t, Converter::factory_t> info = boost::spirit::pt_parse<Converter::factory_t>( it_begin, it_end, grammar, boost::spirit::space_p); // successful parse? if( !info.full ) throw SyntaxError("Could not parse complete input!", info.stop.get_position().line, this->source); // if this is not ok, there is some bug and the following code will be incomplete assert(info.trees.size() == 1); // create dlvhex AST from spirit parser tree Converter converter; converter.convertPTToAST(*info.trees.begin(), program, EDB); } void HexParserDriver::parse(const std::string& file, Program &program, AtomSet& EDB) throw (SyntaxError) { this->source = file; std::ifstream ifs; ifs.open(this->source.c_str()); if (!ifs.is_open()) { throw SyntaxError("File " + this->source + " not found"); } parse(ifs, program, EDB); ifs.close(); } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <singleton-service-impl.h> // EXTERNAL INCLUDES #include <boost/thread/tss.hpp> #include <dali/integration-api/debug.h> // INTERNAL INCLUDES #if defined(DEBUG_ENABLED) #include <tizen-logging.h> Debug::Filter* gSingletonServiceLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_SINGLETON_SERVICE" ); // Need to define own macro as the log function is not installed when this object is created so no logging is shown with DALI_LOG_INFO at construction and destruction #define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message) \ if(gSingletonServiceLogFilter && gSingletonServiceLogFilter->IsEnabledFor(level)) { std::string string(message); Dali::TizenPlatform::LogMessage( Debug::DebugInfo, string ); } #define DALI_LOG_SINGLETON_SERVICE(level, format, args...) DALI_LOG_INFO(gSingletonServiceLogFilter, level, format, ## args ) #else #define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message) #define DALI_LOG_SINGLETON_SERVICE(level, format, args...) #endif namespace Dali { namespace Internal { namespace Adaptor { namespace { /* * Dummy cleanup function required as boost::thread_specific_ptr requires access to destructor but * we should not make the destructor of SingletonService public as it is a ref-counted object. * * We do not expect this to be called as we only release the pointer, and not reset. */ void DummyCleanup( SingletonService* service ) { if ( service ) { service->UnregisterAll(); } } boost::thread_specific_ptr< SingletonService > gSingletonService( &DummyCleanup ); } // unnamed namespace Dali::SingletonService SingletonService::New() { Dali::SingletonService singletonService( new SingletonService ); return singletonService; } Dali::SingletonService SingletonService::Get() { Dali::SingletonService singletonService; if ( gSingletonService.get() ) { singletonService = Dali::SingletonService( gSingletonService.get() ); } return singletonService; } void SingletonService::Register( const std::type_info& info, BaseHandle singleton ) { if( singleton ) { DALI_LOG_SINGLETON_SERVICE( Debug::General, "Singleton Added: %s\n", info.name() ); mSingletonContainer.insert( SingletonPair( info.name(), singleton ) ); } } void SingletonService::UnregisterAll( ) { mSingletonContainer.clear(); } BaseHandle SingletonService::GetSingleton( const std::type_info& info ) const { BaseHandle object; SingletonConstIter iter = mSingletonContainer.find(info.name()); if( iter != mSingletonContainer.end() ) { object = ( *iter ).second; } return object; } SingletonService::SingletonService() : mSingletonContainer() { // Can only have one instance of SingletonService DALI_ASSERT_ALWAYS( !gSingletonService.get() && "Only one instance of SingletonService is allowed"); gSingletonService.reset( this ); DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Created\n" ); } SingletonService::~SingletonService() { gSingletonService.release(); DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Destroyed\n" ); } } // namespace Adaptor } // namespace Internal } // namespace Dali <commit_msg>Boost removal:Singleton service with __thread<commit_after>/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <singleton-service-impl.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> // INTERNAL INCLUDES #if defined(DEBUG_ENABLED) #include <tizen-logging.h> Debug::Filter* gSingletonServiceLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_SINGLETON_SERVICE" ); // Need to define own macro as the log function is not installed when this object is created so no logging is shown with DALI_LOG_INFO at construction and destruction #define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message) \ if(gSingletonServiceLogFilter && gSingletonServiceLogFilter->IsEnabledFor(level)) { std::string string(message); Dali::TizenPlatform::LogMessage( Debug::DebugInfo, string ); } #define DALI_LOG_SINGLETON_SERVICE(level, format, args...) DALI_LOG_INFO(gSingletonServiceLogFilter, level, format, ## args ) #else #define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message) #define DALI_LOG_SINGLETON_SERVICE(level, format, args...) #endif namespace Dali { namespace Internal { namespace Adaptor { // @todo Start using pthread_key_create if we want to avoid leaking the SingletonService on shutdown namespace { __thread SingletonService * gSingletonService = 0; } // unnamed namespace Dali::SingletonService SingletonService::New() { Dali::SingletonService singletonService( new SingletonService ); return singletonService; } Dali::SingletonService SingletonService::Get() { Dali::SingletonService singletonService; if ( gSingletonService ) { singletonService = Dali::SingletonService( gSingletonService ); } return singletonService; } void SingletonService::Register( const std::type_info& info, BaseHandle singleton ) { if( singleton ) { DALI_LOG_SINGLETON_SERVICE( Debug::General, "Singleton Added: %s\n", info.name() ); mSingletonContainer.insert( SingletonPair( info.name(), singleton ) ); } } void SingletonService::UnregisterAll( ) { mSingletonContainer.clear(); } BaseHandle SingletonService::GetSingleton( const std::type_info& info ) const { BaseHandle object; SingletonConstIter iter = mSingletonContainer.find(info.name()); if( iter != mSingletonContainer.end() ) { object = ( *iter ).second; } return object; } SingletonService::SingletonService() : mSingletonContainer() { // Can only have one instance of SingletonService DALI_ASSERT_ALWAYS( !gSingletonService && "Only one instance of SingletonService is allowed"); gSingletonService = this; DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Created\n" ); } SingletonService::~SingletonService() { gSingletonService = 0; DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Destroyed\n" ); } } // namespace Adaptor } // namespace Internal } // namespace Dali <|endoftext|>
<commit_before>/* * This file is part of PlantLight application. * * 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. * */ /* * Built for Attiny85 1Mhz, using AVR USBasp programmer. * VERSION 0.5 */ #include <avr/sleep.h> #include <avr/interrupt.h> #include <Arduino.h> #include <TinyWireM.h> #include <Time.h> #include <BH1750FVI.h> #include <DS1307RTC.h> #define RELAY_SW_OUT 4 // Relay out pin #define CMD_MAN_IN 1 // Manual light switch #define WD_TICK_TIME 8 // Watchdog tick time [s] (check WD_MODE or datasheet) #define WD_WAIT_TIME 16 // Time [s] to count between two sensor read #define SAMPLE_COUNT 7 // Light sample count (average measurement) // ####################### Prototypes ####################### // Setup watchdog wakeup interrupt // tick: watchdog tick time [s] (check WD_MODE or datasheet) void setupWatchdog(float tick); // Set system into the sleep state, // system wakes up when watchdog is timed out void systemSleep(); // Provides a time_t to Time library, wrapper for call // to RTC.get(), which is not a static function (class member) time_t timeProvider(); // Display a date in readable format on the serial interface void SerialDisplayDateTime(const time_t &timeToDisplay); // Sets the RTC to the des time void setTime(); // Automatic management of light depending on actual lux value // and time of day / month of the year void automaticMode(float lux, const time_t &now); // Sample some lux value and calculate the average over time // count: number of sample to calculate the average value float sample(int count); // ####################### Constants ######################## // Watchdog interrupt sleep time // 0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms, 6=1 sec, 7=2 sec, 8=4 sec, 9=8sec const float WD_MODE[10] = { 0.016, 0.032, 0.064, 0.128, 0.25, 0.5, 1 , 2, 4, 8 }; // ####################### Variables ######################## USI_TWI bus; // TinyWireM instance (I2C bus) BH1750FVI BH1750(bus); // Light sensor instance RTC_DS1307 RTC(bus); // RTC clock instance tmDriftInfo di; volatile uint8_t wdCount = 0; // Watchdog interrupt count before reading light value // wd count * wd interval == 4 * 8 s = 32 s uint16_t wdMatch = 0; boolean relayState = false, first = false; float lux = 0.0; void setupWatchdog(float tick) { // 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms // 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec uint8_t wdreg, wdmode = 0; for (uint8_t i = 0; i < 10; ++i) { if (WD_MODE[i] == tick) { wdmode = i; } } if (wdmode > 9) wdmode = 9; wdreg = wdmode & 7; if (wdmode > 7) wdreg |= (1 << 5); wdreg |= (1 << WDCE); MCUSR &= ~(1 << WDRF); // Start timed sequence WDTCR |= (1 << WDCE) | (1 << WDE); // Set new watchdog timeout value WDTCR = wdreg; WDTCR |= _BV(WDIE); } void systemSleep() { set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Sleep mode is set here sleep_enable(); sleep_mode(); // System actually sleeps here sleep_disable(); // System continues execution here when watchdog timed out } // Watchdog Interrupt Service Routine ISR(WDT_vect) { wdCount++; } // PCINT Interrupt Service Routine (unused) ISR(PCINT0_vect) { } time_t timeProvider() { return RTC.get(); } void SerialDisplayDateTime(const time_t &timeToDisplay) { Serial.print(year(timeToDisplay)); Serial.print("/"); Serial.print(month(timeToDisplay)); Serial.print("/"); Serial.print(day(timeToDisplay)); Serial.print(" "); Serial.print(hour(timeToDisplay)); Serial.print(":"); Serial.print(minute(timeToDisplay)); Serial.print(":"); Serial.println(second(timeToDisplay)); } void setTime() { tmElements_t tme; time_t newTime; tme.Year = 46; tme.Month = 2; tme.Day = 07; tme.Hour = 14; tme.Minute = 28; tme.Second = 30; newTime = makeTime(tme); RTC.set(newTime); // Set the RTC setTime(newTime); // Set the system time tmDriftInfo diUpdate = RTC.read_DriftInfo(); // Update DriftInfo in RTC diUpdate.DriftStart = newTime; RTC.write_DriftInfo(diUpdate); SerialDisplayDateTime(newTime); } float sample(int count){ BH1750.wakeUp(BH1750_CONTINUOUS_HIGH_RES_MODE_2); delay(50); float tmpLux = 0.0; for (int i = 0; i < count; ++i) { tmpLux += BH1750.getLightIntensity(); // Get lux value delay(300); } lux = tmpLux / count; // Compute lux average value Serial.println(lux); return lux; } void automaticMode(float lux, const time_t &now) { // TODO light on conditions.. time and lux if (lux <= 10) { relayState = true; } else { relayState = false; } digitalWrite(RELAY_SW_OUT, relayState); } void setup() { Serial.begin(9600); pinMode(RELAY_SW_OUT, OUTPUT); pinMode(CMD_MAN_IN, INPUT_PULLUP); // Setup watchdog timeout to 8 s (mode 9) setupWatchdog(WD_TICK_TIME); // Watchdog interrupt count before reading light value // wd count * wd interval == 4 * 8 s = 32 s wdMatch = (uint16_t) WD_WAIT_TIME / WD_TICK_TIME; // Setup Pin change interrupt on PCINT1 GIMSK |= _BV(PCIE); PCMSK |= _BV(PCINT1); // Set the internal registers to reduce power consumes ACSR = (1 << ACD); // Shut down the analog comparator MCUCR |= (1 << BODS); // BOD disabled // I2C begin() is called BEFORE sensors library "begin" methods: // it is called just once for all the sensors. bus.begin(); // Sensors initialization // Light sensor BH1750.powerOn(); BH1750.setMode(BH1750_CONTINUOUS_HIGH_RES_MODE_2); BH1750.setMtreg(250); // Set measurement time register to high value // Real time clock setSyncProvider(timeProvider); // Pointer to function to get the time from the RTC // Update drift info from RTC di = RTC.read_DriftInfo(); di.DriftDays = 1000; // valid value 0 to 65,535 di.DriftSeconds = 18000; // fine tune this until your RTC sync with your reference time, valid value -32,768 to 32,767 RTC.write_DriftInfo(di); // once you're happy with the dri // if (!RTC.isrunning()) { // setTime(); // } } void loop() { BH1750.sleep(); // Send light sensor to sleep systemSleep(); // Send the unit to sleep // time_t timeNow = now(); // Serial.print("RTC NOW TIME: "); // SerialDisplayDateTime(timeNow); time_t timeNow3 = now3(di); // Serial.print("RTC NOW3 TIME: "); SerialDisplayDateTime(timeNow3); // Manual command to turn light on if (!digitalRead(CMD_MAN_IN)) { digitalWrite(RELAY_SW_OUT, true); first = true; wdCount = 0; } else { // First cycle in automatic mode, after manual mode if (first) { first = false; lux = sample(SAMPLE_COUNT); automaticMode(lux, timeNow3); } if (wdCount >= wdMatch) { wdCount = 0; lux = sample(SAMPLE_COUNT); automaticMode(lux, timeNow3); } } } <commit_msg>Automatic mode splitted in check light and check time functions, removed old comments, unified code in the first cycle of automatic mode. <commit_after>/* * This file is part of PlantLight application. * * 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. * */ /* * Built for Attiny85 1Mhz, using AVR USBasp programmer. * VERSION 0.55 */ #include <avr/sleep.h> #include <avr/interrupt.h> #include <Arduino.h> #include <TinyWireM.h> #include <Time.h> #include <BH1750FVI.h> #include <DS1307RTC.h> #define RELAY_SW_OUT 4 // Relay out pin #define CMD_MAN_IN 1 // Manual light switch #define WD_TICK_TIME 8 // Watchdog tick time [s] (check WD_MODE or datasheet) #define WD_WAIT_TIME 16 // Time [s] to count between two sensor read #define SAMPLE_COUNT 5 // Light sample count (average measurement) // ####################### Prototypes ####################### // Setup watchdog wakeup interrupt // tick: watchdog tick time [s] (check WD_MODE or datasheet) void setupWatchdog(float tick); // Set system into the sleep state, // system wakes up when watchdog is timed out void systemSleep(); // Provides a time_t to Time library, wrapper for call // to RTC.get(), which is not a static function (class member) time_t timeProvider(); // Display a date in readable format on the serial interface void SerialDisplayDateTime(const time_t &timeToDisplay); // Sets the RTC to the new time void setTime(); // Checks the current time of day and month of the year. // Returns true if the light is now enabled. boolean checkEnable(const time_t &now); // Checks actual lux value. Returns true if the conditions // to turn lights on are met. boolean checkLightCond(float lux); // Sample some lux value and calculate the average over time // count: number of sample to calculate the average value float sample(int count); // ####################### Constants ######################## // Watchdog interrupt sleep time // 0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms, 6=1 sec, 7=2 sec, 8=4 sec, 9=8sec const float WD_MODE[10] = { 0.016, 0.032, 0.064, 0.128, 0.25, 0.5, 1 , 2, 4, 8 }; // ####################### Variables ######################## USI_TWI bus; // TinyWireM instance (I2C bus) BH1750FVI BH1750(bus); // Light sensor instance RTC_DS1307 RTC(bus); // RTC clock instance tmDriftInfo di; volatile uint8_t wdCount = 0; // Watchdog interrupt count before reading light value // wd count * wd interval == 4 * 8 s = 32 s uint16_t wdMatch = 0; boolean relayState = false, first = false; // ####################### Functions ######################## void setupWatchdog(float tick) { // 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms // 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec uint8_t wdreg, wdmode = 0; for (uint8_t i = 0; i < 10; ++i) { if (WD_MODE[i] == tick) { wdmode = i; } } if (wdmode > 9) wdmode = 9; wdreg = wdmode & 7; if (wdmode > 7) wdreg |= (1 << 5); wdreg |= (1 << WDCE); MCUSR &= ~(1 << WDRF); // Start timed sequence WDTCR |= (1 << WDCE) | (1 << WDE); // Set new watchdog timeout value WDTCR = wdreg; WDTCR |= _BV(WDIE); } void systemSleep() { set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Sleep mode is set here sleep_enable(); sleep_mode(); // System actually sleeps here sleep_disable(); // System continues execution here when watchdog timed out } // Watchdog Interrupt Service Routine ISR(WDT_vect) { wdCount++; } // PCINT Interrupt Service Routine (unused) ISR(PCINT0_vect) { } time_t timeProvider() { return RTC.get(); } void SerialDisplayDateTime(const time_t &timeToDisplay) { Serial.print(year(timeToDisplay)); Serial.print("/"); Serial.print(month(timeToDisplay)); Serial.print("/"); Serial.print(day(timeToDisplay)); Serial.print(" "); Serial.print(hour(timeToDisplay)); Serial.print(":"); Serial.print(minute(timeToDisplay)); Serial.print(":"); Serial.println(second(timeToDisplay)); } void setTime() { tmElements_t tme; time_t newTime; tme.Year = 46; tme.Month = 2; tme.Day = 07; tme.Hour = 14; tme.Minute = 28; tme.Second = 30; newTime = makeTime(tme); RTC.set(newTime); // Set the RTC setTime(newTime); // Set the system time tmDriftInfo diUpdate = RTC.read_DriftInfo(); // Update DriftInfo in RTC diUpdate.DriftStart = newTime; RTC.write_DriftInfo(diUpdate); SerialDisplayDateTime(newTime); } float sample(int count){ BH1750.wakeUp(BH1750_CONTINUOUS_HIGH_RES_MODE_2); delay(400); float tmpLux = 0.0; for (int i = 0; i < count; ++i) { tmpLux += BH1750.getLightIntensity(); // Get lux value delay(300); } return tmpLux / count; // Compute lux average value } boolean checkEnable(const time_t &now) { int nowH = hour(now); switch (month(now)) { // Winter case 1: case 2: case 10: case 11: case 12: if (nowH <= 12 || nowH >= 23) { return false; } else { return true; } break; // Spring / Autumn case 3: case 4: case 9: return false; break; // Summer case 5: case 6: case 7: case 8: return false; break; default: break; } return false; } boolean checkLightCond(float lux) { if (lux <= 10) { return true; } else { return false; } } void setup() { Serial.begin(9600); pinMode(RELAY_SW_OUT, OUTPUT); pinMode(CMD_MAN_IN, INPUT_PULLUP); // Setup watchdog timeout to 8 s (mode 9) setupWatchdog(WD_TICK_TIME); // Watchdog interrupt count before reading light value // wd count * wd interval == 4 * 8 s = 32 s wdMatch = (uint16_t) WD_WAIT_TIME / WD_TICK_TIME; // Setup Pin change interrupt on PCINT1 GIMSK |= _BV(PCIE); PCMSK |= _BV(PCINT1); // Set the internal registers to reduce power consumes ACSR = (1 << ACD); // Shut down the analog comparator MCUCR |= (1 << BODS); // BOD disabled // I2C begin() is called BEFORE sensors library "begin" methods: // it is called just once for all the sensors. bus.begin(); // Sensors initialization // Light sensor BH1750.powerOn(); BH1750.setMode(BH1750_CONTINUOUS_HIGH_RES_MODE_2); BH1750.setMtreg(250); // Set measurement time register to high value // Real time clock setSyncProvider(timeProvider); // Pointer to function to get the time from the RTC // Update drift info from RTC di = RTC.read_DriftInfo(); di.DriftDays = 1000; di.DriftSeconds = 18000; RTC.write_DriftInfo(di); // setTime(); } void loop() { BH1750.sleep(); // Send light sensor to sleep systemSleep(); // Send the unit to sleep // time_t timeNow = now(); // Serial.print("RTC NOW TIME: "); // SerialDisplayDateTime(timeNow); time_t timeNow3 = now3(di); // Serial.print("RTC NOW3 TIME: "); SerialDisplayDateTime(timeNow3); // Manual command to turn light on if (!digitalRead(CMD_MAN_IN)) { digitalWrite(RELAY_SW_OUT, true); first = true; } else { // first = true -> First cycle in automatic mode, after manual mode if (wdCount >= wdMatch || first) { first = false; wdCount = 0; float lux = sample(SAMPLE_COUNT); Serial.println(lux); if (checkEnable(timeNow3) && checkLightCond(lux)) { digitalWrite(RELAY_SW_OUT, true); } else { digitalWrite(RELAY_SW_OUT, false); } } } } <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <unordered_map> #include <vector> typedef std::unordered_map<std::string, int> WordCount; int main() { WordCount counts; std::string word; while (std::cin >> word) { counts[word]++; } std::vector<std::pair<int, WordCount::iterator>> freq; freq.reserve(counts.size()); for (WordCount::iterator it = counts.begin(); it != counts.end(); ++it) { freq.push_back(make_pair(it->second, it)); } std::sort(freq.begin(), freq.end(), [](const auto& lhs, const auto& rhs) { return lhs.first > rhs.first; }); // printf("%zd\n", sizeof(freq[0])); for (auto item : freq) { std::cout << item.first << '\t' << item.second->first << '\n'; } } <commit_msg>more C++11<commit_after>#include <algorithm> #include <iostream> #include <unordered_map> #include <vector> typedef std::unordered_map<std::string, int> WordCount; int main() { WordCount counts; std::string word; while (std::cin >> word) { counts[word]++; } std::vector<std::pair<int, WordCount::const_iterator>> freq; freq.reserve(counts.size()); for (auto it = counts.cbegin(); it != counts.cend(); ++it) { freq.push_back(make_pair(it->second, it)); } std::sort(freq.begin(), freq.end(), [](const auto& lhs, const auto& rhs) { return lhs.first > rhs.first; }); // printf("%zd\n", sizeof(freq[0])); for (auto item : freq) { std::cout << item.first << '\t' << item.second->first << '\n'; } } <|endoftext|>
<commit_before>/************************************************************************* * Copyright (C) 2011-2013 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of TeapotNet. * * * * TeapotNet 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 (at your option) any later version. * * * * TeapotNet 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 Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with TeapotNet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "tpn/directory.h" #include "tpn/exception.h" #include "tpn/file.h" #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #ifdef WINDOWS #define stat _stat #define PATH_SEPARATOR '\\' #else #ifndef ANDROID #include <sys/statvfs.h> #else #include <sys/vfs.h> #define statvfs statfs #define fstatvfs fstatfs #endif #include <pwd.h> #define PATH_SEPARATOR '/' #endif namespace tpn { const char Directory::Separator = PATH_SEPARATOR; bool Directory::Exist(const String &path) { /*DIR *dir = opendir(fixPath(path).pathEncode().c_str()); if(!dir) return false; closedir(dir); return true;*/ stat_t st; if(tpn::stat(fixPath(path).pathEncode().c_str(), &st)) return false; return S_ISDIR(st.st_mode); } bool Directory::Remove(const String &path) { return (rmdir(fixPath(path).pathEncode().c_str()) == 0); } void Directory::Create(const String &path) { if(mkdir(fixPath(path).pathEncode().c_str(), 0770) != 0) throw IOException("Cannot create directory \""+path+"\""); } uint64_t Directory::GetAvailableSpace(const String &path) { #ifdef WINDOWS ULARGE_INTEGER freeBytesAvailable; std::memset(&freeBytesAvailable, 0, sizeof(freeBytesAvailable)); if(!GetDiskFreeSpaceEx(path.c_str(), &freeBytesAvailable, NULL, NULL)) throw IOException("Unable to get free space for " + path); return uint64_t(freeBytesAvailable.QuadPart); #else struct statvfs f; if(statvfs(path, &f)) throw IOException("Unable to get free space for " + path); return uint64_t(f.f_bavail) * uint64_t(f.f_bsize); #endif } String Directory::GetHomeDirectory(void) { #ifdef WINDOWS char szPath[MAX_PATH]; if(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, szPath) == S_OK) return String(szPath); #else const char *home = getenv("HOME"); if(!home) { struct passwd* pwd = getpwuid(getuid()); if(pwd) home = pwd->pw_dir; } if(home) return String(home); #endif throw Exception("Unable to get home directory path"); return ""; } void Directory::ChangeCurrent(const String &path) { if(chdir(fixPath(path).pathEncode().c_str()) != 0) throw IOException("Cannot change current directory to \""+path+"\""); } Directory::Directory(void) : mDir(NULL), mDirent(NULL) { } Directory::Directory(const String &path) : mDir(NULL), mDirent(NULL) { open(path); } Directory::~Directory(void) { close(); } void Directory::open(const String &path) { close(); mDir = opendir(fixPath(path).pathEncode().c_str()); if(!mDir) throw IOException(String("Unable to open directory: ")+path); mPath = path; if(mPath[mPath.size()-1] != Separator) mPath+= Separator; } void Directory::close(void) { if(mDir) { closedir(mDir); mDir = NULL; mDirent = NULL; mPath.clear(); } } String Directory::path(void) const { return mPath; } bool Directory::nextFile(void) { if(!mDir) return false; mDirent = readdir(mDir); if(!mDirent) return false; if(fileName() == ".") return nextFile(); if(fileName() == "..") return nextFile(); return true; } String Directory::filePath(void) const { if(!mDirent) throw IOException("No more files in directory"); return mPath + String(mDirent->d_name).pathDecode(); } String Directory::fileName(void) const { if(!mDirent) throw IOException("No more files in directory"); return String(mDirent->d_name).pathDecode(); } Time Directory::fileTime(void) const { if(!mDirent) throw IOException("No more files in directory"); stat_t st; if(tpn::stat(filePath().pathEncode().c_str(), &st)) return 0; return Time(st.st_mtime); } uint64_t Directory::fileSize(void) const { if(!mDirent) throw IOException("No more files in directory"); if(fileIsDir()) return 0; stat_t st; if(tpn::stat(filePath().pathEncode().c_str(), &st)) return 0; return uint64_t(st.st_size); } bool Directory::fileIsDir(void) const { if(!mDirent) throw IOException("No more files in directory"); //return (mDirent->d_type == DT_DIR); return Exist(filePath()); } void Directory::getFileInfo(StringMap &map) const { // Note: fileInfo must not contain path map.clear(); map["name"] = fileName(); map["time"] << fileTime(); if(fileIsDir()) map["type"] = "directory"; else { map["type"] = "file"; map["size"] << fileSize(); } } String Directory::fixPath(String path) { if(path.empty()) throw IOException("Empty path"); if(path.size() >= 2 && path[path.size()-1] == Separator) path.resize(path.size()-1); #ifdef WINDOWS if(path.size() == 2 && path[path.size()-1] == ':') path+= Separator; #endif return path; } } <commit_msg>Switched to more compatible GetHomeDirectory for Windows<commit_after>/************************************************************************* * Copyright (C) 2011-2013 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of TeapotNet. * * * * TeapotNet 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 (at your option) any later version. * * * * TeapotNet 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 Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with TeapotNet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "tpn/directory.h" #include "tpn/exception.h" #include "tpn/file.h" #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #ifdef WINDOWS #define stat _stat #define PATH_SEPARATOR '\\' #else #ifndef ANDROID #include <sys/statvfs.h> #else #include <sys/vfs.h> #define statvfs statfs #define fstatvfs fstatfs #endif #include <pwd.h> #define PATH_SEPARATOR '/' #endif namespace tpn { const char Directory::Separator = PATH_SEPARATOR; bool Directory::Exist(const String &path) { /*DIR *dir = opendir(fixPath(path).pathEncode().c_str()); if(!dir) return false; closedir(dir); return true;*/ stat_t st; if(tpn::stat(fixPath(path).pathEncode().c_str(), &st)) return false; return S_ISDIR(st.st_mode); } bool Directory::Remove(const String &path) { return (rmdir(fixPath(path).pathEncode().c_str()) == 0); } void Directory::Create(const String &path) { if(mkdir(fixPath(path).pathEncode().c_str(), 0770) != 0) throw IOException("Cannot create directory \""+path+"\""); } uint64_t Directory::GetAvailableSpace(const String &path) { #ifdef WINDOWS ULARGE_INTEGER freeBytesAvailable; std::memset(&freeBytesAvailable, 0, sizeof(freeBytesAvailable)); if(!GetDiskFreeSpaceEx(path.c_str(), &freeBytesAvailable, NULL, NULL)) throw IOException("Unable to get free space for " + path); return uint64_t(freeBytesAvailable.QuadPart); #else struct statvfs f; if(statvfs(path, &f)) throw IOException("Unable to get free space for " + path); return uint64_t(f.f_bavail) * uint64_t(f.f_bsize); #endif } String Directory::GetHomeDirectory(void) { #ifdef WINDOWS char szPath[MAX_PATH]; /*if(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, szPath) == S_OK) return String(szPath);*/ if(ExpandEnvironmentStrings("%USERPROFILE%", szPath, MAX_PATH)) return String(szPath); #else const char *home = getenv("HOME"); if(!home) { struct passwd* pwd = getpwuid(getuid()); if(pwd) home = pwd->pw_dir; } if(home) return String(home); #endif throw Exception("Unable to get home directory path"); return ""; } void Directory::ChangeCurrent(const String &path) { if(chdir(fixPath(path).pathEncode().c_str()) != 0) throw IOException("Cannot change current directory to \""+path+"\""); } Directory::Directory(void) : mDir(NULL), mDirent(NULL) { } Directory::Directory(const String &path) : mDir(NULL), mDirent(NULL) { open(path); } Directory::~Directory(void) { close(); } void Directory::open(const String &path) { close(); mDir = opendir(fixPath(path).pathEncode().c_str()); if(!mDir) throw IOException(String("Unable to open directory: ")+path); mPath = path; if(mPath[mPath.size()-1] != Separator) mPath+= Separator; } void Directory::close(void) { if(mDir) { closedir(mDir); mDir = NULL; mDirent = NULL; mPath.clear(); } } String Directory::path(void) const { return mPath; } bool Directory::nextFile(void) { if(!mDir) return false; mDirent = readdir(mDir); if(!mDirent) return false; if(fileName() == ".") return nextFile(); if(fileName() == "..") return nextFile(); return true; } String Directory::filePath(void) const { if(!mDirent) throw IOException("No more files in directory"); return mPath + String(mDirent->d_name).pathDecode(); } String Directory::fileName(void) const { if(!mDirent) throw IOException("No more files in directory"); return String(mDirent->d_name).pathDecode(); } Time Directory::fileTime(void) const { if(!mDirent) throw IOException("No more files in directory"); stat_t st; if(tpn::stat(filePath().pathEncode().c_str(), &st)) return 0; return Time(st.st_mtime); } uint64_t Directory::fileSize(void) const { if(!mDirent) throw IOException("No more files in directory"); if(fileIsDir()) return 0; stat_t st; if(tpn::stat(filePath().pathEncode().c_str(), &st)) return 0; return uint64_t(st.st_size); } bool Directory::fileIsDir(void) const { if(!mDirent) throw IOException("No more files in directory"); //return (mDirent->d_type == DT_DIR); return Exist(filePath()); } void Directory::getFileInfo(StringMap &map) const { // Note: fileInfo must not contain path map.clear(); map["name"] = fileName(); map["time"] << fileTime(); if(fileIsDir()) map["type"] = "directory"; else { map["type"] = "file"; map["size"] << fileSize(); } } String Directory::fixPath(String path) { if(path.empty()) throw IOException("Empty path"); if(path.size() >= 2 && path[path.size()-1] == Separator) path.resize(path.size()-1); #ifdef WINDOWS if(path.size() == 2 && path[path.size()-1] == ':') path+= Separator; #endif return path; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <iomanip> #include <map> #include <string> #include <sstream> #include <vector> #include <osquery/core.h> #include <osquery/tables.h> #define FEATURE(name, reg, bit) std::make_pair(name, std::make_pair(reg, bit)) namespace osquery { namespace tables { typedef std::pair<std::string, int> RegisterBit_t; typedef std::pair<std::string, RegisterBit_t> FeatureDef_t; std::map<int, std::vector<FeatureDef_t> > kCPUFeatures = { {1, { FEATURE("pae", "edx", 6), FEATURE("msr", "edx", 5), FEATURE("mtrr", "edx", 12), FEATURE("acpi", "edx", 22), FEATURE("htt", "edx", 28), FEATURE("ia64", "edx", 30), FEATURE("vmx", "ecx", 5), FEATURE("smx", "ecx", 6), FEATURE("hypervisor", "ecx", 31), FEATURE("aes", "ecx", 25), }}, {7, { FEATURE("mpx", "ebx", 14), FEATURE("sha", "ebx", 29), }}, }; static inline void cpuid(size_t eax, size_t ecx, int regs[4]) { #if defined(WIN32) __cpuidex((int*)regs, (int)eax, (int)ecx); #else asm volatile("cpuid" : "=a"(regs[0]), "=b"(regs[1]), "=c"(regs[2]), "=d"(regs[3]) : "a"(eax), "c"(ecx)); #endif } static inline void registerToString(int reg, std::stringstream& stream) { for (size_t i = 0; i < 4; i++) { stream << ((char*)&reg)[i]; } } static inline bool isBitSet(size_t bit, unsigned int reg) { return ((reg & (1 << bit)) != 0); } inline Status genStrings(QueryData& results) { int regs[4] = {-1}; cpuid(0, 0, regs); if (regs[0] < 1) { // The CPUID ASM call is not supported. return Status(1, "Failed to run cpuid"); } std::stringstream vendor_string; registerToString(regs[1], vendor_string); registerToString(regs[3], vendor_string); registerToString(regs[2], vendor_string); Row r; r["feature"] = "vendor"; r["value"] = vendor_string.str(); r["output_register"] = "ebx,edx,ecx"; r["output_bit"] = "0"; r["input_eax"] = "0"; results.push_back(r); // The CPU canonicalized name can also be accessed via cpuid accesses. // Subsequent accesses allow a 32-character CPU name. std::stringstream product_name; for (size_t i = 0; i < 3; i++) { cpuid(0x80000002 + i, 0U, regs); registerToString(regs[0], product_name); registerToString(regs[1], product_name); registerToString(regs[2], product_name); registerToString(regs[3], product_name); } r["feature"] = "product_name"; r["value"] = product_name.str(); r["output_register"] = "eax,ebx,ecx,edx"; r["output_bit"] = "0"; r["input_eax"] = "0x80000002"; results.push_back(r); // Do the same to grab the optional hypervisor ID. cpuid(0x40000000, 0, regs); if (regs[0] && 0xFF000000 != 0) { std::stringstream hypervisor_string; registerToString(regs[1], hypervisor_string); registerToString(regs[2], hypervisor_string); registerToString(regs[3], hypervisor_string); r["feature"] = "hypervisor_id"; r["value"] = hypervisor_string.str(); r["output_register"] = "ebx,ecx,edx"; r["output_bit"] = "0"; r["input_eax"] = "0x40000000"; results.push_back(r); } // Finally, check the processor serial number. std::stringstream serial; cpuid(1, 0, regs); serial << std::hex << std::setw(8) << std::setfill('0') << (int)regs[0]; cpuid(3, 0, regs); serial << std::hex << std::setw(8) << std::setfill('0') << (int)regs[0]; serial << std::hex << std::setw(8) << std::setfill('0') << (int)regs[3]; r["feature"] = "serial"; r["value"] = serial.str(); r["output_register"] = "eax,ebx,ecx,edx"; r["output_bit"] = "0"; r["input_eax"] = "1,3"; results.push_back(r); return Status(0, "OK"); } inline void genFamily(QueryData& results) { int regs[4] = {-1}; cpuid(1, 0, regs); int family = regs[0] & 0xf00; std::stringstream family_string; family_string << std::hex << std::setw(4) << std::setfill('0') << family; Row r; r["feature"] = "family"; r["value"] = family_string.str(); r["output_register"] = "eax"; r["output_bit"] = "0"; r["input_eax"] = "1"; results.push_back(r); } QueryData genCPUID(QueryContext& context) { QueryData results; if (!genStrings(results).ok()) { return results; } // Get the CPU meta-data about the model, stepping, family. genFamily(results); int regs[4] = {-1}; int feature_register, feature_bit; for (auto& feature_set : kCPUFeatures) { int eax = feature_set.first; cpuid(eax, 0, regs); for (auto& feature : feature_set.second) { Row r; r["feature"] = feature.first; // Get the return register holding the feature bit. feature_register = 0; if (feature.second.first == "edx") { feature_register = 3; } else if (feature.second.first == "ebx") { feature_register = 1; } else if (feature.second.first == "ecx") { feature_register = 2; } feature_bit = feature.second.second; r["value"] = isBitSet(feature_bit, regs[feature_register]) ? "1" : "0"; r["output_register"] = feature.second.first; r["output_bit"] = INTEGER(feature_bit); r["input_eax"] = boost::lexical_cast<std::string>(eax); results.push_back(r); } } return results; } } } <commit_msg>Add SGX CPU feature and availability detection to cpuid (#2738)<commit_after>/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <iomanip> #include <map> #include <string> #include <sstream> #include <vector> #include <osquery/core.h> #include <osquery/tables.h> #define FEATURE(name, reg, bit) std::make_pair(name, std::make_pair(reg, bit)) namespace osquery { namespace tables { using RegisterBit = std::pair<std::string, int>; using FeatureDef = std::pair<std::string, RegisterBit>; std::map<int, std::vector<FeatureDef>> kCPUFeatures{ {1, { FEATURE("pae", "edx", 6), FEATURE("msr", "edx", 5), FEATURE("mtrr", "edx", 12), FEATURE("acpi", "edx", 22), FEATURE("htt", "edx", 28), FEATURE("ia64", "edx", 30), FEATURE("vmx", "ecx", 5), FEATURE("smx", "ecx", 6), FEATURE("hypervisor", "ecx", 31), FEATURE("aes", "ecx", 25), }}, {7, { FEATURE("sgx", "ebx", 2), FEATURE("mpx", "ebx", 14), FEATURE("sha", "ebx", 29), }}, }; static inline void cpuid(size_t eax, size_t ecx, int regs[4]) { #if defined(WIN32) __cpuidex((int*)regs, (int)eax, (int)ecx); #else asm volatile("cpuid" : "=a"(regs[0]), "=b"(regs[1]), "=c"(regs[2]), "=d"(regs[3]) : "a"(eax), "c"(ecx)); #endif } static inline void registerToString(int reg, std::stringstream& stream) { for (size_t i = 0; i < 4; i++) { stream << ((char*)&reg)[i]; } } static inline bool isBitSet(size_t bit, unsigned int reg) { return ((reg & (1 << bit)) != 0); } inline Status genStrings(QueryData& results) { int regs[4] = {-1}; cpuid(0, 0, regs); if (regs[0] < 1) { // The CPUID ASM call is not supported. return Status(1, "Failed to run cpuid"); } std::stringstream vendor_string; registerToString(regs[1], vendor_string); registerToString(regs[3], vendor_string); registerToString(regs[2], vendor_string); Row r; r["feature"] = "vendor"; r["value"] = vendor_string.str(); r["output_register"] = "ebx,edx,ecx"; r["output_bit"] = "0"; r["input_eax"] = "0"; results.push_back(r); // The CPU canonicalized name can also be accessed via cpuid accesses. // Subsequent accesses allow a 32-character CPU name. std::stringstream product_name; for (size_t i = 0; i < 3; i++) { cpuid(0x80000002 + i, 0U, regs); registerToString(regs[0], product_name); registerToString(regs[1], product_name); registerToString(regs[2], product_name); registerToString(regs[3], product_name); } r["feature"] = "product_name"; r["value"] = product_name.str(); r["output_register"] = "eax,ebx,ecx,edx"; r["output_bit"] = "0"; r["input_eax"] = "0x80000002"; results.push_back(r); // Do the same to grab the optional hypervisor ID. cpuid(0x40000000, 0, regs); if (regs[0] && 0xFF000000 != 0) { std::stringstream hypervisor; hypervisor << std::hex << std::setw(8) << std::setfill('0') << (int)regs[0]; hypervisor << std::hex << std::setw(8) << std::setfill('0') << (int)regs[1]; hypervisor << std::hex << std::setw(8) << std::setfill('0') << (int)regs[2]; r["feature"] = "hypervisor_id"; r["value"] = hypervisor.str(); r["output_register"] = "ebx,ecx,edx"; r["output_bit"] = "0"; r["input_eax"] = "0x40000000"; results.push_back(r); } // Finally, check the processor serial number. std::stringstream serial; cpuid(1, 0, regs); serial << std::hex << std::setw(8) << std::setfill('0') << (int)regs[0]; cpuid(3, 0, regs); serial << std::hex << std::setw(8) << std::setfill('0') << (int)regs[0]; serial << std::hex << std::setw(8) << std::setfill('0') << (int)regs[3]; r["feature"] = "serial"; r["value"] = serial.str(); r["output_register"] = "eax,eax,ecx"; r["output_bit"] = "0"; r["input_eax"] = "1,3"; results.push_back(r); return Status(0, "OK"); } inline void genFamily(QueryData& results) { int regs[4] = {-1}; cpuid(1, 0, regs); int family = regs[0] & 0xf00; std::stringstream family_string; family_string << std::hex << std::setw(4) << std::setfill('0') << family; Row r; r["feature"] = "family"; r["value"] = family_string.str(); r["output_register"] = "eax"; r["output_bit"] = "0"; r["input_eax"] = "1"; results.push_back(r); } QueryData genCPUID(QueryContext& context) { QueryData results; if (!genStrings(results).ok()) { return results; } // Get the CPU meta-data about the model, stepping, family. genFamily(results); int regs[4] = {-1}; int feature_register = 0; int feature_bit = 0; for (const auto& feature_set : kCPUFeatures) { int eax = feature_set.first; cpuid(eax, 0, regs); for (const auto& feature : feature_set.second) { Row r; r["feature"] = feature.first; // Get the return register holding the feature bit. feature_register = 0; if (feature.second.first == "edx") { feature_register = 3; } else if (feature.second.first == "ebx") { feature_register = 1; } else if (feature.second.first == "ecx") { feature_register = 2; } feature_bit = feature.second.second; r["value"] = isBitSet(feature_bit, regs[feature_register]) ? "1" : "0"; r["output_register"] = feature.second.first; r["output_bit"] = INTEGER(feature_bit); r["input_eax"] = boost::lexical_cast<std::string>(eax); results.push_back(r); } } { Row r; r["output_register"] = "eax,ebx,ecx,edx"; r["output_bit"] = INTEGER(0); cpuid(0x12, 0, regs); std::stringstream sgx0; sgx0 << std::hex << std::setw(8) << std::setfill('0') << (int)regs[0]; sgx0 << std::hex << std::setw(8) << std::setfill('0') << (int)regs[1]; sgx0 << std::hex << std::setw(8) << std::setfill('0') << (int)regs[2]; sgx0 << std::hex << std::setw(8) << std::setfill('0') << (int)regs[3]; r["feature"] = "sgx0"; r["value"] = sgx0.str(); r["input_eax"] = std::to_string(0x12); results.push_back(r); cpuid(0x12, 1, regs); std::stringstream sgx1; sgx1 << std::hex << std::setw(8) << std::setfill('0') << (int)regs[0]; sgx1 << std::hex << std::setw(8) << std::setfill('0') << (int)regs[1]; sgx1 << std::hex << std::setw(8) << std::setfill('0') << (int)regs[2]; sgx1 << std::hex << std::setw(8) << std::setfill('0') << (int)regs[3]; r["feature"] = "sgx1"; r["value"] = sgx1.str(); r["input_eax"] = std::to_string(0x12) + ",1"; results.push_back(r); } return results; } } } <|endoftext|>
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved. //#include <algorithm> //#include <map> #include <string> //#include <unordered_set> #include <stdio.h> #include <stdlib.h> //#include <boost/filesystem/operations.hpp> //#include <boost/filesystem/path.hpp> #include <boost/lexical_cast.hpp> #include <IOKit/IOKitLib.h> #include <IOKit/IOKitKeys.h> #include <CoreFoundation/CoreFoundation.h> #include <glog/logging.h> #include "osquery/core.h" #include "osquery/database.h" using namespace osquery::core; using namespace osquery::db; namespace osquery { namespace tables { void genVariable(const void *key, const void *value, void *results) { Row nvram_row; // Get the OF variable's name. CFIndex nameLen; char *nameBuffer = 0; nameLen = CFStringGetLength((CFStringRef) key) + 1; nameBuffer = (char*) malloc(nameLen); if(nameBuffer && CFStringGetCString((CFStringRef) key, nameBuffer, nameLen, kCFStringEncodingUTF8) ) { nvram_row["name"] = boost::lexical_cast<std::string>(nameBuffer); } else { LOG(WARNING) << "Unable to convert NVRAM property name to C string"; goto cleanup; } // Get the OF variable's type. CFTypeID typeID; CFIndex typeLen; char *typeBuffer; typeID = CFGetTypeID(value); typeLen = CFStringGetLength(CFCopyTypeIDDescription(typeID)) + 1; typeBuffer = (char*) malloc(typeLen); if ( typeBuffer && CFStringGetCString(CFCopyTypeIDDescription(typeID), typeBuffer, typeLen, kCFStringEncodingUTF8) ) { nvram_row["type"] = boost::lexical_cast<std::string>(typeBuffer); free(typeBuffer); } // Variable type casting members. long cnt, cnt2; const uint8_t *dataPtr; uint8_t dataChar; char numberBuffer[10]; char *dataBuffer = 0; CFIndex valueLen; char *valueBuffer = 0; const char *valueString = 0; uint32_t number, length; // Based on the type, get a texual representation of the variable. if (typeID == CFBooleanGetTypeID()) { valueString = (CFBooleanGetValue((CFBooleanRef) value)) ? "true" : "false"; } else if (typeID == CFNumberGetTypeID()) { CFNumberGetValue((CFNumberRef) value, kCFNumberSInt32Type, &number); if (number == 0xFFFFFFFF) { sprintf(numberBuffer, "-1"); } else if (number < 1000) { sprintf(numberBuffer, "%d", number); } else { sprintf(numberBuffer, "0x%x", number); } valueString = numberBuffer; } else if (typeID == CFStringGetTypeID()) { valueLen = CFStringGetLength((CFStringRef) value) + 1; valueBuffer = (char*) malloc(valueLen + 1); if ( valueBuffer && CFStringGetCString((CFStringRef) value, valueBuffer, valueLen, kCFStringEncodingUTF8) ) { valueString = valueBuffer; } else { LOG(WARNING) << "Unable to convert NVRAM value to C string"; goto cleanup; } } else if (typeID == CFDataGetTypeID()) { length = CFDataGetLength((CFDataRef) value); if (length == 0) { valueString = ""; } else { dataBuffer = (char*) malloc(length * 3 + 1); if (dataBuffer != 0) { dataPtr = CFDataGetBytePtr((CFDataRef) value); for (cnt = cnt2 = 0; cnt < length; cnt++) { dataChar = dataPtr[cnt]; if (isprint(dataChar)) { dataBuffer[cnt2++] = dataChar; } else { sprintf(dataBuffer + cnt2, "%%%02x", dataChar); cnt2 += 3; } } dataBuffer[cnt2] = '\0'; valueString = dataBuffer; } } } else { valueString = "<INVALID>"; } // Finally, add the variable's value to the row. if (valueString != 0) { nvram_row["value"] = boost::lexical_cast<std::string>(valueString); } ((QueryData *) results)->push_back(nvram_row); cleanup: if (nameBuffer != 0) { free(nameBuffer); } if (dataBuffer != 0) { free(dataBuffer); } if (valueBuffer != 0) { free(valueBuffer); } } QueryData genNVRAM() { QueryData results; kern_return_t status; mach_port_t master_port; io_registry_entry_t options_ref; status = IOMasterPort(bootstrap_port, &master_port); if (status != KERN_SUCCESS) { LOG(ERROR) << "Error getting the IOMaster port"; return {}; } // NVRAM registry entry is :/options. options_ref = IORegistryEntryFromPath(master_port, "IODeviceTree:/options"); if (options_ref == 0) { LOG(ERROR) << "NVRAM is not supported on this system"; return {}; } CFMutableDictionaryRef options_dict; status = IORegistryEntryCreateCFProperties(options_ref, &options_dict, 0, 0); if (status != KERN_SUCCESS) { LOG(ERROR) << "Error getting the firmware variables"; goto cleanup; } CFDictionaryApplyFunction(options_dict, &genVariable, &results); cleanup: // Cleanup (registry entry context). IOObjectRelease(options_ref); return results; } }} <commit_msg>[vtable_nvram] Various code cleanups<commit_after>// Copyright 2004-present Facebook. All Rights Reserved. #include <string> #include <stdio.h> #include <stdlib.h> #include <boost/lexical_cast.hpp> #include <IOKit/IOKitLib.h> #include <IOKit/IOKitKeys.h> #include <CoreFoundation/CoreFoundation.h> #include <glog/logging.h> #include "osquery/core.h" #include "osquery/database.h" using namespace osquery::core; using namespace osquery::db; namespace osquery { namespace tables { void genVariable(const void *key, const void *value, void *results) { Row nvram_row; // Get the OF variable's name. CFIndex nameLen; char *nameBuffer = 0; nameLen = CFStringGetLength((CFStringRef) key) + 1; nameBuffer = (char*) malloc(nameLen); if(nameBuffer && CFStringGetCString((CFStringRef) key, nameBuffer, nameLen, kCFStringEncodingUTF8)) { nvram_row["name"] = boost::lexical_cast<std::string>(nameBuffer); } else { LOG(WARNING) << "Unable to convert NVRAM property name to C string"; goto cleanup; } // Get the OF variable's type. CFTypeID typeID; CFIndex typeLen; char *typeBuffer; typeID = CFGetTypeID(value); typeLen = CFStringGetLength(CFCopyTypeIDDescription(typeID)) + 1; typeBuffer = (char*) malloc(typeLen); if (typeBuffer && CFStringGetCString(CFCopyTypeIDDescription(typeID), typeBuffer, typeLen, kCFStringEncodingUTF8)) { nvram_row["type"] = boost::lexical_cast<std::string>(typeBuffer); free(typeBuffer); } // Variable type casting members. long cnt, cnt2; const uint8_t *dataPtr; uint8_t dataChar; char numberBuffer[10]; char *dataBuffer = 0; CFIndex valueLen; char *valueBuffer = 0; const char *valueString = 0; uint32_t number, length; // Based on the type, get a texual representation of the variable. if (typeID == CFBooleanGetTypeID()) { valueString = (CFBooleanGetValue((CFBooleanRef) value)) ? "true" : "false"; } else if (typeID == CFNumberGetTypeID()) { CFNumberGetValue((CFNumberRef) value, kCFNumberSInt32Type, &number); if (number == 0xFFFFFFFF) { sprintf(numberBuffer, "-1"); } else if (number < 1000) { sprintf(numberBuffer, "%d", number); } else { sprintf(numberBuffer, "0x%x", number); } valueString = numberBuffer; } else if (typeID == CFStringGetTypeID()) { valueLen = CFStringGetLength((CFStringRef) value) + 1; valueBuffer = (char*) malloc(valueLen); if (valueBuffer && CFStringGetCString((CFStringRef) value, valueBuffer, valueLen, kCFStringEncodingUTF8)) { valueString = valueBuffer; } else { LOG(WARNING) << "Unable to convert NVRAM value to C string"; goto cleanup; } } else if (typeID == CFDataGetTypeID()) { length = CFDataGetLength((CFDataRef) value); if (length == 0) { valueString = ""; } else { dataBuffer = (char*) malloc(length * 3 + 1); if (dataBuffer != 0) { dataPtr = CFDataGetBytePtr((CFDataRef) value); for (cnt = cnt2 = 0; cnt < length; cnt++) { dataChar = dataPtr[cnt]; if (isprint(dataChar)) { dataBuffer[cnt2++] = dataChar; } else { sprintf(dataBuffer + cnt2, "%%%02x", dataChar); cnt2 += 3; } } dataBuffer[cnt2] = '\0'; valueString = dataBuffer; } } } else { valueString = "<INVALID>"; } // Finally, add the variable's value to the row. if (valueString != 0) { nvram_row["value"] = boost::lexical_cast<std::string>(valueString); } ((QueryData *) results)->push_back(nvram_row); cleanup: if (nameBuffer != 0) { free(nameBuffer); } if (dataBuffer != 0) { free(dataBuffer); } if (valueBuffer != 0) { free(valueBuffer); } } QueryData genNVRAM() { QueryData results; kern_return_t status; mach_port_t master_port; io_registry_entry_t options_ref; status = IOMasterPort(bootstrap_port, &master_port); if (status != KERN_SUCCESS) { LOG(ERROR) << "Error getting the IOMaster port"; return {}; } // NVRAM registry entry is :/options. options_ref = IORegistryEntryFromPath(master_port, "IODeviceTree:/options"); if (options_ref == 0) { LOG(ERROR) << "NVRAM is not supported on this system"; return {}; } CFMutableDictionaryRef options_dict; status = IORegistryEntryCreateCFProperties(options_ref, &options_dict, 0, 0); if (status != KERN_SUCCESS) { LOG(ERROR) << "Error getting the firmware variables"; goto cleanup; } CFDictionaryApplyFunction(options_dict, &genVariable, &results); cleanup: // Cleanup (registry entry context). IOObjectRelease(options_ref); return results; } }} <|endoftext|>
<commit_before>/** * Copyright (C) 2015 Dato, Inc. * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #include <process/process.hpp> #include <logger/logger.hpp> #include <limits> namespace graphlab { // Programmer responsible for calling delete[] on returned char* char *convert_args(const std::string &cmd, const std::vector<std::string> &args) { // Convert argument list to a single string std::stringstream master_arg_list; master_arg_list << cmd << " "; for(auto &i : args) { master_arg_list << "\""; master_arg_list << i; master_arg_list << "\""; master_arg_list << " "; } size_t c_arglist_sz = master_arg_list.str().size() + 1; char* c_arglist = new char[c_arglist_sz]; memcpy(c_arglist, master_arg_list.str().c_str(), c_arglist_sz); return c_arglist; } bool process::launch(const std::string &cmd, const std::vector<std::string> &args) { PROCESS_INFORMATION proc_info; STARTUPINFO startup_info; ZeroMemory(&proc_info, sizeof(PROCESS_INFORMATION)); ZeroMemory(&startup_info, sizeof(STARTUPINFO)); char *c_arglist = convert_args(cmd, args); BOOL ret; // For Windows, we include the cmd with the arguments so that a search path // is used for any executable without a full path ret = CreateProcess(NULL, c_arglist, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startup_info, &proc_info); if(!ret) { auto err = GetLastError(); logstream(LOG_ERROR) << "Failed to launch process: " << get_last_err_str(err) << std::endl; delete[] c_arglist; return false; } else { // Don't need to have a thread handle. We'll just cancel the process if // need be CloseHandle(proc_info.hThread); m_launched = true; } // Used for killing the process m_proc_handle = proc_info.hProcess; m_pid = proc_info.dwProcessId; logstream(LOG_INFO) << "Launched process with pid: " << m_pid << std::endl; return true; } bool process::popen(const std::string &cmd, const std::vector<std::string> &args, int child_write_fd) { // We will only support stdout and stderr in Windows if(child_write_fd != STDOUT_FILENO && child_write_fd != STDERR_FILENO) { logstream(LOG_ERROR) << "Cannot read anything other than stdout or stderr " "from child on Windows." << std::endl; return false; } SECURITY_ATTRIBUTES sa_attr; sa_attr.nLength=sizeof(SECURITY_ATTRIBUTES); // Allow handles to be inherited when process created sa_attr.bInheritHandle = TRUE; sa_attr.lpSecurityDescriptor = NULL; if(!CreatePipe(&m_read_handle, &m_write_handle, &sa_attr, 0)) { //TODO: Figure out how to get error string on Windows logstream(LOG_ERROR) << "Failed to create pipe: " << get_last_err_str(GetLastError()) << std::endl; return false; } // Make sure the parent end of the pipe is NOT inherited if(!SetHandleInformation(m_read_handle, HANDLE_FLAG_INHERIT, 0)) { logstream(LOG_ERROR) << "Failed to set handle information: " << get_last_err_str(GetLastError()) << std::endl; return false; } PROCESS_INFORMATION proc_info; STARTUPINFO startup_info; ZeroMemory(&proc_info, sizeof(PROCESS_INFORMATION)); ZeroMemory(&startup_info, sizeof(STARTUPINFO)); if(m_read_handle != NULL) { startup_info.cb = sizeof(STARTUPINFO); if(child_write_fd == STDOUT_FILENO) { startup_info.hStdOutput = m_write_handle; } else if(child_write_fd == STDERR_FILENO) { startup_info.hStdError = m_write_handle; } startup_info.dwFlags |= STARTF_USESTDHANDLES; } else { logstream(LOG_ERROR) << "Read handle NULL after pipe created." << std::endl; return false; } char *c_arglist = convert_args(cmd, args); BOOL ret; // For Windows, we include the cmd with the arguments so that a search path // is used for any executable without a full path ret = CreateProcess(NULL, c_arglist, NULL, NULL, TRUE, 0, NULL, NULL, &startup_info, &proc_info); if(!ret) { auto err = GetLastError(); logstream(LOG_ERROR) << "Failed to launch process: " << get_last_err_str(err) << std::endl; delete[] c_arglist; return false; } else { // Don't need to have a thread handle. We'll just cancel the process if // need be CloseHandle(proc_info.hThread); // Now that the process has been created, close the handle that was // inherited by the child. Apparently if you DON'T do this, reading from // the child will never report an error when the child is done writing, and // you'll hang forever waiting for an EOF. There goes a few hours of my // life. CloseHandle(m_write_handle); m_write_handle = NULL; m_launched = TRUE; m_launched_with_popen = TRUE; } // Used for killing the process m_proc_handle = proc_info.hProcess; m_pid = proc_info.dwProcessId; logstream(LOG_INFO) << "Launched process with pid: " << m_pid << std::endl; return true; } ssize_t process::read_from_child(void *buf, size_t count) { if(!m_launched) log_and_throw("No process launched!"); if(!m_launched_with_popen || m_read_handle == NULL) log_and_throw("Cannot read from child, no pipe initialized. " "Launch with popen to do this."); // Keep from overflowing if(count > std::numeric_limits<DWORD>::max()) { count = std::numeric_limits<DWORD>::max(); } DWORD bytes_read; BOOL ret = ReadFile(m_read_handle, (LPWORD)buf, count, &bytes_read, NULL); if(!ret) { logstream(LOG_ERROR) << "ReadFile failed: " << get_last_err_str(GetLastError()) << std::endl; } return ret ? ssize_t(bytes_read) : ssize_t(-1); } void process::close_read_pipe() { if(!m_launched) log_and_throw("No process launched!"); if(!m_launched_with_popen || m_read_handle == NULL) log_and_throw("Cannot close read pipe from child, no pipe initialized."); CloseHandle(m_read_handle); m_read_handle = NULL; } bool process::kill(bool async) { if(!m_launched) log_and_throw("No process launched!"); if(m_proc_handle != NULL) { BOOL ret = TerminateProcess(m_proc_handle, 1); auto err_code = GetLastError(); if(!async) WaitForSingleObject(m_proc_handle, 10000); CloseHandle(m_proc_handle); m_proc_handle = NULL; if(!ret) { logstream(LOG_INFO) << get_last_err_str(err_code); return false; } return true; } return false; } bool process::exists() { if(!m_launched) log_and_throw("No process launched!"); if(m_proc_handle != NULL) { DWORD exit_code; auto rc = GetExitCodeProcess(m_proc_handle, &exit_code); return (rc && exit_code == STILL_ACTIVE); } return false; } int process::get_return_code() { DWORD exit_code; if(m_proc_handle != NULL) { auto rc = GetExitCodeProcess(m_proc_handle, &exit_code); if(!rc) return INT_MAX; } if(exit_code == STILL_ACTIVE) return INT_MIN; return exit_code; } size_t process::get_pid() { return size_t(m_pid); } process::~process() { if(m_proc_handle != NULL) { CloseHandle(m_proc_handle); } if(m_read_handle != NULL) { CloseHandle(m_read_handle); } if(m_write_handle != NULL) { CloseHandle(m_write_handle); } } // no op on windows void process::autoreap() { } } //namespace graphlab <commit_msg>Fix for space issue in process launching path.<commit_after>/** * Copyright (C) 2015 Dato, Inc. * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #include <process/process.hpp> #include <logger/logger.hpp> #include <limits> namespace graphlab { // Programmer responsible for calling delete[] on returned char* char *convert_args(const std::string &cmd, const std::vector<std::string> &args) { // Convert argument list to a single string std::stringstream master_arg_list; master_arg_list << "\"" << cmd << "\" "; for(auto &i : args) { master_arg_list << "\""; master_arg_list << i; master_arg_list << "\""; master_arg_list << " "; } size_t c_arglist_sz = master_arg_list.str().size() + 1; char* c_arglist = new char[c_arglist_sz]; memcpy(c_arglist, master_arg_list.str().c_str(), c_arglist_sz); return c_arglist; } bool process::launch(const std::string &cmd, const std::vector<std::string> &args) { PROCESS_INFORMATION proc_info; STARTUPINFO startup_info; ZeroMemory(&proc_info, sizeof(PROCESS_INFORMATION)); ZeroMemory(&startup_info, sizeof(STARTUPINFO)); char *c_arglist = convert_args(cmd, args); BOOL ret; // For Windows, we include the cmd with the arguments so that a search path // is used for any executable without a full path ret = CreateProcess(NULL, c_arglist, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startup_info, &proc_info); if(!ret) { auto err = GetLastError(); logstream(LOG_ERROR) << "Failed to launch process: " << get_last_err_str(err) << std::endl; delete[] c_arglist; return false; } else { // Don't need to have a thread handle. We'll just cancel the process if // need be CloseHandle(proc_info.hThread); m_launched = true; } // Used for killing the process m_proc_handle = proc_info.hProcess; m_pid = proc_info.dwProcessId; logstream(LOG_INFO) << "Launched process with pid: " << m_pid << std::endl; return true; } bool process::popen(const std::string &cmd, const std::vector<std::string> &args, int child_write_fd) { // We will only support stdout and stderr in Windows if(child_write_fd != STDOUT_FILENO && child_write_fd != STDERR_FILENO) { logstream(LOG_ERROR) << "Cannot read anything other than stdout or stderr " "from child on Windows." << std::endl; return false; } SECURITY_ATTRIBUTES sa_attr; sa_attr.nLength=sizeof(SECURITY_ATTRIBUTES); // Allow handles to be inherited when process created sa_attr.bInheritHandle = TRUE; sa_attr.lpSecurityDescriptor = NULL; if(!CreatePipe(&m_read_handle, &m_write_handle, &sa_attr, 0)) { //TODO: Figure out how to get error string on Windows logstream(LOG_ERROR) << "Failed to create pipe: " << get_last_err_str(GetLastError()) << std::endl; return false; } // Make sure the parent end of the pipe is NOT inherited if(!SetHandleInformation(m_read_handle, HANDLE_FLAG_INHERIT, 0)) { logstream(LOG_ERROR) << "Failed to set handle information: " << get_last_err_str(GetLastError()) << std::endl; return false; } PROCESS_INFORMATION proc_info; STARTUPINFO startup_info; ZeroMemory(&proc_info, sizeof(PROCESS_INFORMATION)); ZeroMemory(&startup_info, sizeof(STARTUPINFO)); if(m_read_handle != NULL) { startup_info.cb = sizeof(STARTUPINFO); if(child_write_fd == STDOUT_FILENO) { startup_info.hStdOutput = m_write_handle; } else if(child_write_fd == STDERR_FILENO) { startup_info.hStdError = m_write_handle; } startup_info.dwFlags |= STARTF_USESTDHANDLES; } else { logstream(LOG_ERROR) << "Read handle NULL after pipe created." << std::endl; return false; } char *c_arglist = convert_args(cmd, args); BOOL ret; // For Windows, we include the cmd with the arguments so that a search path // is used for any executable without a full path ret = CreateProcess(NULL, c_arglist, NULL, NULL, TRUE, 0, NULL, NULL, &startup_info, &proc_info); if(!ret) { auto err = GetLastError(); logstream(LOG_ERROR) << "Failed to launch process: " << get_last_err_str(err) << std::endl; delete[] c_arglist; return false; } else { // Don't need to have a thread handle. We'll just cancel the process if // need be CloseHandle(proc_info.hThread); // Now that the process has been created, close the handle that was // inherited by the child. Apparently if you DON'T do this, reading from // the child will never report an error when the child is done writing, and // you'll hang forever waiting for an EOF. There goes a few hours of my // life. CloseHandle(m_write_handle); m_write_handle = NULL; m_launched = TRUE; m_launched_with_popen = TRUE; } // Used for killing the process m_proc_handle = proc_info.hProcess; m_pid = proc_info.dwProcessId; logstream(LOG_INFO) << "Launched process with pid: " << m_pid << std::endl; return true; } ssize_t process::read_from_child(void *buf, size_t count) { if(!m_launched) log_and_throw("No process launched!"); if(!m_launched_with_popen || m_read_handle == NULL) log_and_throw("Cannot read from child, no pipe initialized. " "Launch with popen to do this."); // Keep from overflowing if(count > std::numeric_limits<DWORD>::max()) { count = std::numeric_limits<DWORD>::max(); } DWORD bytes_read; BOOL ret = ReadFile(m_read_handle, (LPWORD)buf, count, &bytes_read, NULL); if(!ret) { logstream(LOG_ERROR) << "ReadFile failed: " << get_last_err_str(GetLastError()) << std::endl; } return ret ? ssize_t(bytes_read) : ssize_t(-1); } void process::close_read_pipe() { if(!m_launched) log_and_throw("No process launched!"); if(!m_launched_with_popen || m_read_handle == NULL) log_and_throw("Cannot close read pipe from child, no pipe initialized."); CloseHandle(m_read_handle); m_read_handle = NULL; } bool process::kill(bool async) { if(!m_launched) log_and_throw("No process launched!"); if(m_proc_handle != NULL) { BOOL ret = TerminateProcess(m_proc_handle, 1); auto err_code = GetLastError(); if(!async) WaitForSingleObject(m_proc_handle, 10000); CloseHandle(m_proc_handle); m_proc_handle = NULL; if(!ret) { logstream(LOG_INFO) << get_last_err_str(err_code); return false; } return true; } return false; } bool process::exists() { if(!m_launched) log_and_throw("No process launched!"); if(m_proc_handle != NULL) { DWORD exit_code; auto rc = GetExitCodeProcess(m_proc_handle, &exit_code); return (rc && exit_code == STILL_ACTIVE); } return false; } int process::get_return_code() { DWORD exit_code; if(m_proc_handle != NULL) { auto rc = GetExitCodeProcess(m_proc_handle, &exit_code); if(!rc) return INT_MAX; } if(exit_code == STILL_ACTIVE) return INT_MIN; return exit_code; } size_t process::get_pid() { return size_t(m_pid); } process::~process() { if(m_proc_handle != NULL) { CloseHandle(m_proc_handle); } if(m_read_handle != NULL) { CloseHandle(m_read_handle); } if(m_write_handle != NULL) { CloseHandle(m_write_handle); } } // no op on windows void process::autoreap() { } } //namespace graphlab <|endoftext|>
<commit_before>/* * Copyright (c) 2015 - 2021, Intel Corporation * * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ServiceProxy.hpp" #include <sstream> #include "geopm/Exception.hpp" #include "geopm/Helper.hpp" #include "SDBus.hpp" #include "SDBusMessage.hpp" #include "geopm_internal.h" namespace geopm { std::unique_ptr<ServiceProxy> ServiceProxy::make_unique(void) { return geopm::make_unique<ServiceProxyImp>(); } ServiceProxyImp::ServiceProxyImp() : ServiceProxyImp(SDBus::make_unique()) { } ServiceProxyImp::ServiceProxyImp(std::shared_ptr<SDBus> bus) : m_bus(bus) { } void ServiceProxyImp::platform_get_user_access(std::vector<std::string> &signal_names, std::vector<std::string> &control_names) { std::shared_ptr<SDBusMessage> bus_message = m_bus->call_method("PlatformGetUserAccess"); bus_message->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "asas"); signal_names = read_string_array(bus_message); control_names = read_string_array(bus_message); bus_message->exit_container(); } std::vector<signal_info_s> ServiceProxyImp::platform_get_signal_info( const std::vector<std::string> &signal_names) { std::vector<signal_info_s> result; std::shared_ptr<SDBusMessage> bus_message = m_bus->make_call_message("PlatformGetSignalInfo"); bus_message->append_strings(signal_names); std::shared_ptr<SDBusMessage> bus_reply = m_bus->call_method(bus_message); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_ARRAY, "(ssiiii)"); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "ssiiii"); while (bus_reply->was_success()) { std::string name = bus_reply->read_string(); std::string description = bus_reply->read_string(); int domain = bus_reply->read_integer(); int aggregation = bus_reply->read_integer(); int string_format = bus_reply->read_integer(); int behavior = bus_reply->read_integer(); bus_reply->exit_container(); result.push_back({name, description, domain, aggregation, string_format, behavior}); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "ssiiii"); } bus_reply->exit_container(); return result; } std::vector<control_info_s> ServiceProxyImp::platform_get_control_info( const std::vector<std::string> &control_names) { std::vector<control_info_s> result; std::shared_ptr<SDBusMessage> bus_message = m_bus->make_call_message("PlatformGetControlInfo"); bus_message->append_strings(control_names); std::shared_ptr<SDBusMessage> bus_reply = m_bus->call_method(bus_message); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_ARRAY, "(ssi)"); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "ssi"); while (bus_reply->was_success()) { std::string name = bus_reply->read_string(); std::string description = bus_reply->read_string(); int domain = bus_reply->read_integer(); bus_reply->exit_container(); result.push_back({name, description, domain}); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "ssi"); } bus_reply->exit_container(); return result; } void ServiceProxyImp::platform_open_session(void) { (void)m_bus->call_method("PlatformOpenSession"); } void ServiceProxyImp::platform_close_session(void) { (void)m_bus->call_method("PlatformCloseSession"); } void ServiceProxyImp::platform_start_batch(const std::vector<struct geopm_request_s> &signal_config, const std::vector<struct geopm_request_s> &control_config, int &server_pid, std::string &server_key) { throw Exception("ServiceProxyImp::platform_start_batch()", GEOPM_ERROR_NOT_IMPLEMENTED, __FILE__, __LINE__); } void ServiceProxyImp::platform_stop_batch(int server_pid) { throw Exception("ServiceProxyImp::platform_stop_batch()", GEOPM_ERROR_NOT_IMPLEMENTED, __FILE__, __LINE__); } double ServiceProxyImp::platform_read_signal(const std::string &signal_name, int domain, int domain_idx) { std::shared_ptr<SDBusMessage> reply_message = m_bus->call_method("PlatformReadSignal", signal_name, domain, domain_idx); return reply_message->read_double(); } void ServiceProxyImp::platform_write_control(const std::string &control_name, int domain, int domain_idx, double setting) { (void)m_bus->call_method("PlatformWriteControl", control_name, domain, domain_idx, setting); } std::vector<std::string> ServiceProxyImp::read_string_array( std::shared_ptr<SDBusMessage> bus_message) { std::vector<std::string> result; bus_message->enter_container(SDBusMessage::M_MESSAGE_TYPE_ARRAY, "s"); std::string str = bus_message->read_string(); while (bus_message->was_success()) { result.push_back(str); str = bus_message->read_string(); } bus_message->exit_container(); return result; } } <commit_msg>Implement ServiceProxyImp::platform_start_batch<commit_after>/* * Copyright (c) 2015 - 2021, Intel Corporation * * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ServiceProxy.hpp" #include <sstream> #include "geopm/Exception.hpp" #include "geopm/Helper.hpp" #include "SDBus.hpp" #include "SDBusMessage.hpp" #include "geopm_internal.h" namespace geopm { std::unique_ptr<ServiceProxy> ServiceProxy::make_unique(void) { return geopm::make_unique<ServiceProxyImp>(); } ServiceProxyImp::ServiceProxyImp() : ServiceProxyImp(SDBus::make_unique()) { } ServiceProxyImp::ServiceProxyImp(std::shared_ptr<SDBus> bus) : m_bus(bus) { } void ServiceProxyImp::platform_get_user_access(std::vector<std::string> &signal_names, std::vector<std::string> &control_names) { std::shared_ptr<SDBusMessage> bus_message = m_bus->call_method("PlatformGetUserAccess"); bus_message->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "asas"); signal_names = read_string_array(bus_message); control_names = read_string_array(bus_message); bus_message->exit_container(); } std::vector<signal_info_s> ServiceProxyImp::platform_get_signal_info( const std::vector<std::string> &signal_names) { std::vector<signal_info_s> result; std::shared_ptr<SDBusMessage> bus_message = m_bus->make_call_message("PlatformGetSignalInfo"); bus_message->append_strings(signal_names); std::shared_ptr<SDBusMessage> bus_reply = m_bus->call_method(bus_message); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_ARRAY, "(ssiiii)"); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "ssiiii"); while (bus_reply->was_success()) { std::string name = bus_reply->read_string(); std::string description = bus_reply->read_string(); int domain = bus_reply->read_integer(); int aggregation = bus_reply->read_integer(); int string_format = bus_reply->read_integer(); int behavior = bus_reply->read_integer(); bus_reply->exit_container(); result.push_back({name, description, domain, aggregation, string_format, behavior}); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "ssiiii"); } bus_reply->exit_container(); return result; } std::vector<control_info_s> ServiceProxyImp::platform_get_control_info( const std::vector<std::string> &control_names) { std::vector<control_info_s> result; std::shared_ptr<SDBusMessage> bus_message = m_bus->make_call_message("PlatformGetControlInfo"); bus_message->append_strings(control_names); std::shared_ptr<SDBusMessage> bus_reply = m_bus->call_method(bus_message); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_ARRAY, "(ssi)"); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "ssi"); while (bus_reply->was_success()) { std::string name = bus_reply->read_string(); std::string description = bus_reply->read_string(); int domain = bus_reply->read_integer(); bus_reply->exit_container(); result.push_back({name, description, domain}); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "ssi"); } bus_reply->exit_container(); return result; } void ServiceProxyImp::platform_open_session(void) { (void)m_bus->call_method("PlatformOpenSession"); } void ServiceProxyImp::platform_close_session(void) { (void)m_bus->call_method("PlatformCloseSession"); } void ServiceProxyImp::platform_start_batch(const std::vector<struct geopm_request_s> &signal_config, const std::vector<struct geopm_request_s> &control_config, int &server_pid, std::string &server_key) { std::shared_ptr<SDBusMessage> bus_message = m_bus->make_call_message("PlatformStartBatch"); bus_message->open_container(SDBusMessage::M_MESSAGE_TYPE_ARRAY, "(iis)"); bus_message->open_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "iis"); while (bus_message->was_success()) { bus_message->append_request_s(signal_config); } bus_message->close_container(); // iis bus_message->close_container(); // (iis) bus_message->open_container(SDBusMessage::M_MESSAGE_TYPE_ARRAY, "(iis)"); bus_message->open_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "iis"); while (bus_message->was_success()) { bus_message->append_request_s(control_config); } bus_message->close_container(); // iis bus_message->close_container(); // (iis) std::shared_ptr<SDBusMessage> bus_reply = m_bus->call_method("PlatformStartBatch"); bus_reply->enter_container(SDBusMessage::M_MESSAGE_TYPE_STRUCT, "is"); while (bus_reply->was_success()) { server_pid = bus_reply->read_integer(); server_key = bus_reply->read_string(); } bus_reply->exit_container(); } void ServiceProxyImp::platform_stop_batch(int server_pid) { throw Exception("ServiceProxyImp::platform_stop_batch()", GEOPM_ERROR_NOT_IMPLEMENTED, __FILE__, __LINE__); } double ServiceProxyImp::platform_read_signal(const std::string &signal_name, int domain, int domain_idx) { std::shared_ptr<SDBusMessage> reply_message = m_bus->call_method("PlatformReadSignal", signal_name, domain, domain_idx); return reply_message->read_double(); } void ServiceProxyImp::platform_write_control(const std::string &control_name, int domain, int domain_idx, double setting) { (void)m_bus->call_method("PlatformWriteControl", control_name, domain, domain_idx, setting); } std::vector<std::string> ServiceProxyImp::read_string_array( std::shared_ptr<SDBusMessage> bus_message) { std::vector<std::string> result; bus_message->enter_container(SDBusMessage::M_MESSAGE_TYPE_ARRAY, "s"); std::string str = bus_message->read_string(); while (bus_message->was_success()) { result.push_back(str); str = bus_message->read_string(); } bus_message->exit_container(); return result; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: appdata.cxx,v $ * * $Revision: 1.20 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:32:46 $ * * 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 _CACHESTR_HXX //autogen #include <tools/cachestr.hxx> #endif #ifndef _CONFIG_HXX #include <tools/config.hxx> #endif #ifndef _INETSTRM_HXX //autogen #include <svtools/inetstrm.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #define _SVSTDARR_STRINGS #include <svtools/svstdarr.hxx> #include <vos/mutex.hxx> #include <vcl/menu.hxx> #ifndef _LOGINERR_HXX #include <svtools/loginerr.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _DATETIMEITEM_HXX //autogen #include <svtools/dateitem.hxx> #endif #ifndef _SV_MENU_HXX #include <vcl/menu.hxx> #endif #ifndef _SV_WRKWIN_HXX #include <vcl/wrkwin.hxx> #endif #include "comphelper/processfactory.hxx" #include "viewfrm.hxx" #include "appdata.hxx" #include "dispatch.hxx" #include "event.hxx" #include "sfxtypes.hxx" #include "sfxdir.hxx" #include "doctempl.hxx" //#include "dataurl.hxx" #include "arrdecl.hxx" #include "docfac.hxx" #include "docfile.hxx" #include "request.hxx" #include "referers.hxx" #include "app.hrc" #include "sfxresid.hxx" #include "objshimp.hxx" #include "appuno.hxx" #include "imestatuswindow.hxx" SfxAppData_Impl::SfxAppData_Impl( SfxApplication* pApp ) : bServer( false ), pDdeService( 0 ), pDocTopics( 0 ), pTriggerTopic(0), pDdeService2(0), pFactArr(0), pSfxPluginObjectFactoryPtr( 0 ), pSfxPlugInObjectShellFactory( 0 ), pSfxFrameObjectFactoryPtr( 0 ), pTopFrames( new SfxFrameArr_Impl ), pInitLinkList(0), pMatcher( 0 ), pCancelMgr( 0 ), pLabelResMgr( 0 ), pAppDispatch(NULL), pTemplates( 0 ), pFilterIni( 0 ), pPool(0), pEventConfig(0), pDisabledSlotList( 0 ), pSecureURLs(0), pMiscConfig(0), pSaveOptions( 0 ), pUndoOptions( 0 ), pHelpOptions( 0 ), pThisDocument(0), pProgress(0), pDefFocusWin( 0 ), pTemplateCommon( 0 ), nDocModalMode(0), nAutoTabPageId(0), nExecutingSID( 0 ), nBasicCallLevel(0), nRescheduleLocks(0), nInReschedule(0), nAsynchronCalls(0), bPlugged(sal_False), bDirectAliveCount(sal_False), bInQuit(sal_False), bInvalidateOnUnlock(sal_False), bBean( sal_False ), bMinimized( sal_False ), bInvisible( sal_False ), bInException( sal_False ), nAppEvent( 0 ), m_xImeStatusWindow(new sfx2::appl::ImeStatusWindow( *pApp, comphelper::getProcessServiceFactory())) { StartListening( *pApp ); } SfxAppData_Impl::~SfxAppData_Impl() { //#ifdef DBG_UTIL DeInitDDE(); delete pTopFrames; delete pCancelMgr; delete pFilterIni; delete pSecureURLs; //#endif } IMPL_STATIC_LINK( SfxAppData_Impl, CreateDocumentTemplates, void*, EMPTYARG) { pThis->GetDocumentTemplates(); return 0; } void SfxAppData_Impl::UpdateApplicationSettings( sal_Bool bDontHide ) { AllSettings aAllSet = Application::GetSettings(); StyleSettings aStyleSet = aAllSet.GetStyleSettings(); sal_uInt32 nStyleOptions = aStyleSet.GetOptions(); if ( bDontHide ) nStyleOptions &= ~STYLE_OPTION_HIDEDISABLED; else nStyleOptions |= STYLE_OPTION_HIDEDISABLED; aStyleSet.SetOptions( nStyleOptions ); aAllSet.SetStyleSettings( aStyleSet ); Application::SetSettings( aAllSet ); } SfxDocumentTemplates* SfxAppData_Impl::GetDocumentTemplates() { if ( !pTemplates ) pTemplates = new SfxDocumentTemplates; else pTemplates->ReInitFromComponent(); return pTemplates; } void SfxAppData_Impl::Notify( SfxBroadcaster &rBC, const SfxHint &rHint ) { SfxSimpleHint* pHint = PTR_CAST( SfxSimpleHint, &rHint ); if( pHint && pHint->GetId() == SFX_HINT_CANCELLABLE ) { /* // vom Cancel-Manager for ( SfxViewFrame *pFrame = SfxViewFrame::GetFirst(); pFrame; pFrame = SfxViewFrame::GetNext(*pFrame) ) { SfxBindings &rBind = pFrame->GetBindings(); rBind.Invalidate( SID_BROWSE_STOP ); if ( !rBind.IsInRegistrations() ) rBind.Update( SID_BROWSE_STOP ); rBind.Invalidate( SID_BROWSE_STOP ); } */ } } <commit_msg>INTEGRATION: CWS sfxcleanup (1.20.154); FILE MERGED 2006/03/04 13:02:50 mba 1.20.154.3: #132394#: remove superfluous code 2006/02/26 17:09:50 mba 1.20.154.2: #132394#: remove superfluous code 2006/02/24 23:08:54 mba 1.20.154.1: #132394#: remove obviously superfluous members and methods from SfxApplication<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: appdata.cxx,v $ * * $Revision: 1.21 $ * * last change: $Author: rt $ $Date: 2006-05-02 16:15:08 $ * * 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 _CACHESTR_HXX //autogen #include <tools/cachestr.hxx> #endif #ifndef _CONFIG_HXX #include <tools/config.hxx> #endif #ifndef _INETSTRM_HXX //autogen #include <svtools/inetstrm.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #define _SVSTDARR_STRINGS #include <svtools/svstdarr.hxx> #include <vos/mutex.hxx> #include <vcl/menu.hxx> #ifndef _LOGINERR_HXX #include <svtools/loginerr.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _DATETIMEITEM_HXX //autogen #include <svtools/dateitem.hxx> #endif #ifndef _SV_MENU_HXX #include <vcl/menu.hxx> #endif #ifndef _SV_WRKWIN_HXX #include <vcl/wrkwin.hxx> #endif #include "comphelper/processfactory.hxx" #include "viewfrm.hxx" #include "appdata.hxx" #include "dispatch.hxx" #include "event.hxx" #include "sfxtypes.hxx" #include "doctempl.hxx" #include "arrdecl.hxx" #include "docfac.hxx" #include "docfile.hxx" #include "request.hxx" #include "referers.hxx" #include "app.hrc" #include "sfxresid.hxx" #include "objshimp.hxx" #include "appuno.hxx" #include "imestatuswindow.hxx" SfxAppData_Impl::SfxAppData_Impl( SfxApplication* pApp ) : pDdeService( 0 ), pDocTopics( 0 ), pTriggerTopic(0), pDdeService2(0), pFactArr(0), pTopFrames( new SfxFrameArr_Impl ), pInitLinkList(0), pMatcher( 0 ), pCancelMgr( 0 ), pLabelResMgr( 0 ), pAppDispatch(NULL), pTemplates( 0 ), pPool(0), pEventConfig(0), pDisabledSlotList( 0 ), pSecureURLs(0), pMiscConfig(0), pSaveOptions( 0 ), pUndoOptions( 0 ), pHelpOptions( 0 ), pThisDocument(0), pProgress(0), pTemplateCommon( 0 ), nDocModalMode(0), nAutoTabPageId(0), nBasicCallLevel(0), nRescheduleLocks(0), nInReschedule(0), nAsynchronCalls(0), bInQuit(sal_False), bInvalidateOnUnlock(sal_False), m_xImeStatusWindow(new sfx2::appl::ImeStatusWindow( *pApp, comphelper::getProcessServiceFactory())) , pViewFrame( 0 ) , pSlotPool( 0 ) , pResMgr( 0 ) , pAppDispat( 0 ) , nInterfaces( 0 ) , pInterfaces( 0 ) , bDowning( sal_True ) , nDocNo(0) , pTbxCtrlFac(0) , pStbCtrlFac(0) , pViewFrames(0) , pObjShells(0) , pBasicLibContainer(0) , pDialogLibContainer(0) , pSfxResManager(0) , pOfaResMgr(0) , pSimpleResManager(0) { } SfxAppData_Impl::~SfxAppData_Impl() { DeInitDDE(); delete pTopFrames; delete pCancelMgr; delete pSecureURLs; } IMPL_STATIC_LINK( SfxAppData_Impl, CreateDocumentTemplates, void*, EMPTYARG) { pThis->GetDocumentTemplates(); return 0; } void SfxAppData_Impl::UpdateApplicationSettings( sal_Bool bDontHide ) { AllSettings aAllSet = Application::GetSettings(); StyleSettings aStyleSet = aAllSet.GetStyleSettings(); sal_uInt32 nStyleOptions = aStyleSet.GetOptions(); if ( bDontHide ) nStyleOptions &= ~STYLE_OPTION_HIDEDISABLED; else nStyleOptions |= STYLE_OPTION_HIDEDISABLED; aStyleSet.SetOptions( nStyleOptions ); aAllSet.SetStyleSettings( aStyleSet ); Application::SetSettings( aAllSet ); } SfxDocumentTemplates* SfxAppData_Impl::GetDocumentTemplates() { if ( !pTemplates ) pTemplates = new SfxDocumentTemplates; else pTemplates->ReInitFromComponent(); return pTemplates; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef _SFX_SFXTYPES_HXX #define _SFX_SFXTYPES_HXX #include <tools/debug.hxx> #include <tools/rc.hxx> #include <tools/rcid.h> #include <tools/resid.hxx> #include <vcl/svapp.hxx> #include <vcl/wrkwin.hxx> #include <osl/mutex.hxx> #ifndef DELETEZ #define DELETEZ(pPtr) ( delete pPtr, pPtr = 0 ) #endif #ifndef DELETEX #ifdef DBG_UTIL #define DELETEX(T, pPtr) \ ( delete pPtr, pPtr = reinterpret_cast<T *>(sal_IntPtr(-1)) ) #else #define DELETEX(T, pPtr) delete pPtr #endif #endif //------------------------------------------------------------------------ // Macro for the Call-Profiler under WinNT // with S_CAP a measurement can be started, and stopped with E_CAP #if defined( WNT ) && defined( PROFILE ) extern "C" { void StartCAP(); void StopCAP(); void DumpCAP(); }; #define S_CAP() StartCAP(); #define E_CAP() StopCAP(); DumpCAP(); struct _Capper { _Capper() { S_CAP(); } ~_Capper() { E_CAP(); } }; #define CAP _Capper _aCap_ #else #define S_CAP() #define E_CAP() #define CAP #endif #ifdef DBG_UTIL #ifndef DBG #define DBG(statement) statement #endif #define DBG_OUTF(x) DbgOutf x #else #ifndef DBG #define DBG(statement) #endif #define DBG_OUTF(x) #endif //------------------------------------------------------------------------ #if defined(DBG_UTIL) && defined(WNT) class SfxStack { static unsigned nLevel; public: SfxStack( const char *pName ) { ++nLevel; DbgOutf( "STACK: enter %3d %s", nLevel, pName ); } ~SfxStack() { DbgOutf( "STACK: leave %3d", nLevel ); --nLevel; } }; #define SFX_STACK(s) SfxStack aSfxStack_( #s ) #else #define SFX_STACK(s) #endif //------------------------------------------------------------------------ struct StringList_Impl : private Resource { ResId aResId; StringList_Impl( const ResId& rErrIdP, sal_uInt16 nId) : Resource( rErrIdP ),aResId(nId, *rErrIdP.GetResMgr()){} ~StringList_Impl() { FreeResource(); } String GetString(){ return aResId.toString(); } operator sal_Bool(){return IsAvailableRes(aResId.SetRT(RSC_STRING));} }; #endif // #ifndef _SFX_SFXTYPES_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>convert sfx2/source/inc/sfxtypes.hxx from String to OUString<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef _SFX_SFXTYPES_HXX #define _SFX_SFXTYPES_HXX #include <tools/debug.hxx> #include <tools/rc.hxx> #include <tools/rcid.h> #include <tools/resid.hxx> #include <vcl/svapp.hxx> #include <vcl/wrkwin.hxx> #include <osl/mutex.hxx> #ifndef DELETEZ #define DELETEZ(pPtr) ( delete pPtr, pPtr = 0 ) #endif #ifndef DELETEX #ifdef DBG_UTIL #define DELETEX(T, pPtr) \ ( delete pPtr, pPtr = reinterpret_cast<T *>(sal_IntPtr(-1)) ) #else #define DELETEX(T, pPtr) delete pPtr #endif #endif //------------------------------------------------------------------------ // Macro for the Call-Profiler under WinNT // with S_CAP a measurement can be started, and stopped with E_CAP #if defined( WNT ) && defined( PROFILE ) extern "C" { void StartCAP(); void StopCAP(); void DumpCAP(); }; #define S_CAP() StartCAP(); #define E_CAP() StopCAP(); DumpCAP(); struct _Capper { _Capper() { S_CAP(); } ~_Capper() { E_CAP(); } }; #define CAP _Capper _aCap_ #else #define S_CAP() #define E_CAP() #define CAP #endif #ifdef DBG_UTIL #ifndef DBG #define DBG(statement) statement #endif #define DBG_OUTF(x) DbgOutf x #else #ifndef DBG #define DBG(statement) #endif #define DBG_OUTF(x) #endif //------------------------------------------------------------------------ #if defined(DBG_UTIL) && defined(WNT) class SfxStack { static unsigned nLevel; public: SfxStack( const char *pName ) { ++nLevel; DbgOutf( "STACK: enter %3d %s", nLevel, pName ); } ~SfxStack() { DbgOutf( "STACK: leave %3d", nLevel ); --nLevel; } }; #define SFX_STACK(s) SfxStack aSfxStack_( #s ) #else #define SFX_STACK(s) #endif //------------------------------------------------------------------------ struct StringList_Impl : private Resource { ResId aResId; StringList_Impl( const ResId& rErrIdP, sal_uInt16 nId) : Resource( rErrIdP ),aResId(nId, *rErrIdP.GetResMgr()){} ~StringList_Impl() { FreeResource(); } OUString GetString(){ return aResId.toString(); } operator sal_Bool(){return IsAvailableRes(aResId.SetRT(RSC_STRING));} }; #endif // #ifndef _SFX_SFXTYPES_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: templdgi.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: gt $ $Date: 2002-05-14 13:19:30 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SFX_TEMPDLGI_HXX #define _SFX_TEMPDLGI_HXX class SfxTemplateControllerItem; #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _TOOLBOX_HXX //autogen #include <vcl/toolbox.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SFXLSTNER_HXX //autogen #include <svtools/lstner.hxx> #endif #ifndef _SVTREEBOX_HXX //autogen #include <svtools/svtreebx.hxx> #endif #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #define _SVSTDARR_USHORTS #include <svtools/svstdarr.hxx> // SvUShorts #include <rsc/rscsfx.hxx> #include <tools/rtti.hxx> #include "childwin.hxx" #include "templdlg.hxx" class SfxStyleFamilies; class SfxStyleFamilyItem; class SfxTemplateItem; class SfxBindings; class SfxStyleSheetBasePool; class SvTreeListBox ; class StyleTreeListBox_Impl; class SfxTemplateDialog_Impl; class SfxCommonTemplateDialog_Impl; class SfxTemplateDialogWrapper; class SfxDockingWindow; // class DropListBox_Impl ------------------------------------------------ class DropListBox_Impl : public SvTreeListBox { private: DECL_LINK( OnAsyncExecuteDrop, SvLBoxEntry* ); DECL_LINK( OnAsyncExecuteError, void* ); protected: SvLBoxEntry* pPreDropEntry; SfxCommonTemplateDialog_Impl* pDialog; USHORT nModifier; public: DropListBox_Impl( Window* pParent, const ResId& rId, SfxCommonTemplateDialog_Impl* pD ) : SvTreeListBox( pParent, rId ), pDialog( pD ), pPreDropEntry( NULL ) {} DropListBox_Impl( Window* pParent, WinBits nWinBits, SfxCommonTemplateDialog_Impl* pD ) : SvTreeListBox( pParent, nWinBits ), pDialog( pD ), pPreDropEntry( NULL ) {} virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ); USHORT GetModifier() const { return nModifier; } SvLBoxEntry* GetPreDropEntry() const { return pPreDropEntry; } virtual long Notify( NotifyEvent& rNEvt ); }; // class SfxActionListBox ------------------------------------------------ class SfxActionListBox : public DropListBox_Impl { protected: public: SfxActionListBox( SfxCommonTemplateDialog_Impl* pParent, WinBits nWinBits ); SfxActionListBox( SfxCommonTemplateDialog_Impl* pParent, const ResId &rResId ); virtual PopupMenu* CreateContextMenu( void ); }; // class SfxCommonTemplateDialog_Impl ------------------------------------ class SfxCommonTemplateDialog_Impl : public SfxListener { private: class ISfxTemplateCommon_Impl : public ISfxTemplateCommon { private: SfxCommonTemplateDialog_Impl* pDialog; public: ISfxTemplateCommon_Impl( SfxCommonTemplateDialog_Impl* pDialogP ) : pDialog( pDialogP ) {} virtual SfxStyleFamily GetActualFamily() const { return pDialog->GetActualFamily(); } virtual String GetSelectedEntry() const { return pDialog->GetSelectedEntry(); } }; ISfxTemplateCommon_Impl aISfxTemplateCommon; void ReadResource(); void ClearResource(); protected: #define MAX_FAMILIES 5 #define COUNT_BOUND_FUNC 13 #define UPDATE_FAMILY_LIST 0x0001 #define UPDATE_FAMILY 0x0002 friend class DropListBox_Impl; friend class SfxTemplateControllerItem; friend class SfxTemplateDialogWrapper; SfxBindings* pBindings; SfxTemplateControllerItem* pBoundItems[COUNT_BOUND_FUNC]; Window* pWindow; SfxModule* pModule; Timer* pTimer; SfxStyleFamilies* pStyleFamilies; SfxTemplateItem* pFamilyState[MAX_FAMILIES]; SfxStyleSheetBasePool* pStyleSheetPool; SvTreeListBox* pTreeBox; SfxObjectShell* pCurObjShell; SfxActionListBox aFmtLb; ListBox aFilterLb; Size aSize; USHORT nActFamily; // Id in der ToolBox = Position - 1 USHORT nActFilter; // FilterIdx USHORT nAppFilter; // Filter, den die Applikation gesetzt hat (fuer automatisch) BOOL bDontUpdate :1, bIsWater :1, bEnabled :1, bUpdate :1, bUpdateFamily :1, bCanEdit :1, bCanDel :1, bCanNew :1, bWaterDisabled :1, bNewByExampleDisabled :1, bUpdateByExampleDisabled:1, bTreeDrag :1, bHierarchical :1, bBindingUpdate :1; DECL_LINK( FilterSelectHdl, ListBox * ); DECL_LINK( FmtSelectHdl, SvTreeListBox * ); DECL_LINK( ApplyHdl, Control * ); DECL_LINK( DropHdl, StyleTreeListBox_Impl * ); DECL_LINK( TimeOut, Timer * ); // Rechnet von den SFX_STYLE_FAMILY Ids auf 1-5 um static USHORT SfxFamilyIdToNId( USHORT nFamily ); virtual void EnableItem( USHORT nMesId, BOOL bCheck = TRUE ) {} virtual void CheckItem( USHORT nMesId, BOOL bCheck = TRUE ) {} virtual BOOL IsCheckedItem( USHORT nMesId ) { return TRUE; } virtual void Resize() {} virtual void Update() { UpdateStyles_Impl(UPDATE_FAMILY_LIST); } virtual void InvalidateBindings(); virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten ) = 0; virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE ) = 0; virtual void ClearFamilyList() = 0; void NewHdl( void* ); void EditHdl( void* ); void DeleteHdl( void* ); BOOL Execute_Impl( USHORT nId, const String& rStr, const String& rRefStr, USHORT nFamily, USHORT nMask = 0, USHORT* pIdx = NULL, const USHORT* pModifier = NULL ); void UpdateStyles_Impl(USHORT nFlags); const SfxStyleFamilyItem* GetFamilyItem_Impl() const; BOOL IsInitialized() { return nActFamily != 0xffff; } void ResetFocus(); void EnableDelete(); void Initialize(); void FilterSelect( USHORT nFilterIdx, BOOL bForce = FALSE ); void SetFamilyState( USHORT nSlotId, const SfxTemplateItem* ); void SetWaterCanState( const SfxBoolItem* pItem ); void SelectStyle( const String& rStyle ); BOOL HasSelectedStyle() const; void FillTreeBox(); void Update_Impl(); void UpdateFamily_Impl(); // In welchem FamilyState muss ich nachsehen, um die Info der i-ten // Family in der pStyleFamilies zu bekommen. USHORT StyleNrToInfoOffset( USHORT i ); USHORT InfoOffsetToStyleNr( USHORT i ); void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); void FamilySelect( USHORT nId ); void SetFamily( USHORT nId ); void ActionSelect( USHORT nId ); public: TYPEINFO(); SfxCommonTemplateDialog_Impl( SfxBindings* pB, SfxDockingWindow* ); SfxCommonTemplateDialog_Impl( SfxBindings* pB, ModalDialog* ); ~SfxCommonTemplateDialog_Impl(); DECL_LINK( MenuSelectHdl, Menu * ); virtual void EnableEdit( BOOL b = TRUE ) { bCanEdit = b; } virtual void EnableDel( BOOL b = TRUE ) { bCanDel = b; } virtual void EnableNew( BOOL b = TRUE ) { bCanNew = b; } ISfxTemplateCommon* GetISfxTemplateCommon() { return &aISfxTemplateCommon; } Window* GetWindow() { return pWindow; } void EnableTreeDrag( BOOL b = TRUE ); void ExecuteContextMenu_Impl( const Point& rPos, Window* pWin ); void EnableExample_Impl( USHORT nId, BOOL bEnable ); SfxStyleFamily GetActualFamily() const; String GetSelectedEntry() const; SfxObjectShell* GetObjectShell() const { return pCurObjShell; } virtual void PrepareDeleteAction(); // disable buttons, change button text, etc. when del is going to happen inline BOOL CanEdit( void ) const { return bCanEdit; } inline BOOL CanDel( void ) const { return bCanDel; } inline BOOL CanNew( void ) const { return bCanNew; } // normaly for derivates from SvTreeListBoxes, but in this case the dialog handles context menus virtual PopupMenu* CreateContextMenu( void ); }; // class SfxTemplateDialog_Impl ------------------------------------------ class SfxTemplateDialog_Impl : public SfxCommonTemplateDialog_Impl { private: friend class SfxTemplateControllerItem; friend class SfxTemplateDialogWrapper; SfxTemplateDialog* pFloat; BOOL bZoomIn; ToolBox aActionTbL; ToolBox aActionTbR; DECL_LINK( ToolBoxLSelect, ToolBox * ); DECL_LINK( ToolBoxRSelect, ToolBox * ); protected: virtual void Command( const CommandEvent& rMEvt ); virtual void EnableEdit( BOOL = TRUE ); virtual void EnableItem( USHORT nMesId, BOOL bCheck = TRUE ); virtual void CheckItem( USHORT nMesId, BOOL bCheck = TRUE ); virtual BOOL IsCheckedItem( USHORT nMesId ); virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten ); virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE ); virtual void ClearFamilyList(); void Resize(); Size GetMinOutputSizePixel(); public: friend class SfxTemplateDialog; TYPEINFO(); SfxTemplateDialog_Impl( Window* pParent, SfxBindings*, SfxTemplateDialog* pWindow ); ~SfxTemplateDialog_Impl(); }; // class SfxTemplateCatalog_Impl ----------------------------------------- class SfxTemplateCatalog_Impl : public SfxCommonTemplateDialog_Impl { private: friend class SfxTemplateControllerItem; friend class SfxCommonTemplateDialog_Impl; ListBox aFamList; OKButton aOkBtn; CancelButton aCancelBtn; PushButton aNewBtn; PushButton aChangeBtn; PushButton aDelBtn; PushButton aOrgBtn; HelpButton aHelpBtn; SfxTemplateCatalog* pReal; SvUShorts aFamIds; SfxModalDefParentHelper aHelper; protected: virtual void EnableItem( USHORT nMesId, BOOL bCheck = TRUE ); virtual void CheckItem( USHORT nMesId, BOOL bCheck = TRUE ); virtual BOOL IsCheckedItem( USHORT nMesId ); virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten ); virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE ); virtual void ClearFamilyList(); virtual void EnableEdit( BOOL = TRUE ); virtual void EnableDel( BOOL = TRUE ); virtual void EnableNew( BOOL = TRUE ); DECL_LINK( FamListSelect, ListBox * ); DECL_LINK( OkHdl, Button * ); DECL_LINK( CancelHdl, Button * ); DECL_LINK( NewHdl, Button * ); DECL_LINK( ChangeHdl, Button * ); DECL_LINK( DelHdl, Button * ); DECL_LINK( OrgHdl, Button * ); public: TYPEINFO(); SfxTemplateCatalog_Impl( Window* pParent, SfxBindings*, SfxTemplateCatalog* pWindow ); ~SfxTemplateCatalog_Impl(); friend class SfxTemplateCatalog; virtual void PrepareDeleteAction(); }; #endif // #ifndef _SFX_TEMPDLGI_HXX <commit_msg>#99484# +updateFamilyImages for high contrast support<commit_after>/************************************************************************* * * $RCSfile: templdgi.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: fs $ $Date: 2002-05-27 09:55:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SFX_TEMPDLGI_HXX #define _SFX_TEMPDLGI_HXX class SfxTemplateControllerItem; #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _TOOLBOX_HXX //autogen #include <vcl/toolbox.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SFXLSTNER_HXX //autogen #include <svtools/lstner.hxx> #endif #ifndef _SVTREEBOX_HXX //autogen #include <svtools/svtreebx.hxx> #endif #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #define _SVSTDARR_USHORTS #include <svtools/svstdarr.hxx> // SvUShorts #include <rsc/rscsfx.hxx> #include <tools/rtti.hxx> #include "childwin.hxx" #include "templdlg.hxx" class SfxStyleFamilies; class SfxStyleFamilyItem; class SfxTemplateItem; class SfxBindings; class SfxStyleSheetBasePool; class SvTreeListBox ; class StyleTreeListBox_Impl; class SfxTemplateDialog_Impl; class SfxCommonTemplateDialog_Impl; class SfxTemplateDialogWrapper; class SfxDockingWindow; // class DropListBox_Impl ------------------------------------------------ class DropListBox_Impl : public SvTreeListBox { private: DECL_LINK( OnAsyncExecuteDrop, SvLBoxEntry* ); DECL_LINK( OnAsyncExecuteError, void* ); protected: SvLBoxEntry* pPreDropEntry; SfxCommonTemplateDialog_Impl* pDialog; USHORT nModifier; public: DropListBox_Impl( Window* pParent, const ResId& rId, SfxCommonTemplateDialog_Impl* pD ) : SvTreeListBox( pParent, rId ), pDialog( pD ), pPreDropEntry( NULL ) {} DropListBox_Impl( Window* pParent, WinBits nWinBits, SfxCommonTemplateDialog_Impl* pD ) : SvTreeListBox( pParent, nWinBits ), pDialog( pD ), pPreDropEntry( NULL ) {} virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ); USHORT GetModifier() const { return nModifier; } SvLBoxEntry* GetPreDropEntry() const { return pPreDropEntry; } virtual long Notify( NotifyEvent& rNEvt ); }; // class SfxActionListBox ------------------------------------------------ class SfxActionListBox : public DropListBox_Impl { protected: public: SfxActionListBox( SfxCommonTemplateDialog_Impl* pParent, WinBits nWinBits ); SfxActionListBox( SfxCommonTemplateDialog_Impl* pParent, const ResId &rResId ); virtual PopupMenu* CreateContextMenu( void ); }; // class SfxCommonTemplateDialog_Impl ------------------------------------ class SfxCommonTemplateDialog_Impl : public SfxListener { private: class ISfxTemplateCommon_Impl : public ISfxTemplateCommon { private: SfxCommonTemplateDialog_Impl* pDialog; public: ISfxTemplateCommon_Impl( SfxCommonTemplateDialog_Impl* pDialogP ) : pDialog( pDialogP ) {} virtual SfxStyleFamily GetActualFamily() const { return pDialog->GetActualFamily(); } virtual String GetSelectedEntry() const { return pDialog->GetSelectedEntry(); } }; ISfxTemplateCommon_Impl aISfxTemplateCommon; void ReadResource(); void ClearResource(); protected: #define MAX_FAMILIES 5 #define COUNT_BOUND_FUNC 13 #define UPDATE_FAMILY_LIST 0x0001 #define UPDATE_FAMILY 0x0002 friend class DropListBox_Impl; friend class SfxTemplateControllerItem; friend class SfxTemplateDialogWrapper; SfxBindings* pBindings; SfxTemplateControllerItem* pBoundItems[COUNT_BOUND_FUNC]; Window* pWindow; SfxModule* pModule; Timer* pTimer; ResId* m_pStyleFamiliesId; SfxStyleFamilies* pStyleFamilies; SfxTemplateItem* pFamilyState[MAX_FAMILIES]; SfxStyleSheetBasePool* pStyleSheetPool; SvTreeListBox* pTreeBox; SfxObjectShell* pCurObjShell; SfxActionListBox aFmtLb; ListBox aFilterLb; Size aSize; USHORT nActFamily; // Id in der ToolBox = Position - 1 USHORT nActFilter; // FilterIdx USHORT nAppFilter; // Filter, den die Applikation gesetzt hat (fuer automatisch) BOOL bDontUpdate :1, bIsWater :1, bEnabled :1, bUpdate :1, bUpdateFamily :1, bCanEdit :1, bCanDel :1, bCanNew :1, bWaterDisabled :1, bNewByExampleDisabled :1, bUpdateByExampleDisabled:1, bTreeDrag :1, bHierarchical :1, bBindingUpdate :1; DECL_LINK( FilterSelectHdl, ListBox * ); DECL_LINK( FmtSelectHdl, SvTreeListBox * ); DECL_LINK( ApplyHdl, Control * ); DECL_LINK( DropHdl, StyleTreeListBox_Impl * ); DECL_LINK( TimeOut, Timer * ); // Rechnet von den SFX_STYLE_FAMILY Ids auf 1-5 um static USHORT SfxFamilyIdToNId( USHORT nFamily ); virtual void EnableItem( USHORT nMesId, BOOL bCheck = TRUE ) {} virtual void CheckItem( USHORT nMesId, BOOL bCheck = TRUE ) {} virtual BOOL IsCheckedItem( USHORT nMesId ) { return TRUE; } virtual void LoadedFamilies() {} virtual void Update() { UpdateStyles_Impl(UPDATE_FAMILY_LIST); } virtual void InvalidateBindings(); virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten ) = 0; virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE ) = 0; virtual void ClearFamilyList() = 0; void NewHdl( void* ); void EditHdl( void* ); void DeleteHdl( void* ); BOOL Execute_Impl( USHORT nId, const String& rStr, const String& rRefStr, USHORT nFamily, USHORT nMask = 0, USHORT* pIdx = NULL, const USHORT* pModifier = NULL ); void UpdateStyles_Impl(USHORT nFlags); const SfxStyleFamilyItem* GetFamilyItem_Impl() const; BOOL IsInitialized() { return nActFamily != 0xffff; } void ResetFocus(); void EnableDelete(); void Initialize(); void FilterSelect( USHORT nFilterIdx, BOOL bForce = FALSE ); void SetFamilyState( USHORT nSlotId, const SfxTemplateItem* ); void SetWaterCanState( const SfxBoolItem* pItem ); void SelectStyle( const String& rStyle ); BOOL HasSelectedStyle() const; void FillTreeBox(); void Update_Impl(); void UpdateFamily_Impl(); // In welchem FamilyState muss ich nachsehen, um die Info der i-ten // Family in der pStyleFamilies zu bekommen. USHORT StyleNrToInfoOffset( USHORT i ); USHORT InfoOffsetToStyleNr( USHORT i ); void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); void FamilySelect( USHORT nId ); void SetFamily( USHORT nId ); void ActionSelect( USHORT nId ); public: TYPEINFO(); SfxCommonTemplateDialog_Impl( SfxBindings* pB, SfxDockingWindow* ); SfxCommonTemplateDialog_Impl( SfxBindings* pB, ModalDialog* ); ~SfxCommonTemplateDialog_Impl(); DECL_LINK( MenuSelectHdl, Menu * ); virtual void EnableEdit( BOOL b = TRUE ) { bCanEdit = b; } virtual void EnableDel( BOOL b = TRUE ) { bCanDel = b; } virtual void EnableNew( BOOL b = TRUE ) { bCanNew = b; } ISfxTemplateCommon* GetISfxTemplateCommon() { return &aISfxTemplateCommon; } Window* GetWindow() { return pWindow; } void EnableTreeDrag( BOOL b = TRUE ); void ExecuteContextMenu_Impl( const Point& rPos, Window* pWin ); void EnableExample_Impl( USHORT nId, BOOL bEnable ); SfxStyleFamily GetActualFamily() const; String GetSelectedEntry() const; SfxObjectShell* GetObjectShell() const { return pCurObjShell; } virtual void PrepareDeleteAction(); // disable buttons, change button text, etc. when del is going to happen inline BOOL CanEdit( void ) const { return bCanEdit; } inline BOOL CanDel( void ) const { return bCanDel; } inline BOOL CanNew( void ) const { return bCanNew; } // normaly for derivates from SvTreeListBoxes, but in this case the dialog handles context menus virtual PopupMenu* CreateContextMenu( void ); }; // class SfxTemplateDialog_Impl ------------------------------------------ class SfxTemplateDialog_Impl : public SfxCommonTemplateDialog_Impl { private: friend class SfxTemplateControllerItem; friend class SfxTemplateDialogWrapper; SfxTemplateDialog* pFloat; BOOL bZoomIn; ToolBox aActionTbL; ToolBox aActionTbR; DECL_LINK( ToolBoxLSelect, ToolBox * ); DECL_LINK( ToolBoxRSelect, ToolBox * ); protected: virtual void Command( const CommandEvent& rMEvt ); virtual void EnableEdit( BOOL = TRUE ); virtual void EnableItem( USHORT nMesId, BOOL bCheck = TRUE ); virtual void CheckItem( USHORT nMesId, BOOL bCheck = TRUE ); virtual BOOL IsCheckedItem( USHORT nMesId ); virtual void LoadedFamilies(); virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten ); virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE ); virtual void ClearFamilyList(); void Resize(); Size GetMinOutputSizePixel(); void updateFamilyImages(); public: friend class SfxTemplateDialog; TYPEINFO(); SfxTemplateDialog_Impl( Window* pParent, SfxBindings*, SfxTemplateDialog* pWindow ); ~SfxTemplateDialog_Impl(); }; // class SfxTemplateCatalog_Impl ----------------------------------------- class SfxTemplateCatalog_Impl : public SfxCommonTemplateDialog_Impl { private: friend class SfxTemplateControllerItem; friend class SfxCommonTemplateDialog_Impl; ListBox aFamList; OKButton aOkBtn; CancelButton aCancelBtn; PushButton aNewBtn; PushButton aChangeBtn; PushButton aDelBtn; PushButton aOrgBtn; HelpButton aHelpBtn; SfxTemplateCatalog* pReal; SvUShorts aFamIds; SfxModalDefParentHelper aHelper; protected: virtual void EnableItem( USHORT nMesId, BOOL bCheck = TRUE ); virtual void CheckItem( USHORT nMesId, BOOL bCheck = TRUE ); virtual BOOL IsCheckedItem( USHORT nMesId ); virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten ); virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE ); virtual void ClearFamilyList(); virtual void EnableEdit( BOOL = TRUE ); virtual void EnableDel( BOOL = TRUE ); virtual void EnableNew( BOOL = TRUE ); DECL_LINK( FamListSelect, ListBox * ); DECL_LINK( OkHdl, Button * ); DECL_LINK( CancelHdl, Button * ); DECL_LINK( NewHdl, Button * ); DECL_LINK( ChangeHdl, Button * ); DECL_LINK( DelHdl, Button * ); DECL_LINK( OrgHdl, Button * ); public: TYPEINFO(); SfxTemplateCatalog_Impl( Window* pParent, SfxBindings*, SfxTemplateCatalog* pWindow ); ~SfxTemplateCatalog_Impl(); friend class SfxTemplateCatalog; virtual void PrepareDeleteAction(); }; #endif // #ifndef _SFX_TEMPDLGI_HXX <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewfac.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" // INCLUDE --------------------------------------------------------------- #include <sfx2/app.hxx> #include <rtl/ustrbuf.hxx> #include "viewfac.hxx" // STATIC DATA ----------------------------------------------------------- DBG_NAME(SfxViewFactory) SfxViewShell *SfxViewFactory::CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldSh ) { DBG_CHKTHIS(SfxViewFactory, 0); return (*fnCreate)(pFrame, pOldSh); } void SfxViewFactory::InitFactory() { DBG_CHKTHIS(SfxViewFactory, 0); (*fnInit)(); } String SfxViewFactory::GetViewName() const { ::rtl::OUStringBuffer aViewName; aViewName.appendAscii( "view" ); aViewName.append( GetOrdinal() ); return aViewName.makeStringAndClear(); } // CTOR / DTOR ----------------------------------------------------------- SfxViewFactory::SfxViewFactory( SfxViewCtor fnC, SfxViewInit fnI, USHORT nOrdinal, const ResId& aDescrResId ): fnCreate(fnC), fnInit(fnI), nOrd(nOrdinal), aDescription(aDescrResId.GetId(), *aDescrResId.GetResMgr()) { aDescription.SetRT(aDescrResId.GetRT()); DBG_CTOR(SfxViewFactory, 0); // SFX_APP()->RegisterViewFactory_Impl(*this); } SfxViewFactory::~SfxViewFactory() { DBG_DTOR(SfxViewFactory, 0); } <commit_msg>autorecovery: corrected GetViewName<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewfac.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" // INCLUDE --------------------------------------------------------------- #include <sfx2/app.hxx> #include <rtl/ustrbuf.hxx> #include "viewfac.hxx" // STATIC DATA ----------------------------------------------------------- DBG_NAME(SfxViewFactory) SfxViewShell *SfxViewFactory::CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldSh ) { DBG_CHKTHIS(SfxViewFactory, 0); return (*fnCreate)(pFrame, pOldSh); } void SfxViewFactory::InitFactory() { DBG_CHKTHIS(SfxViewFactory, 0); (*fnInit)(); } String SfxViewFactory::GetViewName() const { ::rtl::OUStringBuffer aViewName; aViewName.appendAscii( "view" ); aViewName.append( sal_Int32( GetOrdinal() ) ); return aViewName.makeStringAndClear(); } // CTOR / DTOR ----------------------------------------------------------- SfxViewFactory::SfxViewFactory( SfxViewCtor fnC, SfxViewInit fnI, USHORT nOrdinal, const ResId& aDescrResId ): fnCreate(fnC), fnInit(fnI), nOrd(nOrdinal), aDescription(aDescrResId.GetId(), *aDescrResId.GetResMgr()) { aDescription.SetRT(aDescrResId.GetRT()); DBG_CTOR(SfxViewFactory, 0); // SFX_APP()->RegisterViewFactory_Impl(*this); } SfxViewFactory::~SfxViewFactory() { DBG_DTOR(SfxViewFactory, 0); } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -g -emit-llvm -o - %s | FileCheck %s // Make sure that clang outputs distinct debug info for a function // that is inlined twice on the same line. Otherwise it would appear // as if the function was only inlined once. #define INLINE inline __attribute__((always_inline)) INLINE int product (int x, int y) { int result = x * y; return result; } INLINE int sum (int a, int b) { int result = a + b; return result; } int strange_max (int m, int n) { if (m > n) return m; else if (n > m) return n; else return 0; } int foo (int i, int j) { if (strange_max (i, j) == i) return product (i, j); else if (strange_max (i, j) == j) return sum (i, j); else return product (sum (i, i), sum (j, j)); } int main(int argc, char const *argv[]) { int array[3]; array[0] = foo (1238, 78392); array[1] = foo (379265, 23674); array[2] = foo (872934, 234); return 0; } // CHECK: define i32 @_Z3fooii(i32 %i, i32 %j) // i // CHECK: call void @llvm.dbg.declare // j // CHECK: call void @llvm.dbg.declare // x // CHECK: call void @llvm.dbg.declare // y // CHECK: call void @llvm.dbg.declare // result // CHECK: call void @llvm.dbg.declare // CHECK: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[A_MD:[0-9]+]]), !dbg ![[A_DI:[0-9]+]] // CHECK: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[B_MD:[0-9]+]]), !dbg ![[B_DI:[0-9]+]] // result // CHECK: call void @llvm.dbg.declare // We want to see a distinct !dbg node. // CHECK-NOT: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[A_MD]]), !dbg ![[A_DI]] // CHECK: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[A_MD]]), !dbg !{{.*}} // CHECK-NOT: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[B_MD]]), !dbg ![[B_DI]] // CHECK: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[B_MD]]), !dbg !{{.*}} // result // CHECK: call void @llvm.dbg.declare <commit_msg>relax check to allow for attributes (fix buildbot for elf-ppc64)<commit_after>// RUN: %clang_cc1 -g -emit-llvm -o - %s | FileCheck %s // Make sure that clang outputs distinct debug info for a function // that is inlined twice on the same line. Otherwise it would appear // as if the function was only inlined once. #define INLINE inline __attribute__((always_inline)) INLINE int product (int x, int y) { int result = x * y; return result; } INLINE int sum (int a, int b) { int result = a + b; return result; } int strange_max (int m, int n) { if (m > n) return m; else if (n > m) return n; else return 0; } int foo (int i, int j) { if (strange_max (i, j) == i) return product (i, j); else if (strange_max (i, j) == j) return sum (i, j); else return product (sum (i, i), sum (j, j)); } int main(int argc, char const *argv[]) { int array[3]; array[0] = foo (1238, 78392); array[1] = foo (379265, 23674); array[2] = foo (872934, 234); return 0; } // CHECK: define {{.*}} @_Z3fooii // i // CHECK: call void @llvm.dbg.declare // j // CHECK: call void @llvm.dbg.declare // x // CHECK: call void @llvm.dbg.declare // y // CHECK: call void @llvm.dbg.declare // result // CHECK: call void @llvm.dbg.declare // CHECK: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[A_MD:[0-9]+]]), !dbg ![[A_DI:[0-9]+]] // CHECK: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[B_MD:[0-9]+]]), !dbg ![[B_DI:[0-9]+]] // result // CHECK: call void @llvm.dbg.declare // We want to see a distinct !dbg node. // CHECK-NOT: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[A_MD]]), !dbg ![[A_DI]] // CHECK: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[A_MD]]), !dbg !{{.*}} // CHECK-NOT: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[B_MD]]), !dbg ![[B_DI]] // CHECK: call void @llvm.dbg.declare(metadata !{i32* %{{.*}}}, metadata ![[B_MD]]), !dbg !{{.*}} // result // CHECK: call void @llvm.dbg.declare <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2014 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // // TODO: we still need to check if windows are closed somehow. // Google Test. #include <gtest/gtest.h> // DO-CV. #include <DO/Core/Timer.hpp> #include <DO/Graphics.hpp> #include <DO/Graphics/GraphicsUtilities.hpp> using namespace DO; #ifdef TRAVIS_CI_SEGFAULT_SOLVED TEST(TestWindow, DISABLED_test_open_and_close_window) { std::cout << "trying to open window: " << std::endl; Window w = openWindow(300, 300, "My Window", 10, 10); std::cout << "OK" << std::endl; EXPECT_NE(w, Window(0)); std::cout << "check window attributes: " << std::endl; EXPECT_EQ(getWindowWidth(w), w->width()); EXPECT_EQ(getWindowHeight(w), w->height()); EXPECT_EQ(getWindowSizes(w), Vector2i(w->width(), w->height())); PaintingWindow *pw = qobject_cast<PaintingWindow *>(w); EXPECT_EQ(pw->windowTitle().toStdString(), "My Window"); std::cout << "OK" << std::endl; QPointer<QWidget> guarded_widget(pw->scrollArea()); EXPECT_EQ(guarded_widget->pos(), QPoint(10, 10)); std::cout << "closing window: " << std::endl; closeWindow(w); std::cout << "OK" << std::endl; } TEST(TestWindow, DISABLED_test_open_and_close_gl_window) { Window w = openGLWindow(300, 300, "My Window", 10, 10); EXPECT_NE(w, Window(0)); EXPECT_EQ(getWindowWidth(w), w->width()); EXPECT_EQ(getWindowHeight(w), w->height()); EXPECT_EQ(getWindowSizes(w), Vector2i(w->width(), w->height())); EXPECT_EQ(w->windowTitle().toStdString(), "My Window"); EXPECT_EQ(w->pos(), QPoint(10, 10)); closeWindow(w); } TEST(TestWindow, DISABLED_test_open_and_close_graphics_view) { Window w = openGraphicsView(300, 300, "My Window", 10, 10); EXPECT_NE(w, Window(0)); EXPECT_EQ(getWindowWidth(w), w->width()); EXPECT_EQ(getWindowHeight(w), w->height()); EXPECT_EQ(getWindowSizes(w), Vector2i(w->width(), w->height())); EXPECT_EQ(w->windowTitle().toStdString(), "My Window"); EXPECT_EQ(w->pos(), QPoint(10, 10)); closeWindow(w); } TEST(TestWindow, DISABLED_test_set_active_window) { Window w1 = openWindow(300, 300, "My Window", 10, 10); Window w2 = openGLWindow(300, 300, "My GL Window", 10, 10); // TODO: FIXME. //Window w3 = openGraphicsView(300, 300, "My Graphics View", 10, 10); EXPECT_EQ(w1, getActiveWindow()); setActiveWindow(w2); EXPECT_EQ(w2, getActiveWindow()); // TODO: FIXME. //setActiveWindow(w3); //EXPECT_EQ(w3, getActiveWindow()); closeWindow(w1); closeWindow(w2); // TODO: FIXME. //closeWindow(w3); } TEST(TestWindow, DISABLED_test_resize_window) { Window w = openWindow(300, 300, "My Window", 10, 10); EXPECT_EQ(w, getActiveWindow()); EXPECT_EQ(getWindowSizes(w), Vector2i(300, 300)); fillCircle(100, 100, 30, Red8); resizeWindow(500, 500); EXPECT_EQ(getWindowSizes(w), Vector2i(500, 500)); fillCircle(100, 100, 30, Red8); } #undef main int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #else #include "event_scheduler.hpp" EventScheduler *global_scheduler; class TestSleepFunctions: public testing::Test { protected: Window test_window_; TestSleepFunctions() { test_window_ = openWindow(300, 300); } virtual ~TestSleepFunctions() { closeWindow(test_window_); } }; TEST_F(TestSleepFunctions, test_milliSleep) { } int worker_thread_task(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #undef main int main(int argc, char **argv) { // Create Qt Application. GraphicsApplication gui_app_(argc, argv); // Create an event scheduler on the GUI thread. global_scheduler = new EventScheduler; // Run the worker thread gui_app_.registerUserMain(worker_thread_task); int return_code = gui_app_.exec(); // Cleanup and terminate delete global_scheduler; return return_code; } #endif<commit_msg>Revert "Disconnect any connection between user thread and the event scheduler."<commit_after>// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2014 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // // TODO: we still need to check if windows are closed somehow. // Google Test. #include <gtest/gtest.h> // DO-CV. #include <DO/Core/Timer.hpp> #include <DO/Graphics.hpp> #include <DO/Graphics/GraphicsUtilities.hpp> using namespace DO; #ifdef TRAVIS_CI_SEGFAULT_SOLVED TEST(TestWindow, DISABLED_test_open_and_close_window) { std::cout << "trying to open window: " << std::endl; Window w = openWindow(300, 300, "My Window", 10, 10); std::cout << "OK" << std::endl; EXPECT_NE(w, Window(0)); std::cout << "check window attributes: " << std::endl; EXPECT_EQ(getWindowWidth(w), w->width()); EXPECT_EQ(getWindowHeight(w), w->height()); EXPECT_EQ(getWindowSizes(w), Vector2i(w->width(), w->height())); PaintingWindow *pw = qobject_cast<PaintingWindow *>(w); EXPECT_EQ(pw->windowTitle().toStdString(), "My Window"); std::cout << "OK" << std::endl; QPointer<QWidget> guarded_widget(pw->scrollArea()); EXPECT_EQ(guarded_widget->pos(), QPoint(10, 10)); std::cout << "closing window: " << std::endl; closeWindow(w); std::cout << "OK" << std::endl; } TEST(TestWindow, DISABLED_test_open_and_close_gl_window) { Window w = openGLWindow(300, 300, "My Window", 10, 10); EXPECT_NE(w, Window(0)); EXPECT_EQ(getWindowWidth(w), w->width()); EXPECT_EQ(getWindowHeight(w), w->height()); EXPECT_EQ(getWindowSizes(w), Vector2i(w->width(), w->height())); EXPECT_EQ(w->windowTitle().toStdString(), "My Window"); EXPECT_EQ(w->pos(), QPoint(10, 10)); closeWindow(w); } TEST(TestWindow, DISABLED_test_open_and_close_graphics_view) { Window w = openGraphicsView(300, 300, "My Window", 10, 10); EXPECT_NE(w, Window(0)); EXPECT_EQ(getWindowWidth(w), w->width()); EXPECT_EQ(getWindowHeight(w), w->height()); EXPECT_EQ(getWindowSizes(w), Vector2i(w->width(), w->height())); EXPECT_EQ(w->windowTitle().toStdString(), "My Window"); EXPECT_EQ(w->pos(), QPoint(10, 10)); closeWindow(w); } TEST(TestWindow, DISABLED_test_set_active_window) { Window w1 = openWindow(300, 300, "My Window", 10, 10); Window w2 = openGLWindow(300, 300, "My GL Window", 10, 10); // TODO: FIXME. //Window w3 = openGraphicsView(300, 300, "My Graphics View", 10, 10); EXPECT_EQ(w1, getActiveWindow()); setActiveWindow(w2); EXPECT_EQ(w2, getActiveWindow()); // TODO: FIXME. //setActiveWindow(w3); //EXPECT_EQ(w3, getActiveWindow()); closeWindow(w1); closeWindow(w2); // TODO: FIXME. //closeWindow(w3); } TEST(TestWindow, DISABLED_test_resize_window) { Window w = openWindow(300, 300, "My Window", 10, 10); EXPECT_EQ(w, getActiveWindow()); EXPECT_EQ(getWindowSizes(w), Vector2i(300, 300)); fillCircle(100, 100, 30, Red8); resizeWindow(500, 500); EXPECT_EQ(getWindowSizes(w), Vector2i(500, 500)); fillCircle(100, 100, 30, Red8); } #undef main int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #else #include "event_scheduler.hpp" EventScheduler *global_scheduler; class TestSleepFunctions: public testing::Test { protected: Window test_window_; TestSleepFunctions() { test_window_ = openWindow(300, 300); } virtual ~TestSleepFunctions() { closeWindow(test_window_); } }; TEST_F(TestSleepFunctions, test_milliSleep) { } int worker_thread_task(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #undef main int main(int argc, char **argv) { // Create Qt Application. GraphicsApplication gui_app_(argc, argv); // Create an event scheduler on the GUI thread. global_scheduler = new EventScheduler; // Connect the user thread and the event scheduler. QObject::connect(&getUserThread(), SIGNAL(sendEvent(QEvent *, int)), global_scheduler, SLOT(schedule_event(QEvent*, int))); // Run the worker thread gui_app_.registerUserMain(worker_thread_task); int return_code = gui_app_.exec(); // Cleanup and terminate delete global_scheduler; return return_code; } #endif<|endoftext|>
<commit_before>#include "pubsub_man.h" #include "event_loop.h" #include "log_macros.h" #include "WampTypes.h" #include "SessionMan.h" #include "kernel.h" #include "wamp_utils.h" #include <list> #include <iostream> namespace XXX { /* Thread safety for pubsub. Currently the public methods: - inbound_publish - subscribe ... are both called on the event loop thead, so presently no need for any synchronization around the managed topics. Additionally for the addition of a new subscriber, the synchronization of the initially snapshot followed by updates is also acheived through the single threaded approach. */ struct managed_topic { std::vector< std::weak_ptr<wamp_session> > m_subscribers; // current upto date image of the value jalson::json_value image; // Note, we are tieing the subscription ID direct to the topic. WAMP does // allow this, and it has the benefit that we can perform a single message // serialisation for all subscribers. Might have to change later if more // complex subscription features are supported. size_t subscription_id; managed_topic(size_t __subscription_id) : subscription_id(__subscription_id) { } uint64_t next_publication_id() { return m_id_gen.next(); } private: global_scope_id_generator m_id_gen; }; /* Constructor */ pubsub_man::pubsub_man(kernel& k) : __logger(k.get_logger()), m_next_subscription_id(1) /* zero used for initial snapshot */ { } pubsub_man::~pubsub_man() { // destructor needed here so that unique_ptr can see the definition of // managed_topic } /* static bool compare_session(const session_handle& p1, const session_handle& p2) { return ( !p1.owner_before(p2) && !p2.owner_before(p1) ); } */ managed_topic* pubsub_man::find_topic(const std::string& topic, const std::string& realm, bool allow_create) { auto realm_iter = m_topics.find( realm ); if (realm_iter == m_topics.end()) { if (allow_create) { auto result = m_topics.insert(std::make_pair(realm, topic_registry())); realm_iter = result.first; } else return nullptr; } auto topic_iter = realm_iter->second.find( topic ); if (topic_iter == realm_iter->second.end()) { if (allow_create) { std::unique_ptr<managed_topic> ptr(new managed_topic(m_next_subscription_id++)); auto result = realm_iter->second.insert(std::make_pair(topic, std::move( ptr ))); topic_iter = result.first; } else return nullptr; } return topic_iter->second.get(); } void pubsub_man::update_topic(const std::string& topic, const std::string& realm, jalson::json_object options, wamp_args args) { /* EVENT thread */ // resolve topic managed_topic* mt = find_topic(topic, realm, true); // TODO: do we want to reply to the originating client, if we reject the // publish? Also, we can have other exceptions (below), e.g., patch // exceptions. Also, dont want to throw, if it is an internal update if (!mt) return; if (options.find("_p") != options.end() && args.args_list.is_array()) { // apply the patch std::cout << "@" << topic << ", patch\n"; std::cout << "BEFORE: " << mt->image << "\n"; std::cout << "PATCH : " << args.args_list << "\n"; jalson::json_array & change = args.args_list.as_array(); mt->image.patch(change[0].as_array()); std::cout << "AFTER : " << mt->image << "\n"; std::cout << "-------\n"; } // broadcast event to subscribers jalson::json_array msg; msg.reserve(6); msg.push_back( EVENT ); msg.push_back( mt->subscription_id ); msg.push_back( mt->next_publication_id() ); msg.push_back( std::move(options) ); if (!args.args_list.is_null()) { msg.push_back( args.args_list ); if (!args.args_dict.is_null()) msg.push_back( args.args_dict ); } size_t num_active = 0; for (auto & item : mt->m_subscribers) { if (auto sp = item.lock()) { sp->send_msg(msg); num_active++; } } // remove any expired sessions if (num_active != mt->m_subscribers.size()) { std::vector< std::weak_ptr<wamp_session> > temp; temp.resize(num_active); for (auto item : mt->m_subscribers) { if (!item.expired()) temp.push_back( std::move(item) ); } mt->m_subscribers.swap( temp ); } } /* Handle arrival of the a PUBLISH event, targeted at a topic. This will write * to a managed topic. */ void pubsub_man::inbound_publish(std::string realm, std::string topic, jalson::json_object options, wamp_args args) { /* EV thread */ update_topic(topic, realm, std::move(options), args); } /* Add a subscription to a managed topic. Need to sync the addition of the subscriber, with the series of images and updates it sees. This is done via single threaded access to this class. */ uint64_t pubsub_man::subscribe(wamp_session* sptr, t_request_id request_id, std::string uri, jalson::json_object & options) { /* EV thread */ /* We have received an external request to subscribe to a top */ // validate the URI // TODO: implement Strict URIs if (uri.empty()) throw wamp_error(WAMP_ERROR_INVALID_URI, "URI zero length"); // find or create a topic managed_topic* mt = find_topic(uri, sptr->realm(), true); if (!mt) throw wamp_error(WAMP_ERROR_INVALID_URI); LOG_INFO("session " << sptr->unique_id() << " subscribing to '"<< uri<< "'"); /* SUBSCRIBED acknowledgement */ jalson::json_array subscribed_msg; subscribed_msg.reserve(3); subscribed_msg.push_back(SUBSCRIBED); subscribed_msg.push_back(request_id); subscribed_msg.push_back(mt->subscription_id); sptr->send_msg(subscribed_msg); /* for stateful topic must send initial snapshot */ if (options.find("_p") != options.end()) { XXX::wamp_args pub_args; pub_args.args_list = jalson::json_array(); jalson::json_array patch; jalson::json_object& operation = jalson::append_object(patch); operation["op"] = "replace"; operation["path"] = ""; /* replace whole document */ operation["value"] = mt->image; pub_args.args_list.as_array().push_back(std::move(patch)); pub_args.args_list.as_array().push_back(jalson::json_array()); // empty event jalson::json_object event_options; event_options["_p"] = options["_p"]; event_options["_snap"] = 1; jalson::json_array snapshot_msg; snapshot_msg.reserve(5); snapshot_msg.push_back( EVENT ); snapshot_msg.push_back( mt->subscription_id ); snapshot_msg.push_back( 0 ); // publication id snapshot_msg.push_back( std::move(event_options) ); snapshot_msg.push_back( pub_args.args_list ); sptr->send_msg(snapshot_msg); } mt->m_subscribers.push_back(sptr->handle()); return mt->subscription_id; } void pubsub_man::session_closed(session_handle /*sh*/) { /* EV loop */ // // design of this can be improved, ie, we should track what topics a session // // has subscribed too, rather than searching every topic. // for (auto & realm_iter : m_topics) // for (auto & item : realm_iter.second) // { // for (auto it = item.second->m_subscribers.begin(); // it != item.second->m_subscribers.end(); it++) // { // if (compare_session( *it, sh)) // { // item.second->m_subscribers.erase( it ); // break; // } // } // } } } // namespace XXX <commit_msg>log warn for failed topic update<commit_after>#include "pubsub_man.h" #include "event_loop.h" #include "log_macros.h" #include "WampTypes.h" #include "SessionMan.h" #include "kernel.h" #include "wamp_utils.h" #include <list> #include <iostream> namespace XXX { /* Thread safety for pubsub. Currently the public methods: - inbound_publish - subscribe ... are both called on the event loop thead, so presently no need for any synchronization around the managed topics. Additionally for the addition of a new subscriber, the synchronization of the initially snapshot followed by updates is also acheived through the single threaded approach. */ struct managed_topic { std::vector< std::weak_ptr<wamp_session> > m_subscribers; // current upto date image of the value jalson::json_value image; // Note, we are tieing the subscription ID direct to the topic. WAMP does // allow this, and it has the benefit that we can perform a single message // serialisation for all subscribers. Might have to change later if more // complex subscription features are supported. size_t subscription_id; managed_topic(size_t __subscription_id) : subscription_id(__subscription_id) { } uint64_t next_publication_id() { return m_id_gen.next(); } private: global_scope_id_generator m_id_gen; }; /* Constructor */ pubsub_man::pubsub_man(kernel& k) : __logger(k.get_logger()), m_next_subscription_id(1) /* zero used for initial snapshot */ { } pubsub_man::~pubsub_man() { // destructor needed here so that unique_ptr can see the definition of // managed_topic } /* static bool compare_session(const session_handle& p1, const session_handle& p2) { return ( !p1.owner_before(p2) && !p2.owner_before(p1) ); } */ managed_topic* pubsub_man::find_topic(const std::string& topic, const std::string& realm, bool allow_create) { auto realm_iter = m_topics.find( realm ); if (realm_iter == m_topics.end()) { if (allow_create) { auto result = m_topics.insert(std::make_pair(realm, topic_registry())); realm_iter = result.first; } else return nullptr; } auto topic_iter = realm_iter->second.find( topic ); if (topic_iter == realm_iter->second.end()) { if (allow_create) { std::unique_ptr<managed_topic> ptr(new managed_topic(m_next_subscription_id++)); auto result = realm_iter->second.insert(std::make_pair(topic, std::move( ptr ))); topic_iter = result.first; } else return nullptr; } return topic_iter->second.get(); } void pubsub_man::update_topic(const std::string& topic, const std::string& realm, jalson::json_object options, wamp_args args) { /* EVENT thread */ managed_topic* mt = find_topic(topic, realm, true); if (!mt) { LOG_WARN("Discarding update to non existing topic '" << topic << "'"); return; } if (options.find("_p") != options.end() && args.args_list.is_array()) { // apply the patch std::cout << "@" << topic << ", patch\n"; std::cout << "BEFORE: " << mt->image << "\n"; std::cout << "PATCH : " << args.args_list << "\n"; jalson::json_array & change = args.args_list.as_array(); mt->image.patch(change[0].as_array()); std::cout << "AFTER : " << mt->image << "\n"; std::cout << "-------\n"; } // broadcast event to subscribers jalson::json_array msg; msg.reserve(6); msg.push_back( EVENT ); msg.push_back( mt->subscription_id ); msg.push_back( mt->next_publication_id() ); msg.push_back( std::move(options) ); if (!args.args_list.is_null()) { msg.push_back( args.args_list ); if (!args.args_dict.is_null()) msg.push_back( args.args_dict ); } size_t num_active = 0; for (auto & item : mt->m_subscribers) { if (auto sp = item.lock()) { sp->send_msg(msg); num_active++; } } // remove any expired sessions if (num_active != mt->m_subscribers.size()) { std::vector< std::weak_ptr<wamp_session> > temp; temp.resize(num_active); for (auto item : mt->m_subscribers) { if (!item.expired()) temp.push_back( std::move(item) ); } mt->m_subscribers.swap( temp ); } } /* Handle arrival of the a PUBLISH event, targeted at a topic. This will write * to a managed topic. */ void pubsub_man::inbound_publish(std::string realm, std::string topic, jalson::json_object options, wamp_args args) { /* EV thread */ update_topic(topic, realm, std::move(options), args); } /* Add a subscription to a managed topic. Need to sync the addition of the subscriber, with the series of images and updates it sees. This is done via single threaded access to this class. */ uint64_t pubsub_man::subscribe(wamp_session* sptr, t_request_id request_id, std::string uri, jalson::json_object & options) { /* EV thread */ /* We have received an external request to subscribe to a top */ // validate the URI // TODO: implement Strict URIs if (uri.empty()) throw wamp_error(WAMP_ERROR_INVALID_URI, "URI zero length"); // find or create a topic managed_topic* mt = find_topic(uri, sptr->realm(), true); if (!mt) throw wamp_error(WAMP_ERROR_INVALID_URI); LOG_INFO("session " << sptr->unique_id() << " subscribing to '"<< uri<< "'"); /* SUBSCRIBED acknowledgement */ jalson::json_array subscribed_msg; subscribed_msg.reserve(3); subscribed_msg.push_back(SUBSCRIBED); subscribed_msg.push_back(request_id); subscribed_msg.push_back(mt->subscription_id); sptr->send_msg(subscribed_msg); /* for stateful topic must send initial snapshot */ if (options.find("_p") != options.end()) { XXX::wamp_args pub_args; pub_args.args_list = jalson::json_array(); jalson::json_array patch; jalson::json_object& operation = jalson::append_object(patch); operation["op"] = "replace"; operation["path"] = ""; /* replace whole document */ operation["value"] = mt->image; pub_args.args_list.as_array().push_back(std::move(patch)); pub_args.args_list.as_array().push_back(jalson::json_array()); // empty event jalson::json_object event_options; event_options["_p"] = options["_p"]; event_options["_snap"] = 1; jalson::json_array snapshot_msg; snapshot_msg.reserve(5); snapshot_msg.push_back( EVENT ); snapshot_msg.push_back( mt->subscription_id ); snapshot_msg.push_back( 0 ); // publication id snapshot_msg.push_back( std::move(event_options) ); snapshot_msg.push_back( pub_args.args_list ); sptr->send_msg(snapshot_msg); } mt->m_subscribers.push_back(sptr->handle()); return mt->subscription_id; } void pubsub_man::session_closed(session_handle /*sh*/) { /* EV loop */ // // design of this can be improved, ie, we should track what topics a session // // has subscribed too, rather than searching every topic. // for (auto & realm_iter : m_topics) // for (auto & item : realm_iter.second) // { // for (auto it = item.second->m_subscribers.begin(); // it != item.second->m_subscribers.end(); it++) // { // if (compare_session( *it, sh)) // { // item.second->m_subscribers.erase( it ); // break; // } // } // } } } // namespace XXX <|endoftext|>
<commit_before>#include "inputControl.hpp" // Implementation headers #include "pause.hpp" #include "Ghost.hpp" typedef GameData::io_bools _bools; static void handleEvent_keyDown(GameData &d, SDL_Event &event, _bools&); static void handleEvent_keyUp(GameData &d, SDL_Event &event, _bools&); static void inputControl(GameData &, _bools &); static void enableGhostInput(GameData &, Ghost*, _bools &); static void disableGhostInput(GameData &, Ghost*, _bools &); static void inputControl(GameData &d, _bools &bools) { SDL_Event event; if (!SDL_PollEvent(&event)) return; // no new event switch (event.type) { case SDL_QUIT : bools.exit = true; break; case SDL_KEYDOWN : handleEvent_keyDown(d, event, bools); break; case SDL_KEYUP : handleEvent_keyUp(d, event, bools); break; default : ; } } // inputControl static void enableGhostInput(GameData &d, Ghost *g, _bools &bools) { g->setControlled(true); d.ghost.player2 = g; bools.second_player = true; }// enableGhostInput static void disableGhostInput(GameData &d, Ghost *g, _bools &bools) { g->setControlled(false); bools.second_player = false; }// disableGhostInput void handleEvent_keyDown(GameData &d, SDL_Event &event, _bools &bools) { enum ActorMovement::move_t pressed = ActorMovement::NOWHERE, pressed2 = ActorMovement::NOWHERE; switch (event.key.keysym.sym) { // Pacman actor directive buttons -- notify ActorMovement case SDLK_UP : pressed = ActorMovement::UP; break; case SDLK_DOWN : pressed = ActorMovement::DOWN; break; case SDLK_LEFT : pressed = ActorMovement::LEFT; break; case SDLK_RIGHT : pressed = ActorMovement::RIGHT; break; // ------------------------------------------------------ // Ghost actor directive buttons -- notify ActorMovement case SDLK_w : pressed2 = ActorMovement::UP; break; case SDLK_s : pressed2 = ActorMovement::DOWN; break; case SDLK_a : pressed2 = ActorMovement::LEFT; break; case SDLK_d : pressed2 = ActorMovement::RIGHT; break; // ------------------------------------------------------ // Exit -- notify and return case SDLK_ESCAPE : bools.exit = true; return; // ------------------------------------------------------ // Pause -- notify and return case SDLK_p : // do stuff only if not in theatre mode if (!bools.theatre_mode) cleanPause(d, bools.paused); return; // ------------------------------------------------------ // Enabling second player -- probably temporary case SDLK_2 : enableGhostInput(d, d.ghost.stalker, bools); // ------------------------------------------------------ default: return ; // nothing } if (bools.paused) { // paused-mode input processing } else if (bools.theatre_mode) { // theatre mode - no movement still } else { // running-mode input processing d.akmovs[d.pacman]->pressed(pressed, d.currTime); if(bools.second_player) d.akmovs[d.ghost.player2]->pressed(pressed2, d.currTime); } } void handleEvent_keyUp(GameData &d, SDL_Event &event, _bools &bools) { enum ActorMovement::move_t released = ActorMovement::NOWHERE, released2 = ActorMovement::NOWHERE; switch (event.key.keysym.sym) { // Pacman actor directive buttons -- notify ActorMovement case SDLK_UP : released = ActorMovement::UP; break; case SDLK_DOWN : released = ActorMovement::DOWN; break; case SDLK_LEFT : released = ActorMovement::LEFT; break; case SDLK_RIGHT : released = ActorMovement::RIGHT; break; // ------------------------------------------------------ // Ghost actor directive buttons -- notify ActorMovement case SDLK_w : released2 = ActorMovement::UP; break; case SDLK_s : released2 = ActorMovement::DOWN; break; case SDLK_a : released2 = ActorMovement::LEFT; break; case SDLK_d : released2 = ActorMovement::RIGHT; break; // ------------------------------------------------------ default: return ; // nothing } if (bools.paused) { // paused-mode input processing } else if (bools.theatre_mode) { // theatre mode - no movement issue } else { // running-mode input processing d.akmovs[d.pacman]->released(released, d.currTime); if(bools.second_player) d.akmovs[d.ghost.player2]->released(released2, d.currTime); } } InputControl::InputControl(GameData &_d) : d(_d) { } InputControl::~InputControl(void) { } InputControl::result_type InputControl::operator () (argument_type) { inputControl(d, *d.bools); } <commit_msg>Removed ghost parameter from disableGhostInput. It now used the last ghost.<commit_after>#include "inputControl.hpp" // Implementation headers #include "pause.hpp" #include "Ghost.hpp" typedef GameData::io_bools _bools; static void handleEvent_keyDown(GameData &d, SDL_Event &event, _bools&); static void handleEvent_keyUp(GameData &d, SDL_Event &event, _bools&); static void inputControl(GameData &, _bools &); static void enableGhostInput(GameData &, Ghost*, _bools &); static void disableGhostInput(GameData &, _bools &); static void inputControl(GameData &d, _bools &bools) { SDL_Event event; if (!SDL_PollEvent(&event)) return; // no new event switch (event.type) { case SDL_QUIT : bools.exit = true; break; case SDL_KEYDOWN : handleEvent_keyDown(d, event, bools); break; case SDL_KEYUP : handleEvent_keyUp(d, event, bools); break; default : ; } } // inputControl static void enableGhostInput(GameData &d, Ghost *g, _bools &bools) { g->setControlled(true); d.ghost.player2 = g; bools.second_player = true; }// enableGhostInput static void disableGhostInput(GameData &d, _bools &bools) { d.ghost.player2->setControlled(false); bools.second_player = false; }// disableGhostInput void handleEvent_keyDown(GameData &d, SDL_Event &event, _bools &bools) { enum ActorMovement::move_t pressed = ActorMovement::NOWHERE, pressed2 = ActorMovement::NOWHERE; switch (event.key.keysym.sym) { // Pacman actor directive buttons -- notify ActorMovement case SDLK_UP : pressed = ActorMovement::UP; break; case SDLK_DOWN : pressed = ActorMovement::DOWN; break; case SDLK_LEFT : pressed = ActorMovement::LEFT; break; case SDLK_RIGHT : pressed = ActorMovement::RIGHT; break; // ------------------------------------------------------ // Ghost actor directive buttons -- notify ActorMovement case SDLK_w : pressed2 = ActorMovement::UP; break; case SDLK_s : pressed2 = ActorMovement::DOWN; break; case SDLK_a : pressed2 = ActorMovement::LEFT; break; case SDLK_d : pressed2 = ActorMovement::RIGHT; break; // ------------------------------------------------------ // Exit -- notify and return case SDLK_ESCAPE : bools.exit = true; return; // ------------------------------------------------------ // Pause -- notify and return case SDLK_p : // do stuff only if not in theatre mode if (!bools.theatre_mode) cleanPause(d, bools.paused); return; // ------------------------------------------------------ // Enabling second player -- probably temporary case SDLK_2 : enableGhostInput(d, d.ghost.stalker, bools); // ------------------------------------------------------ default: return ; // nothing } if (bools.paused) { // paused-mode input processing } else if (bools.theatre_mode) { // theatre mode - no movement still } else { // running-mode input processing d.akmovs[d.pacman]->pressed(pressed, d.currTime); if(bools.second_player) d.akmovs[d.ghost.player2]->pressed(pressed2, d.currTime); } } void handleEvent_keyUp(GameData &d, SDL_Event &event, _bools &bools) { enum ActorMovement::move_t released = ActorMovement::NOWHERE, released2 = ActorMovement::NOWHERE; switch (event.key.keysym.sym) { // Pacman actor directive buttons -- notify ActorMovement case SDLK_UP : released = ActorMovement::UP; break; case SDLK_DOWN : released = ActorMovement::DOWN; break; case SDLK_LEFT : released = ActorMovement::LEFT; break; case SDLK_RIGHT : released = ActorMovement::RIGHT; break; // ------------------------------------------------------ // Ghost actor directive buttons -- notify ActorMovement case SDLK_w : released2 = ActorMovement::UP; break; case SDLK_s : released2 = ActorMovement::DOWN; break; case SDLK_a : released2 = ActorMovement::LEFT; break; case SDLK_d : released2 = ActorMovement::RIGHT; break; // ------------------------------------------------------ default: return ; // nothing } if (bools.paused) { // paused-mode input processing } else if (bools.theatre_mode) { // theatre mode - no movement issue } else { // running-mode input processing d.akmovs[d.pacman]->released(released, d.currTime); if(bools.second_player) d.akmovs[d.ghost.player2]->released(released2, d.currTime); } } InputControl::InputControl(GameData &_d) : d(_d) { } InputControl::~InputControl(void) { } InputControl::result_type InputControl::operator () (argument_type) { inputControl(d, *d.bools); } <|endoftext|>
<commit_before>#include "js_helpers.h" #include "common/RhodesApp.h" #include "net/URI.h" #include "logging/RhoLog.h" #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "js_helper" namespace rho { namespace apiGenerator { using namespace rho::json; static rho::Hashtable<rho::String,Func_JS> g_hashJSStaticMethods; static rho::Hashtable<rho::String,Func_JS> g_hashJSInstanceMethods; static const String ID("id"); static const String METHOD("method"); static const String RHO_CLASS("__rhoClass"); static const String RHO_ID("__rhoID"); static const String RHO_CALLBACK("__rhoCallback"); static const String VM_ID("vmID"); static const String RHO_CALLBACK_PARAM("optParams"); void js_define_static_method(const char* szMethodPath, Func_JS pFunc ) { g_hashJSStaticMethods[szMethodPath] = pFunc; RAWTRACE1("Static method: %s", szMethodPath); } void js_define_instance_method(const char* szMethodPath, Func_JS pFunc ) { g_hashJSInstanceMethods[szMethodPath] = pFunc; RAWTRACE1("Instance method: %s", szMethodPath); } rho::String js_entry_point(const char* szJSON) { RAWTRACE(szJSON); rho::String strReqId, strMethod, strObjID, strCallbackID, strJsVmID, strCallbackParam; CJSONEntry oEntry(szJSON); if ( !oEntry.hasName(ID) ) { RAWLOG_ERROR1("There is no %s string in JSON request", ID.c_str()); return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32700, \"message\": \"Parse error\"}, \"id\": null}"; } strReqId = oEntry.getString(ID.c_str()); if ( !oEntry.hasName(METHOD) ) { RAWLOG_ERROR1("There is no %s string in JSON request object", METHOD.c_str()); return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32700, \"message\": \"Parse error\"}, \"id\": " + strReqId + "}"; } strMethod = oEntry.getString(METHOD.c_str()); if ( oEntry.hasName(RHO_CLASS) ) { RAWTRACE("Parsing module class"); rho::String strModule = oEntry.getString(RHO_CLASS.c_str()); strMethod = strModule + ":" + strMethod; } if ( oEntry.hasName(RHO_ID) ) strObjID = oEntry.getString(RHO_ID.c_str()); if ( oEntry.hasName(RHO_CALLBACK) ) { RAWTRACE("Parsing callback"); CJSONEntry oCallback = oEntry.getEntry(RHO_CALLBACK.c_str()); RAWTRACE1("Got %s JSON object", RHO_CALLBACK.c_str()); if ( !oCallback.hasName(ID) ) { RAWLOG_ERROR1("There is no %s string in __rhoCallback request", ID.c_str()); return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32700, \"message\": \"Parse error\"}, \"id\": " + strReqId + "}"; } const char* pcszCallbackID = oCallback.getString(ID.c_str()); const char* pcszJsVmID = oCallback.getString(VM_ID.c_str()); const char* pcszCallbackParam = oCallback.getString(RHO_CALLBACK_PARAM.c_str()); if (pcszCallbackID) strCallbackID = pcszCallbackID; if (pcszJsVmID) strJsVmID = pcszJsVmID;//oCallback.getString(pcszJsVmID); if (pcszCallbackParam) strCallbackParam = pcszCallbackParam; } String_replace(strMethod, '.', ':'); Func_JS pMethod = NULL; if (strObjID == "0") { pMethod = g_hashJSStaticMethods[strMethod]; if (!pMethod) { RAWLOG_ERROR1("Static API method is not found: %s", strMethod.c_str()); return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32601, \"message\": \"Static method not found.\"}, \"id\": " + strReqId + "}"; } } else { pMethod = g_hashJSInstanceMethods[strMethod]; if (!pMethod) { RAWLOG_ERROR1("Instance API method is not found: %s", strMethod.c_str()); return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32601, \"message\": \"Instance method not found.\"}, \"id\": " + strReqId + "}"; } } CJSONArray oParams(oEntry.getEntry("params")); RAWTRACE3("Calling API: object: %s, method: %s, callback id: %s", strObjID.c_str(), strMethod.c_str(), strCallbackID.c_str()); String methodResult = pMethod( strObjID, oParams, strCallbackID, strJsVmID, strCallbackParam ); #ifdef RHO_DEBUG String res = "{"+methodResult+"}"; CJSONEntry jsonValidator(res.c_str()); #endif return "{\"jsonrpc\": \"2.0\", " + methodResult + ", \"id\": " + strReqId + "}"; } void rho_http_js_entry_point(void *arg, rho::String const &query ) { rho::String res = js_entry_point(query.c_str()); rho_http_sendresponse(arg, res.c_str()); } } } <commit_msg>common api: remove extra traces<commit_after>#include "js_helpers.h" #include "common/RhodesApp.h" #include "net/URI.h" #include "logging/RhoLog.h" #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "js_helper" namespace rho { namespace apiGenerator { using namespace rho::json; static rho::Hashtable<rho::String,Func_JS> g_hashJSStaticMethods; static rho::Hashtable<rho::String,Func_JS> g_hashJSInstanceMethods; static const String ID("id"); static const String METHOD("method"); static const String RHO_CLASS("__rhoClass"); static const String RHO_ID("__rhoID"); static const String RHO_CALLBACK("__rhoCallback"); static const String VM_ID("vmID"); static const String RHO_CALLBACK_PARAM("optParams"); void js_define_static_method(const char* szMethodPath, Func_JS pFunc ) { g_hashJSStaticMethods[szMethodPath] = pFunc; //RAWTRACE1("Static method: %s", szMethodPath); } void js_define_instance_method(const char* szMethodPath, Func_JS pFunc ) { g_hashJSInstanceMethods[szMethodPath] = pFunc; //RAWTRACE1("Instance method: %s", szMethodPath); } rho::String js_entry_point(const char* szJSON) { RAWTRACE(szJSON); rho::String strReqId, strMethod, strObjID, strCallbackID, strJsVmID, strCallbackParam; CJSONEntry oEntry(szJSON); if ( !oEntry.hasName(ID) ) { RAWLOG_ERROR1("There is no %s string in JSON request", ID.c_str()); return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32700, \"message\": \"Parse error\"}, \"id\": null}"; } strReqId = oEntry.getString(ID.c_str()); if ( !oEntry.hasName(METHOD) ) { RAWLOG_ERROR1("There is no %s string in JSON request object", METHOD.c_str()); return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32700, \"message\": \"Parse error\"}, \"id\": " + strReqId + "}"; } strMethod = oEntry.getString(METHOD.c_str()); if ( oEntry.hasName(RHO_CLASS) ) { RAWTRACE("Parsing module class"); rho::String strModule = oEntry.getString(RHO_CLASS.c_str()); strMethod = strModule + ":" + strMethod; } if ( oEntry.hasName(RHO_ID) ) strObjID = oEntry.getString(RHO_ID.c_str()); if ( oEntry.hasName(RHO_CALLBACK) ) { RAWTRACE("Parsing callback"); CJSONEntry oCallback = oEntry.getEntry(RHO_CALLBACK.c_str()); RAWTRACE1("Got %s JSON object", RHO_CALLBACK.c_str()); if ( !oCallback.hasName(ID) ) { RAWLOG_ERROR1("There is no %s string in __rhoCallback request", ID.c_str()); return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32700, \"message\": \"Parse error\"}, \"id\": " + strReqId + "}"; } const char* pcszCallbackID = oCallback.getString(ID.c_str()); const char* pcszJsVmID = oCallback.getString(VM_ID.c_str()); const char* pcszCallbackParam = oCallback.getString(RHO_CALLBACK_PARAM.c_str()); if (pcszCallbackID) strCallbackID = pcszCallbackID; if (pcszJsVmID) strJsVmID = pcszJsVmID;//oCallback.getString(pcszJsVmID); if (pcszCallbackParam) strCallbackParam = pcszCallbackParam; } String_replace(strMethod, '.', ':'); Func_JS pMethod = NULL; if (strObjID == "0") { pMethod = g_hashJSStaticMethods[strMethod]; if (!pMethod) { RAWLOG_ERROR1("Static API method is not found: %s", strMethod.c_str()); return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32601, \"message\": \"Static method not found.\"}, \"id\": " + strReqId + "}"; } } else { pMethod = g_hashJSInstanceMethods[strMethod]; if (!pMethod) { RAWLOG_ERROR1("Instance API method is not found: %s", strMethod.c_str()); return "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32601, \"message\": \"Instance method not found.\"}, \"id\": " + strReqId + "}"; } } CJSONArray oParams(oEntry.getEntry("params")); RAWTRACE3("Calling API: object: %s, method: %s, callback id: %s", strObjID.c_str(), strMethod.c_str(), strCallbackID.c_str()); String methodResult = pMethod( strObjID, oParams, strCallbackID, strJsVmID, strCallbackParam ); #ifdef RHO_DEBUG String res = "{"+methodResult+"}"; CJSONEntry jsonValidator(res.c_str()); #endif return "{\"jsonrpc\": \"2.0\", " + methodResult + ", \"id\": " + strReqId + "}"; } void rho_http_js_entry_point(void *arg, rho::String const &query ) { rho::String res = js_entry_point(query.c_str()); rho_http_sendresponse(arg, res.c_str()); } } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/utils/Util.h" #include "paddle/math/SparseMatrix.h" #include "paddle/utils/Error.h" #include "paddle/utils/Logging.h" #include "AddtoLayer.h" #include "CRFLayer.h" #include "CosSimLayer.h" #include "CostLayer.h" #include "DataLayer.h" #include "ExpandConvLayer.h" #include "FullyConnectedLayer.h" #include "HierarchicalSigmoidLayer.h" #include "MaxLayer.h" #include "MixedLayer.h" #include "NormLayer.h" #include "PoolLayer.h" #include "TensorLayer.h" #include "TransLayer.h" #include "ValidationLayer.h" DEFINE_bool(log_error_clipping, false, "enable log error clipping or not"); namespace paddle { Layer::Layer(const LayerConfig& config, bool useGpu) : config_(config), useGpu_(useGpu), deviceId_(CPU_DEVICE), needSequenceInfo_(true) {} bool Layer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { if (useGpu_ && FLAGS_parallel_nn) { /* gpu environment is specified by device property */ deviceId_ = config_.device(); if (deviceId_ < 0) { useGpu_ = false; } } output_.deviceId = deviceId_; for (auto& inputConfig : config_.inputs()) { std::string inputName = inputConfig.input_layer_name(); LayerPtr inputLayer; CHECK(mapGet(inputName, layerMap, &inputLayer)) << "Cannot find input layer " << inputName << " for layer " << getName(); this->addPrev(inputLayer); inputLayer->addOutputArgument(deviceId_); if (inputConfig.has_input_parameter_name()) { ParameterPtr parameter; CHECK( mapGet(inputConfig.input_parameter_name(), parameterMap, &parameter)) << "Cannot find input parameter " << inputConfig.input_parameter_name() << " for layer " << getName(); parameter->incShared(); CHECK_EQ(parameter->getDeviceId(), getDeviceId()); parameters_.push_back(parameter); } else { parameters_.push_back(nullptr); } if (inputConfig.has_input_layer_argument()) { inputArgument_.push_back(inputConfig.input_layer_argument()); } else { inputArgument_.push_back(""); } } if (config_.has_bias_parameter_name()) { CHECK(mapGet(config_.bias_parameter_name(), parameterMap, &biasParameter_)) << "Cannot find bias parameter " << config_.bias_parameter_name() << " for layer " << getName(); biasParameter_->incShared(); CHECK_EQ(biasParameter_->getDeviceId(), getDeviceId()); } /* specify the activation function according to the configuration */ std::string action_type = config_.active_type(); activation_.reset(ActivationFunction::create(action_type)); CHECK(activation_); initNeedFlags(); markInBackward_.assign(inputLayers_.size(), false); return true; } ClassRegistrar<Layer, LayerConfig> Layer::registrar_; LayerPtr Layer::create(const LayerConfig& config) { std::string type = config.type(); if (type == "multi-class-cross-entropy") return LayerPtr(new MultiClassCrossEntropy(config)); else if (type == "rank-cost") return LayerPtr(new RankingCost(config)); else if (type == "auc-validation") return LayerPtr(new AucValidation(config)); else if (type == "pnpair-validation") return LayerPtr(new PnpairValidation(config)); // NOTE: stop adding "if" statements here. // Instead, use REGISTER_LAYER to add more layer types return LayerPtr(registrar_.createByType(config.type(), config)); } void Layer::resetSpecifyOutput(Argument& output, size_t height, size_t width, bool isValueClean, bool isGradClean) { SetDevice device(output.deviceId); Matrix::resizeOrCreate( output.value, height, width, /* trans */ false, useGpu(output.deviceId)); if (isValueClean) { output.value->zeroMem(); } if (passType_ != PASS_TEST && needGradient()) { Matrix::resizeOrCreate( output.grad, height, width, /* trans */ false, useGpu(output.deviceId)); if (isGradClean) { output.grad->zeroMem(); } } } void Layer::resizeOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, false, false); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, false, false); } } void Layer::reserveOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, false, true); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, false, true); } } void Layer::resetOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, true, true); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, true, true); } } void Layer::addOutputArgument(int deviceId) { if (deviceId == deviceId_) { output_.countIncrement(); return; } else { for (size_t i = 0; i < outputOtherDevice_.size(); i++) { if (outputOtherDevice_[i].deviceId == deviceId) { outputOtherDevice_[i].countIncrement(); return; } } } Argument argu; argu.deviceId = deviceId; outputOtherDevice_.push_back(argu); outputOtherDevice_.back().countIncrement(); } void Layer::copyOutputToOtherDevice() { for (size_t i = 0; i != outputOtherDevice_.size(); i++) { SetDevice device(outputOtherDevice_[i].deviceId); // If outputOtherDevice_[i].value is a CpuMatrix, // the copyFrom is a synchronous interface. // If outputOtherDevice_[i].value is a GpuMatrix, since subsequent // calculations are all on HPPL_STREAM_DEFAULT, // copyFrom can be an asynchronous interface. outputOtherDevice_[i].value->copyFrom(*getOutputValue(), HPPL_STREAM_DEFAULT); outputOtherDevice_[i].sequenceStartPositions = output_.sequenceStartPositions; outputOtherDevice_[i].subSequenceStartPositions = output_.subSequenceStartPositions; outputOtherDevice_[i].cpuSequenceDims = output_.cpuSequenceDims; outputOtherDevice_[i].notifyValueReady(); } } void Layer::waitInputValue() { for (size_t i = 0; i != inputLayers_.size(); i++) { if (inputLayers_[i]->getDeviceId() != deviceId_) { getInput(i).waitValueReady(); } } } void Layer::waitAndMergeOutputGrad() { if (!output_.grad || !outputOtherDevice_.size()) { return; } for (size_t i = 0; i != outputOtherDevice_.size(); i++) { outputOtherDevice_[i].waitGradReady(); } /* merge output grad */ size_t i = 0; if (!output_.getAllCount()) { output_.grad->copyFrom(*outputOtherDevice_[0].grad, HPPL_STREAM_1); hl_stream_synchronize(HPPL_STREAM_1); i++; if (outputOtherDevice_.size() == 1) return; } Matrix::resizeOrCreate(tmpGrad_, output_.grad->getHeight(), output_.grad->getWidth(), /* trans */ false, useGpu(output_.deviceId)); for (; i != outputOtherDevice_.size(); i++) { tmpGrad_->copyFrom(*outputOtherDevice_[i].grad, HPPL_STREAM_1); hl_stream_synchronize(HPPL_STREAM_1); output_.grad->add(*tmpGrad_); } } void Layer::markAllInputGrad() { for (size_t i = 0; i != inputLayers_.size(); ++i) { if (!markInBackward_[i]) { inputLayers_[i]->getOutput(deviceId_).notifyGradReady(); } markInBackward_[i] = false; } } void Layer::markInputGrad(int inputIndex) { inputLayers_[inputIndex]->getOutput(deviceId_).notifyGradReady(); markInBackward_[inputIndex] = true; } void Layer::zeroGrad() { CHECK(output_.grad.get() != NULL); output_.grad->zeroMem(); } void Layer::initNeedFlags() { auto initFlag = [this]( bool& flag, bool (Layer::*flagQueryFunc)() const, ParameterType type) { flag = false; if (biasParameter_ && biasParameter_->hasType(type)) { flag = true; } if (!flag) { for (auto& para : parameters_) { if (para && para->hasType(type)) { flag = true; break; } } } if (!flag) { for (auto& layer : inputLayers_) { if ((layer.get()->*flagQueryFunc)()) { flag = true; } } } }; initFlag(needGradient_, &Layer::needGradient, PARAMETER_GRADIENT); } void Layer::showOutputStats() { MatrixPtr out = getOutputValue(); if (!out) return; if (!out->getElementCnt()) { LOG(INFO) << "The number of output of " << config_.name() << " is 0, skip to show the statistics"; return; } MatrixPtr outSquare; if (dynamic_cast<GpuSparseMatrix*>(out.get())) { GpuSparseMatrix* tmp = dynamic_cast<GpuSparseMatrix*>(out.get()); outSquare = std::make_shared<CpuSparseMatrix>(tmp->getHeight(), tmp->getWidth(), tmp->getElementCnt(), tmp->getValueType(), tmp->getFormat()); } else { outSquare = out->clone(); } outSquare->copyFrom(*out, HPPL_STREAM_DEFAULT); hl_stream_synchronize(HPPL_STREAM_DEFAULT); real mean = outSquare->getSum() / out->getElementCnt(); real min; real max; if (dynamic_cast<CpuSparseMatrix*>(outSquare.get())) { auto tmpMat = dynamic_cast<CpuSparseMatrix*>(outSquare.get()); min = tmpMat->getMin(); max = tmpMat->getMax(); tmpMat->square2(); LOG(INFO) << "show statistics of [none zero values] in sparse matrix"; } else { min = outSquare->getMin(); max = outSquare->getMax(); outSquare->square2(); } real std = (outSquare->getSum() / outSquare->getElementCnt()) - mean * mean; std = std > 0 ? std : 0; LOG(INFO) << "The output state of " << config_.name() << ": mean=" << mean << ", " << "std=" << std << ", " << "min=" << min << ", " << "max=" << max; } void Layer::forwardActivation() { /* activation */ auto status = activation_->forward(output_); status.check(); /* dropout */ if (config_.drop_rate() > 0) { forwardDropOut(); CHECK_NE(activation_->getName(), "softmax") << "Softmax activation cannot be used with Dropout"; } if (FLAGS_show_layer_stat) { showOutputStats(); } } void Layer::backwardActivation() { /* Do error clipping */ if (config_.error_clipping_threshold() > 0.0f) { if (FLAGS_log_error_clipping) { VectorPtr outGradVec = Vector::create( output_.grad->getData(), output_.grad->getElementCnt(), useGpu_); real maxAbsGrad = outGradVec->getAbsMax(); if (maxAbsGrad > config_.error_clipping_threshold()) { real avgAbsGrad = outGradVec->getAbsSum() / outGradVec->getSize(); LOG(INFO) << " layer=" << config_.name() << " need clipping," << " max error=" << maxAbsGrad << " avg error=" << avgAbsGrad; } } output_.grad->clip(-config_.error_clipping_threshold(), config_.error_clipping_threshold()); } /* Do dropout for delta*/ if (config_.drop_rate() > 0 && passType_ != PASS_TEST) { MatrixPtr oGrad = getOutputGrad(); oGrad->dotMul(*oGrad, *dropOutMask_); } auto status = activation_->backward(output_); status.check(); } void Layer::forwardDropOut() { auto& outV = getOutputValue(); if (passType_ == PASS_TRAIN) { // new dropOutMask_ if dropOutMask_ is null ptr Matrix::resizeOrCreate(dropOutMask_, outV->getHeight(), outV->getWidth(), false, useGpu(deviceId_)); dropOutMask_->randomizeUniform(); // generate a uniform random matrix dropOutMask_->biggerThanScalar(config_.drop_rate()); // random mask outV->dotMul(*outV, *dropOutMask_); // dropout } else if (passType_ == PASS_GC) { // only initialize once if (!dropOutMask_) { dropOutMask_ = Matrix::create( outV->getHeight(), outV->getWidth(), false, useGpu(deviceId_)); // We use cpu matrix to generate mask so that the mask // will be same for both gpu version and cpu version. // This will help unittest to make sure they have same result. MatrixPtr tmpMask = Matrix::create(outV->getHeight(), outV->getWidth()); tmpMask->randomizeUniform(); // generate a uniform random matrix tmpMask->biggerThanScalar(config_.drop_rate()); // random mask dropOutMask_->copyFrom(*tmpMask); } outV->dotMul(*outV, *dropOutMask_); } else { // passType == PASS_TEST outV->mulScalar(1.0 - config_.drop_rate()); } } } // namespace paddle <commit_msg>remove unused XXXLayer.h in Layer.cpp<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/utils/Util.h" #include "Layer.h" #include "paddle/math/SparseMatrix.h" #include "paddle/utils/Error.h" #include "paddle/utils/Logging.h" DEFINE_bool(log_error_clipping, false, "enable log error clipping or not"); namespace paddle { Layer::Layer(const LayerConfig& config, bool useGpu) : config_(config), useGpu_(useGpu), deviceId_(CPU_DEVICE), needSequenceInfo_(true) {} bool Layer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { if (useGpu_ && FLAGS_parallel_nn) { /* gpu environment is specified by device property */ deviceId_ = config_.device(); if (deviceId_ < 0) { useGpu_ = false; } } output_.deviceId = deviceId_; for (auto& inputConfig : config_.inputs()) { std::string inputName = inputConfig.input_layer_name(); LayerPtr inputLayer; CHECK(mapGet(inputName, layerMap, &inputLayer)) << "Cannot find input layer " << inputName << " for layer " << getName(); this->addPrev(inputLayer); inputLayer->addOutputArgument(deviceId_); if (inputConfig.has_input_parameter_name()) { ParameterPtr parameter; CHECK( mapGet(inputConfig.input_parameter_name(), parameterMap, &parameter)) << "Cannot find input parameter " << inputConfig.input_parameter_name() << " for layer " << getName(); parameter->incShared(); CHECK_EQ(parameter->getDeviceId(), getDeviceId()); parameters_.push_back(parameter); } else { parameters_.push_back(nullptr); } if (inputConfig.has_input_layer_argument()) { inputArgument_.push_back(inputConfig.input_layer_argument()); } else { inputArgument_.push_back(""); } } if (config_.has_bias_parameter_name()) { CHECK(mapGet(config_.bias_parameter_name(), parameterMap, &biasParameter_)) << "Cannot find bias parameter " << config_.bias_parameter_name() << " for layer " << getName(); biasParameter_->incShared(); CHECK_EQ(biasParameter_->getDeviceId(), getDeviceId()); } /* specify the activation function according to the configuration */ std::string action_type = config_.active_type(); activation_.reset(ActivationFunction::create(action_type)); CHECK(activation_); initNeedFlags(); markInBackward_.assign(inputLayers_.size(), false); return true; } ClassRegistrar<Layer, LayerConfig> Layer::registrar_; LayerPtr Layer::create(const LayerConfig& config) { std::string type = config.type(); return LayerPtr(registrar_.createByType(config.type(), config)); } void Layer::resetSpecifyOutput(Argument& output, size_t height, size_t width, bool isValueClean, bool isGradClean) { SetDevice device(output.deviceId); Matrix::resizeOrCreate( output.value, height, width, /* trans */ false, useGpu(output.deviceId)); if (isValueClean) { output.value->zeroMem(); } if (passType_ != PASS_TEST && needGradient()) { Matrix::resizeOrCreate( output.grad, height, width, /* trans */ false, useGpu(output.deviceId)); if (isGradClean) { output.grad->zeroMem(); } } } void Layer::resizeOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, false, false); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, false, false); } } void Layer::reserveOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, false, true); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, false, true); } } void Layer::resetOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, true, true); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, true, true); } } void Layer::addOutputArgument(int deviceId) { if (deviceId == deviceId_) { output_.countIncrement(); return; } else { for (size_t i = 0; i < outputOtherDevice_.size(); i++) { if (outputOtherDevice_[i].deviceId == deviceId) { outputOtherDevice_[i].countIncrement(); return; } } } Argument argu; argu.deviceId = deviceId; outputOtherDevice_.push_back(argu); outputOtherDevice_.back().countIncrement(); } void Layer::copyOutputToOtherDevice() { for (size_t i = 0; i != outputOtherDevice_.size(); i++) { SetDevice device(outputOtherDevice_[i].deviceId); // If outputOtherDevice_[i].value is a CpuMatrix, // the copyFrom is a synchronous interface. // If outputOtherDevice_[i].value is a GpuMatrix, since subsequent // calculations are all on HPPL_STREAM_DEFAULT, // copyFrom can be an asynchronous interface. outputOtherDevice_[i].value->copyFrom(*getOutputValue(), HPPL_STREAM_DEFAULT); outputOtherDevice_[i].sequenceStartPositions = output_.sequenceStartPositions; outputOtherDevice_[i].subSequenceStartPositions = output_.subSequenceStartPositions; outputOtherDevice_[i].cpuSequenceDims = output_.cpuSequenceDims; outputOtherDevice_[i].notifyValueReady(); } } void Layer::waitInputValue() { for (size_t i = 0; i != inputLayers_.size(); i++) { if (inputLayers_[i]->getDeviceId() != deviceId_) { getInput(i).waitValueReady(); } } } void Layer::waitAndMergeOutputGrad() { if (!output_.grad || !outputOtherDevice_.size()) { return; } for (size_t i = 0; i != outputOtherDevice_.size(); i++) { outputOtherDevice_[i].waitGradReady(); } /* merge output grad */ size_t i = 0; if (!output_.getAllCount()) { output_.grad->copyFrom(*outputOtherDevice_[0].grad, HPPL_STREAM_1); hl_stream_synchronize(HPPL_STREAM_1); i++; if (outputOtherDevice_.size() == 1) return; } Matrix::resizeOrCreate(tmpGrad_, output_.grad->getHeight(), output_.grad->getWidth(), /* trans */ false, useGpu(output_.deviceId)); for (; i != outputOtherDevice_.size(); i++) { tmpGrad_->copyFrom(*outputOtherDevice_[i].grad, HPPL_STREAM_1); hl_stream_synchronize(HPPL_STREAM_1); output_.grad->add(*tmpGrad_); } } void Layer::markAllInputGrad() { for (size_t i = 0; i != inputLayers_.size(); ++i) { if (!markInBackward_[i]) { inputLayers_[i]->getOutput(deviceId_).notifyGradReady(); } markInBackward_[i] = false; } } void Layer::markInputGrad(int inputIndex) { inputLayers_[inputIndex]->getOutput(deviceId_).notifyGradReady(); markInBackward_[inputIndex] = true; } void Layer::zeroGrad() { CHECK(output_.grad.get() != NULL); output_.grad->zeroMem(); } void Layer::initNeedFlags() { auto initFlag = [this]( bool& flag, bool (Layer::*flagQueryFunc)() const, ParameterType type) { flag = false; if (biasParameter_ && biasParameter_->hasType(type)) { flag = true; } if (!flag) { for (auto& para : parameters_) { if (para && para->hasType(type)) { flag = true; break; } } } if (!flag) { for (auto& layer : inputLayers_) { if ((layer.get()->*flagQueryFunc)()) { flag = true; } } } }; initFlag(needGradient_, &Layer::needGradient, PARAMETER_GRADIENT); } void Layer::showOutputStats() { MatrixPtr out = getOutputValue(); if (!out) return; if (!out->getElementCnt()) { LOG(INFO) << "The number of output of " << config_.name() << " is 0, skip to show the statistics"; return; } MatrixPtr outSquare; if (dynamic_cast<GpuSparseMatrix*>(out.get())) { GpuSparseMatrix* tmp = dynamic_cast<GpuSparseMatrix*>(out.get()); outSquare = std::make_shared<CpuSparseMatrix>(tmp->getHeight(), tmp->getWidth(), tmp->getElementCnt(), tmp->getValueType(), tmp->getFormat()); } else { outSquare = out->clone(); } outSquare->copyFrom(*out, HPPL_STREAM_DEFAULT); hl_stream_synchronize(HPPL_STREAM_DEFAULT); real mean = outSquare->getSum() / out->getElementCnt(); real min; real max; if (dynamic_cast<CpuSparseMatrix*>(outSquare.get())) { auto tmpMat = dynamic_cast<CpuSparseMatrix*>(outSquare.get()); min = tmpMat->getMin(); max = tmpMat->getMax(); tmpMat->square2(); LOG(INFO) << "show statistics of [none zero values] in sparse matrix"; } else { min = outSquare->getMin(); max = outSquare->getMax(); outSquare->square2(); } real std = (outSquare->getSum() / outSquare->getElementCnt()) - mean * mean; std = std > 0 ? std : 0; LOG(INFO) << "The output state of " << config_.name() << ": mean=" << mean << ", " << "std=" << std << ", " << "min=" << min << ", " << "max=" << max; } void Layer::forwardActivation() { /* activation */ auto status = activation_->forward(output_); status.check(); /* dropout */ if (config_.drop_rate() > 0) { forwardDropOut(); CHECK_NE(activation_->getName(), "softmax") << "Softmax activation cannot be used with Dropout"; } if (FLAGS_show_layer_stat) { showOutputStats(); } } void Layer::backwardActivation() { /* Do error clipping */ if (config_.error_clipping_threshold() > 0.0f) { if (FLAGS_log_error_clipping) { VectorPtr outGradVec = Vector::create( output_.grad->getData(), output_.grad->getElementCnt(), useGpu_); real maxAbsGrad = outGradVec->getAbsMax(); if (maxAbsGrad > config_.error_clipping_threshold()) { real avgAbsGrad = outGradVec->getAbsSum() / outGradVec->getSize(); LOG(INFO) << " layer=" << config_.name() << " need clipping," << " max error=" << maxAbsGrad << " avg error=" << avgAbsGrad; } } output_.grad->clip(-config_.error_clipping_threshold(), config_.error_clipping_threshold()); } /* Do dropout for delta*/ if (config_.drop_rate() > 0 && passType_ != PASS_TEST) { MatrixPtr oGrad = getOutputGrad(); oGrad->dotMul(*oGrad, *dropOutMask_); } auto status = activation_->backward(output_); status.check(); } void Layer::forwardDropOut() { auto& outV = getOutputValue(); if (passType_ == PASS_TRAIN) { // new dropOutMask_ if dropOutMask_ is null ptr Matrix::resizeOrCreate(dropOutMask_, outV->getHeight(), outV->getWidth(), false, useGpu(deviceId_)); dropOutMask_->randomizeUniform(); // generate a uniform random matrix dropOutMask_->biggerThanScalar(config_.drop_rate()); // random mask outV->dotMul(*outV, *dropOutMask_); // dropout } else if (passType_ == PASS_GC) { // only initialize once if (!dropOutMask_) { dropOutMask_ = Matrix::create( outV->getHeight(), outV->getWidth(), false, useGpu(deviceId_)); // We use cpu matrix to generate mask so that the mask // will be same for both gpu version and cpu version. // This will help unittest to make sure they have same result. MatrixPtr tmpMask = Matrix::create(outV->getHeight(), outV->getWidth()); tmpMask->randomizeUniform(); // generate a uniform random matrix tmpMask->biggerThanScalar(config_.drop_rate()); // random mask dropOutMask_->copyFrom(*tmpMask); } outV->dotMul(*outV, *dropOutMask_); } else { // passType == PASS_TEST outV->mulScalar(1.0 - config_.drop_rate()); } } } // namespace paddle <|endoftext|>
<commit_before>#include "datastream_ROS.h" #include <QTextStream> #include <QFile> #include <QMessageBox> #include <QDebug> #include <thread> #include <mutex> #include <chrono> #include <thread> #include <QProgressDialog> #include <QtGlobal> #include <QApplication> #include <QProcess> #include <QCheckBox> #include <QSettings> #include <QFileDialog> #include <ros/callback_queue.h> #include <rosbag/bag.h> #include <topic_tools/shape_shifter.h> #include <ros/transport_hints.h> #include "../dialog_select_ros_topics.h" #include "../rule_editing.h" #include "../qnodedialog.h" #include "../shape_shifter_factory.hpp" DataStreamROS::DataStreamROS(): DataStreamer(), _node(nullptr), _destination_data(nullptr), _action_saveIntoRosbag(nullptr), _prev_clock_time(0) { _running = false; _periodic_timer = new QTimer(); connect( _periodic_timer, &QTimer::timeout, this, &DataStreamROS::timerCallback); loadDefaultSettings(); } void DataStreamROS::topicCallback(const topic_tools::ShapeShifter::ConstPtr& msg, const std::string &topic_name) { if( !_running ){ return; } using namespace RosIntrospection; const auto& md5sum = msg->getMD5Sum(); const auto& datatype = msg->getDataType(); const auto& definition = msg->getMessageDefinition() ; // register the message type _ros_parser.registerSchema( topic_name, md5sum, RosIntrospection::ROSType(datatype), definition); RosIntrospectionFactory::registerMessage(topic_name, md5sum, datatype, definition ); //------------------------------------ // it is more efficient to recycle this elements static std::vector<uint8_t> buffer; buffer.resize( msg->size() ); ros::serialization::OStream stream(buffer.data(), buffer.size()); msg->write(stream); double msg_time = ros::Time::now().toSec(); if( msg_time < _prev_clock_time ) { // clean for (auto& it: dataMap().numeric ) { it.second.clear(); auto dst = _destination_data->numeric.find(it.first); if( dst != _destination_data->numeric.end()){ dst->second.clear(); } } for (auto& it: dataMap().user_defined ){ it.second.clear(); auto dst = _destination_data->user_defined.find(it.first); if( dst != _destination_data->user_defined.end()){ dst->second.clear(); } } } _prev_clock_time = msg_time; MessageRef buffer_view( buffer ); _ros_parser.pushMessageRef( topic_name, buffer_view, msg_time ); std::lock_guard<std::mutex> lock( mutex() ); const std::string prefixed_topic_name = _prefix + topic_name; // adding raw serialized msg for future uses. // do this before msg_time normalization { auto plot_pair = dataMap().user_defined.find( prefixed_topic_name ); if( plot_pair == dataMap().user_defined.end() ) { plot_pair = dataMap().addUserDefined( prefixed_topic_name ); } PlotDataAny& user_defined_data = plot_pair->second; user_defined_data.pushBack( PlotDataAny::Point(msg_time, nonstd::any(std::move(buffer)) )); } _ros_parser.extractData(dataMap(), _prefix); //------------------------------ { int& index = _msg_index[topic_name]; index++; const std::string key = prefixed_topic_name + ("/_MSG_INDEX_") ; auto index_it = dataMap().numeric.find(key); if( index_it == dataMap().numeric.end()) { index_it = dataMap().addNumeric( key ); } index_it->second.pushBack( PlotData::Point(msg_time, index) ); } } void DataStreamROS::extractInitialSamples() { using namespace std::chrono; milliseconds wait_time_ms(1000); QProgressDialog progress_dialog; progress_dialog.setLabelText( "Collecting ROS topic samples to understand data layout. "); progress_dialog.setRange(0, wait_time_ms.count()); progress_dialog.setAutoClose(true); progress_dialog.setAutoReset(true); progress_dialog.show(); auto start_time = system_clock::now(); while ( system_clock::now() - start_time < (wait_time_ms) ) { ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(0.1)); int i = duration_cast<milliseconds>(system_clock::now() - start_time).count() ; progress_dialog.setValue( i ); QApplication::processEvents(); if( progress_dialog.wasCanceled() ) { break; } } if( progress_dialog.wasCanceled() == false ) { progress_dialog.cancel(); } } void DataStreamROS::timerCallback() { if( _running && ros::master::check() == false && !_roscore_disconnection_already_notified) { auto ret = QMessageBox::warning(nullptr, tr("Disconnected!"), tr("The roscore master cannot be detected.\n\n" "Do you want to try reconnecting to it? \n\n" "NOTE: if you select CONTINUE, you might need" " to stop and restart this plugin."), tr("Stop Plugin"), tr("Try reconnect"), tr("Continue"), 0); _roscore_disconnection_already_notified = ( ret == 2 ); if( ret == 1 ) { this->shutdown(); _node = RosManager::getNode(); if( !_node ){ emit connectionClosed(); return; } subscribe(); _running = true; _spinner = std::make_shared<ros::AsyncSpinner>(1); _spinner->start(); _periodic_timer->start(); } else if( ret == 0) { this->shutdown(); emit connectionClosed(); } } } void DataStreamROS::saveIntoRosbag(const PlotDataMapRef& data) { if( data.user_defined.empty()){ QMessageBox::warning(nullptr, tr("Warning"), tr("Your buffer is empty. Nothing to save.\n") ); return; } QFileDialog saveDialog; saveDialog.setAcceptMode(QFileDialog::AcceptSave); saveDialog.setDefaultSuffix("bag"); saveDialog.exec(); if(saveDialog.result() != QDialog::Accepted || saveDialog.selectedFiles().empty()) { return; } QString fileName = saveDialog.selectedFiles().first(); if( fileName.size() > 0) { rosbag::Bag rosbag(fileName.toStdString(), rosbag::bagmode::Write ); for (const auto& it: data.user_defined ) { const std::string& topicname = it.first; const auto& plotdata = it.second; auto registered_msg_type = RosIntrospectionFactory::get().getShapeShifter(topicname); if(!registered_msg_type) continue; RosIntrospection::ShapeShifter msg; msg.morph(registered_msg_type->getMD5Sum(), registered_msg_type->getDataType(), registered_msg_type->getMessageDefinition()); for (int i=0; i< plotdata.size(); i++) { const auto& point = plotdata.at(i); const PlotDataAny::TimeType msg_time = point.x; const nonstd::any& type_erased_buffer = point.y; if(type_erased_buffer.type() != typeid( std::vector<uint8_t> )) { // can't cast to expected type continue; } std::vector<uint8_t> raw_buffer = nonstd::any_cast<std::vector<uint8_t>>( type_erased_buffer ); ros::serialization::IStream stream( raw_buffer.data(), raw_buffer.size() ); msg.read( stream ); rosbag.write( topicname, ros::Time(msg_time), msg); } } rosbag.close(); QProcess process; QStringList args; args << "reindex" << fileName; process.start("rosbag" , args); } } void DataStreamROS::subscribe() { _subscribers.clear(); { boost::function<void(const rosgraph_msgs::Clock::ConstPtr&) > callback; callback = [this](const rosgraph_msgs::Clock::ConstPtr& msg) -> void { this->clockCallback(msg) ; }; } for (int i=0; i< _config.selected_topics.size(); i++ ) { const std::string topic_name = _config.selected_topics[i].toStdString(); boost::function<void(const topic_tools::ShapeShifter::ConstPtr&) > callback; callback = [this, topic_name](const topic_tools::ShapeShifter::ConstPtr& msg) -> void { this->topicCallback(msg, topic_name) ; }; ros::SubscribeOptions ops; ops.initByFullCallbackType(topic_name, 1, callback); ops.transport_hints = ros::TransportHints().tcpNoDelay(); _subscribers.insert( {topic_name, _node->subscribe(ops) } ); } } bool DataStreamROS::start(QStringList* selected_datasources) { _ros_parser.clear(); if( !_node ) { _node = RosManager::getNode(); } if( !_node ){ return false; } { std::lock_guard<std::mutex> lock( mutex() ); dataMap().numeric.clear(); dataMap().user_defined.clear(); } using namespace RosIntrospection; std::vector<std::pair<QString,QString>> all_topics; ros::master::V_TopicInfo topic_infos; ros::master::getTopics(topic_infos); for (ros::master::TopicInfo topic_info: topic_infos) { all_topics.push_back( std::make_pair(QString(topic_info.name.c_str()), QString(topic_info.datatype.c_str()) ) ); } QTimer timer; timer.setSingleShot(false); timer.setInterval( 1000); timer.start(); DialogSelectRosTopics dialog( all_topics, _config ); connect( &timer, &QTimer::timeout, [&]() { all_topics.clear(); topic_infos.clear(); ros::master::getTopics(topic_infos); for (ros::master::TopicInfo topic_info: topic_infos) { all_topics.push_back( std::make_pair(QString(topic_info.name.c_str()), QString(topic_info.datatype.c_str()) ) ); } dialog.updateTopicList(all_topics); }); int res = dialog.exec(); _config = dialog.getResult(); timer.stop(); if( res != QDialog::Accepted || _config.selected_topics.empty() ) { return false; } saveDefaultSettings(); _ros_parser.setUseHeaderStamp( _config.use_header_stamp ); if( _config.use_renaming_rules ) { _ros_parser.addRules( RuleEditing::getRenamingRules() ); } _ros_parser.setMaxArrayPolicy( _config.max_array_size, _config.discard_large_arrays ); //------------------------- subscribe(); _running = true; extractInitialSamples(); _spinner = std::make_shared<ros::AsyncSpinner>(1); _spinner->start(); _periodic_timer->setInterval(500); _roscore_disconnection_already_notified = false; _periodic_timer->start(); return true; } bool DataStreamROS::isRunning() const { return _running; } void DataStreamROS::shutdown() { _periodic_timer->stop(); if(_spinner) { _spinner->stop(); } for(auto& it: _subscribers) { it.second.shutdown(); } _subscribers.clear(); _running = false; _node.reset(); _spinner.reset(); } DataStreamROS::~DataStreamROS() { shutdown(); } bool DataStreamROS::xmlSaveState(QDomDocument &doc, QDomElement &plugin_elem) const { QDomElement stamp_elem = doc.createElement("use_header_stamp"); stamp_elem.setAttribute("value", _config.use_header_stamp ? "true" : "false"); plugin_elem.appendChild( stamp_elem ); QDomElement rename_elem = doc.createElement("use_renaming_rules"); rename_elem.setAttribute("value", _config.use_renaming_rules ? "true" : "false"); plugin_elem.appendChild( rename_elem ); QDomElement discard_elem = doc.createElement("discard_large_arrays"); discard_elem.setAttribute("value", _config.discard_large_arrays ? "true" : "false"); plugin_elem.appendChild( discard_elem ); QDomElement max_elem = doc.createElement("max_array_size"); max_elem.setAttribute("value", QString::number(_config.max_array_size)); plugin_elem.appendChild( max_elem ); return true; } bool DataStreamROS::xmlLoadState(const QDomElement &parent_element) { QDomElement stamp_elem = parent_element.firstChildElement( "use_header_stamp" ); _config.use_header_stamp = ( stamp_elem.attribute("value") == "true"); QDomElement rename_elem = parent_element.firstChildElement( "use_renaming_rules" ); _config.use_renaming_rules = ( rename_elem.attribute("value") == "true"); QDomElement discard_elem = parent_element.firstChildElement( "discard_large_arrays" ); _config.discard_large_arrays = ( discard_elem.attribute("value") == "true"); QDomElement max_elem = parent_element.firstChildElement( "max_array_size" ); _config.max_array_size = max_elem.attribute("value").toInt(); return true; } void DataStreamROS::addActionsToParentMenu(QMenu *menu) { _action_saveIntoRosbag = new QAction(QString("Save cached value in a rosbag"), menu); menu->addAction( _action_saveIntoRosbag ); connect( _action_saveIntoRosbag, &QAction::triggered, this, [this]() { DataStreamROS::saveIntoRosbag( *_destination_data ); }); } void DataStreamROS::saveDefaultSettings() { QSettings settings; settings.setValue("DataStreamROS/default_topics", _config.selected_topics); settings.setValue("DataStreamROS/use_renaming", _config.use_renaming_rules); settings.setValue("DataStreamROS/use_header_stamp", _config.use_header_stamp); settings.setValue("DataStreamROS/max_array_size", (int)_config.max_array_size); settings.setValue("DataStreamROS/discard_large_arrays", _config.discard_large_arrays); } void DataStreamROS::loadDefaultSettings() { QSettings settings; _config.selected_topics = settings.value("DataStreamROS/default_topics", false ).toStringList(); _config.use_header_stamp = settings.value("DataStreamROS/use_header_stamp", false ).toBool(); _config.use_renaming_rules = settings.value("DataStreamROS/use_renaming", true ).toBool(); _config.max_array_size = settings.value("DataStreamROS/max_array_size", 100 ).toInt(); _config.discard_large_arrays = settings.value("DataStreamROS/discard_large_arrays", true ).toBool(); } <commit_msg>minor bug fix<commit_after>#include "datastream_ROS.h" #include <QTextStream> #include <QFile> #include <QMessageBox> #include <QDebug> #include <thread> #include <mutex> #include <chrono> #include <thread> #include <QProgressDialog> #include <QtGlobal> #include <QApplication> #include <QProcess> #include <QCheckBox> #include <QSettings> #include <QFileDialog> #include <ros/callback_queue.h> #include <rosbag/bag.h> #include <topic_tools/shape_shifter.h> #include <ros/transport_hints.h> #include "../dialog_select_ros_topics.h" #include "../rule_editing.h" #include "../qnodedialog.h" #include "../shape_shifter_factory.hpp" DataStreamROS::DataStreamROS(): DataStreamer(), _node(nullptr), _destination_data(nullptr), _action_saveIntoRosbag(nullptr), _prev_clock_time(0) { _running = false; _periodic_timer = new QTimer(); connect( _periodic_timer, &QTimer::timeout, this, &DataStreamROS::timerCallback); loadDefaultSettings(); } void DataStreamROS::topicCallback(const topic_tools::ShapeShifter::ConstPtr& msg, const std::string &topic_name) { if( !_running ){ return; } using namespace RosIntrospection; const auto& md5sum = msg->getMD5Sum(); const auto& datatype = msg->getDataType(); const auto& definition = msg->getMessageDefinition() ; // register the message type _ros_parser.registerSchema( topic_name, md5sum, RosIntrospection::ROSType(datatype), definition); RosIntrospectionFactory::registerMessage(topic_name, md5sum, datatype, definition ); //------------------------------------ // it is more efficient to recycle this elements static std::vector<uint8_t> buffer; buffer.resize( msg->size() ); ros::serialization::OStream stream(buffer.data(), buffer.size()); msg->write(stream); double msg_time = ros::Time::now().toSec(); if( msg_time == 0) { // corner case: use_sim_time == true but topic /clock is not published msg_time = ros::WallTime::now().toSec(); } if( msg_time < _prev_clock_time ) { // clean for (auto& it: dataMap().numeric ) { it.second.clear(); auto dst = _destination_data->numeric.find(it.first); if( dst != _destination_data->numeric.end()){ dst->second.clear(); } } for (auto& it: dataMap().user_defined ){ it.second.clear(); auto dst = _destination_data->user_defined.find(it.first); if( dst != _destination_data->user_defined.end()){ dst->second.clear(); } } } _prev_clock_time = msg_time; MessageRef buffer_view( buffer ); _ros_parser.pushMessageRef( topic_name, buffer_view, msg_time ); std::lock_guard<std::mutex> lock( mutex() ); const std::string prefixed_topic_name = _prefix + topic_name; // adding raw serialized msg for future uses. // do this before msg_time normalization { auto plot_pair = dataMap().user_defined.find( prefixed_topic_name ); if( plot_pair == dataMap().user_defined.end() ) { plot_pair = dataMap().addUserDefined( prefixed_topic_name ); } PlotDataAny& user_defined_data = plot_pair->second; user_defined_data.pushBack( PlotDataAny::Point(msg_time, nonstd::any(std::move(buffer)) )); } _ros_parser.extractData(dataMap(), _prefix); //------------------------------ { int& index = _msg_index[topic_name]; index++; const std::string key = prefixed_topic_name + ("/_MSG_INDEX_") ; auto index_it = dataMap().numeric.find(key); if( index_it == dataMap().numeric.end()) { index_it = dataMap().addNumeric( key ); } index_it->second.pushBack( PlotData::Point(msg_time, index) ); } } void DataStreamROS::extractInitialSamples() { using namespace std::chrono; milliseconds wait_time_ms(1000); QProgressDialog progress_dialog; progress_dialog.setLabelText( "Collecting ROS topic samples to understand data layout. "); progress_dialog.setRange(0, wait_time_ms.count()); progress_dialog.setAutoClose(true); progress_dialog.setAutoReset(true); progress_dialog.show(); auto start_time = system_clock::now(); while ( system_clock::now() - start_time < (wait_time_ms) ) { ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(0.1)); int i = duration_cast<milliseconds>(system_clock::now() - start_time).count() ; progress_dialog.setValue( i ); QApplication::processEvents(); if( progress_dialog.wasCanceled() ) { break; } } if( progress_dialog.wasCanceled() == false ) { progress_dialog.cancel(); } } void DataStreamROS::timerCallback() { if( _running && ros::master::check() == false && !_roscore_disconnection_already_notified) { auto ret = QMessageBox::warning(nullptr, tr("Disconnected!"), tr("The roscore master cannot be detected.\n\n" "Do you want to try reconnecting to it? \n\n" "NOTE: if you select CONTINUE, you might need" " to stop and restart this plugin."), tr("Stop Plugin"), tr("Try reconnect"), tr("Continue"), 0); _roscore_disconnection_already_notified = ( ret == 2 ); if( ret == 1 ) { this->shutdown(); _node = RosManager::getNode(); if( !_node ){ emit connectionClosed(); return; } subscribe(); _running = true; _spinner = std::make_shared<ros::AsyncSpinner>(1); _spinner->start(); _periodic_timer->start(); } else if( ret == 0) { this->shutdown(); emit connectionClosed(); } } } void DataStreamROS::saveIntoRosbag(const PlotDataMapRef& data) { if( data.user_defined.empty()){ QMessageBox::warning(nullptr, tr("Warning"), tr("Your buffer is empty. Nothing to save.\n") ); return; } QFileDialog saveDialog; saveDialog.setAcceptMode(QFileDialog::AcceptSave); saveDialog.setDefaultSuffix("bag"); saveDialog.exec(); if(saveDialog.result() != QDialog::Accepted || saveDialog.selectedFiles().empty()) { return; } QString fileName = saveDialog.selectedFiles().first(); if( fileName.size() > 0) { rosbag::Bag rosbag(fileName.toStdString(), rosbag::bagmode::Write ); for (const auto& it: data.user_defined ) { const std::string& topicname = it.first; const auto& plotdata = it.second; auto registered_msg_type = RosIntrospectionFactory::get().getShapeShifter(topicname); if(!registered_msg_type) continue; RosIntrospection::ShapeShifter msg; msg.morph(registered_msg_type->getMD5Sum(), registered_msg_type->getDataType(), registered_msg_type->getMessageDefinition()); for (int i=0; i< plotdata.size(); i++) { const auto& point = plotdata.at(i); const PlotDataAny::TimeType msg_time = point.x; const nonstd::any& type_erased_buffer = point.y; if(type_erased_buffer.type() != typeid( std::vector<uint8_t> )) { // can't cast to expected type continue; } std::vector<uint8_t> raw_buffer = nonstd::any_cast<std::vector<uint8_t>>( type_erased_buffer ); ros::serialization::IStream stream( raw_buffer.data(), raw_buffer.size() ); msg.read( stream ); rosbag.write( topicname, ros::Time(msg_time), msg); } } rosbag.close(); QProcess process; QStringList args; args << "reindex" << fileName; process.start("rosbag" , args); } } void DataStreamROS::subscribe() { _subscribers.clear(); { boost::function<void(const rosgraph_msgs::Clock::ConstPtr&) > callback; callback = [this](const rosgraph_msgs::Clock::ConstPtr& msg) -> void { this->clockCallback(msg) ; }; } for (int i=0; i< _config.selected_topics.size(); i++ ) { const std::string topic_name = _config.selected_topics[i].toStdString(); boost::function<void(const topic_tools::ShapeShifter::ConstPtr&) > callback; callback = [this, topic_name](const topic_tools::ShapeShifter::ConstPtr& msg) -> void { this->topicCallback(msg, topic_name) ; }; ros::SubscribeOptions ops; ops.initByFullCallbackType(topic_name, 1, callback); ops.transport_hints = ros::TransportHints().tcpNoDelay(); _subscribers.insert( {topic_name, _node->subscribe(ops) } ); } } bool DataStreamROS::start(QStringList* selected_datasources) { _ros_parser.clear(); if( !_node ) { _node = RosManager::getNode(); } if( !_node ){ return false; } { std::lock_guard<std::mutex> lock( mutex() ); dataMap().numeric.clear(); dataMap().user_defined.clear(); } using namespace RosIntrospection; std::vector<std::pair<QString,QString>> all_topics; ros::master::V_TopicInfo topic_infos; ros::master::getTopics(topic_infos); for (ros::master::TopicInfo topic_info: topic_infos) { all_topics.push_back( std::make_pair(QString(topic_info.name.c_str()), QString(topic_info.datatype.c_str()) ) ); } QTimer timer; timer.setSingleShot(false); timer.setInterval( 1000); timer.start(); DialogSelectRosTopics dialog( all_topics, _config ); connect( &timer, &QTimer::timeout, [&]() { all_topics.clear(); topic_infos.clear(); ros::master::getTopics(topic_infos); for (ros::master::TopicInfo topic_info: topic_infos) { all_topics.push_back( std::make_pair(QString(topic_info.name.c_str()), QString(topic_info.datatype.c_str()) ) ); } dialog.updateTopicList(all_topics); }); int res = dialog.exec(); _config = dialog.getResult(); timer.stop(); if( res != QDialog::Accepted || _config.selected_topics.empty() ) { return false; } saveDefaultSettings(); _ros_parser.setUseHeaderStamp( _config.use_header_stamp ); if( _config.use_renaming_rules ) { _ros_parser.addRules( RuleEditing::getRenamingRules() ); } _ros_parser.setMaxArrayPolicy( _config.max_array_size, _config.discard_large_arrays ); //------------------------- subscribe(); _running = true; extractInitialSamples(); _spinner = std::make_shared<ros::AsyncSpinner>(1); _spinner->start(); _periodic_timer->setInterval(500); _roscore_disconnection_already_notified = false; _periodic_timer->start(); return true; } bool DataStreamROS::isRunning() const { return _running; } void DataStreamROS::shutdown() { _periodic_timer->stop(); if(_spinner) { _spinner->stop(); } for(auto& it: _subscribers) { it.second.shutdown(); } _subscribers.clear(); _running = false; _node.reset(); _spinner.reset(); } DataStreamROS::~DataStreamROS() { shutdown(); } bool DataStreamROS::xmlSaveState(QDomDocument &doc, QDomElement &plugin_elem) const { QDomElement stamp_elem = doc.createElement("use_header_stamp"); stamp_elem.setAttribute("value", _config.use_header_stamp ? "true" : "false"); plugin_elem.appendChild( stamp_elem ); QDomElement rename_elem = doc.createElement("use_renaming_rules"); rename_elem.setAttribute("value", _config.use_renaming_rules ? "true" : "false"); plugin_elem.appendChild( rename_elem ); QDomElement discard_elem = doc.createElement("discard_large_arrays"); discard_elem.setAttribute("value", _config.discard_large_arrays ? "true" : "false"); plugin_elem.appendChild( discard_elem ); QDomElement max_elem = doc.createElement("max_array_size"); max_elem.setAttribute("value", QString::number(_config.max_array_size)); plugin_elem.appendChild( max_elem ); return true; } bool DataStreamROS::xmlLoadState(const QDomElement &parent_element) { QDomElement stamp_elem = parent_element.firstChildElement( "use_header_stamp" ); _config.use_header_stamp = ( stamp_elem.attribute("value") == "true"); QDomElement rename_elem = parent_element.firstChildElement( "use_renaming_rules" ); _config.use_renaming_rules = ( rename_elem.attribute("value") == "true"); QDomElement discard_elem = parent_element.firstChildElement( "discard_large_arrays" ); _config.discard_large_arrays = ( discard_elem.attribute("value") == "true"); QDomElement max_elem = parent_element.firstChildElement( "max_array_size" ); _config.max_array_size = max_elem.attribute("value").toInt(); return true; } void DataStreamROS::addActionsToParentMenu(QMenu *menu) { _action_saveIntoRosbag = new QAction(QString("Save cached value in a rosbag"), menu); menu->addAction( _action_saveIntoRosbag ); connect( _action_saveIntoRosbag, &QAction::triggered, this, [this]() { DataStreamROS::saveIntoRosbag( *_destination_data ); }); } void DataStreamROS::saveDefaultSettings() { QSettings settings; settings.setValue("DataStreamROS/default_topics", _config.selected_topics); settings.setValue("DataStreamROS/use_renaming", _config.use_renaming_rules); settings.setValue("DataStreamROS/use_header_stamp", _config.use_header_stamp); settings.setValue("DataStreamROS/max_array_size", (int)_config.max_array_size); settings.setValue("DataStreamROS/discard_large_arrays", _config.discard_large_arrays); } void DataStreamROS::loadDefaultSettings() { QSettings settings; _config.selected_topics = settings.value("DataStreamROS/default_topics", false ).toStringList(); _config.use_header_stamp = settings.value("DataStreamROS/use_header_stamp", false ).toBool(); _config.use_renaming_rules = settings.value("DataStreamROS/use_renaming", true ).toBool(); _config.max_array_size = settings.value("DataStreamROS/max_array_size", 100 ).toInt(); _config.discard_large_arrays = settings.value("DataStreamROS/discard_large_arrays", true ).toBool(); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "postgis_featureset.hpp" #include "resultset.hpp" #include "cursorresultset.hpp" // mapnik #include <mapnik/global.hpp> #include <mapnik/wkb.hpp> #include <mapnik/unicode.hpp> #include <mapnik/sql_utils.hpp> #include <mapnik/feature_factory.hpp> #include <mapnik/util/conversions.hpp> // boost #include <boost/algorithm/string.hpp> #include <boost/spirit/include/qi.hpp> // stl #include <sstream> #include <string> using boost::trim_copy; using mapnik::geometry_type; using mapnik::byte; using mapnik::geometry_utils; using mapnik::feature_factory; using mapnik::context_ptr; postgis_featureset::postgis_featureset(boost::shared_ptr<IResultSet> const& rs, context_ptr const& ctx, std::string const& encoding, bool key_field) : rs_(rs), ctx_(ctx), tr_(new transcoder(encoding)), totalGeomSize_(0), feature_id_(1), key_field_(key_field) { } feature_ptr postgis_featureset::next() { if (rs_->next()) { // new feature unsigned pos = 1; feature_ptr feature; if (key_field_) { // create feature with user driven id from attribute int oid = rs_->getTypeOID(pos); const char* buf = rs_->getValue(pos); std::string name = rs_->getFieldName(pos); // validation happens of this type at bind() int val; if (oid == 20) { val = int8net(buf); } else if (oid == 21) { val = int2net(buf); } else { val = int4net(buf); } feature = feature_factory::create(ctx_, val); // TODO - extend feature class to know // that its id is also an attribute to avoid // this duplication feature->put(name,val); ++pos; } else { // fallback to auto-incrementing id feature = feature_factory::create(ctx_, feature_id_); ++feature_id_; } // parse geometry int size = rs_->getFieldLength(0); const char *data = rs_->getValue(0); geometry_utils::from_wkb(feature->paths(), data, size); totalGeomSize_ += size; int num_attrs = ctx_->size() + 1; for (; pos < num_attrs; ++pos) { std::string name = rs_->getFieldName(pos); if (rs_->isNull(pos)) { feature->put(name, mapnik::value_null()); } else { const char* buf = rs_->getValue(pos); const int oid = rs_->getTypeOID(pos); switch (oid) { case 16: //bool { feature->put(name, (buf[0] != 0)); break; } case 23: //int4 { int val = int4net(buf); feature->put(name, val); break; } case 21: //int2 { int val = int2net(buf); feature->put(name, val); break; } case 20: //int8/BigInt { // TODO - need to support boost::uint64_t in mapnik::value // https://github.com/mapnik/mapnik/issues/895 int val = int8net(buf); feature->put(name, val); break; } case 700: //float4 { float val; float4net(val, buf); feature->put(name, val); break; } case 701: //float8 { double val; float8net(val, buf); feature->put(name, val); break; } case 25: //text case 1043: //varchar { feature->put(name, tr_->transcode(buf)); break; } case 1042: //bpchar { feature->put(name, tr_->transcode(trim_copy(std::string(buf)).c_str())); break; } case 1700: //numeric { double val; std::string str = mapnik::sql_utils::numeric2string(buf); if (mapnik::util::string2double(str, val)) { feature->put(name, val); } break; } default: { #ifdef MAPNIK_DEBUG std::clog << "Postgis Plugin: uknown OID = " << oid << std::endl; #endif break; } } } } return feature; } else { rs_->close(); return feature_ptr(); } } postgis_featureset::~postgis_featureset() { rs_->close(); } <commit_msg>avoid copy<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "postgis_featureset.hpp" #include "resultset.hpp" #include "cursorresultset.hpp" // mapnik #include <mapnik/global.hpp> #include <mapnik/wkb.hpp> #include <mapnik/unicode.hpp> #include <mapnik/sql_utils.hpp> #include <mapnik/feature_factory.hpp> #include <mapnik/util/conversions.hpp> // boost #include <boost/algorithm/string.hpp> #include <boost/spirit/include/qi.hpp> // stl #include <sstream> #include <string> using mapnik::geometry_type; using mapnik::byte; using mapnik::geometry_utils; using mapnik::feature_factory; using mapnik::context_ptr; postgis_featureset::postgis_featureset(boost::shared_ptr<IResultSet> const& rs, context_ptr const& ctx, std::string const& encoding, bool key_field) : rs_(rs), ctx_(ctx), tr_(new transcoder(encoding)), totalGeomSize_(0), feature_id_(1), key_field_(key_field) { } feature_ptr postgis_featureset::next() { if (rs_->next()) { // new feature unsigned pos = 1; feature_ptr feature; if (key_field_) { // create feature with user driven id from attribute int oid = rs_->getTypeOID(pos); const char* buf = rs_->getValue(pos); std::string name = rs_->getFieldName(pos); // validation happens of this type at bind() int val; if (oid == 20) { val = int8net(buf); } else if (oid == 21) { val = int2net(buf); } else { val = int4net(buf); } feature = feature_factory::create(ctx_, val); // TODO - extend feature class to know // that its id is also an attribute to avoid // this duplication feature->put(name,val); ++pos; } else { // fallback to auto-incrementing id feature = feature_factory::create(ctx_, feature_id_); ++feature_id_; } // parse geometry int size = rs_->getFieldLength(0); const char *data = rs_->getValue(0); geometry_utils::from_wkb(feature->paths(), data, size); totalGeomSize_ += size; int num_attrs = ctx_->size() + 1; for (; pos < num_attrs; ++pos) { std::string name = rs_->getFieldName(pos); if (rs_->isNull(pos)) { feature->put(name, mapnik::value_null()); } else { const char* buf = rs_->getValue(pos); const int oid = rs_->getTypeOID(pos); switch (oid) { case 16: //bool { feature->put(name, (buf[0] != 0)); break; } case 23: //int4 { int val = int4net(buf); feature->put(name, val); break; } case 21: //int2 { int val = int2net(buf); feature->put(name, val); break; } case 20: //int8/BigInt { // TODO - need to support boost::uint64_t in mapnik::value // https://github.com/mapnik/mapnik/issues/895 int val = int8net(buf); feature->put(name, val); break; } case 700: //float4 { float val; float4net(val, buf); feature->put(name, val); break; } case 701: //float8 { double val; float8net(val, buf); feature->put(name, val); break; } case 25: //text case 1043: //varchar { feature->put(name, tr_->transcode(buf)); break; } case 1042: //bpchar { std::string str(buf); boost::trim(str); feature->put(name, tr_->transcode(str.c_str())); break; } case 1700: //numeric { double val; std::string str = mapnik::sql_utils::numeric2string(buf); if (mapnik::util::string2double(str, val)) { feature->put(name, val); } break; } default: { #ifdef MAPNIK_DEBUG std::clog << "Postgis Plugin: uknown OID = " << oid << std::endl; #endif break; } } } } return feature; } else { rs_->close(); return feature_ptr(); } } postgis_featureset::~postgis_featureset() { rs_->close(); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwmpplayercontrol.h" #include "qwmpevents.h" #include "qwmpglobal.h" #include "qwmpmetadata.h" #include "qwmpplaylist.h" #include <qmediaplayer.h> #include <qmediaplaylist.h> #include <QtCore/qdebug.h> #include <QtCore/qurl.h> #include <QtCore/qvariant.h> QWmpPlayerControl::QWmpPlayerControl(IWMPCore3 *player, QWmpEvents *events, QObject *parent) : QMediaPlayerControl(parent) , m_player(player) , m_controls(0) , m_settings(0) , m_state(QMediaPlayer::StoppedState) , m_duration(0) , m_buffering(false) , m_videoAvailable(false) { m_player->get_controls(&m_controls); m_player->get_settings(&m_settings); m_player->get_network(&m_network); WMPPlayState state = wmppsUndefined; if (m_player->get_playState(&state) == S_OK) playStateChangeEvent(state); connect(events, SIGNAL(Buffering(VARIANT_BOOL)), this, SLOT(bufferingEvent(VARIANT_BOOL))); connect(events, SIGNAL(PositionChange(double,double)), this, SLOT(positionChangeEvent(double,double))); connect(events, SIGNAL(PlayStateChange(long)), this, SLOT(playStateChangeEvent(long))); connect(events, SIGNAL(CurrentItemChange(IDispatch*)), this, SLOT(currentItemChangeEvent(IDispatch*))); connect(events, SIGNAL(MediaChange(IDispatch*)), this, SLOT(mediaChangeEvent(IDispatch*))); } QWmpPlayerControl::~QWmpPlayerControl() { if (m_controls) m_controls->Release(); if (m_settings) m_settings->Release(); if (m_network) m_network->Release(); } QMediaPlayer::State QWmpPlayerControl::state() const { return m_state; } QMediaPlayer::MediaStatus QWmpPlayerControl::mediaStatus() const { return m_status; } qint64 QWmpPlayerControl::duration() const { double duration = 0.; IWMPMedia *media = 0; if (m_controls && m_controls->get_currentItem(&media) == S_OK) { media->get_duration(&duration); media->Release(); } return m_duration * 1000; } qint64 QWmpPlayerControl::position() const { double position; if (m_controls) m_controls->get_currentPosition(&position); return position * 1000; } void QWmpPlayerControl::setPosition(qint64 position) { if (m_controls) m_controls->put_currentPosition(double(position) / 1000.); } int QWmpPlayerControl::volume() const { long volume = 0; if (m_settings) m_settings->get_volume(&volume); return volume; } void QWmpPlayerControl::setVolume(int volume) { if (m_settings && m_settings->put_volume(volume) == S_OK) emit volumeChanged(volume); } bool QWmpPlayerControl::isMuted() const { VARIANT_BOOL mute = FALSE; if (m_settings) m_settings->get_mute(&mute); return mute; } void QWmpPlayerControl::setMuted(bool muted) { if (m_settings && m_settings->put_mute(muted ? TRUE : FALSE) == S_OK) emit mutedChanged(muted); } int QWmpPlayerControl::bufferStatus() const { long progress = 0; if (m_network) m_network->get_bufferingProgress(&progress); return progress; } bool QWmpPlayerControl::isVideoAvailable() const { return m_videoAvailable; } void QWmpPlayerControl::setVideoAvailable(bool available) { if (m_videoAvailable != available) emit this->videoAvailableChanged(m_videoAvailable = available); } bool QWmpPlayerControl::isSeekable() const { return true; } QPair<qint64, qint64> QWmpPlayerControl::seekRange() const { double duration = 0.; IWMPMedia *media = 0; if (m_controls && m_controls->get_currentItem(&media) == S_OK) { media->get_duration(&duration); media->Release(); } return qMakePair<qint64, qint64>(0, m_duration * 1000); } qreal QWmpPlayerControl::playbackRate() const { double rate = 0.; if (m_settings) m_settings->get_rate(&rate); return rate; } void QWmpPlayerControl::setPlaybackRate(qreal rate) { if (m_settings) m_settings->put_rate(rate); } void QWmpPlayerControl::play() { if (m_controls) m_controls->play(); } void QWmpPlayerControl::pause() { if (m_controls) m_controls->pause(); } void QWmpPlayerControl::stop() { if (m_controls) m_controls->stop(); } QMediaContent QWmpPlayerControl::media() const { QMediaResourceList resources; QUrl url = url(); if (!url.isEmpty()) resources << QMediaResource(url); return resources; } const QIODevice *QWmpPlayerControl::mediaStream() const { return 0; } void QWmpPlayerControl::setMedia(const QMediaContent &content, QIODevice *stream) { if (!content.isNull() && !stream) setUrl(content.canonicalUrl()); else setUrl(QUrl()); } void QWmpPlayerControl::bufferingEvent(VARIANT_BOOL buffering) { if (m_state != QMediaPlayer::StoppedState) { emit mediaStatusChanged(m_status = buffering ? QMediaPlayer::BufferingMedia : QMediaPlayer::BufferedMedia); } } void QWmpPlayerControl::currentItemChangeEvent(IDispatch *dispatch) { IWMPMedia *media = 0; if (dispatch && dispatch->QueryInterface( __uuidof(IWMPMedia), reinterpret_cast<void **>(&media)) == S_OK) { double duration = 0; if (media->get_duration(&duration) == S_OK) emit durationChanged(duration * 1000); } } void QWmpPlayerControl::mediaChangeEvent(IDispatch *dispatch) { IWMPMedia *media = 0; if (dispatch && dispatch->QueryInterface( __uuidof(IWMPMedia), reinterpret_cast<void **>(&media)) == S_OK) { IWMPMedia *currentMedia = 0; if (m_controls && m_controls->get_currentItem(&currentMedia) == S_OK) { VARIANT_BOOL isEqual = VARIANT_FALSE; if (media->get_isIdentical(currentMedia, &isEqual) == S_OK && isEqual) { double duration = 0; if (media->get_duration(&duration) == S_OK) emit durationChanged(duration * 1000); } currentMedia->Release(); } media->Release(); } } void QWmpPlayerControl::positionChangeEvent(double from, double to) { Q_UNUSED(from); emit positionChanged(to * 1000); } void QWmpPlayerControl::playStateChangeEvent(long state) { switch (state) { case wmppsUndefined: m_state = QMediaPlayer::StoppedState; m_status = QMediaPlayer::UnknownMediaStatus; emit stateChanged(m_state); emit mediaStatusChanged(m_status); break; case wmppsStopped: if (m_state != QMediaPlayer::StoppedState) { m_state = QMediaPlayer::StoppedState; m_status = QMediaPlayer::LoadedMedia; emit stateChanged(m_state); emit mediaStatusChanged(m_status); } break; case wmppsPaused: if (m_state != QMediaPlayer::PausedState && m_status != QMediaPlayer::BufferedMedia) { m_state = QMediaPlayer::PausedState; m_status = QMediaPlayer::BufferedMedia; emit stateChanged(m_state); emit mediaStatusChanged(m_status); } else if (m_state != QMediaPlayer::PausedState) { emit stateChanged(m_state = QMediaPlayer::PausedState); } else if (m_status != QMediaPlayer::BufferedMedia) { emit mediaStatusChanged(m_status = QMediaPlayer::BufferedMedia); } break; case wmppsPlaying: case wmppsScanForward: case wmppsScanReverse: if (m_state != QMediaPlayer::PlayingState && m_status != QMediaPlayer::BufferedMedia) { m_state = QMediaPlayer::PlayingState; m_status = QMediaPlayer::BufferedMedia; emit stateChanged(m_state); emit mediaStatusChanged(m_status); } else if (m_state != QMediaPlayer::PlayingState) { emit stateChanged(m_state = QMediaPlayer::PlayingState); } else if (m_status != QMediaPlayer::BufferedMedia) { emit mediaStatusChanged(m_status = QMediaPlayer::BufferedMedia); } if (m_state != QMediaPlayer::PlayingState) emit stateChanged(m_state = QMediaPlayer::PlayingState); if (m_status != QMediaPlayer::BufferedMedia) emit mediaStatusChanged(m_status = QMediaPlayer::BufferedMedia); break; case wmppsBuffering: case wmppsWaiting: if (m_status != QMediaPlayer::StalledMedia && m_state != QMediaPlayer::StoppedState) emit mediaStatusChanged(m_status = QMediaPlayer::StalledMedia); break; case wmppsMediaEnded: if (m_status != QMediaPlayer::EndOfMedia && m_state != QMediaPlayer::StoppedState) { m_state = QMediaPlayer::StoppedState; m_status = QMediaPlayer::StalledMedia; emit stateChanged(m_state); emit mediaStatusChanged(m_status); } break; case wmppsTransitioning: if (m_status != QMediaPlayer::LoadingMedia) emit mediaStatusChanged(m_status = QMediaPlayer::LoadingMedia); break; case wmppsReady: if (m_status != QMediaPlayer::LoadedMedia) m_status = m_status = QMediaPlayer::LoadedMedia; if (m_state != QMediaPlayer::StoppedState) emit stateChanged(QMediaPlayer::StoppedState); emit mediaStatusChanged(m_status); break; case wmppsReconnecting: if (m_status != QMediaPlayer::StalledMedia && m_state != QMediaPlayer::StoppedState) emit mediaStatusChanged(m_status = QMediaPlayer::StalledMedia); break; default: break; } } QUrl QWmpPlayerControl::url() const { BSTR string; if (m_player && m_player->get_URL(&string) == S_OK) { QUrl url(QString::fromWCharArray(string, SysStringLen(string)), QUrl::StrictMode); SysFreeString(string); return url; } else { return QUrl(); } } void QWmpPlayerControl::setUrl(const QUrl &url) { if (m_player) { BSTR string = SysAllocString(reinterpret_cast<const wchar_t *>(url.toString().unicode())); m_player->put_URL(string); SysFreeString(string); } } <commit_msg>Make compile.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwmpplayercontrol.h" #include "qwmpevents.h" #include "qwmpglobal.h" #include "qwmpmetadata.h" #include "qwmpplaylist.h" #include <qmediaplayer.h> #include <qmediaplaylist.h> #include <QtCore/qdebug.h> #include <QtCore/qurl.h> #include <QtCore/qvariant.h> QWmpPlayerControl::QWmpPlayerControl(IWMPCore3 *player, QWmpEvents *events, QObject *parent) : QMediaPlayerControl(parent) , m_player(player) , m_controls(0) , m_settings(0) , m_state(QMediaPlayer::StoppedState) , m_duration(0) , m_buffering(false) , m_videoAvailable(false) { m_player->get_controls(&m_controls); m_player->get_settings(&m_settings); m_player->get_network(&m_network); WMPPlayState state = wmppsUndefined; if (m_player->get_playState(&state) == S_OK) playStateChangeEvent(state); connect(events, SIGNAL(Buffering(VARIANT_BOOL)), this, SLOT(bufferingEvent(VARIANT_BOOL))); connect(events, SIGNAL(PositionChange(double,double)), this, SLOT(positionChangeEvent(double,double))); connect(events, SIGNAL(PlayStateChange(long)), this, SLOT(playStateChangeEvent(long))); connect(events, SIGNAL(CurrentItemChange(IDispatch*)), this, SLOT(currentItemChangeEvent(IDispatch*))); connect(events, SIGNAL(MediaChange(IDispatch*)), this, SLOT(mediaChangeEvent(IDispatch*))); } QWmpPlayerControl::~QWmpPlayerControl() { if (m_controls) m_controls->Release(); if (m_settings) m_settings->Release(); if (m_network) m_network->Release(); } QMediaPlayer::State QWmpPlayerControl::state() const { return m_state; } QMediaPlayer::MediaStatus QWmpPlayerControl::mediaStatus() const { return m_status; } qint64 QWmpPlayerControl::duration() const { double duration = 0.; IWMPMedia *media = 0; if (m_controls && m_controls->get_currentItem(&media) == S_OK) { media->get_duration(&duration); media->Release(); } return m_duration * 1000; } qint64 QWmpPlayerControl::position() const { double position; if (m_controls) m_controls->get_currentPosition(&position); return position * 1000; } void QWmpPlayerControl::setPosition(qint64 position) { if (m_controls) m_controls->put_currentPosition(double(position) / 1000.); } int QWmpPlayerControl::volume() const { long volume = 0; if (m_settings) m_settings->get_volume(&volume); return volume; } void QWmpPlayerControl::setVolume(int volume) { if (m_settings && m_settings->put_volume(volume) == S_OK) emit volumeChanged(volume); } bool QWmpPlayerControl::isMuted() const { VARIANT_BOOL mute = FALSE; if (m_settings) m_settings->get_mute(&mute); return mute; } void QWmpPlayerControl::setMuted(bool muted) { if (m_settings && m_settings->put_mute(muted ? TRUE : FALSE) == S_OK) emit mutedChanged(muted); } int QWmpPlayerControl::bufferStatus() const { long progress = 0; if (m_network) m_network->get_bufferingProgress(&progress); return progress; } bool QWmpPlayerControl::isVideoAvailable() const { return m_videoAvailable; } void QWmpPlayerControl::setVideoAvailable(bool available) { if (m_videoAvailable != available) emit this->videoAvailableChanged(m_videoAvailable = available); } bool QWmpPlayerControl::isSeekable() const { return true; } QPair<qint64, qint64> QWmpPlayerControl::seekRange() const { double duration = 0.; IWMPMedia *media = 0; if (m_controls && m_controls->get_currentItem(&media) == S_OK) { media->get_duration(&duration); media->Release(); } return qMakePair<qint64, qint64>(0, m_duration * 1000); } qreal QWmpPlayerControl::playbackRate() const { double rate = 0.; if (m_settings) m_settings->get_rate(&rate); return rate; } void QWmpPlayerControl::setPlaybackRate(qreal rate) { if (m_settings) m_settings->put_rate(rate); } void QWmpPlayerControl::play() { if (m_controls) m_controls->play(); } void QWmpPlayerControl::pause() { if (m_controls) m_controls->pause(); } void QWmpPlayerControl::stop() { if (m_controls) m_controls->stop(); } QMediaContent QWmpPlayerControl::media() const { QMediaResourceList resources; QUrl tmpUrl = url(); if (!tmpUrl.isEmpty()) resources << QMediaResource(url); return resources; } const QIODevice *QWmpPlayerControl::mediaStream() const { return 0; } void QWmpPlayerControl::setMedia(const QMediaContent &content, QIODevice *stream) { if (!content.isNull() && !stream) setUrl(content.canonicalUrl()); else setUrl(QUrl()); } void QWmpPlayerControl::bufferingEvent(VARIANT_BOOL buffering) { if (m_state != QMediaPlayer::StoppedState) { emit mediaStatusChanged(m_status = buffering ? QMediaPlayer::BufferingMedia : QMediaPlayer::BufferedMedia); } } void QWmpPlayerControl::currentItemChangeEvent(IDispatch *dispatch) { IWMPMedia *media = 0; if (dispatch && dispatch->QueryInterface( __uuidof(IWMPMedia), reinterpret_cast<void **>(&media)) == S_OK) { double duration = 0; if (media->get_duration(&duration) == S_OK) emit durationChanged(duration * 1000); } } void QWmpPlayerControl::mediaChangeEvent(IDispatch *dispatch) { IWMPMedia *media = 0; if (dispatch && dispatch->QueryInterface( __uuidof(IWMPMedia), reinterpret_cast<void **>(&media)) == S_OK) { IWMPMedia *currentMedia = 0; if (m_controls && m_controls->get_currentItem(&currentMedia) == S_OK) { VARIANT_BOOL isEqual = VARIANT_FALSE; if (media->get_isIdentical(currentMedia, &isEqual) == S_OK && isEqual) { double duration = 0; if (media->get_duration(&duration) == S_OK) emit durationChanged(duration * 1000); } currentMedia->Release(); } media->Release(); } } void QWmpPlayerControl::positionChangeEvent(double from, double to) { Q_UNUSED(from); emit positionChanged(to * 1000); } void QWmpPlayerControl::playStateChangeEvent(long state) { switch (state) { case wmppsUndefined: m_state = QMediaPlayer::StoppedState; m_status = QMediaPlayer::UnknownMediaStatus; emit stateChanged(m_state); emit mediaStatusChanged(m_status); break; case wmppsStopped: if (m_state != QMediaPlayer::StoppedState) { m_state = QMediaPlayer::StoppedState; m_status = QMediaPlayer::LoadedMedia; emit stateChanged(m_state); emit mediaStatusChanged(m_status); } break; case wmppsPaused: if (m_state != QMediaPlayer::PausedState && m_status != QMediaPlayer::BufferedMedia) { m_state = QMediaPlayer::PausedState; m_status = QMediaPlayer::BufferedMedia; emit stateChanged(m_state); emit mediaStatusChanged(m_status); } else if (m_state != QMediaPlayer::PausedState) { emit stateChanged(m_state = QMediaPlayer::PausedState); } else if (m_status != QMediaPlayer::BufferedMedia) { emit mediaStatusChanged(m_status = QMediaPlayer::BufferedMedia); } break; case wmppsPlaying: case wmppsScanForward: case wmppsScanReverse: if (m_state != QMediaPlayer::PlayingState && m_status != QMediaPlayer::BufferedMedia) { m_state = QMediaPlayer::PlayingState; m_status = QMediaPlayer::BufferedMedia; emit stateChanged(m_state); emit mediaStatusChanged(m_status); } else if (m_state != QMediaPlayer::PlayingState) { emit stateChanged(m_state = QMediaPlayer::PlayingState); } else if (m_status != QMediaPlayer::BufferedMedia) { emit mediaStatusChanged(m_status = QMediaPlayer::BufferedMedia); } if (m_state != QMediaPlayer::PlayingState) emit stateChanged(m_state = QMediaPlayer::PlayingState); if (m_status != QMediaPlayer::BufferedMedia) emit mediaStatusChanged(m_status = QMediaPlayer::BufferedMedia); break; case wmppsBuffering: case wmppsWaiting: if (m_status != QMediaPlayer::StalledMedia && m_state != QMediaPlayer::StoppedState) emit mediaStatusChanged(m_status = QMediaPlayer::StalledMedia); break; case wmppsMediaEnded: if (m_status != QMediaPlayer::EndOfMedia && m_state != QMediaPlayer::StoppedState) { m_state = QMediaPlayer::StoppedState; m_status = QMediaPlayer::StalledMedia; emit stateChanged(m_state); emit mediaStatusChanged(m_status); } break; case wmppsTransitioning: if (m_status != QMediaPlayer::LoadingMedia) emit mediaStatusChanged(m_status = QMediaPlayer::LoadingMedia); break; case wmppsReady: if (m_status != QMediaPlayer::LoadedMedia) m_status = m_status = QMediaPlayer::LoadedMedia; if (m_state != QMediaPlayer::StoppedState) emit stateChanged(QMediaPlayer::StoppedState); emit mediaStatusChanged(m_status); break; case wmppsReconnecting: if (m_status != QMediaPlayer::StalledMedia && m_state != QMediaPlayer::StoppedState) emit mediaStatusChanged(m_status = QMediaPlayer::StalledMedia); break; default: break; } } QUrl QWmpPlayerControl::url() const { BSTR string; if (m_player && m_player->get_URL(&string) == S_OK) { QUrl url(QString::fromWCharArray(string, SysStringLen(string)), QUrl::StrictMode); SysFreeString(string); return url; } else { return QUrl(); } } void QWmpPlayerControl::setUrl(const QUrl &url) { if (m_player) { BSTR string = SysAllocString(reinterpret_cast<const wchar_t *>(url.toString().unicode())); m_player->put_URL(string); SysFreeString(string); } } <|endoftext|>
<commit_before>#include <cmath> #include "Math/SVector.h" #include "Math/SMatrix.h" #include <iostream> #include <vector> using namespace ROOT::Math; using std::cout; using std::endl; //#define TEST_STATIC_CHECK // for testing compiler failures (static check) #define XXX int test1() { SVector<float,3> x(4,5,6); SVector<float,2> y(2.0,3.0); cout << "x: " << x << endl; cout << "y: " << y << endl; // float yy1=2.; float yy2 = 3; // SVector<float,2> y2(yy1,yy2); SMatrix<float,4,3> A; SMatrix<float,2,2> B; A.Place_in_row(y, 1, 1); A.Place_in_col(x + 2, 1, 0); A.Place_at(B , 2, 1); cout << "A: " << endl << A << endl; #ifdef TEST_STATIC_CHECK // create a vector of size 2 from 3 arguments SVector<float, 2> v(1,2,3); #endif // test STL interface //double p[2] = {1,2}; double m[4] = {1,2,3,4}; //SVector<float, 2> sp(p,2); SMatrix<float, 2,2> sm(m,4); //cout << "sp: " << endl << sp << endl; cout << "sm: " << endl << sm << endl; //std::vector<float> vp(sp.begin(), sp.end() ); std::vector<float> vm(sm.begin(), sm.end() ); //SVector<float, 2> sp2(vp.begin(),vp.end()); //SVector<float, 2> sp2(vp.begin(),vp.size()); SMatrix<float, 2,2> sm2(vm.begin(),vm.end()); //if ( sp2 != sp) { cout << "Test STL interface for SVector failed" << endl; return -1; } if ( sm2 != sm) { cout << "Test STL interface for SMatrix failed" << endl; return -1; } return 0; } int test2() { #ifdef XXX SMatrix<double,3> A; A(0,0) = A(1,0) = 1; A(0,1) = 3; A(1,1) = A(2,2) = 2; cout << "A: " << endl << A << endl; SVector<double,3> x = A.Row(0); cout << "x: " << x << endl; SVector<double,3> y = A.Col(1); cout << "y: " << y << endl; return 0; #endif } int test3() { #ifdef XXX SMatrix<double,3> A; A(0,0) = A(0,1) = A(1,0) = 1; A(1,1) = A(2,2) = 2; SMatrix<double,3> B = A; // save A in B cout << "A: " << endl << A << endl; double det = 0.; A.Sdet(det); cout << "Determinant: " << det << endl; // WARNING: A has changed!! cout << "A again: " << endl << A << endl; A.Sinvert(); cout << "A^-1: " << endl << A << endl; // check if this is really the inverse: cout << "A^-1 * B: " << endl << A * B << endl; return 0; #endif } int test4() { #ifdef XXX SMatrix<double,3> A; A(0,0) = A(0,1) = A(1,0) = 1; A(1,1) = A(2,2) = 2; cout << " A: " << endl << A << endl; SVector<double,3> x(1,2,3); cout << "x: " << x << endl; // we add 1 to each component of x and A cout << " (x+1)^T * (A+1) * (x+1): " << Product(x+1,A+1) << endl; return 0; #endif } int test5() { #ifdef XXX SMatrix<float,4,3> A; A(0,0) = A(0,1) = A(1,1) = A(2,2) = 4.; A(2,3) = 1.; cout << "A: " << endl << A << endl; SVector<float,4> x(1,2,3,4); cout << " x: " << x << endl; SVector<float,3> a(1,2,3); cout << " a: " << a << endl; SVector<float,4> y = x + A * a; // SVector<float,4> y = A * a; cout << " y: " << y << endl; SVector<float,3> b = (x+1) * (A+1); cout << " b: " << b << endl; return 0; #endif } int test6() { #ifdef XXX SMatrix<float,4,2> A; A(0,0) = A(0,1) = A(1,1) = A(2,0) = A(3,1) = 4.; cout << "A: " << endl << A << endl; SMatrix<float,2,3> S; S(0,0) = S(0,1) = S(1,1) = S(0,2) = 1.; cout << " S: " << endl << S << endl; SMatrix<float,4,3> C = A * S; cout << " C: " << endl << C << endl; return 0; #endif } int test7() { #ifdef XXX SVector<float,3> xv(4,4,4); SVector<float,3> yv(5,5,5); SVector<float,2> zv(64,64); SMatrix<float,2,3> x; x.Place_in_row(xv,0,0); x.Place_in_row(xv,1,0); SMatrix<float,2,3> y; y.Place_in_row(yv,0,0); y.Place_in_row(yv,1,0); SMatrix<float,2,3> z; z.Place_in_col(zv,0,0); z.Place_in_col(zv,0,1); z.Place_in_col(zv,0,2); // element wise multiplication cout << "x * y: " << endl << times(x, -y) << endl; x += z - y; cout << "x += z - y: " << endl << x << endl; // element wise square root cout << "sqrt(z): " << endl << sqrt(z) << endl; // element wise multiplication with constant cout << "2 * y: " << endl << 2 * y << endl; // a more complex expression cout << "fabs(-z + 3*x): " << endl << fabs(-z + 3*x) << endl; return 0; #endif } int test8() { #ifdef XXX SMatrix<float,2,3> A; SVector<float,3> av1(5.,15.,5.); SVector<float,3> av2(15.,5.,15.); A.Place_in_row(av1,0,0); A.Place_in_row(av2,1,0); cout << "A: " << endl << A << endl; SVector<float,3> x(1,2,3); SVector<float,3> y(4,5,6); cout << "dot(x,y): " << Dot(x,y) << endl; cout << "mag(x): " << Mag(x) << endl; cout << "cross(x,y): " << Cross(x,y) << endl; cout << "unit(x): " << Unit(x) << endl; SVector<float,3> z(4,16,64); cout << "x + y: " << x+y << endl; cout << "x * y: " << x * -y << endl; x += z - y; cout << "x += z - y: " << x << endl; // element wise square root cout << "sqrt(z): " << sqrt(z) << endl; // element wise multiplication with constant cout << "2 * y: " << 2 * y << endl; // a more complex expression cout << "fabs(-z + 3*x): " << fabs(-z + 3*x) << endl; SVector<float,4> a; SVector<float,2> b(1,2); a.Place_at(b,2); cout << "a: " << a << endl; #endif return 0; } #define TEST(N) \ itest = N; \ if (test##N() == 0) std::cout << " Test " << itest << " OK " << std::endl; \ else {std::cout << " Test " << itest << " Failed " << std::endl; \ return -1;} int main(void) { int itest; TEST(1); TEST(2); TEST(3); TEST(4); TEST(5); TEST(6); TEST(7); TEST(8); return 0; } <commit_msg>remove a warning in the test<commit_after>#include <cmath> #include "Math/SVector.h" #include "Math/SMatrix.h" #include <iostream> #include <vector> using namespace ROOT::Math; using std::cout; using std::endl; //#define TEST_STATIC_CHECK // for testing compiler failures (static check) #define XXX int test1() { SVector<float,3> x(4,5,6); SVector<float,2> y(2.0,3.0); cout << "x: " << x << endl; cout << "y: " << y << endl; // float yy1=2.; float yy2 = 3; // SVector<float,2> y2(yy1,yy2); SMatrix<float,4,3> A; SMatrix<float,2,2> B; A.Place_in_row(y, 1, 1); A.Place_in_col(x + 2, 1, 0); A.Place_at(B , 2, 1); cout << "A: " << endl << A << endl; #ifdef TEST_STATIC_CHECK // create a vector of size 2 from 3 arguments SVector<float, 2> v(1,2,3); #endif // test STL interface //float p[2] = {1,2}; float m[4] = {1,2,3,4}; //SVector<float, 2> sp(p,2); SMatrix<float, 2,2> sm(m,4); //cout << "sp: " << endl << sp << endl; cout << "sm: " << endl << sm << endl; //std::vector<float> vp(sp.begin(), sp.end() ); std::vector<float> vm(sm.begin(), sm.end() ); //SVector<float, 2> sp2(vp.begin(),vp.end()); //SVector<float, 2> sp2(vp.begin(),vp.size()); SMatrix<float, 2,2> sm2(vm.begin(),vm.end()); //if ( sp2 != sp) { cout << "Test STL interface for SVector failed" << endl; return -1; } if ( sm2 != sm) { cout << "Test STL interface for SMatrix failed" << endl; return -1; } return 0; } int test2() { #ifdef XXX SMatrix<double,3> A; A(0,0) = A(1,0) = 1; A(0,1) = 3; A(1,1) = A(2,2) = 2; cout << "A: " << endl << A << endl; SVector<double,3> x = A.Row(0); cout << "x: " << x << endl; SVector<double,3> y = A.Col(1); cout << "y: " << y << endl; return 0; #endif } int test3() { #ifdef XXX SMatrix<double,3> A; A(0,0) = A(0,1) = A(1,0) = 1; A(1,1) = A(2,2) = 2; SMatrix<double,3> B = A; // save A in B cout << "A: " << endl << A << endl; double det = 0.; A.Sdet(det); cout << "Determinant: " << det << endl; // WARNING: A has changed!! cout << "A again: " << endl << A << endl; A.Sinvert(); cout << "A^-1: " << endl << A << endl; // check if this is really the inverse: cout << "A^-1 * B: " << endl << A * B << endl; return 0; #endif } int test4() { #ifdef XXX SMatrix<double,3> A; A(0,0) = A(0,1) = A(1,0) = 1; A(1,1) = A(2,2) = 2; cout << " A: " << endl << A << endl; SVector<double,3> x(1,2,3); cout << "x: " << x << endl; // we add 1 to each component of x and A cout << " (x+1)^T * (A+1) * (x+1): " << Product(x+1,A+1) << endl; return 0; #endif } int test5() { #ifdef XXX SMatrix<float,4,3> A; A(0,0) = A(0,1) = A(1,1) = A(2,2) = 4.; A(2,3) = 1.; cout << "A: " << endl << A << endl; SVector<float,4> x(1,2,3,4); cout << " x: " << x << endl; SVector<float,3> a(1,2,3); cout << " a: " << a << endl; SVector<float,4> y = x + A * a; // SVector<float,4> y = A * a; cout << " y: " << y << endl; SVector<float,3> b = (x+1) * (A+1); cout << " b: " << b << endl; return 0; #endif } int test6() { #ifdef XXX SMatrix<float,4,2> A; A(0,0) = A(0,1) = A(1,1) = A(2,0) = A(3,1) = 4.; cout << "A: " << endl << A << endl; SMatrix<float,2,3> S; S(0,0) = S(0,1) = S(1,1) = S(0,2) = 1.; cout << " S: " << endl << S << endl; SMatrix<float,4,3> C = A * S; cout << " C: " << endl << C << endl; return 0; #endif } int test7() { #ifdef XXX SVector<float,3> xv(4,4,4); SVector<float,3> yv(5,5,5); SVector<float,2> zv(64,64); SMatrix<float,2,3> x; x.Place_in_row(xv,0,0); x.Place_in_row(xv,1,0); SMatrix<float,2,3> y; y.Place_in_row(yv,0,0); y.Place_in_row(yv,1,0); SMatrix<float,2,3> z; z.Place_in_col(zv,0,0); z.Place_in_col(zv,0,1); z.Place_in_col(zv,0,2); // element wise multiplication cout << "x * y: " << endl << times(x, -y) << endl; x += z - y; cout << "x += z - y: " << endl << x << endl; // element wise square root cout << "sqrt(z): " << endl << sqrt(z) << endl; // element wise multiplication with constant cout << "2 * y: " << endl << 2 * y << endl; // a more complex expression cout << "fabs(-z + 3*x): " << endl << fabs(-z + 3*x) << endl; return 0; #endif } int test8() { #ifdef XXX SMatrix<float,2,3> A; SVector<float,3> av1(5.,15.,5.); SVector<float,3> av2(15.,5.,15.); A.Place_in_row(av1,0,0); A.Place_in_row(av2,1,0); cout << "A: " << endl << A << endl; SVector<float,3> x(1,2,3); SVector<float,3> y(4,5,6); cout << "dot(x,y): " << Dot(x,y) << endl; cout << "mag(x): " << Mag(x) << endl; cout << "cross(x,y): " << Cross(x,y) << endl; cout << "unit(x): " << Unit(x) << endl; SVector<float,3> z(4,16,64); cout << "x + y: " << x+y << endl; cout << "x * y: " << x * -y << endl; x += z - y; cout << "x += z - y: " << x << endl; // element wise square root cout << "sqrt(z): " << sqrt(z) << endl; // element wise multiplication with constant cout << "2 * y: " << 2 * y << endl; // a more complex expression cout << "fabs(-z + 3*x): " << fabs(-z + 3*x) << endl; SVector<float,4> a; SVector<float,2> b(1,2); a.Place_at(b,2); cout << "a: " << a << endl; #endif return 0; } #define TEST(N) \ itest = N; \ if (test##N() == 0) std::cout << " Test " << itest << " OK " << std::endl; \ else {std::cout << " Test " << itest << " Failed " << std::endl; \ return -1;} int main(void) { int itest; TEST(1); TEST(2); TEST(3); TEST(4); TEST(5); TEST(6); TEST(7); TEST(8); return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <opencv2/video/background_segm.hpp> #include "opencv2/opencv.hpp" #include "physics.h" using namespace cv; using namespace std; const char *win = "Flying Pancake"; static bool reverseMirror = true; int main(int argc, char **argv) { if (argc > 2) { fprintf(stderr, "Error: Please limit arguments to 1 or none.\n"); exit(1); } else if (argc == 2) { if (!strcmp(argv[1], "-r")) reverseMirror = false; else { fprintf(stderr, "Usage: videoBall [-r]\n"); exit(1); } } int cam = 0; // default camera VideoCapture cap(cam); if (!cap.isOpened()) { fprintf(stderr, "Error: Cannot open camera %d\n", cam); exit(1); } namedWindow(win, CV_WINDOW_AUTOSIZE); Mat fgMaskMOG; BackgroundSubtractorMOG2 MOG; Mat inputFrame, outFrame, scoreFrame; cap >> inputFrame; int height = inputFrame.rows; int width = inputFrame.cols; // initial position Point pt; pt.x = width / 2; pt.y = height / 2; // initial momentum Point momentum; momentum.x = 0; momentum.y = 0; Mat circ; cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR); cvtColor(inputFrame, scoreFrame, CV_LOAD_IMAGE_COLOR); cvtColor(inputFrame, circ, CV_BGR2GRAY); int count = 0; int sum; Mat reverseFrame; Mat ballFrame, handFrame; Mat foregroundMask, backgroundMask; Point small; int score=0, left=0, right=0; int timer = 50; // 50 frames between points are scored //Initialize the scoreFrame here scoreFrame = scoreFrame > 256; putText(scoreFrame, to_string(left), Point(50,height-50), FONT_HERSHEY_SCRIPT_SIMPLEX, 3, Scalar(255,255,255), 1, 8, false ); // Put right score on right putText(scoreFrame, to_string(right), Point(width-50,height-50), FONT_HERSHEY_SCRIPT_SIMPLEX, 3, Scalar(255,255,255), 1, 8, false ); while(++count) { cap >> inputFrame; if (reverseMirror) { inputFrame.copyTo(reverseFrame); flip(reverseFrame, inputFrame, 1); } cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR); MOG(inputFrame, fgMaskMOG); foregroundMask = fgMaskMOG > THRESH; backgroundMask = fgMaskMOG <= THRESH; score = pongDir(&momentum, &pt, height, width); if (!score) { // still moving // blank canvas circ.setTo(Scalar(0, 0, 0)); Rect ballRegion(pt.x - RADIUS, pt.y - RADIUS, 2 * RADIUS, 2 * RADIUS); ballFrame = circ(ballRegion); fgMaskMOG.setTo(Scalar(255, 255, 255), foregroundMask); // clean up fgMaskMOG.setTo(Scalar(0, 0, 0), backgroundMask); handFrame = fgMaskMOG(ballRegion); int halfRad = RADIUS / 2; // top left small.x = halfRad; small.y = halfRad; sum = getOverlap(&ballFrame, &handFrame, &small); momentum.x += pt.x < width / 2 ? sum : 0; momentum.y += sum; // top right small.x = 3 * halfRad; small.y = halfRad; sum = getOverlap(&ballFrame, &handFrame, &small); momentum.x += pt.x >= width / 2 ? -sum : 0; momentum.y += sum; // bottom left small.x = halfRad; small.y = 3 * halfRad; sum = getOverlap(&ballFrame, &handFrame, &small); momentum.x += pt.x < width / 2 ? sum : 0; momentum.y -= sum; // bottom right small.x = 3 * halfRad; small.y = 3 * halfRad; sum = getOverlap(&ballFrame, &handFrame, &small); momentum.x += pt.x >= width / 2 ? -sum : 0; momentum.y -= sum; }else if (!timer--){ //someone scored, so decrement timer and reset when timer = 0 timer = 50; reset_board(&pt, &momentum, width, height); if (score >0){ left +=1; } else{ right += 1; } scoreFrame = scoreFrame > 256; putText(scoreFrame, to_string(left), Point(50,height-50), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar(255,255,255), 1, 8, false ); // Put right score on right putText(scoreFrame, to_string(right), Point(width-50,height-50), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar(255,255,255), 1, 8, false ); if ( right >= 5 || left >= 5){ //Game over, stop playing // game_over(right,left); break; } } // outFrame -= Scalar(50,50,50); // cvtColor(foregroundMask, inputFrame, CV_LOAD_IMAGE_COLOR); // outFrame.setTo(Scalar(0, 0, 0)); // outFrame.setTo(Scalar(255, 255, 255), foregroundMask); //Set the color of the ball here. cvtColor(foregroundMask,foregroundMask ,COLOR_GRAY2BGR); addWeighted(outFrame, 0.75, foregroundMask, 0.25, 1, outFrame, -1); drawCircle(outFrame, pt, RADIUS, Scalar( 0, 0, 255 )); // Put score frame onto image addWeighted(outFrame, 0.75, scoreFrame, 1.0, 1, outFrame, -1); imshow(win,outFrame); // listening for key press char c = waitKey(30); if (c >= 0) { if (c == 'r') { pt.x = width / 2; pt.y = height / 2; continue; } else break; } } return 0; } <commit_msg>Added in text at the beginning and a dividing line. NEED THE SCOREFRAME FOR TEXT, DO NOT REMOVE<commit_after>#include <stdio.h> #include <opencv2/video/background_segm.hpp> #include "opencv2/opencv.hpp" #include "physics.h" using namespace cv; using namespace std; const char *win = "Flying Pancake"; static bool reverseMirror = true; int main(int argc, char **argv) { if (argc > 2) { fprintf(stderr, "Error: Please limit arguments to 1 or none.\n"); exit(1); } else if (argc == 2) { if (!strcmp(argv[1], "-r")) reverseMirror = false; else { fprintf(stderr, "Usage: videoBall [-r]\n"); exit(1); } } int cam = 0; // default camera VideoCapture cap(cam); if (!cap.isOpened()) { fprintf(stderr, "Error: Cannot open camera %d\n", cam); exit(1); } namedWindow(win, CV_WINDOW_AUTOSIZE); Mat fgMaskMOG; BackgroundSubtractorMOG2 MOG; Mat inputFrame, outFrame, scoreFrame; cap >> inputFrame; int height = inputFrame.rows; int width = inputFrame.cols; // initial position Point pt; pt.x = RADIUS; pt.y = height / 4; // initial momentum Point momentum; momentum.x = 0; momentum.y = 0; Mat circ; cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR); cvtColor(inputFrame, scoreFrame, CV_LOAD_IMAGE_COLOR); cvtColor(inputFrame, circ, CV_BGR2GRAY); int count = 0; int sum; Mat reverseFrame; Mat ballFrame, handFrame; Mat foregroundMask, backgroundMask; Point small; int score=0, left=0, right=0; int timer = 50; // 50 frames between points are scored /* A score frame is used because drawing text is a VERY expensive operation, adding two images together is almost 10x faster than using the putText function SO: A mask is created with the current score, and it is only updated between points being scored. */ //Initialize the scoreFrame here string text = "First to 5 Points Wins"; int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX; int baseline=0; double fontScale = 3; Size textSize = getTextSize(text, fontFace, fontScale, 8, &baseline); // center the text Point textOrg((scoreFrame.cols - textSize.width)/2, (scoreFrame.rows + textSize.height)/2); scoreFrame = scoreFrame > 256; putText(scoreFrame, "First to 5 points wins", textOrg, fontFace, fontScale, Scalar(255,255,255), 1, 8, false ); //Hackish way to Initialize the game right = -1; score = -1; while(++count) { cap >> inputFrame; if (reverseMirror) { inputFrame.copyTo(reverseFrame); flip(reverseFrame, inputFrame, 1); } cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR); MOG(inputFrame, fgMaskMOG); foregroundMask = fgMaskMOG > THRESH; backgroundMask = fgMaskMOG <= THRESH; score = pongDir(&momentum, &pt, height, width); if (!score) { // still moving // blank canvas circ.setTo(Scalar(0, 0, 0)); Rect ballRegion(pt.x - RADIUS, pt.y - RADIUS, 2 * RADIUS, 2 * RADIUS); ballFrame = circ(ballRegion); fgMaskMOG.setTo(Scalar(255, 255, 255), foregroundMask); // clean up fgMaskMOG.setTo(Scalar(0, 0, 0), backgroundMask); handFrame = fgMaskMOG(ballRegion); int halfRad = RADIUS / 2; // top left small.x = halfRad; small.y = halfRad; sum = getOverlap(&ballFrame, &handFrame, &small); momentum.x += pt.x < width / 2 ? sum : 0; momentum.y += sum; // top right small.x = 3 * halfRad; small.y = halfRad; sum = getOverlap(&ballFrame, &handFrame, &small); momentum.x += pt.x >= width / 2 ? -sum : 0; momentum.y += sum; // bottom left small.x = halfRad; small.y = 3 * halfRad; sum = getOverlap(&ballFrame, &handFrame, &small); momentum.x += pt.x < width / 2 ? sum : 0; momentum.y -= sum; // bottom right small.x = 3 * halfRad; small.y = 3 * halfRad; sum = getOverlap(&ballFrame, &handFrame, &small); momentum.x += pt.x >= width / 2 ? -sum : 0; momentum.y -= sum; }else if (!timer--){ //someone scored, so decrement timer and reset when timer = 0 timer = 50; reset_board(&pt, &momentum, width, height); if (score >0){ left +=1; } else{ right += 1; } //Zero out scoreFrame scoreFrame = scoreFrame > 256; //Put score on the left putText(scoreFrame, to_string(left), Point(50-RADIUS,height-50), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar(255,255,255), 1, 8, false ); // Put right score on right putText(scoreFrame, to_string(right), Point(width-50,height-50), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar(255,255,255), 1, 8, false ); //Draw the games dividing line line(scoreFrame, Point(width/2,0), Point(width/2,height), Scalar(0,255,0), 2, 0,0 ); if ( right >= 5 || left >= 5){ //Game over, stop playing // game_over(right,left); break; } } // outFrame -= Scalar(50,50,50); // cvtColor(foregroundMask, inputFrame, CV_LOAD_IMAGE_COLOR); // outFrame.setTo(Scalar(0, 0, 0)); // outFrame.setTo(Scalar(255, 255, 255), foregroundMask); //Set the color of the ball here. cvtColor(foregroundMask,foregroundMask ,COLOR_GRAY2BGR); addWeighted(outFrame, 0.75, foregroundMask, 0.25, 1, outFrame, -1); drawCircle(outFrame, pt, RADIUS, Scalar( 0, 0, 255 )); // Put score frame onto image addWeighted(outFrame, 0.75, scoreFrame, 1.0, 1, outFrame, -1); imshow(win,outFrame); // listening for key press char c = waitKey(30); if (c >= 0) { if (c == 'r') { pt.x = width / 2; pt.y = height / 2; continue; } else break; } } return 0; } <|endoftext|>
<commit_before><commit_msg>spaces<commit_after><|endoftext|>
<commit_before>#include "X.h" #include "Units.h" #include "Planar.h" using namespace GeFiCa; void X::GetBoundaryConditionFrom(Detector &detector) { Grid::GetBoundaryConditionFrom(detector); // check number of calls TString type(detector.ClassName()); if (type.Contains("Planar")==false) { Error("GetBoundaryConditionFrom", "%s is not expected. " "Please pass in a Planar detector.", type.Data()); abort(); } Planar& planar = (Planar&) detector; planar.CheckConfigurations(); fDetector = &detector; // for GetC to use fDetector->Bias[] for (size_t i=0; i<N1; i++) { dC1p.push_back(planar.Height/(N1-1)); dC1m.push_back(planar.Height/(N1-1)); C1.push_back(i*dC1p[i]); E1.push_back(0); Et.push_back(0); fIsFixed.push_back(false); fIsDepleted.push_back(false); Src.push_back(-planar.GetImpurity(C1[i])*Qe/epsilon); } dC1m[0]=0; dC1p[N1-1]=0; // fix 1st and last points fIsFixed[0]=true; fIsFixed[N1-1]=true; // linear interpolation between Bias[0] and Bias[1] double slope = (planar.Bias[1]-planar.Bias[0])/(N1-1); for (size_t i=0; i<N1; i++) Vp.push_back(planar.Bias[0]+slope*i); Vp[N1-1]=planar.Bias[1]; } //_____________________________________________________________________________ // void X::SolveAnalytically() { Grid::SolveAnalytically(); // check if impurity is constant double h=C1[N1-1]-C1[0]; double a=-Src[0]/2; double b=(Vp[N1-1]-Vp[0]-a*h*h)/h; double c=Vp[0]; for (size_t i=0; i<N1; i++) Vp[i] = a*C1[i]*C1[i]+b*C1[i]+c; CalculateE(); } //_____________________________________________________________________________ // void X::OverRelaxAt(size_t idx) { if (fIsFixed[idx]) return; // no need to calculate on boundaries // calculate Vp[idx] from Vp[idx-1] and Vp[idx+1] double vnew = Src[idx]*dC1m[idx]*dC1p[idx]/2 + (dC1p[idx]*Vp[idx-1]+dC1m[idx]*Vp[idx+1])/(dC1m[idx]+dC1p[idx]); vnew = RelaxationFactor*(vnew-Vp[idx]) + Vp[idx]; // over relax // check depletion and update Vp[idx] accordingly double min=Vp[idx-1], max=Vp[idx-1]; if (min>Vp[idx+1]) min=Vp[idx+1]; if (max<Vp[idx+1]) max=Vp[idx+1]; if (vnew<min) { fIsDepleted[idx]=false; Vp[idx]=min; } else if (vnew>max) { fIsDepleted[idx]=false; Vp[idx]=max; } else { fIsDepleted[idx]=true; Vp[idx]=vnew; } // update Vp for impurity-only case even if the point is undepleted if (Vp[0]==Vp[N1-1]) Vp[idx]=vnew; } //_____________________________________________________________________________ // void X::CalculateE() { for (size_t i=1; i<N1-1; i++) { E1[i]=(Vp[i+1]-Vp[i-1])/(dC1p[i]+dC1m[i]); Et[i]=E1[i]; } E1[0]=(Vp[1]-Vp[0])/dC1p[0]; Et[0]=E1[0]; E1[N1-1]=(Vp[N1-1]-Vp[N1-2])/dC1m[N1-1]; Et[N1-1]=E1[N1-1]; } <commit_msg>added GetC back<commit_after>#include "X.h" #include "Units.h" #include "Planar.h" using namespace GeFiCa; void X::GetBoundaryConditionFrom(Detector &detector) { Grid::GetBoundaryConditionFrom(detector); // check number of calls TString type(detector.ClassName()); if (type.Contains("Planar")==false) { Error("GetBoundaryConditionFrom", "%s is not expected. " "Please pass in a Planar detector.", type.Data()); abort(); } Planar& planar = (Planar&) detector; planar.CheckConfigurations(); fDetector = &detector; // for GetC to use fDetector->Bias[] for (size_t i=0; i<N1; i++) { dC1p.push_back(planar.Height/(N1-1)); dC1m.push_back(planar.Height/(N1-1)); C1.push_back(i*dC1p[i]); E1.push_back(0); Et.push_back(0); fIsFixed.push_back(false); fIsDepleted.push_back(false); Src.push_back(-planar.GetImpurity(C1[i])*Qe/epsilon); } dC1m[0]=0; dC1p[N1-1]=0; // fix 1st and last points fIsFixed[0]=true; fIsFixed[N1-1]=true; // linear interpolation between Bias[0] and Bias[1] double slope = (planar.Bias[1]-planar.Bias[0])/(N1-1); for (size_t i=0; i<N1; i++) Vp.push_back(planar.Bias[0]+slope*i); Vp[N1-1]=planar.Bias[1]; } //______________________________________________________________________________ // void X::SolveAnalytically() { Grid::SolveAnalytically(); // check if impurity is constant double h=C1[N1-1]-C1[0]; double a=-Src[0]/2; double b=(Vp[N1-1]-Vp[0]-a*h*h)/h; double c=Vp[0]; for (size_t i=0; i<N1; i++) Vp[i] = a*C1[i]*C1[i]+b*C1[i]+c; CalculateE(); } //______________________________________________________________________________ // double X::GetC() { Grid::GetC(); // calculate field excluding undepleted region double dV = fDetector->Bias[1]-fDetector->Bias[0]; if (dV<0) dV=-dV; double integral=0; for (size_t i=0; i<GetN(); i++) { integral+=E1[i]*E1[i]*dC1p[i]; if (!fIsDepleted[i]) fIsFixed[i]=false; // release undepleted points } double c=integral*epsilon/dV/dV; Info("GetC","%.2f pF/cm2",c/pF*cm2); return c; } //______________________________________________________________________________ // void X::OverRelaxAt(size_t idx) { if (fIsFixed[idx]) return; // no need to calculate on boundaries // calculate Vp[idx] from Vp[idx-1] and Vp[idx+1] double vnew = Src[idx]*dC1m[idx]*dC1p[idx]/2 + (dC1p[idx]*Vp[idx-1]+dC1m[idx]*Vp[idx+1])/(dC1m[idx]+dC1p[idx]); vnew = RelaxationFactor*(vnew-Vp[idx]) + Vp[idx]; // over relax // check depletion and update Vp[idx] accordingly double min=Vp[idx-1], max=Vp[idx-1]; if (min>Vp[idx+1]) min=Vp[idx+1]; if (max<Vp[idx+1]) max=Vp[idx+1]; if (vnew<min) { fIsDepleted[idx]=false; Vp[idx]=min; } else if (vnew>max) { fIsDepleted[idx]=false; Vp[idx]=max; } else { fIsDepleted[idx]=true; Vp[idx]=vnew; } // update Vp for impurity-only case even if the point is undepleted if (Vp[0]==Vp[N1-1]) Vp[idx]=vnew; } //_____________________________________________________________________________ // void X::CalculateE() { for (size_t i=1; i<N1-1; i++) { E1[i]=(Vp[i+1]-Vp[i-1])/(dC1p[i]+dC1m[i]); Et[i]=E1[i]; } E1[0]=(Vp[1]-Vp[0])/dC1p[0]; Et[0]=E1[0]; E1[N1-1]=(Vp[N1-1]-Vp[N1-2])/dC1m[N1-1]; Et[N1-1]=E1[N1-1]; } <|endoftext|>
<commit_before>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <iostream> #include "common.hh" namespace avl6 { struct AVLNodeBase; using Base = AVLNodeBase; using BasePtr = Base*; using ConstBasePtr = const Base*; struct AVLNodeBase { BasePtr parent; BasePtr left; BasePtr right; int height; inline int left_height() const noexcept { return left != nullptr ? left->height : 0; } inline int right_height() const noexcept { return right != nullptr ? right->height : 0; } inline void update_height() noexcept { height = Xt::max(left_height(), right_height()) + 1; } static inline BasePtr _minimum(BasePtr x) noexcept { while (x->left != nullptr) x = x->left; return x; } static inline ConstBasePtr _minimum(ConstBasePtr x) noexcept { return _minimum(const_cast<BasePtr>(x)); } static inline BasePtr _maximum(BasePtr x) noexcept { while (x->right != nullptr) x = x->right; return x; } static inline ConstBasePtr _maximum(ConstBasePtr x) noexcept { return _maximum(const_cast<BasePtr>(x)); } }; template <typename Value> struct AVLNode : public AVLNodeBase { Value value; }; struct AVLIterBase { BasePtr _node{}; AVLIterBase() noexcept {} AVLIterBase(BasePtr x) noexcept : _node(x) {} AVLIterBase(ConstBasePtr x) noexcept : _node(const_cast<BasePtr>(x)) {} inline void increment() noexcept { if (_node->right != nullptr) { _node = _node->right; while (_node->left != nullptr) _node = _node->left; } else { BasePtr y = _node->parent; while (_node == y->right) { _node = y; y = y->parent; } if (_node->right != y) _node = y; } } inline void decrement() noexcept { if (_node->parent->parent == _node) { _node = _node->parent; } else if (_node->left != nullptr) { _node = _node->left; while (_node->right != nullptr) _node = _node->right; } else { BasePtr y = _node->parent; while (_node == y->left) { _node = y; y = y->parent; } _node = y; } } }; template <typename _Tp, typename _Ref, typename _Ptr> struct AVLIter : public AVLIterBase { using Iter = AVLIter<_Tp, _Tp&, _Tp*>; using Self = AVLIter<_Tp, _Ref, _Ptr>; using Ref = _Ref; using Ptr = _Ptr; using Node = AVLNode<_Tp>; using Link = Node*; using ConstLink = const Node*; AVLIter() noexcept {} AVLIter(BasePtr x) noexcept : AVLIterBase(x) {} AVLIter(ConstBasePtr x) noexcept : AVLIterBase(x) {} AVLIter(Link x) noexcept : AVLIterBase(x) {} AVLIter(ConstLink x) noexcept : AVLIterBase(x) {} AVLIter(const Iter& x) noexcept { _node = x._node; } inline bool operator==(const Self& x) const noexcept { return _node == x._node; } inline bool operator!=(const Self& x) const noexcept { return _node != x._node; } inline Ref operator*() const noexcept { return Link(_node)->value; } inline Ptr operator->() const noexcept { return &Link(_node)->value; } inline Self& operator++() noexcept { increment(); return *this; } inline Self operator++(int) noexcept { Self tmp(*this); increment(); return tmp; } inline Self& operator--() noexcept { decrement(); return *this; } inline Self operator--(int) noexcept { Self tmp(*this); decrement(); return tmp; } }; } void test_avl6() { avl6::AVLIter<int, int&, int*> i; } <commit_msg>:construction: chore(avl-tree): updated the avl-tree implementation<commit_after>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <iostream> #include "common.hh" namespace avl6 { struct AVLNodeBase; using Base = AVLNodeBase; using BasePtr = Base*; using ConstBasePtr = const Base*; struct AVLNodeBase { BasePtr parent; BasePtr left; BasePtr right; int height; inline int lheight() const noexcept { return left != nullptr ? left->height : 0; } inline int rheight() const noexcept { return right != nullptr ? right->height : 0; } inline void update_height() noexcept { height = Xt::max(lheight(), rheight()) + 1; } static inline BasePtr _minimum(BasePtr x) noexcept { while (x->left != nullptr) x = x->left; return x; } static inline ConstBasePtr _minimum(ConstBasePtr x) noexcept { return _minimum(const_cast<BasePtr>(x)); } static inline BasePtr _maximum(BasePtr x) noexcept { while (x->right != nullptr) x = x->right; return x; } static inline ConstBasePtr _maximum(ConstBasePtr x) noexcept { return _maximum(const_cast<BasePtr>(x)); } }; inline void _avlnode_replace_child( BasePtr x, BasePtr y, BasePtr p, BasePtr& root) noexcept { if (p != nullptr) { if (p->left == x) p->left = y; else p->right = y; } else { root = y; } } inline BasePtr avlnode_rotate_left(BasePtr x, BasePtr& root) noexcept { // | | // x y // \ / \ // y x b // / \ \ // [a] b [a] BasePtr y = x->right; x->right = y->left; if (x->right != nullptr) x->right->parent = x; y->parent = x->parent; _avlnode_replace_child(x, y, x->parent, root); y->left = x; x->parent = y; return y; } inline BasePtr avlnode_rotate_right(BasePtr x, BasePtr& root) noexcept { // | | // x y // / / \ // y a x // / \ / // a [b] [b] BasePtr y = x->left; x->left = y->right; if (x->left != nullptr) x->left->parent = x; y->parent = x->parent; _avlnode_replace_child(x, y, x->parent, root); y->right = x; x->parent = y; return y; } template <typename Value> struct AVLNode : public AVLNodeBase { Value value; }; struct AVLIterBase { BasePtr _node{}; AVLIterBase() noexcept {} AVLIterBase(BasePtr x) noexcept : _node(x) {} AVLIterBase(ConstBasePtr x) noexcept : _node(const_cast<BasePtr>(x)) {} inline void increment() noexcept { if (_node->right != nullptr) { _node = _node->right; while (_node->left != nullptr) _node = _node->left; } else { BasePtr y = _node->parent; while (_node == y->right) { _node = y; y = y->parent; } if (_node->right != y) _node = y; } } inline void decrement() noexcept { if (_node->parent->parent == _node) { _node = _node->parent; } else if (_node->left != nullptr) { _node = _node->left; while (_node->right != nullptr) _node = _node->right; } else { BasePtr y = _node->parent; while (_node == y->left) { _node = y; y = y->parent; } _node = y; } } }; template <typename _Tp, typename _Ref, typename _Ptr> struct AVLIter : public AVLIterBase { using Iter = AVLIter<_Tp, _Tp&, _Tp*>; using Self = AVLIter<_Tp, _Ref, _Ptr>; using Ref = _Ref; using Ptr = _Ptr; using Node = AVLNode<_Tp>; using Link = Node*; using ConstLink = const Node*; AVLIter() noexcept {} AVLIter(BasePtr x) noexcept : AVLIterBase(x) {} AVLIter(ConstBasePtr x) noexcept : AVLIterBase(x) {} AVLIter(Link x) noexcept : AVLIterBase(x) {} AVLIter(ConstLink x) noexcept : AVLIterBase(x) {} AVLIter(const Iter& x) noexcept { _node = x._node; } inline bool operator==(const Self& x) const noexcept { return _node == x._node; } inline bool operator!=(const Self& x) const noexcept { return _node != x._node; } inline Ref operator*() const noexcept { return Link(_node)->value; } inline Ptr operator->() const noexcept { return &Link(_node)->value; } inline Self& operator++() noexcept { increment(); return *this; } inline Self operator++(int) noexcept { Self tmp(*this); increment(); return tmp; } inline Self& operator--() noexcept { decrement(); return *this; } inline Self operator--(int) noexcept { Self tmp(*this); decrement(); return tmp; } }; template <typename Tp> class AVLTree final : private UnCopyable { public: using ValueType = Tp; using SizeType = std::size_t; using Iter = AVLIter<Tp, Tp&, Tp*>; using ConstIter = AVLIter<Tp, const Tp&, const Tp*>; using Ref = Tp&; using ConstRef = const Tp&; private: using Node = AVLNode<ValueType>; using Link = Node*; using ConstLink = const Node*; using Alloc = Xt::SimpleAlloc<Node>; SizeType size_{}; Node head_{}; static inline Link _parent(BasePtr x) noexcept { return static_cast<Link>(x->parent); } static inline Link _parent(Link x) noexcept { return static_cast<Link>(x->parent); } static inline Link _left(BasePtr x) noexcept { return static_cast<Link>(x->left); } static inline Link _left(Link x) noexcept { return static_cast<Link>(x->left); } static inline Link _right(BasePtr x) noexcept { return static_cast<Link>(x->right); } static inline Link _right(Link x) noexcept { return static_cast<Link>(x->right); } inline Link _root_link() noexcept { return static_cast<Link>(head_.left); } inline Link _tail_link() noexcept { return static_cast<Link>(&head_); } inline void initialize() noexcept { head_.parent = nullptr; head_.left = head_.right = &head_; head_.height = 0; } inline Link create_node(const ValueType& x) { Link tmp = Alloc::create_node(); try { Xt::construct(&tmp->value, x); } catch (...) { Alloc::deallocate(tmp); throw; } return tmp; } inline void destroy_node(Link p) { Xt::destroy(&p->value); Alloc::deallocate(p); } inline void insert_aux(const ValueType& value) { } public: AVLTree() noexcept { initialize(); } ~AVLTree() noexcept { } inline bool empty() const noexcept { return size_ == 0; } inline SizeType size() const noexcept { return size_; } inline Iter begin() noexcept { return Iter(head_.left); } inline ConstIter begin() const noexcept { return ConstIter(head_.left); } inline Iter end() noexcept { return Iter(&head_); } inline ConstIter end() const noexcept { return ConstIter(&head_); } inline Ref get_head() noexcept { return *begin(); } inline ConstRef get_head() const noexcept { return *begin(); } inline Ref get_tail() noexcept { return *(--end()); } inline ConstRef get_tail() const noexcept { return *(--end()); } template <typename Function> inline void for_each(Function&& fn) noexcept { for (auto i = begin(); i != end(); ++i) fn(*i); } }; } void test_avl6() { avl6::AVLIter<int, int&, int*> i; avl6::AVLTree<int> t; } <|endoftext|>
<commit_before>#include "../stdafx.h" #include "wrapper/cms/signed_data.h" Handle<CertificateCollection> SignedData::certificates(){ LOGGER_FN(); STACK_OF(X509) *certs; LOGGER_OPENSSL(CMS_get1_certs); certs = CMS_get1_certs(this->internal()); return new CertificateCollection(certs); } Handle<Certificate> SignedData::certificates(int index){ LOGGER_FN(); return this->certificates()->items(index); } Handle<SignerCollection> SignedData::signers(){ LOGGER_FN(); stack_st_CMS_SignerInfo *signers_ = CMS_get0_SignerInfos(this->internal()); return new SignerCollection(signers_, this->handle()); } Handle<Signer> SignedData::signers(int index){ LOGGER_FN(); return this->signers()->items(index); } bool SignedData::isDetached(){ LOGGER_FN(); LOGGER_OPENSSL("CMS_is_detached"); int res = CMS_is_detached(this->internal()); if (res == -1){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "CMS_is_detached"); } return res == 1; } void SignedData::read(Handle<Bio> in, DataFormat::DATA_FORMAT format){ LOGGER_FN(); try{ if (in.isEmpty()){ THROW_EXCEPTION(0, SignedData, NULL, "Parameter %d cann't be NULL", 1); } CMS_ContentInfo *ci = NULL; in->reset(); switch (format){ case DataFormat::DER: LOGGER_OPENSSL(d2i_CMS_bio); ci = d2i_CMS_bio(in->internal(), NULL); if (ci == NULL){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "d2i_CMS_bio"); } LOGGER_OPENSSL(CMS_is_detached); if (ci && !CMS_is_detached(ci)){ LOGGER_INFO("Get content from DER file"); LOGGER_OPENSSL(CMS_get0_content); ASN1_OCTET_STRING *asn = (*CMS_get0_content(ci)); if (asn == NULL){ THROW_EXCEPTION(0, SignedData, NULL, "CMS_get0_content"); } LOGGER_OPENSSL(BIO_new_mem_buf); Handle<Bio> content = new Bio(BIO_new_mem_buf(asn->data, asn->length)); if (content->internal() == NULL){ THROW_EXCEPTION(0, SignedData, NULL, "Error set content cms to BIO"); } this->setContent(content); } break; case DataFormat::BASE64: { LOGGER_OPENSSL("PEM_read_bio_CMS"); if ((ci = PEM_read_bio_CMS(in->internal(), NULL, NULL, NULL)) == NULL){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "PEM_read_bio_CMS"); }; LOGGER_OPENSSL(CMS_is_detached); if (ci && !CMS_is_detached(ci)){ LOGGER_INFO("Get content from DER file"); ASN1_OCTET_STRING *asn = (*CMS_get0_content(ci)); if (asn == NULL){ THROW_EXCEPTION(0, SignedData, NULL, "CMS_get0_content"); } Handle<Bio> content = new Bio(BIO_new_mem_buf(asn->data, asn->length)); if (content->internal() == NULL){ THROW_EXCEPTION(0, SignedData, NULL, "Error set content cms to BIO"); } this->setContent(content); } break; } default: THROW_EXCEPTION(0, SignedData, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format); } if (!ci) { puts(OpenSSL::printErrors()->c_str()); THROW_EXCEPTION(0, SignedData, NULL, "Can not read CMS signed data from BIO"); } this->setData(ci); } catch (Handle<Exception> e){ THROW_EXCEPTION(0, SignedData, e, "Error read cms"); } } void SignedData::write(Handle<Bio> out, DataFormat::DATA_FORMAT format){ LOGGER_FN(); if (out.isEmpty()) THROW_EXCEPTION(0, SignedData, NULL, "Parameter %d is NULL", 1); switch (format){ case DataFormat::DER: LOGGER_OPENSSL("i2d_CMS_bio"); if (i2d_CMS_bio(out->internal(), this->internal()) < 1) THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "i2d_CMS_bio", NULL); // LOGGER_OPENSSL("i2d_CMS_bio_stream"); // if (i2d_CMS_bio_stream(out->internal(), this->internal(), this->content->internal(), flags) < 1) // THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "i2d_CMS_bio_stream", NULL); break; case DataFormat::BASE64: LOGGER_OPENSSL("PEM_write_bio_CMS"); if (PEM_write_bio_CMS(out->internal(), this->internal()) < 1) THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "PEM_write_bio_CMS", NULL); // LOGGER_OPENSSL("PEM_write_bio_CMS_stream"); // if (PEM_write_bio_CMS_stream(out->internal(), this->internal(), this->content->internal(), flags) < 1) // THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "PEM_write_bio_CMS_stream", NULL); break; default: THROW_EXCEPTION(0, SignedData, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format); } } Handle<Signer> SignedData::createSigner(Handle<Certificate> cert, Handle<Key> pkey){ LOGGER_FN(); int def_nid; LOGGER_OPENSSL("EVP_PKEY_get_default_digest_nid"); if (EVP_PKEY_get_default_digest_nid(pkey->internal(), &def_nid) <= 0) { THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "Unknown digest name"); } LOGGER_OPENSSL("EVP_PKEY_get_default_digest_nid"); const EVP_MD *md = EVP_get_digestbynid(def_nid); if (md == NULL) { THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "No default digest"); } LOGGER_OPENSSL("CMS_add1_signer"); CMS_SignerInfo *signer = CMS_add1_signer(this->internal(), cert->internal(), pkey->internal(), md, flags); if (!signer){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "CMS_add1_signer"); } return new Signer(signer, this->handle()); } void SignedData::addCertificate(Handle<Certificate> cert){ LOGGER_FN(); Handle<Certificate> cert_copy = cert->duplicate(); LOGGER_OPENSSL("CMS_add0_cert"); if (CMS_add0_cert(this->internal(), cert_copy->internal()) < 1){ THROW_EXCEPTION(0, SignedData, NULL, "Certificate already present"); } cert_copy->setParent(this->handle()); } void SignedData::setContent(Handle<Bio> value){ LOGGER_FN(); this->content = value; } Handle<Bio> SignedData::getContent(){ LOGGER_FN(); this->content->reset(); return this->content; } bool SignedData::verify(Handle<CertificateCollection> certs){ LOGGER_FN(); int res; try { stack_st_X509 *pCerts = NULL; if (!certs.isEmpty()){ pCerts = certs->internal(); } // content->reset(); X509_STORE *store = X509_STORE_new(); LOGGER_OPENSSL("CMS_verify"); res = CMS_verify(this->internal(), pCerts, store, content->internal(), NULL, flags); LOGGER_OPENSSL("X509_STORE_free"); X509_STORE_free(store); return res == 1; } catch (Handle<Exception> e){ THROW_EXCEPTION(0, SignedData, e, "Error CMS verify"); } } Handle<SignedData> SignedData::sign(Handle<Certificate> cert, Handle<Key> pkey, Handle<CertificateCollection> certs, Handle<Bio> content, unsigned int flags){ LOGGER_FN(); LOGGER_OPENSSL("CMS_sign"); CMS_ContentInfo *res = CMS_sign(cert->internal(), pkey->internal(), certs->internal(), content->internal(), flags); if (!res){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "CMS_sign"); } Handle<SignedData> sd = new SignedData(res); sd->flags = flags; return sd; } void SignedData::sign(){ LOGGER_FN(); if (!(flags & CMS_DETACHED)){ CMS_set_detached(this->internal(), 0); } flags |= CMS_BINARY; /*Don't translate message to text*/ LOGGER_OPENSSL("CMS_final"); if (CMS_final(this->internal(), this->content->internal(), NULL, flags) < 1){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "CMS_final"); } } int SignedData::getFlags(){ LOGGER_FN(); return this->flags; } void SignedData::setFlags(int v){ LOGGER_FN(); this->flags = v; } void SignedData::addFlag(int v){ LOGGER_FN(); this->flags |= v; } void SignedData::removeFlags(int v){ LOGGER_FN(); this->flags ^= v; } <commit_msg>wrapper: changed function for get default md<commit_after>#include "../stdafx.h" #include "wrapper/cms/signed_data.h" Handle<CertificateCollection> SignedData::certificates(){ LOGGER_FN(); STACK_OF(X509) *certs; LOGGER_OPENSSL(CMS_get1_certs); certs = CMS_get1_certs(this->internal()); return new CertificateCollection(certs); } Handle<Certificate> SignedData::certificates(int index){ LOGGER_FN(); return this->certificates()->items(index); } Handle<SignerCollection> SignedData::signers(){ LOGGER_FN(); stack_st_CMS_SignerInfo *signers_ = CMS_get0_SignerInfos(this->internal()); return new SignerCollection(signers_, this->handle()); } Handle<Signer> SignedData::signers(int index){ LOGGER_FN(); return this->signers()->items(index); } bool SignedData::isDetached(){ LOGGER_FN(); LOGGER_OPENSSL("CMS_is_detached"); int res = CMS_is_detached(this->internal()); if (res == -1){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "CMS_is_detached"); } return res == 1; } void SignedData::read(Handle<Bio> in, DataFormat::DATA_FORMAT format){ LOGGER_FN(); try{ if (in.isEmpty()){ THROW_EXCEPTION(0, SignedData, NULL, "Parameter %d cann't be NULL", 1); } CMS_ContentInfo *ci = NULL; in->reset(); switch (format){ case DataFormat::DER: LOGGER_OPENSSL(d2i_CMS_bio); ci = d2i_CMS_bio(in->internal(), NULL); if (ci == NULL){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "d2i_CMS_bio"); } LOGGER_OPENSSL(CMS_is_detached); if (ci && !CMS_is_detached(ci)){ LOGGER_INFO("Get content from DER file"); LOGGER_OPENSSL(CMS_get0_content); ASN1_OCTET_STRING *asn = (*CMS_get0_content(ci)); if (asn == NULL){ THROW_EXCEPTION(0, SignedData, NULL, "CMS_get0_content"); } LOGGER_OPENSSL(BIO_new_mem_buf); Handle<Bio> content = new Bio(BIO_new_mem_buf(asn->data, asn->length)); if (content->internal() == NULL){ THROW_EXCEPTION(0, SignedData, NULL, "Error set content cms to BIO"); } this->setContent(content); } break; case DataFormat::BASE64: { LOGGER_OPENSSL("PEM_read_bio_CMS"); if ((ci = PEM_read_bio_CMS(in->internal(), NULL, NULL, NULL)) == NULL){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "PEM_read_bio_CMS"); }; LOGGER_OPENSSL(CMS_is_detached); if (ci && !CMS_is_detached(ci)){ LOGGER_INFO("Get content from DER file"); ASN1_OCTET_STRING *asn = (*CMS_get0_content(ci)); if (asn == NULL){ THROW_EXCEPTION(0, SignedData, NULL, "CMS_get0_content"); } Handle<Bio> content = new Bio(BIO_new_mem_buf(asn->data, asn->length)); if (content->internal() == NULL){ THROW_EXCEPTION(0, SignedData, NULL, "Error set content cms to BIO"); } this->setContent(content); } break; } default: THROW_EXCEPTION(0, SignedData, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format); } if (!ci) { puts(OpenSSL::printErrors()->c_str()); THROW_EXCEPTION(0, SignedData, NULL, "Can not read CMS signed data from BIO"); } this->setData(ci); } catch (Handle<Exception> e){ THROW_EXCEPTION(0, SignedData, e, "Error read cms"); } } void SignedData::write(Handle<Bio> out, DataFormat::DATA_FORMAT format){ LOGGER_FN(); if (out.isEmpty()) THROW_EXCEPTION(0, SignedData, NULL, "Parameter %d is NULL", 1); switch (format){ case DataFormat::DER: LOGGER_OPENSSL("i2d_CMS_bio"); if (i2d_CMS_bio(out->internal(), this->internal()) < 1) THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "i2d_CMS_bio", NULL); // LOGGER_OPENSSL("i2d_CMS_bio_stream"); // if (i2d_CMS_bio_stream(out->internal(), this->internal(), this->content->internal(), flags) < 1) // THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "i2d_CMS_bio_stream", NULL); break; case DataFormat::BASE64: LOGGER_OPENSSL("PEM_write_bio_CMS"); if (PEM_write_bio_CMS(out->internal(), this->internal()) < 1) THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "PEM_write_bio_CMS", NULL); // LOGGER_OPENSSL("PEM_write_bio_CMS_stream"); // if (PEM_write_bio_CMS_stream(out->internal(), this->internal(), this->content->internal(), flags) < 1) // THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "PEM_write_bio_CMS_stream", NULL); break; default: THROW_EXCEPTION(0, SignedData, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format); } } Handle<Signer> SignedData::createSigner(Handle<Certificate> cert, Handle<Key> pkey){ LOGGER_FN(); const EVP_MD *md = EVP_get_digestbyname(cert->getSignatureDigest()->c_str()); LOGGER_OPENSSL("CMS_add1_signer"); CMS_SignerInfo *signer = CMS_add1_signer(this->internal(), cert->internal(), pkey->internal(), md, flags); if (!signer){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "CMS_add1_signer"); } return new Signer(signer, this->handle()); } void SignedData::addCertificate(Handle<Certificate> cert){ LOGGER_FN(); Handle<Certificate> cert_copy = cert->duplicate(); LOGGER_OPENSSL("CMS_add0_cert"); if (CMS_add0_cert(this->internal(), cert_copy->internal()) < 1){ THROW_EXCEPTION(0, SignedData, NULL, "Certificate already present"); } cert_copy->setParent(this->handle()); } void SignedData::setContent(Handle<Bio> value){ LOGGER_FN(); this->content = value; } Handle<Bio> SignedData::getContent(){ LOGGER_FN(); this->content->reset(); return this->content; } bool SignedData::verify(Handle<CertificateCollection> certs){ LOGGER_FN(); int res; try { stack_st_X509 *pCerts = NULL; if (!certs.isEmpty()){ pCerts = certs->internal(); } // content->reset(); X509_STORE *store = X509_STORE_new(); LOGGER_OPENSSL("CMS_verify"); res = CMS_verify(this->internal(), pCerts, store, content->internal(), NULL, flags); LOGGER_OPENSSL("X509_STORE_free"); X509_STORE_free(store); return res == 1; } catch (Handle<Exception> e){ THROW_EXCEPTION(0, SignedData, e, "Error CMS verify"); } } Handle<SignedData> SignedData::sign(Handle<Certificate> cert, Handle<Key> pkey, Handle<CertificateCollection> certs, Handle<Bio> content, unsigned int flags){ LOGGER_FN(); LOGGER_OPENSSL("CMS_sign"); CMS_ContentInfo *res = CMS_sign(cert->internal(), pkey->internal(), certs->internal(), content->internal(), flags); if (!res){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "CMS_sign"); } Handle<SignedData> sd = new SignedData(res); sd->flags = flags; return sd; } void SignedData::sign(){ LOGGER_FN(); if (!(flags & CMS_DETACHED)){ CMS_set_detached(this->internal(), 0); } flags |= CMS_BINARY; /*Don't translate message to text*/ LOGGER_OPENSSL("CMS_final"); if (CMS_final(this->internal(), this->content->internal(), NULL, flags) < 1){ THROW_OPENSSL_EXCEPTION(0, SignedData, NULL, "CMS_final"); } } int SignedData::getFlags(){ LOGGER_FN(); return this->flags; } void SignedData::setFlags(int v){ LOGGER_FN(); this->flags = v; } void SignedData::addFlag(int v){ LOGGER_FN(); this->flags |= v; } void SignedData::removeFlags(int v){ LOGGER_FN(); this->flags ^= v; } <|endoftext|>
<commit_before>#ifndef CAFFE_MOLGRID_DATA_LAYER_HPP_ #define CAFFE_MOLGRID_DATA_LAYER_HPP_ #include <string> #include <utility> #include <vector> #include <boost/array.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/unordered_map.hpp> #include <boost/math/quaternion.hpp> #include <boost/multi_array/multi_array_ref.hpp> #include "caffe/blob.hpp" #include "caffe/data_transformer.hpp" #include "caffe/internal_thread.hpp" #include "caffe/layer.hpp" #include "caffe/layers/base_data_layer.hpp" #include "caffe/proto/caffe.pb.h" #include "gninasrc/lib/atom_constants.h" #include "gninasrc/lib/gridmaker.h" namespace caffe { /** * @brief Provides data to the Net from n-dimension files of raw floating point data. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class MolGridDataLayer : public BaseDataLayer<Dtype> { public: explicit MolGridDataLayer(const LayerParameter& param) : BaseDataLayer<Dtype>(param), actives_pos_(0), decoys_pos_(0), all_pos_(0), num_rotations(0), current_rotation(0), example_size(0),balanced(false),inmem(false), resolution(0.5), dimension(23.5), radiusmultiple(1.5), randtranslate(0), binary(false), randrotate(false), dim(0), numgridpoints(0), numReceptorTypes(0),numLigandTypes(0), gpu_alloc_size(0), gpu_gridatoms(NULL), gpu_gridwhich(NULL) {} virtual ~MolGridDataLayer(); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "MolGridData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int ExactNumTopBlobs() const { return 2; } virtual inline void resetRotation() { current_rotation = 0; } virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); //set in memory buffer template<typename Atom> void setReceptor(const vector<Atom>& receptor) { //make this a template mostly so I don't have to pull in gnina atom class mem_rec.atoms.clear(); mem_rec.whichGrid.clear(); mem_rec.gradient.clear(); //receptor atoms for(unsigned i = 0, n = receptor.size(); i < n; i++) { const Atom& a = receptor[i]; smt t = a.sm; float4 ainfo; ainfo.x = a.coords[0]; ainfo.y = a.coords[1]; ainfo.z = a.coords[2]; ainfo.w = xs_radius(t); float3 gradient; gradient.x = 0.0; gradient.y = 0.0; gradient.z = 0.0; mem_rec.atoms.push_back(ainfo); mem_rec.whichGrid.push_back(rmap[t]); mem_rec.gradient.push_back(gradient); } } //set in memory buffer template<typename Atom, typename Vec3> void setLigand(const vector<Atom>& ligand, const vector<Vec3>& coords) { mem_lig.atoms.clear(); mem_lig.whichGrid.clear(); mem_lig.gradient.clear(); //ligand atoms, grid positions offset and coordinates are specified separately vec center(0,0,0); unsigned acnt = 0; for(unsigned i = 0, n = ligand.size(); i < n; i++) { smt t = ligand[i].sm; if(lmap[t] >= 0) { const Vec3& coord = coords[i]; float4 ainfo; ainfo.x = coord[0]; ainfo.y = coord[1]; ainfo.z = coord[2]; ainfo.w = xs_radius(t); float3 gradient; gradient.x = 0.0; gradient.y = 0.0; gradient.z = 0.0; mem_lig.atoms.push_back(ainfo); mem_lig.whichGrid.push_back(lmap[t]+numReceptorTypes); mem_lig.gradient.push_back(gradient); center += coord; acnt++; } } center /= acnt; //not ligand.size() because of hydrogens mem_lig.center = center; } protected: typedef GridMaker::quaternion quaternion; typedef typename boost::multi_array_ref<Dtype, 4> Grids; struct example { string receptor; string ligand; Dtype label; example(): label(0) {} example(Dtype l, const string& r, const string& lig): receptor(r), ligand(lig), label(l) {} }; virtual void Shuffle(); vector<example> actives_; vector<example> decoys_; vector<example> all_; string root_folder; int actives_pos_, decoys_pos_, all_pos_; unsigned num_rotations; unsigned current_rotation; unsigned example_size; //channels*numgridpoints vector<int> top_shape; bool balanced; bool inmem; vector<Dtype> labels; //grid stuff GridMaker gmaker; double resolution; double dimension; double radiusmultiple; //extra to consider past vdw radius double randtranslate; bool binary; //produce binary occupancies bool randrotate; unsigned dim; //grid points on one side unsigned numgridpoints; //dim*dim*dim vector<int> rmap; //map atom types to position in grid vectors vector<int> lmap; unsigned numReceptorTypes; unsigned numLigandTypes; unsigned gpu_alloc_size; float4 *gpu_gridatoms; short *gpu_gridwhich; void allocateGPUMem(unsigned sz); struct mol_info { vector<float4> atoms; vector<short> whichGrid; //separate for better memory layout on gpu vector<float3> gradient; vec center; //precalculate centroid, includes any random translation boost::array< pair<float, float>, 3> dims; mol_info() { center[0] = center[1] = center[2] = 0;} void append(const mol_info& a) { atoms.insert(atoms.end(), a.atoms.begin(), a.atoms.end()); whichGrid.insert(whichGrid.end(), a.whichGrid.begin(), a.whichGrid.end()); gradient.insert(gradient.end(), a.gradient.begin(), a.gradient.end()); } }; struct mol_transform { mol_info mol; quaternion Q; // rotation vec center; // translation mol_transform() { mol = mol_info(); Q = quaternion(0,0,0,0); center[0] = center[1] = center[2] = 0; } }; //need to remember how mols were transformed for backward pass vector<mol_transform> batch_transform; boost::unordered_map<string, mol_info> molcache; mol_info mem_rec; //molecular data set programmatically with setReceptor mol_info mem_lig; //molecular data set programmatically with setLigand quaternion axial_quaternion(); void set_mol_info(const string& file, const vector<int>& atommap, unsigned atomoffset, mol_info& minfo); void set_grid_ex(Dtype *grid, const example& ex, mol_transform& transform, bool gpu); void set_grid_minfo(Dtype *grid, const mol_info& recatoms, const mol_info& ligatoms, mol_transform& transform, bool gpu); void forward(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top, bool gpu); void backward(const vector<Blob<Dtype>*>& top, const vector<Blob<Dtype>*>& bottom, bool gpu); }; } // namespace caffe #endif // CAFFE_MOLGRID_DATA_LAYER_HPP_ <commit_msg>add getAtomGradient() to molgrid_data_layer.hpp<commit_after>#ifndef CAFFE_MOLGRID_DATA_LAYER_HPP_ #define CAFFE_MOLGRID_DATA_LAYER_HPP_ #include <string> #include <utility> #include <vector> #include <boost/array.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/unordered_map.hpp> #include <boost/math/quaternion.hpp> #include <boost/multi_array/multi_array_ref.hpp> #include "caffe/blob.hpp" #include "caffe/data_transformer.hpp" #include "caffe/internal_thread.hpp" #include "caffe/layer.hpp" #include "caffe/layers/base_data_layer.hpp" #include "caffe/proto/caffe.pb.h" #include "gninasrc/lib/atom_constants.h" #include "gninasrc/lib/gridmaker.h" namespace caffe { /** * @brief Provides data to the Net from n-dimension files of raw floating point data. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class MolGridDataLayer : public BaseDataLayer<Dtype> { public: explicit MolGridDataLayer(const LayerParameter& param) : BaseDataLayer<Dtype>(param), actives_pos_(0), decoys_pos_(0), all_pos_(0), num_rotations(0), current_rotation(0), example_size(0),balanced(false),inmem(false), resolution(0.5), dimension(23.5), radiusmultiple(1.5), randtranslate(0), binary(false), randrotate(false), dim(0), numgridpoints(0), numReceptorTypes(0),numLigandTypes(0), gpu_alloc_size(0), gpu_gridatoms(NULL), gpu_gridwhich(NULL) {} virtual ~MolGridDataLayer(); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "MolGridData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int ExactNumTopBlobs() const { return 2; } virtual inline void resetRotation() { current_rotation = 0; } virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); //getter for atom gradient of a structure in current batch vector<float3> getAtomGradient(int batch_idx) { return batch_transform[batch_idx].mol.gradient; } //set in memory buffer template<typename Atom> void setReceptor(const vector<Atom>& receptor) { //make this a template mostly so I don't have to pull in gnina atom class mem_rec.atoms.clear(); mem_rec.whichGrid.clear(); mem_rec.gradient.clear(); //receptor atoms for(unsigned i = 0, n = receptor.size(); i < n; i++) { const Atom& a = receptor[i]; smt t = a.sm; float4 ainfo; ainfo.x = a.coords[0]; ainfo.y = a.coords[1]; ainfo.z = a.coords[2]; ainfo.w = xs_radius(t); float3 gradient; gradient.x = 0.0; gradient.y = 0.0; gradient.z = 0.0; mem_rec.atoms.push_back(ainfo); mem_rec.whichGrid.push_back(rmap[t]); mem_rec.gradient.push_back(gradient); } } //set in memory buffer template<typename Atom, typename Vec3> void setLigand(const vector<Atom>& ligand, const vector<Vec3>& coords) { mem_lig.atoms.clear(); mem_lig.whichGrid.clear(); mem_lig.gradient.clear(); //ligand atoms, grid positions offset and coordinates are specified separately vec center(0,0,0); unsigned acnt = 0; for(unsigned i = 0, n = ligand.size(); i < n; i++) { smt t = ligand[i].sm; if(lmap[t] >= 0) { const Vec3& coord = coords[i]; float4 ainfo; ainfo.x = coord[0]; ainfo.y = coord[1]; ainfo.z = coord[2]; ainfo.w = xs_radius(t); float3 gradient; gradient.x = 0.0; gradient.y = 0.0; gradient.z = 0.0; mem_lig.atoms.push_back(ainfo); mem_lig.whichGrid.push_back(lmap[t]+numReceptorTypes); mem_lig.gradient.push_back(gradient); center += coord; acnt++; } } center /= acnt; //not ligand.size() because of hydrogens mem_lig.center = center; } protected: typedef GridMaker::quaternion quaternion; typedef typename boost::multi_array_ref<Dtype, 4> Grids; struct example { string receptor; string ligand; Dtype label; example(): label(0) {} example(Dtype l, const string& r, const string& lig): receptor(r), ligand(lig), label(l) {} }; virtual void Shuffle(); vector<example> actives_; vector<example> decoys_; vector<example> all_; string root_folder; int actives_pos_, decoys_pos_, all_pos_; unsigned num_rotations; unsigned current_rotation; unsigned example_size; //channels*numgridpoints vector<int> top_shape; bool balanced; bool inmem; vector<Dtype> labels; //grid stuff GridMaker gmaker; double resolution; double dimension; double radiusmultiple; //extra to consider past vdw radius double randtranslate; bool binary; //produce binary occupancies bool randrotate; unsigned dim; //grid points on one side unsigned numgridpoints; //dim*dim*dim vector<int> rmap; //map atom types to position in grid vectors vector<int> lmap; unsigned numReceptorTypes; unsigned numLigandTypes; unsigned gpu_alloc_size; float4 *gpu_gridatoms; short *gpu_gridwhich; void allocateGPUMem(unsigned sz); struct mol_info { vector<float4> atoms; vector<short> whichGrid; //separate for better memory layout on gpu vector<float3> gradient; vec center; //precalculate centroid, includes any random translation boost::array< pair<float, float>, 3> dims; mol_info() { center[0] = center[1] = center[2] = 0;} void append(const mol_info& a) { atoms.insert(atoms.end(), a.atoms.begin(), a.atoms.end()); whichGrid.insert(whichGrid.end(), a.whichGrid.begin(), a.whichGrid.end()); gradient.insert(gradient.end(), a.gradient.begin(), a.gradient.end()); } }; struct mol_transform { mol_info mol; quaternion Q; // rotation vec center; // translation mol_transform() { mol = mol_info(); Q = quaternion(0,0,0,0); center[0] = center[1] = center[2] = 0; } }; //need to remember how mols were transformed for backward pass vector<mol_transform> batch_transform; boost::unordered_map<string, mol_info> molcache; mol_info mem_rec; //molecular data set programmatically with setReceptor mol_info mem_lig; //molecular data set programmatically with setLigand quaternion axial_quaternion(); void set_mol_info(const string& file, const vector<int>& atommap, unsigned atomoffset, mol_info& minfo); void set_grid_ex(Dtype *grid, const example& ex, mol_transform& transform, bool gpu); void set_grid_minfo(Dtype *grid, const mol_info& recatoms, const mol_info& ligatoms, mol_transform& transform, bool gpu); void forward(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top, bool gpu); void backward(const vector<Blob<Dtype>*>& top, const vector<Blob<Dtype>*>& bottom, bool gpu); }; } // namespace caffe #endif // CAFFE_MOLGRID_DATA_LAYER_HPP_ <|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2011-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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : tests implicit interfaces // *************************************************************************** // Boost.Test #include <boost/test/unit_test.hpp> #include <boost/test/data/monomorphic/singleton.hpp> #include <boost/test/data/monomorphic/collection.hpp> #include <boost/test/data/monomorphic/array.hpp> #include <boost/test/data/monomorphic/join.hpp> #include <boost/test/data/monomorphic/zip.hpp> namespace data=boost::unit_test::data; #include "test_datasets.hpp" //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_implicit_for_each ) { data::for_each_sample( 2, check_arg_type<int>() ); data::for_each_sample( "ch", check_arg_type<char const*>() ); data::for_each_sample( 2., check_arg_type<double>() ); data::for_each_sample( std::vector<int>( 3 ), check_arg_type<int>() ); data::for_each_sample( std::list<double>( 2 ), check_arg_type<double>() ); invocation_count ic; ic.m_value = 0; data::for_each_sample( std::vector<int>( 3 ), ic ); BOOST_TEST( ic.m_value == 3 ); ic.m_value = 0; data::for_each_sample( std::list<double>( 2 ), ic, 1 ); BOOST_TEST( ic.m_value == 1 ); copy_count::value() = 0; std::vector<copy_count> samples1( 2 ); data::for_each_sample( samples1, check_arg_type<copy_count>() ); #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES BOOST_TEST( copy_count::value() == 0 ); #else // clang/darwin has apparently a non standard constructor for std::vector // in c++03 mode #if defined(BOOST_CLANG) && __APPLE__ BOOST_CHECK_MESSAGE( copy_count::value() == 2, BOOST_PLATFORM ); #else BOOST_TEST( copy_count::value() == 4 ); #endif #endif copy_count::value() = 0; copy_count samples2[] = { copy_count(), copy_count() }; data::for_each_sample( samples2, check_arg_type<copy_count>() ); BOOST_TEST( copy_count::value() == 0 ); } //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_implicit_join ) { #ifndef BOOST_NO_CXX11_AUTO_DECLARATIONS auto ds = data::make( 5 ); BOOST_TEST( (1 + ds).size() == 2 ); BOOST_TEST( (ds + 1).size() == 2 ); #endif #ifndef BOOST_NO_CXX11_DECLTYPE BOOST_TEST( (1 + data::make( 5 )).size() == 2 ); BOOST_TEST( (data::make( 5 ) + 1).size() == 2 ); #endif } //____________________________________________________________________________// #ifndef BOOST_TEST_NO_ZIP_COMPOSITION_AVAILABLE BOOST_AUTO_TEST_CASE( test_implicit_zip ) { #ifndef BOOST_NO_CXX11_AUTO_DECLARATIONS auto ds = data::make( 5 ); BOOST_TEST( (1 ^ ds).size() == 1 ); BOOST_TEST( (ds ^ 1).size() == 1 ); #endif BOOST_TEST( (1 ^ data::make( 5 )).size() == 1 ); BOOST_TEST( (data::make( 5 ) ^ 1).size() == 1 ); } #endif <commit_msg>Fixing counter for r-value ref supported but std::vector still lacking the proper constructor<commit_after>// (C) Copyright Gennadiy Rozental 2011-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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : tests implicit interfaces // *************************************************************************** // Boost.Test #include <boost/test/unit_test.hpp> #include <boost/test/data/monomorphic/singleton.hpp> #include <boost/test/data/monomorphic/collection.hpp> #include <boost/test/data/monomorphic/array.hpp> #include <boost/test/data/monomorphic/join.hpp> #include <boost/test/data/monomorphic/zip.hpp> namespace data=boost::unit_test::data; #include "test_datasets.hpp" //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_implicit_for_each ) { data::for_each_sample( 2, check_arg_type<int>() ); data::for_each_sample( "ch", check_arg_type<char const*>() ); data::for_each_sample( 2., check_arg_type<double>() ); data::for_each_sample( std::vector<int>( 3 ), check_arg_type<int>() ); data::for_each_sample( std::list<double>( 2 ), check_arg_type<double>() ); invocation_count ic; ic.m_value = 0; data::for_each_sample( std::vector<int>( 3 ), ic ); BOOST_TEST( ic.m_value == 3 ); ic.m_value = 0; data::for_each_sample( std::list<double>( 2 ), ic, 1 ); BOOST_TEST( ic.m_value == 1 ); std::vector<copy_count> samples1( 2 ); copy_count::value() = 0; // we do not test the construction of the vector data::for_each_sample( samples1, check_arg_type<copy_count>() ); #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES BOOST_TEST( copy_count::value() == 0 ); #else // clang/darwin has apparently a non standard constructor for std::vector // in c++03 mode #if defined(BOOST_CLANG) && __APPLE__ BOOST_CHECK_MESSAGE( copy_count::value() == 2, BOOST_PLATFORM ); #else BOOST_TEST( copy_count::value() == 4 ); #endif #endif copy_count::value() = 0; copy_count samples2[] = { copy_count(), copy_count() }; data::for_each_sample( samples2, check_arg_type<copy_count>() ); BOOST_TEST( copy_count::value() == 0 ); } //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_implicit_join ) { #ifndef BOOST_NO_CXX11_AUTO_DECLARATIONS auto ds = data::make( 5 ); BOOST_TEST( (1 + ds).size() == 2 ); BOOST_TEST( (ds + 1).size() == 2 ); #endif #ifndef BOOST_NO_CXX11_DECLTYPE BOOST_TEST( (1 + data::make( 5 )).size() == 2 ); BOOST_TEST( (data::make( 5 ) + 1).size() == 2 ); #endif } //____________________________________________________________________________// #ifndef BOOST_TEST_NO_ZIP_COMPOSITION_AVAILABLE BOOST_AUTO_TEST_CASE( test_implicit_zip ) { #ifndef BOOST_NO_CXX11_AUTO_DECLARATIONS auto ds = data::make( 5 ); BOOST_TEST( (1 ^ ds).size() == 1 ); BOOST_TEST( (ds ^ 1).size() == 1 ); #endif BOOST_TEST( (1 ^ data::make( 5 )).size() == 1 ); BOOST_TEST( (data::make( 5 ) ^ 1).size() == 1 ); } #endif <|endoftext|>
<commit_before>/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2008 Steven Noonan. * Licensed under the New BSD License. * */ #ifndef __included_cc_darray_h #error "This file shouldn't be compiled directly." #endif #include <crisscross/debug.h> #include <crisscross/darray.h> #include <crisscross/dstack.h> namespace CrissCross { namespace Data { template <class T> DArray <T>::DArray() { m_stepSize = -1; m_numUsed = m_arraySize = 0; m_shadow = NULL; m_array = NULL; m_emptyNodes = new DStack<size_t>; m_emptyNodes->push((size_t)-1); m_encapsulated = true; } template <class T> DArray <T>::DArray(T *_array, size_t _indices, bool _encapsulate) { m_encapsulated = _encapsulate; if ( _encapsulate ) { m_array = new T[_indices]; memcpy(m_array, _array, _indices * sizeof(T)); } else { m_array = _array; } m_shadow = new char[_indices]; memset(m_shadow, 0, _indices * sizeof(char)); m_numUsed = 0; for (size_t i = 0; i < _indices; i++) { m_shadow[i] = m_array[i] != NULL ? 1 : 0; if ( m_shadow[i] ) { m_numUsed++; } } m_numUsed = m_numUsed; m_arraySize = _indices; m_stepSize = -1; m_emptyNodes = new DStack<size_t>; rebuildStack(); } template <class T> DArray <T>::DArray(DArray const &_array, bool _encapsulate) { m_encapsulated = _encapsulate; if ( _encapsulate ) { m_array = new T[_array.m_arraySize]; memcpy(m_array, _array.m_array, _array.m_arraySize * sizeof(T)); } else { m_array = _array.m_array; } m_shadow = new char[_array.m_arraySize]; memset(m_shadow, 0, _array.m_arraySize * sizeof(char)); m_numUsed = 0; for (size_t i = 0; i < _array.m_arraySize; i++) { m_shadow[i] = m_array[i] != NULL ? 1 : 0; if ( m_shadow[i] ) { m_numUsed++; } } m_arraySize = _array.m_arraySize; m_stepSize = _array.m_stepSize; m_emptyNodes = new DStack<size_t>; rebuildStack(); } template <class T> DArray <T>::DArray(int _newStepSize) { if (_newStepSize < 1) m_stepSize = -1; else m_stepSize = _newStepSize; m_numUsed = m_arraySize = 0; m_shadow = NULL; m_array = NULL; m_emptyNodes = new DStack<size_t> (_newStepSize + 1); m_emptyNodes->push((size_t)-1); m_encapsulated = true; } template <class T> DArray <T>::~DArray() { empty(); delete m_emptyNodes; m_emptyNodes = NULL; } template <class T> size_t DArray <T>::pop() { CoreAssert ( m_encapsulated ); size_t freeslot = getNextFree(); if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> void DArray <T>::rebuildStack() { if ( !m_encapsulated ) return; /* Reset free list */ m_emptyNodes->empty(); m_emptyNodes->push((size_t)-1); /* Step through, rebuilding */ for (size_t i = m_arraySize - 1; (int)i >= 0; i--) if (m_shadow[i] == 0) m_emptyNodes->push(i); } template <class T> void DArray <T>::recount() { if ( !m_encapsulated ) return; m_numUsed = 0; for (size_t i = 0; i < m_arraySize; i++) if (m_shadow[i] == 1) m_numUsed++; } template <class T> void DArray <T>::setSize(size_t newsize) { if ( !m_encapsulated ) return; if (newsize > m_arraySize) { size_t oldarraysize = m_arraySize; m_arraySize = newsize; T *temparray = new T[m_arraySize]; char *tempshadow = new char[m_arraySize]; if (m_array && m_shadow) { memcpy(&temparray[0], &m_array[0], sizeof(temparray[0]) * oldarraysize); memcpy(&tempshadow[0], &m_shadow[0], sizeof(tempshadow[0]) * oldarraysize); } memset(&temparray[oldarraysize], 0, sizeof(temparray[0]) * (m_arraySize - oldarraysize)); memset(&tempshadow[oldarraysize], 0, sizeof(tempshadow[0]) * (m_arraySize - oldarraysize)); for (size_t a = m_arraySize - 1; (int)a >= (int)oldarraysize; a--) { m_emptyNodes->push(a); } delete [] m_array; delete [] m_shadow; m_array = temparray; m_shadow = tempshadow; } else if (newsize < m_arraySize) { m_arraySize = newsize; T *temparray = new T[m_arraySize]; char *tempshadow = new char[m_arraySize]; if (m_array && m_shadow) { memcpy(&temparray[0], &m_array[0], sizeof(temparray[0]) * m_arraySize); memcpy(&tempshadow[0], &m_shadow[0], sizeof(tempshadow[0]) * m_arraySize); } /* We may have lost more than one node. It's worth rebuilding over. */ rebuildStack(); recount(); delete [] m_array; delete [] m_shadow; m_array = temparray; m_shadow = tempshadow; } else if (newsize == m_arraySize) { /* Do nothing */ } } template <class T> void DArray <T>::grow() { CoreAssert ( m_encapsulated ); if (m_stepSize == -1) { /* Double array size */ if (m_arraySize == 0) { setSize(64); } else { setSize(m_arraySize * 2); } } else { /* Increase array size by fixed amount */ setSize(m_arraySize + m_stepSize); } } template <class T> void DArray <T>::setStepSize(int _stepSize) { m_stepSize = _stepSize; } template <class T> void DArray <T>::setStepDouble() { m_stepSize = -1; } template <class T> size_t DArray <T>::insert(T const & newdata) { CoreAssert ( m_encapsulated ); size_t freeslot = getNextFree(); m_array[freeslot] = newdata; if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> void DArray <T>::insert(T const & newdata, size_t index) { CoreAssert ( m_encapsulated ); while (index >= m_arraySize) grow(); m_array[index] = newdata; if (m_shadow[index] == 0) m_numUsed++; m_shadow[index] = 1; } template <class T> void DArray <T>::empty() { if ( m_encapsulated ) { delete [] m_array; m_array = NULL; } m_array = NULL; delete [] m_shadow; m_shadow = NULL; m_emptyNodes->empty(); m_emptyNodes->push((size_t)-1); m_arraySize = 0; m_numUsed = 0; m_encapsulated = true; } template <class T> size_t DArray <T>::getNextFree() { if ( !m_encapsulated ) return -1; /* WARNING: This function assumes the node returned */ /* will be used by the calling function. */ if (!m_shadow) grow(); size_t freeslot = (size_t)-2; while ((freeslot = m_emptyNodes->pop()) != (size_t)-1) { if (m_shadow[freeslot] == 0) break; } if (freeslot == (size_t)-1) { m_emptyNodes->push((size_t)-1); freeslot = m_arraySize; grow(); } if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> T DArray <T>::get(size_t index) const { CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> T & DArray <T>::operator [](size_t index) { /* Ugh. Messy. Don't run into this. >.< */ CoreAssert ( m_encapsulated ); CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> const T &DArray <T>::operator [](size_t index) const { /* Ugh. Messy. Don't run into this. >.< */ CoreAssert ( m_encapsulated ); CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> size_t DArray<T>::mem_usage() const { size_t ret = sizeof(*this); ret += m_arraySize * sizeof(T); ret += m_arraySize * sizeof(char); return ret; } template <class T> void DArray <T>::remove(size_t index) { if ( !m_encapsulated ) return; CoreAssert(m_shadow[index] != 0); CoreAssert(index < m_arraySize); m_emptyNodes->push(index); if (m_shadow[index] == 1) m_numUsed--; m_shadow[index] = 0; } template <class T> size_t DArray <T>::find(T const & newdata) { for (size_t a = 0; a < m_arraySize; ++a) if (m_shadow[a]) if (Compare(m_array[a], newdata) == 0) return a; return -1; } #ifdef ENABLE_SORTS template <class T> int DArray <T>::sort(Sorter<T> *_sortMethod) { if ( !m_encapsulated ) return -1; int ret; T *temp_array = new T[m_numUsed]; T *temp_ptr = temp_array; memset(temp_array, 0, m_numUsed * sizeof(T)); for (size_t i = 0; i < m_arraySize; i++) { if (valid(i)) { *temp_ptr = m_array[i]; temp_ptr++; } } ret = _sortMethod->Sort(temp_array, m_numUsed); delete [] m_shadow; m_shadow = new char[m_numUsed]; memset(m_shadow, 1, m_numUsed); delete [] m_array; m_array = temp_array; m_arraySize = m_numUsed; rebuildStack(); recount(); return ret; } template <class T> int DArray <T>::sort(Sorter<T> &_sortMethod) { if ( !m_encapsulated ) return -1; return sort(&_sortMethod); } #endif template <class T> void DArray<T>::flush() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete m_array[i]; } } } empty(); } template <class T> void DArray<T>::flushArray() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete [] m_array[i]; } } } empty(); } /* BELOW ARE DEPRECATED FUNCTIONS */ #if !defined(DISABLE_DEPRECATED_CODE) template <class T> void DArray<T>::EmptyAndDelete() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete m_array[i]; } } } empty(); } template <class T> void DArray<T>::EmptyAndDeleteArray() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete [] m_array[i]; } } } empty(); } template <class T> void DArray<T>::ChangeData(T const & _rec, size_t index) { if ( !m_encapsulated ) return; CoreAssert(m_shadow[index] == 1); m_array[index] = _rec; } #endif } } <commit_msg>darray: make safe for non-integer/pointer types<commit_after>/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2008 Steven Noonan. * Licensed under the New BSD License. * */ #ifndef __included_cc_darray_h #error "This file shouldn't be compiled directly." #endif #include <crisscross/debug.h> #include <crisscross/darray.h> #include <crisscross/dstack.h> namespace CrissCross { namespace Data { template <class T> DArray <T>::DArray() { m_stepSize = -1; m_numUsed = m_arraySize = 0; m_shadow = NULL; m_array = NULL; m_emptyNodes = new DStack<size_t>; m_emptyNodes->push((size_t)-1); m_encapsulated = true; } template <class T> DArray <T>::DArray(T *_array, size_t _indices, bool _encapsulate) { m_encapsulated = _encapsulate; if ( _encapsulate ) { m_array = new T[_indices]; memcpy(m_array, _array, _indices * sizeof(T)); } else { m_array = _array; } m_shadow = new char[_indices]; memset(m_shadow, 0, _indices * sizeof(char)); m_numUsed = 0; for (size_t i = 0; i < _indices; i++) { m_shadow[i] = m_array[i] != NULL ? 1 : 0; if ( m_shadow[i] ) { m_numUsed++; } } m_numUsed = m_numUsed; m_arraySize = _indices; m_stepSize = -1; m_emptyNodes = new DStack<size_t>; rebuildStack(); } template <class T> DArray <T>::DArray(DArray const &_array, bool _encapsulate) { m_encapsulated = _encapsulate; if ( _encapsulate ) { m_array = new T[_array.m_arraySize]; memcpy(m_array, _array.m_array, _array.m_arraySize * sizeof(T)); } else { m_array = _array.m_array; } m_shadow = new char[_array.m_arraySize]; memset(m_shadow, 0, _array.m_arraySize * sizeof(char)); m_numUsed = 0; for (size_t i = 0; i < _array.m_arraySize; i++) { m_shadow[i] = m_array[i] != NULL ? 1 : 0; if ( m_shadow[i] ) { m_numUsed++; } } m_arraySize = _array.m_arraySize; m_stepSize = _array.m_stepSize; m_emptyNodes = new DStack<size_t>; rebuildStack(); } template <class T> DArray <T>::DArray(int _newStepSize) { if (_newStepSize < 1) m_stepSize = -1; else m_stepSize = _newStepSize; m_numUsed = m_arraySize = 0; m_shadow = NULL; m_array = NULL; m_emptyNodes = new DStack<size_t> (_newStepSize + 1); m_emptyNodes->push((size_t)-1); m_encapsulated = true; } template <class T> DArray <T>::~DArray() { empty(); delete m_emptyNodes; m_emptyNodes = NULL; } template <class T> size_t DArray <T>::pop() { CoreAssert ( m_encapsulated ); size_t freeslot = getNextFree(); if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> void DArray <T>::rebuildStack() { if ( !m_encapsulated ) return; /* Reset free list */ m_emptyNodes->empty(); m_emptyNodes->push((size_t)-1); /* Step through, rebuilding */ for (size_t i = m_arraySize - 1; (int)i >= 0; i--) if (m_shadow[i] == 0) m_emptyNodes->push(i); } template <class T> void DArray <T>::recount() { if ( !m_encapsulated ) return; m_numUsed = 0; for (size_t i = 0; i < m_arraySize; i++) if (m_shadow[i] == 1) m_numUsed++; } template <class T> void DArray <T>::setSize(size_t newsize) { if ( !m_encapsulated ) return; if (newsize > m_arraySize) { size_t oldarraysize = m_arraySize; m_arraySize = newsize; T *temparray = new T[m_arraySize]; char *tempshadow = new char[m_arraySize]; if (m_array && m_shadow) { //memcpy(&temparray[0], &m_array[0], sizeof(temparray[0]) * oldarraysize); for ( size_t a = 0; a < oldarraysize; a++ ) { temparray[0] = m_array[0]; } memcpy(&tempshadow[0], &m_shadow[0], sizeof(tempshadow[0]) * oldarraysize); } //memset(&temparray[oldarraysize], 0, sizeof(temparray[0]) * (m_arraySize - oldarraysize)); memset(&tempshadow[oldarraysize], 0, sizeof(tempshadow[0]) * (m_arraySize - oldarraysize)); for (size_t a = m_arraySize - 1; (int)a >= (int)oldarraysize; a--) { m_emptyNodes->push(a); } delete [] m_array; delete [] m_shadow; m_array = temparray; m_shadow = tempshadow; } else if (newsize < m_arraySize) { m_arraySize = newsize; T *temparray = new T[m_arraySize]; char *tempshadow = new char[m_arraySize]; if (m_array && m_shadow) { memcpy(&temparray[0], &m_array[0], sizeof(temparray[0]) * m_arraySize); memcpy(&tempshadow[0], &m_shadow[0], sizeof(tempshadow[0]) * m_arraySize); } /* We may have lost more than one node. It's worth rebuilding over. */ rebuildStack(); recount(); delete [] m_array; delete [] m_shadow; m_array = temparray; m_shadow = tempshadow; } else if (newsize == m_arraySize) { /* Do nothing */ } } template <class T> void DArray <T>::grow() { CoreAssert ( m_encapsulated ); if (m_stepSize == -1) { /* Double array size */ if (m_arraySize == 0) { setSize(64); } else { setSize(m_arraySize * 2); } } else { /* Increase array size by fixed amount */ setSize(m_arraySize + m_stepSize); } } template <class T> void DArray <T>::setStepSize(int _stepSize) { m_stepSize = _stepSize; } template <class T> void DArray <T>::setStepDouble() { m_stepSize = -1; } template <class T> size_t DArray <T>::insert(T const & newdata) { CoreAssert ( m_encapsulated ); size_t freeslot = getNextFree(); m_array[freeslot] = newdata; if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> void DArray <T>::insert(T const & newdata, size_t index) { CoreAssert ( m_encapsulated ); while (index >= m_arraySize) grow(); m_array[index] = newdata; if (m_shadow[index] == 0) m_numUsed++; m_shadow[index] = 1; } template <class T> void DArray <T>::empty() { if ( m_encapsulated ) { delete [] m_array; m_array = NULL; } m_array = NULL; delete [] m_shadow; m_shadow = NULL; m_emptyNodes->empty(); m_emptyNodes->push((size_t)-1); m_arraySize = 0; m_numUsed = 0; m_encapsulated = true; } template <class T> size_t DArray <T>::getNextFree() { if ( !m_encapsulated ) return -1; /* WARNING: This function assumes the node returned */ /* will be used by the calling function. */ if (!m_shadow) grow(); size_t freeslot = (size_t)-2; while ((freeslot = m_emptyNodes->pop()) != (size_t)-1) { if (m_shadow[freeslot] == 0) break; } if (freeslot == (size_t)-1) { m_emptyNodes->push((size_t)-1); freeslot = m_arraySize; grow(); } if (m_shadow[freeslot] == 0) m_numUsed++; m_shadow[freeslot] = 1; return freeslot; } template <class T> T DArray <T>::get(size_t index) const { CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> T & DArray <T>::operator [](size_t index) { /* Ugh. Messy. Don't run into this. >.< */ CoreAssert ( m_encapsulated ); CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> const T &DArray <T>::operator [](size_t index) const { /* Ugh. Messy. Don't run into this. >.< */ CoreAssert ( m_encapsulated ); CoreAssert(m_shadow[index]); CoreAssert(index < m_arraySize); return m_array[index]; } template <class T> size_t DArray<T>::mem_usage() const { size_t ret = sizeof(*this); ret += m_arraySize * sizeof(T); ret += m_arraySize * sizeof(char); return ret; } template <class T> void DArray <T>::remove(size_t index) { if ( !m_encapsulated ) return; CoreAssert(m_shadow[index] != 0); CoreAssert(index < m_arraySize); m_emptyNodes->push(index); if (m_shadow[index] == 1) m_numUsed--; m_shadow[index] = 0; } template <class T> size_t DArray <T>::find(T const & newdata) { for (size_t a = 0; a < m_arraySize; ++a) if (m_shadow[a]) if (Compare(m_array[a], newdata) == 0) return a; return -1; } #ifdef ENABLE_SORTS template <class T> int DArray <T>::sort(Sorter<T> *_sortMethod) { if ( !m_encapsulated ) return -1; int ret; T *temp_array = new T[m_numUsed]; T *temp_ptr = temp_array; memset(temp_array, 0, m_numUsed * sizeof(T)); for (size_t i = 0; i < m_arraySize; i++) { if (valid(i)) { *temp_ptr = m_array[i]; temp_ptr++; } } ret = _sortMethod->Sort(temp_array, m_numUsed); delete [] m_shadow; m_shadow = new char[m_numUsed]; memset(m_shadow, 1, m_numUsed); delete [] m_array; m_array = temp_array; m_arraySize = m_numUsed; rebuildStack(); recount(); return ret; } template <class T> int DArray <T>::sort(Sorter<T> &_sortMethod) { if ( !m_encapsulated ) return -1; return sort(&_sortMethod); } #endif template <class T> void DArray<T>::flush() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete m_array[i]; } } } empty(); } template <class T> void DArray<T>::flushArray() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete [] m_array[i]; } } } empty(); } /* BELOW ARE DEPRECATED FUNCTIONS */ #if !defined(DISABLE_DEPRECATED_CODE) template <class T> void DArray<T>::EmptyAndDelete() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete m_array[i]; } } } empty(); } template <class T> void DArray<T>::EmptyAndDeleteArray() { if ( m_encapsulated ) { for (size_t i = 0; i < m_arraySize; ++i) { if (valid(i)) { delete [] m_array[i]; } } } empty(); } template <class T> void DArray<T>::ChangeData(T const & _rec, size_t index) { if ( !m_encapsulated ) return; CoreAssert(m_shadow[index] == 1); m_array[index] = _rec; } #endif } } <|endoftext|>
<commit_before>/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ /// @file /// @author Don Gagne <don@thegagnes.com> #include "MultiVehicleManager.h" #include "AutoPilotPlugin.h" #include "MAVLinkProtocol.h" #include "UAS.h" #include "QGCApplication.h" #include "FollowMe.h" #ifdef __mobile__ #include "MobileScreenMgr.h" #endif #include <QQmlEngine> QGC_LOGGING_CATEGORY(MultiVehicleManagerLog, "MultiVehicleManagerLog") const char* MultiVehicleManager::_gcsHeartbeatEnabledKey = "gcsHeartbeatEnabled"; MultiVehicleManager::MultiVehicleManager(QGCApplication* app) : QGCTool(app) , _activeVehicleAvailable(false) , _parameterReadyVehicleAvailable(false) , _activeVehicle(NULL) , _disconnectedVehicle(NULL) , _firmwarePluginManager(NULL) , _autopilotPluginManager(NULL) , _joystickManager(NULL) , _mavlinkProtocol(NULL) , _gcsHeartbeatEnabled(true) { QSettings settings; _gcsHeartbeatEnabled = settings.value(_gcsHeartbeatEnabledKey, true).toBool(); _gcsHeartbeatTimer.setInterval(_gcsHeartbeatRateMSecs); _gcsHeartbeatTimer.setSingleShot(false); connect(&_gcsHeartbeatTimer, &QTimer::timeout, this, &MultiVehicleManager::_sendGCSHeartbeat); if (_gcsHeartbeatEnabled) { _gcsHeartbeatTimer.start(); } _disconnectedVehicle = new Vehicle(this); } void MultiVehicleManager::setToolbox(QGCToolbox *toolbox) { QGCTool::setToolbox(toolbox); _firmwarePluginManager = _toolbox->firmwarePluginManager(); _autopilotPluginManager = _toolbox->autopilotPluginManager(); _joystickManager = _toolbox->joystickManager(); _mavlinkProtocol = _toolbox->mavlinkProtocol(); QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership); qmlRegisterUncreatableType<MultiVehicleManager>("QGroundControl.MultiVehicleManager", 1, 0, "MultiVehicleManager", "Reference only"); connect(_mavlinkProtocol, &MAVLinkProtocol::vehicleHeartbeatInfo, this, &MultiVehicleManager::_vehicleHeartbeatInfo); } void MultiVehicleManager::_vehicleHeartbeatInfo(LinkInterface* link, int vehicleId, int vehicleMavlinkVersion, int vehicleFirmwareType, int vehicleType) { if (_ignoreVehicleIds.contains(vehicleId) || getVehicleById(vehicleId) || vehicleId == 0) { return; } qCDebug(MultiVehicleManagerLog()) << "Adding new vehicle link:vehicleId:vehicleMavlinkVersion:vehicleFirmwareType:vehicleType " << link->getName() << vehicleId << vehicleMavlinkVersion << vehicleFirmwareType << vehicleType; if (vehicleId == _mavlinkProtocol->getSystemId()) { _app->showMessage(QString("Warning: A vehicle is using the same system id as QGroundControl: %1").arg(vehicleId)); } QSettings settings; bool mavlinkVersionCheck = settings.value("VERSION_CHECK_ENABLED", true).toBool(); if (mavlinkVersionCheck && vehicleMavlinkVersion != MAVLINK_VERSION) { _ignoreVehicleIds += vehicleId; _app->showMessage(QString("The MAVLink protocol version on vehicle #%1 and QGroundControl differ! " "It is unsafe to use different MAVLink versions. " "QGroundControl therefore refuses to connect to vehicle #%1, which sends MAVLink version %2 (QGroundControl uses version %3).").arg(vehicleId).arg(vehicleMavlinkVersion).arg(MAVLINK_VERSION)); return; } Vehicle* vehicle = new Vehicle(link, vehicleId, (MAV_AUTOPILOT)vehicleFirmwareType, (MAV_TYPE)vehicleType, _firmwarePluginManager, _autopilotPluginManager, _joystickManager); connect(vehicle, &Vehicle::allLinksInactive, this, &MultiVehicleManager::_deleteVehiclePhase1); connect(vehicle->autopilotPlugin(), &AutoPilotPlugin::parametersReadyChanged, this, &MultiVehicleManager::_autopilotParametersReadyChanged); _vehicles.append(vehicle); emit vehicleAdded(vehicle); setActiveVehicle(vehicle); // Mark link as active link->setActive(true); #ifdef __mobile__ if(_vehicles.count() == 1) { //-- Once a vehicle is connected, keep screen from going off qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::keepScreenOn"; MobileScreenMgr::setKeepScreenOn(true); } #endif } /// This slot is connected to the Vehicle::allLinksDestroyed signal such that the Vehicle is deleted /// and all other right things happen when the Vehicle goes away. void MultiVehicleManager::_deleteVehiclePhase1(Vehicle* vehicle) { qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase1" << vehicle; _vehiclesBeingDeleted << vehicle; // Remove from map bool found = false; for (int i=0; i<_vehicles.count(); i++) { if (_vehicles[i] == vehicle) { _vehicles.removeAt(i); found = true; break; } } if (!found) { qWarning() << "Vehicle not found in map!"; } vehicle->setActive(false); vehicle->uas()->shutdownVehicle(); // First we must signal that a vehicle is no longer available. _activeVehicleAvailable = false; _parameterReadyVehicleAvailable = false; emit activeVehicleAvailableChanged(false); emit parameterReadyVehicleAvailableChanged(false); emit vehicleRemoved(vehicle); #ifdef __mobile__ if(_vehicles.count() == 0) { //-- Once no vehicles are connected, we no longer need to keep screen from going off qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::restoreScreenOn"; MobileScreenMgr::setKeepScreenOn(false); } #endif // We must let the above signals flow through the system as well as get back to the main loop event queue // before we can actually delete the Vehicle. The reason is that Qml may be holding on the references to it. // Even though the above signals should unload any Qml which has references, that Qml will not be destroyed // until we get back to the main loop. So we set a short timer which will then fire after Qt has finished // doing all of its internal nastiness to clean up the Qml. This works for both the normal running case // as well as the unit testing case whichof course has a different signal flow! QTimer::singleShot(20, this, &MultiVehicleManager::_deleteVehiclePhase2); } void MultiVehicleManager::_deleteVehiclePhase2(void) { qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase2" << _vehiclesBeingDeleted[0]; /// Qml has been notified of vehicle about to go away and should be disconnected from it by now. /// This means we can now clear the active vehicle property and delete the Vehicle for real. Vehicle* newActiveVehicle = NULL; if (_vehicles.count()) { newActiveVehicle = qobject_cast<Vehicle*>(_vehicles[0]); } _activeVehicle = newActiveVehicle; emit activeVehicleChanged(newActiveVehicle); if (_activeVehicle) { _activeVehicle->setActive(true); emit activeVehicleAvailableChanged(true); if (_activeVehicle->autopilotPlugin()->parametersReady()) { emit parameterReadyVehicleAvailableChanged(true); } } delete _vehiclesBeingDeleted[0]; _vehiclesBeingDeleted.removeAt(0); } void MultiVehicleManager::setActiveVehicle(Vehicle* vehicle) { qCDebug(MultiVehicleManagerLog) << "setActiveVehicle" << vehicle; if (vehicle != _activeVehicle) { if (_activeVehicle) { _activeVehicle->setActive(false); // The sequence of signals is very important in order to not leave Qml elements connected // to a non-existent vehicle. // First we must signal that there is no active vehicle available. This will disconnect // any existing ui from the currently active vehicle. _activeVehicleAvailable = false; _parameterReadyVehicleAvailable = false; emit activeVehicleAvailableChanged(false); emit parameterReadyVehicleAvailableChanged(false); } // See explanation in _deleteVehiclePhase1 _vehicleBeingSetActive = vehicle; QTimer::singleShot(20, this, &MultiVehicleManager::_setActiveVehiclePhase2); } } void MultiVehicleManager::_setActiveVehiclePhase2(void) { qCDebug(MultiVehicleManagerLog) << "_setActiveVehiclePhase2 _vehicleBeingSetActive" << _vehicleBeingSetActive; // Now we signal the new active vehicle _activeVehicle = _vehicleBeingSetActive; emit activeVehicleChanged(_activeVehicle); // And finally vehicle availability if (_activeVehicle) { _activeVehicle->setActive(true); _activeVehicleAvailable = true; emit activeVehicleAvailableChanged(true); if (_activeVehicle->autopilotPlugin()->parametersReady()) { _parameterReadyVehicleAvailable = true; emit parameterReadyVehicleAvailableChanged(true); } } } void MultiVehicleManager::_autopilotParametersReadyChanged(bool parametersReady) { AutoPilotPlugin* autopilot = dynamic_cast<AutoPilotPlugin*>(sender()); if (!autopilot) { qWarning() << "Dynamic cast failed!"; return; } if (autopilot->vehicle() == _activeVehicle) { _parameterReadyVehicleAvailable = parametersReady; emit parameterReadyVehicleAvailableChanged(parametersReady); } } void MultiVehicleManager::saveSetting(const QString &name, const QString& value) { QSettings settings; settings.setValue(name, value); } QString MultiVehicleManager::loadSetting(const QString &name, const QString& defaultValue) { QSettings settings; return settings.value(name, defaultValue).toString(); } Vehicle* MultiVehicleManager::getVehicleById(int vehicleId) { for (int i=0; i< _vehicles.count(); i++) { Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]); if (vehicle->id() == vehicleId) { return vehicle; } } return NULL; } void MultiVehicleManager::setGcsHeartbeatEnabled(bool gcsHeartBeatEnabled) { if (gcsHeartBeatEnabled != _gcsHeartbeatEnabled) { _gcsHeartbeatEnabled = gcsHeartBeatEnabled; emit gcsHeartBeatEnabledChanged(gcsHeartBeatEnabled); QSettings settings; settings.setValue(_gcsHeartbeatEnabledKey, gcsHeartBeatEnabled); if (gcsHeartBeatEnabled) { _gcsHeartbeatTimer.start(); } else { _gcsHeartbeatTimer.stop(); } } } void MultiVehicleManager::_sendGCSHeartbeat(void) { for (int i=0; i< _vehicles.count(); i++) { Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]); mavlink_message_t message; mavlink_msg_heartbeat_pack(_mavlinkProtocol->getSystemId(), _mavlinkProtocol->getComponentId(), &message, MAV_TYPE_GCS, // MAV_TYPE MAV_AUTOPILOT_INVALID, // MAV_AUTOPILOT MAV_MODE_MANUAL_ARMED, // MAV_MODE 0, // custom mode MAV_STATE_ACTIVE); // MAV_STATE vehicle->sendMessageOnPriorityLink(message); } } bool MultiVehicleManager::linkInUse(LinkInterface* link, Vehicle* skipVehicle) { for (int i=0; i< _vehicles.count(); i++) { Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]); if (vehicle != skipVehicle) { if (vehicle->containsLink(link)) { return true; } } } return false; } <commit_msg>Temporarily disable MAVLink version check as the QGC settings have no effect and it will mess with the upgrade from v1 to v2 and has no real value<commit_after>/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ /// @file /// @author Don Gagne <don@thegagnes.com> #include "MultiVehicleManager.h" #include "AutoPilotPlugin.h" #include "MAVLinkProtocol.h" #include "UAS.h" #include "QGCApplication.h" #include "FollowMe.h" #ifdef __mobile__ #include "MobileScreenMgr.h" #endif #include <QQmlEngine> QGC_LOGGING_CATEGORY(MultiVehicleManagerLog, "MultiVehicleManagerLog") const char* MultiVehicleManager::_gcsHeartbeatEnabledKey = "gcsHeartbeatEnabled"; MultiVehicleManager::MultiVehicleManager(QGCApplication* app) : QGCTool(app) , _activeVehicleAvailable(false) , _parameterReadyVehicleAvailable(false) , _activeVehicle(NULL) , _disconnectedVehicle(NULL) , _firmwarePluginManager(NULL) , _autopilotPluginManager(NULL) , _joystickManager(NULL) , _mavlinkProtocol(NULL) , _gcsHeartbeatEnabled(true) { QSettings settings; _gcsHeartbeatEnabled = settings.value(_gcsHeartbeatEnabledKey, true).toBool(); _gcsHeartbeatTimer.setInterval(_gcsHeartbeatRateMSecs); _gcsHeartbeatTimer.setSingleShot(false); connect(&_gcsHeartbeatTimer, &QTimer::timeout, this, &MultiVehicleManager::_sendGCSHeartbeat); if (_gcsHeartbeatEnabled) { _gcsHeartbeatTimer.start(); } _disconnectedVehicle = new Vehicle(this); } void MultiVehicleManager::setToolbox(QGCToolbox *toolbox) { QGCTool::setToolbox(toolbox); _firmwarePluginManager = _toolbox->firmwarePluginManager(); _autopilotPluginManager = _toolbox->autopilotPluginManager(); _joystickManager = _toolbox->joystickManager(); _mavlinkProtocol = _toolbox->mavlinkProtocol(); QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership); qmlRegisterUncreatableType<MultiVehicleManager>("QGroundControl.MultiVehicleManager", 1, 0, "MultiVehicleManager", "Reference only"); connect(_mavlinkProtocol, &MAVLinkProtocol::vehicleHeartbeatInfo, this, &MultiVehicleManager::_vehicleHeartbeatInfo); } void MultiVehicleManager::_vehicleHeartbeatInfo(LinkInterface* link, int vehicleId, int vehicleMavlinkVersion, int vehicleFirmwareType, int vehicleType) { if (_ignoreVehicleIds.contains(vehicleId) || getVehicleById(vehicleId) || vehicleId == 0) { return; } qCDebug(MultiVehicleManagerLog()) << "Adding new vehicle link:vehicleId:vehicleMavlinkVersion:vehicleFirmwareType:vehicleType " << link->getName() << vehicleId << vehicleMavlinkVersion << vehicleFirmwareType << vehicleType; if (vehicleId == _mavlinkProtocol->getSystemId()) { _app->showMessage(QString("Warning: A vehicle is using the same system id as QGroundControl: %1").arg(vehicleId)); } // QSettings settings; // bool mavlinkVersionCheck = settings.value("VERSION_CHECK_ENABLED", true).toBool(); // if (mavlinkVersionCheck && vehicleMavlinkVersion != MAVLINK_VERSION) { // _ignoreVehicleIds += vehicleId; // _app->showMessage(QString("The MAVLink protocol version on vehicle #%1 and QGroundControl differ! " // "It is unsafe to use different MAVLink versions. " // "QGroundControl therefore refuses to connect to vehicle #%1, which sends MAVLink version %2 (QGroundControl uses version %3).").arg(vehicleId).arg(vehicleMavlinkVersion).arg(MAVLINK_VERSION)); // return; // } Vehicle* vehicle = new Vehicle(link, vehicleId, (MAV_AUTOPILOT)vehicleFirmwareType, (MAV_TYPE)vehicleType, _firmwarePluginManager, _autopilotPluginManager, _joystickManager); connect(vehicle, &Vehicle::allLinksInactive, this, &MultiVehicleManager::_deleteVehiclePhase1); connect(vehicle->autopilotPlugin(), &AutoPilotPlugin::parametersReadyChanged, this, &MultiVehicleManager::_autopilotParametersReadyChanged); _vehicles.append(vehicle); emit vehicleAdded(vehicle); setActiveVehicle(vehicle); // Mark link as active link->setActive(true); #ifdef __mobile__ if(_vehicles.count() == 1) { //-- Once a vehicle is connected, keep screen from going off qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::keepScreenOn"; MobileScreenMgr::setKeepScreenOn(true); } #endif } /// This slot is connected to the Vehicle::allLinksDestroyed signal such that the Vehicle is deleted /// and all other right things happen when the Vehicle goes away. void MultiVehicleManager::_deleteVehiclePhase1(Vehicle* vehicle) { qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase1" << vehicle; _vehiclesBeingDeleted << vehicle; // Remove from map bool found = false; for (int i=0; i<_vehicles.count(); i++) { if (_vehicles[i] == vehicle) { _vehicles.removeAt(i); found = true; break; } } if (!found) { qWarning() << "Vehicle not found in map!"; } vehicle->setActive(false); vehicle->uas()->shutdownVehicle(); // First we must signal that a vehicle is no longer available. _activeVehicleAvailable = false; _parameterReadyVehicleAvailable = false; emit activeVehicleAvailableChanged(false); emit parameterReadyVehicleAvailableChanged(false); emit vehicleRemoved(vehicle); #ifdef __mobile__ if(_vehicles.count() == 0) { //-- Once no vehicles are connected, we no longer need to keep screen from going off qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::restoreScreenOn"; MobileScreenMgr::setKeepScreenOn(false); } #endif // We must let the above signals flow through the system as well as get back to the main loop event queue // before we can actually delete the Vehicle. The reason is that Qml may be holding on the references to it. // Even though the above signals should unload any Qml which has references, that Qml will not be destroyed // until we get back to the main loop. So we set a short timer which will then fire after Qt has finished // doing all of its internal nastiness to clean up the Qml. This works for both the normal running case // as well as the unit testing case whichof course has a different signal flow! QTimer::singleShot(20, this, &MultiVehicleManager::_deleteVehiclePhase2); } void MultiVehicleManager::_deleteVehiclePhase2(void) { qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase2" << _vehiclesBeingDeleted[0]; /// Qml has been notified of vehicle about to go away and should be disconnected from it by now. /// This means we can now clear the active vehicle property and delete the Vehicle for real. Vehicle* newActiveVehicle = NULL; if (_vehicles.count()) { newActiveVehicle = qobject_cast<Vehicle*>(_vehicles[0]); } _activeVehicle = newActiveVehicle; emit activeVehicleChanged(newActiveVehicle); if (_activeVehicle) { _activeVehicle->setActive(true); emit activeVehicleAvailableChanged(true); if (_activeVehicle->autopilotPlugin()->parametersReady()) { emit parameterReadyVehicleAvailableChanged(true); } } delete _vehiclesBeingDeleted[0]; _vehiclesBeingDeleted.removeAt(0); } void MultiVehicleManager::setActiveVehicle(Vehicle* vehicle) { qCDebug(MultiVehicleManagerLog) << "setActiveVehicle" << vehicle; if (vehicle != _activeVehicle) { if (_activeVehicle) { _activeVehicle->setActive(false); // The sequence of signals is very important in order to not leave Qml elements connected // to a non-existent vehicle. // First we must signal that there is no active vehicle available. This will disconnect // any existing ui from the currently active vehicle. _activeVehicleAvailable = false; _parameterReadyVehicleAvailable = false; emit activeVehicleAvailableChanged(false); emit parameterReadyVehicleAvailableChanged(false); } // See explanation in _deleteVehiclePhase1 _vehicleBeingSetActive = vehicle; QTimer::singleShot(20, this, &MultiVehicleManager::_setActiveVehiclePhase2); } } void MultiVehicleManager::_setActiveVehiclePhase2(void) { qCDebug(MultiVehicleManagerLog) << "_setActiveVehiclePhase2 _vehicleBeingSetActive" << _vehicleBeingSetActive; // Now we signal the new active vehicle _activeVehicle = _vehicleBeingSetActive; emit activeVehicleChanged(_activeVehicle); // And finally vehicle availability if (_activeVehicle) { _activeVehicle->setActive(true); _activeVehicleAvailable = true; emit activeVehicleAvailableChanged(true); if (_activeVehicle->autopilotPlugin()->parametersReady()) { _parameterReadyVehicleAvailable = true; emit parameterReadyVehicleAvailableChanged(true); } } } void MultiVehicleManager::_autopilotParametersReadyChanged(bool parametersReady) { AutoPilotPlugin* autopilot = dynamic_cast<AutoPilotPlugin*>(sender()); if (!autopilot) { qWarning() << "Dynamic cast failed!"; return; } if (autopilot->vehicle() == _activeVehicle) { _parameterReadyVehicleAvailable = parametersReady; emit parameterReadyVehicleAvailableChanged(parametersReady); } } void MultiVehicleManager::saveSetting(const QString &name, const QString& value) { QSettings settings; settings.setValue(name, value); } QString MultiVehicleManager::loadSetting(const QString &name, const QString& defaultValue) { QSettings settings; return settings.value(name, defaultValue).toString(); } Vehicle* MultiVehicleManager::getVehicleById(int vehicleId) { for (int i=0; i< _vehicles.count(); i++) { Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]); if (vehicle->id() == vehicleId) { return vehicle; } } return NULL; } void MultiVehicleManager::setGcsHeartbeatEnabled(bool gcsHeartBeatEnabled) { if (gcsHeartBeatEnabled != _gcsHeartbeatEnabled) { _gcsHeartbeatEnabled = gcsHeartBeatEnabled; emit gcsHeartBeatEnabledChanged(gcsHeartBeatEnabled); QSettings settings; settings.setValue(_gcsHeartbeatEnabledKey, gcsHeartBeatEnabled); if (gcsHeartBeatEnabled) { _gcsHeartbeatTimer.start(); } else { _gcsHeartbeatTimer.stop(); } } } void MultiVehicleManager::_sendGCSHeartbeat(void) { for (int i=0; i< _vehicles.count(); i++) { Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]); mavlink_message_t message; mavlink_msg_heartbeat_pack(_mavlinkProtocol->getSystemId(), _mavlinkProtocol->getComponentId(), &message, MAV_TYPE_GCS, // MAV_TYPE MAV_AUTOPILOT_INVALID, // MAV_AUTOPILOT MAV_MODE_MANUAL_ARMED, // MAV_MODE 0, // custom mode MAV_STATE_ACTIVE); // MAV_STATE vehicle->sendMessageOnPriorityLink(message); } } bool MultiVehicleManager::linkInUse(LinkInterface* link, Vehicle* skipVehicle) { for (int i=0; i< _vehicles.count(); i++) { Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]); if (vehicle != skipVehicle) { if (vehicle->containsLink(link)) { return true; } } } return false; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: modeltoviewhelper.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2007-06-27 13:21:07 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <modeltoviewhelper.hxx> namespace ModelToViewHelper { /** Converts a model position into a view position */ sal_uInt32 ConvertToViewPosition( const ConversionMap* pMap, sal_uInt32 nModelPos ) { sal_uInt32 nRet = nModelPos; if ( !pMap ) return nRet; // Search for entry behind nPos: ConversionMap::const_iterator aIter; for ( aIter = pMap->begin(); aIter != pMap->end(); ++aIter ) { if ( (*aIter).first >= nModelPos ) { const sal_uInt32 nPosModel = (*aIter).first; const sal_uInt32 nPosExpand = (*aIter).second; const sal_uInt32 nDistToNextModel = nPosModel - nModelPos; nRet = nPosExpand - nDistToNextModel; break; } } return nRet; } /** Converts a view position into a model position */ ModelPosition ConvertToModelPosition( const ConversionMap* pMap, sal_uInt32 nViewPos ) { ModelPosition aRet; aRet.mnPos = nViewPos; if ( !pMap ) return aRet; // Search for entry behind nPos: ConversionMap::const_iterator aIter; for ( aIter = pMap->begin(); aIter != pMap->end(); ++aIter ) { if ( (*aIter).second > nViewPos ) { const sal_uInt32 nPosModel = (*aIter).first; const sal_uInt32 nPosExpand = (*aIter).second; // If nViewPos is in front of first field, we are finished. if ( aIter == pMap->begin() ) break; --aIter; // nPrevPosModel is the field position const sal_uInt32 nPrevPosModel = (*aIter).first; const sal_uInt32 nPrevPosExpand = (*aIter).second; const sal_uInt32 nLengthModel = nPosModel - nPrevPosModel; const sal_uInt32 nLengthExpand = nPosExpand - nPrevPosExpand; const sal_uInt32 nFieldLengthExpand = nLengthExpand - nLengthModel + 1; const sal_uInt32 nFieldEndExpand = nPrevPosExpand + nFieldLengthExpand; // Check if nPos is outside of field: if ( nFieldEndExpand <= nViewPos ) { // nPos is outside of field: const sal_uInt32 nDistToField = nViewPos - nFieldEndExpand + 1; aRet.mnPos = nPrevPosModel + nDistToField; } else { // nViewPos is inside a field: aRet.mnPos = nPrevPosModel; aRet.mnSubPos = nViewPos - nPrevPosExpand; aRet.mbIsField = true; } break; } } return aRet; } } // namespace ModelToViewStringConverter end <commit_msg>INTEGRATION: CWS changefileheader (1.2.372); FILE MERGED 2008/03/31 16:54:58 rt 1.2.372.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: modeltoviewhelper.cxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <modeltoviewhelper.hxx> namespace ModelToViewHelper { /** Converts a model position into a view position */ sal_uInt32 ConvertToViewPosition( const ConversionMap* pMap, sal_uInt32 nModelPos ) { sal_uInt32 nRet = nModelPos; if ( !pMap ) return nRet; // Search for entry behind nPos: ConversionMap::const_iterator aIter; for ( aIter = pMap->begin(); aIter != pMap->end(); ++aIter ) { if ( (*aIter).first >= nModelPos ) { const sal_uInt32 nPosModel = (*aIter).first; const sal_uInt32 nPosExpand = (*aIter).second; const sal_uInt32 nDistToNextModel = nPosModel - nModelPos; nRet = nPosExpand - nDistToNextModel; break; } } return nRet; } /** Converts a view position into a model position */ ModelPosition ConvertToModelPosition( const ConversionMap* pMap, sal_uInt32 nViewPos ) { ModelPosition aRet; aRet.mnPos = nViewPos; if ( !pMap ) return aRet; // Search for entry behind nPos: ConversionMap::const_iterator aIter; for ( aIter = pMap->begin(); aIter != pMap->end(); ++aIter ) { if ( (*aIter).second > nViewPos ) { const sal_uInt32 nPosModel = (*aIter).first; const sal_uInt32 nPosExpand = (*aIter).second; // If nViewPos is in front of first field, we are finished. if ( aIter == pMap->begin() ) break; --aIter; // nPrevPosModel is the field position const sal_uInt32 nPrevPosModel = (*aIter).first; const sal_uInt32 nPrevPosExpand = (*aIter).second; const sal_uInt32 nLengthModel = nPosModel - nPrevPosModel; const sal_uInt32 nLengthExpand = nPosExpand - nPrevPosExpand; const sal_uInt32 nFieldLengthExpand = nLengthExpand - nLengthModel + 1; const sal_uInt32 nFieldEndExpand = nPrevPosExpand + nFieldLengthExpand; // Check if nPos is outside of field: if ( nFieldEndExpand <= nViewPos ) { // nPos is outside of field: const sal_uInt32 nDistToField = nViewPos - nFieldEndExpand + 1; aRet.mnPos = nPrevPosModel + nDistToField; } else { // nViewPos is inside a field: aRet.mnPos = nPrevPosModel; aRet.mnSubPos = nViewPos - nPrevPosExpand; aRet.mbIsField = true; } break; } } return aRet; } } // namespace ModelToViewStringConverter end <|endoftext|>
<commit_before>#include "parameter_acceptor.h" #include "utilities.h" #include <deal.II/base/point.h> #include <string> // Static empty class list std::vector<SmartPointer<ParameterAcceptor> > ParameterAcceptor::class_list; // Static parameter handler ParameterHandler ParameterAcceptor::prm; ParameterAcceptor::ParameterAcceptor(const std::string name) : acceptor_id(class_list.size()), section_name(name) { SmartPointer<ParameterAcceptor> pt(this, type(*this).c_str()); class_list.push_back(pt); } ParameterAcceptor::~ParameterAcceptor() { class_list[acceptor_id] = 0; } std::string ParameterAcceptor::get_section_name() const { return (section_name != "" ? section_name : type(*this)); } void ParameterAcceptor::initialize(const std::string filename) { prm.clear(); declare_all_parameters(prm); if (filename != "") prm.read_input(filename); parse_all_parameters(prm); } void ParameterAcceptor::clear() { class_list.clear(); } void ParameterAcceptor::parse_all_parameters(ParameterHandler &prm) { for (unsigned int i=0; i< class_list.size(); ++i) { prm.enter_subsection(class_list[i]->get_section_name()); class_list[i]->parse_parameters(prm); prm.leave_subsection(); } } void ParameterAcceptor::declare_all_parameters(ParameterHandler &prm) { for (unsigned int i=0; i< class_list.size(); ++i) { prm.enter_subsection(class_list[i]->get_section_name()); class_list[i]->declare_parameters(prm); prm.leave_subsection(); } } void ParameterAcceptor::parse_parameters(ParameterHandler &prm) { for (auto it = parameters.begin(); it != parameters.end(); ++it) { if (it->second.type() == typeid(std::string *)) { *(boost::any_cast<std::string *>(it->second)) = prm.get(it->first); } else if (it->second.type() == typeid(double *)) { *(boost::any_cast<double *>(it->second)) = prm.get_double(it->first); } else if (it->second.type() == typeid(int *)) { *(boost::any_cast<int *>(it->second)) = prm.get_integer(it->first); } else if (it->second.type() == typeid(unsigned int *)) { *(boost::any_cast<unsigned int *>(it->second)) = prm.get_integer(it->first); } else if (it->second.type() == typeid(bool *)) { *(boost::any_cast<bool *>(it->second)) = prm.get_bool(it->first); } // Here we have the difficult types... // First all point types. else if (it->second.type() == typeid(Point<1> *)) { std::vector<double> p = Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first))); AssertDimension(p.size(), 1); Point<1> &pp = *(boost::any_cast<Point<1>*>(it->second)); pp[0] = p[0]; } else if (it->second.type() == typeid(Point<2> *)) { std::vector<double> p = Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first))); AssertDimension(p.size(), 2); Point<2> &pp = *(boost::any_cast<Point<2>*>(it->second)); pp[0] = p[0]; pp[1] = p[1]; } else if (it->second.type() == typeid(Point<3> *)) { std::vector<double> p = Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first))); AssertDimension(p.size(), 3); Point<3> &pp = *(boost::any_cast<Point<3>*>(it->second)); pp[0] = p[0]; pp[1] = p[1]; pp[2] = p[2]; } else if (it->second.type() == typeid(std::vector<std::string> *)) { std::vector<std::string> &string_list = *(boost::any_cast<std::vector<std::string>*>(it->second)); string_list = Utilities::split_string_list(prm.get(it->first)); } else if (it->second.type() == typeid(std::vector<unsigned int> *)) { std::vector<unsigned int> &int_list = *(boost::any_cast<std::vector<unsigned int>*>(it->second)); std::vector<std::string> string_list = Utilities::split_string_list(prm.get(it->first)); int_list.resize(string_list.size()); for (unsigned int i=0; i<string_list.size(); ++i) int_list[i] = std::stoul(string_list[i]); } else if (it->second.type() == typeid(std::vector<double> *)) { std::vector<double> &double_list = *(boost::any_cast<std::vector<double>*>(it->second)); double_list = Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first))); } else { AssertThrow(false, ExcNotImplemented()); } } } void ParameterAcceptor::parse_parameters_call_back() {}; <commit_msg>added another include to parameter_acceptor.cc<commit_after>#include "parameter_acceptor.h" #include "utilities.h" #include <deal.II/base/point.h> #include <string> #include <iostream> // Static empty class list std::vector<SmartPointer<ParameterAcceptor> > ParameterAcceptor::class_list; // Static parameter handler ParameterHandler ParameterAcceptor::prm; ParameterAcceptor::ParameterAcceptor(const std::string name) : acceptor_id(class_list.size()), section_name(name) { SmartPointer<ParameterAcceptor> pt(this, type(*this).c_str()); class_list.push_back(pt); } ParameterAcceptor::~ParameterAcceptor() { class_list[acceptor_id] = 0; } std::string ParameterAcceptor::get_section_name() const { return (section_name != "" ? section_name : type(*this)); } void ParameterAcceptor::initialize(const std::string filename) { prm.clear(); declare_all_parameters(prm); if (filename != "") prm.read_input(filename); parse_all_parameters(prm); } void ParameterAcceptor::clear() { class_list.clear(); } void ParameterAcceptor::parse_all_parameters(ParameterHandler &prm) { for (unsigned int i=0; i< class_list.size(); ++i) { prm.enter_subsection(class_list[i]->get_section_name()); class_list[i]->parse_parameters(prm); prm.leave_subsection(); } } void ParameterAcceptor::declare_all_parameters(ParameterHandler &prm) { for (unsigned int i=0; i< class_list.size(); ++i) { prm.enter_subsection(class_list[i]->get_section_name()); class_list[i]->declare_parameters(prm); prm.leave_subsection(); } } void ParameterAcceptor::parse_parameters(ParameterHandler &prm) { for (auto it = parameters.begin(); it != parameters.end(); ++it) { if (it->second.type() == typeid(std::string *)) { *(boost::any_cast<std::string *>(it->second)) = prm.get(it->first); } else if (it->second.type() == typeid(double *)) { *(boost::any_cast<double *>(it->second)) = prm.get_double(it->first); } else if (it->second.type() == typeid(int *)) { *(boost::any_cast<int *>(it->second)) = prm.get_integer(it->first); } else if (it->second.type() == typeid(unsigned int *)) { *(boost::any_cast<unsigned int *>(it->second)) = prm.get_integer(it->first); } else if (it->second.type() == typeid(bool *)) { *(boost::any_cast<bool *>(it->second)) = prm.get_bool(it->first); } // Here we have the difficult types... // First all point types. else if (it->second.type() == typeid(Point<1> *)) { std::vector<double> p = Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first))); AssertDimension(p.size(), 1); Point<1> &pp = *(boost::any_cast<Point<1>*>(it->second)); pp[0] = p[0]; } else if (it->second.type() == typeid(Point<2> *)) { std::vector<double> p = Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first))); AssertDimension(p.size(), 2); Point<2> &pp = *(boost::any_cast<Point<2>*>(it->second)); pp[0] = p[0]; pp[1] = p[1]; } else if (it->second.type() == typeid(Point<3> *)) { std::vector<double> p = Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first))); AssertDimension(p.size(), 3); Point<3> &pp = *(boost::any_cast<Point<3>*>(it->second)); pp[0] = p[0]; pp[1] = p[1]; pp[2] = p[2]; } else if (it->second.type() == typeid(std::vector<std::string> *)) { std::vector<std::string> &string_list = *(boost::any_cast<std::vector<std::string>*>(it->second)); string_list = Utilities::split_string_list(prm.get(it->first)); } else if (it->second.type() == typeid(std::vector<unsigned int> *)) { std::vector<unsigned int> &int_list = *(boost::any_cast<std::vector<unsigned int>*>(it->second)); std::vector<std::string> string_list = Utilities::split_string_list(prm.get(it->first)); int_list.resize(string_list.size()); for (unsigned int i=0; i<string_list.size(); ++i) int_list[i] = std::stoul(string_list[i]); } else if (it->second.type() == typeid(std::vector<double> *)) { std::vector<double> &double_list = *(boost::any_cast<std::vector<double>*>(it->second)); double_list = Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first))); } else { AssertThrow(false, ExcNotImplemented()); } } } void ParameterAcceptor::parse_parameters_call_back() {}; <|endoftext|>
<commit_before><commit_msg>warning C4510: default constructor could not be generated<commit_after><|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Rene Brun 02/09/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //______________________________________________________________________________ // // TTask is a base class that can be used to build a complex tree of Tasks. // Each TTask derived class may contain other TTasks that can be executed // recursively, such that a complex program can be dynamically built and executed // by invoking the services of the top level Task or one of its subtasks. // // Use the TTask::Add function to add a subtask to an existing TTask. // To execute a TTask, one calls the ExecuteTask function. ExecuteTask will // call recursively: // - the TTask::Exec function of the derived class // - TTask::ExecuteTasks to execute for each task the list of its subtasks. // If the top level task (see example below) is added to the list of Root // browsable objects, the tree of tasks can be visualized by the Root browser. // The browser can be used to start a task, set break points at the beginning // of a task or when the task has completed. At a breakpoint, data structures // generated by the execution up this point may be inspected asyncronously // and then the execution can be resumed by selecting the "Continue" function // of a task. // // A Task may be active or inactive (controlled by TTask::SetActive). // When a task is not active, its sub tasks are not executed. // // A TTask tree may be made persistent, saving the status of all the tasks. // // The picture in the Root browser below has been generated by executing // the following script: // //{ //------------------script tasks.C--------------------------- // TTask *aliroot = new TTask("aliroot","ALICE reconstruction main task"); // TTask *geominit = new TTask("geomInit","Initialize ALICE geometry"); // TTask *matinit = new TTask("matInit","Initialize ALICE materials"); // TTask *physinit = new TTask("physInit","Initialize Physics processes"); // TTask *tracker = new TTask("tracker","Track reconstruction manager"); // TTask *tpcrec = new TTask("tpcrec","TPC reconstruction"); // TTask *itsrec = new TTask("itsrec","ITS reconstruction"); // TTask *muonrec = new TTask("muonRec","Muon Reconstruction"); // TTask *phosrec = new TTask("phosRec","Phos Reconstruction"); // TTask *richrec = new TTask("richRec","Rich Reconstruction"); // TTask *trdrec = new TTask("trdRec","TRD Reconstruction"); // TTask *globrec = new TTask("globRec","Global Track Reconstruction"); // TTask *pstats = new TTask("printStats","Print Run Statistics"); // TTask *run = new TTask("run","Process one run"); // TTask *event = new TTask("event","Process one event"); // aliroot->Add(geominit); // aliroot->Add(matinit); // aliroot->Add(physinit); // aliroot->Add(run); // run->Add(event); // event->Add(tracker); // event->Add(muonrec); // event->Add(phosrec); // event->Add(richrec); // event->Add(trdrec); // event->Add(globrec); // tracker->Add(tpcrec); // tracker->Add(itsrec); // run->Add(pstats); // // gROOT->GetListOfBrowsables()->Add(aliroot,"aliroot"); // new TBrowser; //} //------------------------------------------------------------- // //Begin_Html /* <img src="gif/tasks.gif"> */ //End_Html #include "Riostream.h" #include "TTask.h" #include "TBrowser.h" #include "TROOT.h" #include "TRegexp.h" TTask *TTask::fgBeginTask = 0; TTask *TTask::fgBreakPoint = 0; ClassImp(TTask) //______________________________________________________________________________ TTask::TTask() { // Default constructor invoked when reading a TTask object from a file. fHasExecuted = kFALSE; fActive = kTRUE; fBreakin = 0; fBreakout = 0; fTasks = 0; } //______________________________________________________________________________ TTask::TTask(const char* name, const char *title) : TNamed(name,title) { // Standard constructor. fHasExecuted = kFALSE; fActive = kTRUE; fBreakin = 0; fBreakout = 0; fTasks = new TList(); } //______________________________________________________________________________ TTask& TTask::operator=(const TTask& tt) { //assignment operator (PLEASE DO NOT USE THIS IS WRONG) if(this!=&tt) { TNamed::operator=(tt); fTasks= 0; //<===tobe fixed fOption=tt.fOption; fBreakin=tt.fBreakin; fBreakout=tt.fBreakout; fHasExecuted=tt.fHasExecuted; fActive=tt.fActive; } return *this; } //______________________________________________________________________________ //______________________________________________________________________________ TTask::TTask(const TTask &task) : TNamed(task) { // Copy constructors. (PLEASE DO NOT USE THIS IS WRONG) fTasks = new TList(); } //______________________________________________________________________________ TTask::~TTask() { // Delete a task and its subtasks. if (!fTasks) return; fTasks->Delete(); delete fTasks; } //______________________________________________________________________________ void TTask::Abort() { // Abort current tree of tasks. // After this call, the tree of tasks is ready to be executed again. // The application must take care of cleaning data structures created // by previous executions. if (!fgBeginTask) { printf(" Nothing to abort: No task currently running\n"); return; } CleanTasks(); fgBeginTask = 0; fgBreakPoint = 0; } //______________________________________________________________________________ void TTask::Browse(TBrowser *b) { // Browse the list of tasks. // It is recommended to add the top level task to the list of // ROOT browsables by: // gROOT->GetListOfBrowsables()->Add(myTopLevelTask) fTasks->Browse(b); } //______________________________________________________________________________ void TTask::CleanTasks() { // Reset tasks state: breakpoints and execute flags // also invokes the Clear function of each task to clear all data // structures created by a previous execution of a task. if (fBreakin) fBreakin = 1; if (fBreakout) fBreakout = 1; fHasExecuted = kFALSE; Clear(); TIter next(fTasks); TTask *task; while((task=(TTask*)next())) { task->CleanTasks(); } } //______________________________________________________________________________ void TTask::Clear(Option_t *) { // Recursively call the Clear function of this task and its subtasks. // The Clear function must be implemented for each derived class // to clear all data structures created by a previous execution of a task. // This function is automatically called by the CleanTasks function. } //______________________________________________________________________________ void TTask::Continue() { // Resume execution at the current break point. if (!fgBeginTask) { printf(" No task to continue\n"); return; } fgBreakPoint = 0; fgBeginTask->ExecuteTasks(fOption.Data()); if (!fgBreakPoint) { fgBeginTask->CleanTasks(); fgBeginTask = 0; } } //______________________________________________________________________________ void TTask::Exec(Option_t *) { // Dummy Execute. // This function must be redefined in the derived classes. } //______________________________________________________________________________ void TTask::ExecuteTask(Option_t *option) { // Execute main task and its subtasks. // When calling this function, the Exec function of the corresponding class // is invoked, then the list of its subtasks is executed calling recursively // all the subtasks, etc. // // The option parameter may be used to select different execution steps // within a task. This parameter is passed also to all the subtasks. if (fgBeginTask) { Error("ExecuteTask","Cannot execute task:%s, already running task: %s",GetName(),fgBeginTask->GetName()); return; } if (!IsActive()) return; fOption = option; fgBeginTask = this; fgBreakPoint = 0; if (fBreakin) return; if (gDebug > 1) { TROOT::IndentLevel(); cout<<"Execute task:"<<GetName()<<" : "<<GetTitle()<<endl; TROOT::IncreaseDirLevel(); } Exec(option); fHasExecuted = kTRUE; ExecuteTasks(option); if (gDebug > 1) TROOT::DecreaseDirLevel(); if (fBreakout) return; if (!fgBreakPoint) { fgBeginTask->CleanTasks(); fgBeginTask = 0; } } //______________________________________________________________________________ void TTask::ExecuteTasks(Option_t *option) { // Execute all the subtasks of a task. TIter next(fTasks); TTask *task; while((task=(TTask*)next())) { if (fgBreakPoint) return; if (!task->IsActive()) continue; if (task->fHasExecuted) { task->ExecuteTasks(option); continue; } if (task->fBreakin == 1) { printf("Break at entry of task: %s\n",task->GetName()); fgBreakPoint = this; task->fBreakin++; return; } if (gDebug > 1) { TROOT::IndentLevel(); cout<<"Execute task:"<<task->GetName()<<" : "<<task->GetTitle()<<endl; TROOT::IncreaseDirLevel(); } task->Exec(option); task->fHasExecuted = kTRUE; task->ExecuteTasks(option); if (gDebug > 1) TROOT::DecreaseDirLevel(); if (task->fBreakout == 1) { printf("Break at exit of task: %s\n",task->GetName()); fgBreakPoint = this; task->fBreakout++; return; } } } //______________________________________________________________________________ void TTask::ls(Option_t *option) const { // List the tree of tasks. // Indentation is used to identify the task tree. TROOT::IndentLevel(); cout <<GetName()<<"\t"<<GetTitle()<<endl; TROOT::IncreaseDirLevel(); TString opta = option; TString opt = opta.Strip(TString::kBoth); TRegexp re(opt, kTRUE); TObject *obj; TIter nextobj(fTasks); while ((obj = (TObject *) nextobj())) { TString s = obj->GetName(); if (s.Index(re) == kNPOS) continue; obj->ls(option); } TROOT::DecreaseDirLevel(); } <commit_msg>Correct implementation of the copy constructor and assignment operator<commit_after>// @(#)root/base:$Id$ // Author: Rene Brun 02/09/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //______________________________________________________________________________ // // TTask is a base class that can be used to build a complex tree of Tasks. // Each TTask derived class may contain other TTasks that can be executed // recursively, such that a complex program can be dynamically built and executed // by invoking the services of the top level Task or one of its subtasks. // // Use the TTask::Add function to add a subtask to an existing TTask. // To execute a TTask, one calls the ExecuteTask function. ExecuteTask will // call recursively: // - the TTask::Exec function of the derived class // - TTask::ExecuteTasks to execute for each task the list of its subtasks. // If the top level task (see example below) is added to the list of Root // browsable objects, the tree of tasks can be visualized by the Root browser. // The browser can be used to start a task, set break points at the beginning // of a task or when the task has completed. At a breakpoint, data structures // generated by the execution up this point may be inspected asyncronously // and then the execution can be resumed by selecting the "Continue" function // of a task. // // A Task may be active or inactive (controlled by TTask::SetActive). // When a task is not active, its sub tasks are not executed. // // A TTask tree may be made persistent, saving the status of all the tasks. // // The picture in the Root browser below has been generated by executing // the following script: // //{ //------------------script tasks.C--------------------------- // TTask *aliroot = new TTask("aliroot","ALICE reconstruction main task"); // TTask *geominit = new TTask("geomInit","Initialize ALICE geometry"); // TTask *matinit = new TTask("matInit","Initialize ALICE materials"); // TTask *physinit = new TTask("physInit","Initialize Physics processes"); // TTask *tracker = new TTask("tracker","Track reconstruction manager"); // TTask *tpcrec = new TTask("tpcrec","TPC reconstruction"); // TTask *itsrec = new TTask("itsrec","ITS reconstruction"); // TTask *muonrec = new TTask("muonRec","Muon Reconstruction"); // TTask *phosrec = new TTask("phosRec","Phos Reconstruction"); // TTask *richrec = new TTask("richRec","Rich Reconstruction"); // TTask *trdrec = new TTask("trdRec","TRD Reconstruction"); // TTask *globrec = new TTask("globRec","Global Track Reconstruction"); // TTask *pstats = new TTask("printStats","Print Run Statistics"); // TTask *run = new TTask("run","Process one run"); // TTask *event = new TTask("event","Process one event"); // aliroot->Add(geominit); // aliroot->Add(matinit); // aliroot->Add(physinit); // aliroot->Add(run); // run->Add(event); // event->Add(tracker); // event->Add(muonrec); // event->Add(phosrec); // event->Add(richrec); // event->Add(trdrec); // event->Add(globrec); // tracker->Add(tpcrec); // tracker->Add(itsrec); // run->Add(pstats); // // gROOT->GetListOfBrowsables()->Add(aliroot,"aliroot"); // new TBrowser; //} //------------------------------------------------------------- // //Begin_Html /* <img src="gif/tasks.gif"> */ //End_Html #include "Riostream.h" #include "TTask.h" #include "TBrowser.h" #include "TROOT.h" #include "TRegexp.h" TTask *TTask::fgBeginTask = 0; TTask *TTask::fgBreakPoint = 0; ClassImp(TTask) //______________________________________________________________________________ TTask::TTask() { // Default constructor invoked when reading a TTask object from a file. fHasExecuted = kFALSE; fActive = kTRUE; fBreakin = 0; fBreakout = 0; fTasks = 0; } //______________________________________________________________________________ TTask::TTask(const char* name, const char *title) : TNamed(name,title) { // Standard constructor. fHasExecuted = kFALSE; fActive = kTRUE; fBreakin = 0; fBreakout = 0; fTasks = new TList(); } //______________________________________________________________________________ TTask& TTask::operator=(const TTask& tt) { //assignment operator (PLEASE DO NOT USE THIS IS WRONG) if(this!=&tt) { TNamed::operator=(tt); fTasks->Delete(); TIter next(tt.fTasks); TTask *task; while ((task = (TTask*)next())) { fTasks->Add(new TTask(*task)); } fOption=tt.fOption; fBreakin=tt.fBreakin; fBreakout=tt.fBreakout; fHasExecuted=tt.fHasExecuted; fActive=tt.fActive; } return *this; } //______________________________________________________________________________ //______________________________________________________________________________ TTask::TTask(const TTask &other) : TNamed(other) { // Copy constructor. fTasks = new TList(); TIter next(other.fTasks); TTask *task; while ((task = (TTask*)next())) { fTasks->Add(new TTask(*task)); } fOption = other.fOption; fBreakin = other.fBreakin; fBreakout = other.fBreakout; fHasExecuted = kFALSE; fActive = other.fActive; } //______________________________________________________________________________ TTask::~TTask() { // Delete a task and its subtasks. if (!fTasks) return; fTasks->Delete(); delete fTasks; } //______________________________________________________________________________ void TTask::Abort() { // Abort current tree of tasks. // After this call, the tree of tasks is ready to be executed again. // The application must take care of cleaning data structures created // by previous executions. if (!fgBeginTask) { printf(" Nothing to abort: No task currently running\n"); return; } CleanTasks(); fgBeginTask = 0; fgBreakPoint = 0; } //______________________________________________________________________________ void TTask::Browse(TBrowser *b) { // Browse the list of tasks. // It is recommended to add the top level task to the list of // ROOT browsables by: // gROOT->GetListOfBrowsables()->Add(myTopLevelTask) fTasks->Browse(b); } //______________________________________________________________________________ void TTask::CleanTasks() { // Reset tasks state: breakpoints and execute flags // also invokes the Clear function of each task to clear all data // structures created by a previous execution of a task. if (fBreakin) fBreakin = 1; if (fBreakout) fBreakout = 1; fHasExecuted = kFALSE; Clear(); TIter next(fTasks); TTask *task; while((task=(TTask*)next())) { task->CleanTasks(); } } //______________________________________________________________________________ void TTask::Clear(Option_t *) { // Recursively call the Clear function of this task and its subtasks. // The Clear function must be implemented for each derived class // to clear all data structures created by a previous execution of a task. // This function is automatically called by the CleanTasks function. } //______________________________________________________________________________ void TTask::Continue() { // Resume execution at the current break point. if (!fgBeginTask) { printf(" No task to continue\n"); return; } fgBreakPoint = 0; fgBeginTask->ExecuteTasks(fOption.Data()); if (!fgBreakPoint) { fgBeginTask->CleanTasks(); fgBeginTask = 0; } } //______________________________________________________________________________ void TTask::Exec(Option_t *) { // Dummy Execute. // This function must be redefined in the derived classes. } //______________________________________________________________________________ void TTask::ExecuteTask(Option_t *option) { // Execute main task and its subtasks. // When calling this function, the Exec function of the corresponding class // is invoked, then the list of its subtasks is executed calling recursively // all the subtasks, etc. // // The option parameter may be used to select different execution steps // within a task. This parameter is passed also to all the subtasks. if (fgBeginTask) { Error("ExecuteTask","Cannot execute task:%s, already running task: %s",GetName(),fgBeginTask->GetName()); return; } if (!IsActive()) return; fOption = option; fgBeginTask = this; fgBreakPoint = 0; if (fBreakin) return; if (gDebug > 1) { TROOT::IndentLevel(); cout<<"Execute task:"<<GetName()<<" : "<<GetTitle()<<endl; TROOT::IncreaseDirLevel(); } Exec(option); fHasExecuted = kTRUE; ExecuteTasks(option); if (gDebug > 1) TROOT::DecreaseDirLevel(); if (fBreakout) return; if (!fgBreakPoint) { fgBeginTask->CleanTasks(); fgBeginTask = 0; } } //______________________________________________________________________________ void TTask::ExecuteTasks(Option_t *option) { // Execute all the subtasks of a task. TIter next(fTasks); TTask *task; while((task=(TTask*)next())) { if (fgBreakPoint) return; if (!task->IsActive()) continue; if (task->fHasExecuted) { task->ExecuteTasks(option); continue; } if (task->fBreakin == 1) { printf("Break at entry of task: %s\n",task->GetName()); fgBreakPoint = this; task->fBreakin++; return; } if (gDebug > 1) { TROOT::IndentLevel(); cout<<"Execute task:"<<task->GetName()<<" : "<<task->GetTitle()<<endl; TROOT::IncreaseDirLevel(); } task->Exec(option); task->fHasExecuted = kTRUE; task->ExecuteTasks(option); if (gDebug > 1) TROOT::DecreaseDirLevel(); if (task->fBreakout == 1) { printf("Break at exit of task: %s\n",task->GetName()); fgBreakPoint = this; task->fBreakout++; return; } } } //______________________________________________________________________________ void TTask::ls(Option_t *option) const { // List the tree of tasks. // Indentation is used to identify the task tree. TROOT::IndentLevel(); cout <<GetName()<<"\t"<<GetTitle()<<endl; TROOT::IncreaseDirLevel(); TString opta = option; TString opt = opta.Strip(TString::kBoth); TRegexp re(opt, kTRUE); TObject *obj; TIter nextobj(fTasks); while ((obj = (TObject *) nextobj())) { TString s = obj->GetName(); if (s.Index(re) == kNPOS) continue; obj->ls(option); } TROOT::DecreaseDirLevel(); } <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Claire Xenia Wolf <claire@yosyshq.com> * Copyright (C) 2020 Pepijn de Vos <pepijn@symbioticeda.com> * * 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. * */ #ifdef MAIN_EXECUTABLE #include <fstream> #include <locale> #include <regex> #include "command.h" #include "design_utils.h" #include "log.h" #include "timing.h" USING_NEXTPNR_NAMESPACE class GowinCommandHandler : public CommandHandler { public: GowinCommandHandler(int argc, char **argv); virtual ~GowinCommandHandler(){}; std::unique_ptr<Context> createContext(dict<std::string, Property> &values) override; void setupArchContext(Context *ctx) override{}; void customAfterLoad(Context *ctx) override; protected: po::options_description getArchOptions() override; }; GowinCommandHandler::GowinCommandHandler(int argc, char **argv) : CommandHandler(argc, argv) {} po::options_description GowinCommandHandler::getArchOptions() { po::options_description specific("Architecture specific options"); specific.add_options()("device", po::value<std::string>(), "device name"); specific.add_options()("family", po::value<std::string>(), "family name"); specific.add_options()("cst", po::value<std::string>(), "physical constraints file"); return specific; } std::unique_ptr<Context> GowinCommandHandler::createContext(dict<std::string, Property> &values) { std::regex devicere = std::regex("GW1N([SZ]?)[A-Z]*-(LV|UV|UX)([0-9])(C?).*"); std::smatch match; std::string device = vm["device"].as<std::string>(); if (!std::regex_match(device, match, devicere)) { log_error("Invalid device %s\n", device.c_str()); } ArchArgs chipArgs; chipArgs.gui = vm.count("gui") != 0; if (vm.count("family")) { chipArgs.family = vm["family"].as<std::string>(); } else { char buf[36]; // GW1N and GW1NR variants share the same database. // Most Gowin devices are a System in Package with some SDRAM wirebonded to a GPIO bank. // However, it appears that the S series with embedded ARM core are unique silicon. snprintf(buf, 36, "GW1N%s-%s", match[1].str().c_str(), match[3].str().c_str()); chipArgs.family = buf; } chipArgs.partnumber = match[0]; return std::unique_ptr<Context>(new Context(chipArgs)); } void GowinCommandHandler::customAfterLoad(Context *ctx) { if (vm.count("cst")) { std::string filename = vm["cst"].as<std::string>(); std::ifstream in(filename); if (!in) log_error("Failed to open input CST file %s.\n", filename.c_str()); ctx->read_cst(in); } } int main(int argc, char *argv[]) { // set the locale here because when you create a context you create several // floating point strings whose representation depends on the locale. If // you don't do this, the strings will be in the C locale and later when Qt // starts it won't be able to read them back as numbers. std::locale::global(std::locale("")); GowinCommandHandler handler(argc, argv); return handler.exec(); } #endif <commit_msg>gowin: test locale workaround<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Claire Xenia Wolf <claire@yosyshq.com> * Copyright (C) 2020 Pepijn de Vos <pepijn@symbioticeda.com> * * 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. * */ #ifdef MAIN_EXECUTABLE #include <fstream> #include <locale> #include <regex> #include "command.h" #include "design_utils.h" #include "log.h" #include "timing.h" USING_NEXTPNR_NAMESPACE class GowinCommandHandler : public CommandHandler { public: GowinCommandHandler(int argc, char **argv); virtual ~GowinCommandHandler(){}; std::unique_ptr<Context> createContext(dict<std::string, Property> &values) override; void setupArchContext(Context *ctx) override{}; void customAfterLoad(Context *ctx) override; protected: po::options_description getArchOptions() override; }; GowinCommandHandler::GowinCommandHandler(int argc, char **argv) : CommandHandler(argc, argv) {} po::options_description GowinCommandHandler::getArchOptions() { po::options_description specific("Architecture specific options"); specific.add_options()("device", po::value<std::string>(), "device name"); specific.add_options()("family", po::value<std::string>(), "family name"); specific.add_options()("cst", po::value<std::string>(), "physical constraints file"); return specific; } std::unique_ptr<Context> GowinCommandHandler::createContext(dict<std::string, Property> &values) { std::regex devicere = std::regex("GW1N([SZ]?)[A-Z]*-(LV|UV|UX)([0-9])(C?).*"); std::smatch match; std::string device = vm["device"].as<std::string>(); if (!std::regex_match(device, match, devicere)) { log_error("Invalid device %s\n", device.c_str()); } ArchArgs chipArgs; chipArgs.gui = vm.count("gui") != 0; if (vm.count("family")) { chipArgs.family = vm["family"].as<std::string>(); } else { char buf[36]; // GW1N and GW1NR variants share the same database. // Most Gowin devices are a System in Package with some SDRAM wirebonded to a GPIO bank. // However, it appears that the S series with embedded ARM core are unique silicon. snprintf(buf, 36, "GW1N%s-%s", match[1].str().c_str(), match[3].str().c_str()); chipArgs.family = buf; } chipArgs.partnumber = match[0]; return std::unique_ptr<Context>(new Context(chipArgs)); } void GowinCommandHandler::customAfterLoad(Context *ctx) { if (vm.count("cst")) { std::string filename = vm["cst"].as<std::string>(); std::ifstream in(filename); if (!in) log_error("Failed to open input CST file %s.\n", filename.c_str()); ctx->read_cst(in); } } int main(int argc, char *argv[]) { // set the locale here because when you create a context you create several // floating point strings whose representation depends on the locale. If // you don't do this, the strings will be in the C locale and later when Qt // starts it won't be able to read them back as numbers. try { std::locale::global(std::locale("")); } catch (const std::runtime_error &e) { // the locale is broken in this system, so leave it as it is } GowinCommandHandler handler(argc, argv); return handler.exec(); } #endif <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Quantum 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 "tensorflow_quantum/core/ops/parse_context.h" #include <google/protobuf/text_format.h> #include <string> #include <vector> #include "cirq/google/api/v2/program.pb.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/error_codes.pb.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow_quantum/core/ops/tfq_simulate_utils.h" #include "tensorflow_quantum/core/proto/pauli_sum.pb.h" #include "tensorflow_quantum/core/src/program_resolution.h" namespace tfq { namespace { using ::cirq::google::api::v2::Program; using ::tensorflow::OpKernelContext; using ::tensorflow::Status; using ::tensorflow::Tensor; using ::tfq::proto::PauliSum; template <typename T> Status ParseProto(const std::string& text, T* proto) { // First attempt to parse from the binary representation. if (proto->ParseFromString(text)) { return Status::OK(); } // If that fails, then try to parse from the human readable representation. if (google::protobuf::TextFormat::ParseFromString(text, proto)) { return Status::OK(); } return Status(tensorflow::error::INVALID_ARGUMENT, "Unparseable proto: " + text); } } // namespace Status ParsePrograms(OpKernelContext* context, const std::string& input_name, std::vector<Program>* programs) { const tensorflow::Tensor* input; Status status = context->input(input_name, &input); if (!status.ok()) { return status; } if (input->dims() != 1) { // Never parse anything other than a 1d list of circuits. return Status( tensorflow::error::INVALID_ARGUMENT, absl::StrCat("programs must be rank 1. Got rank ", input->dims(), ".")); } const auto program_strings = input->vec<tensorflow::tstring>(); const int num_programs = program_strings.dimension(0); programs->assign(num_programs, Program()); auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { OP_REQUIRES_OK(context, ParseProto(program_strings(i), &programs->at(i))); } }; // TODO(mbbrough): Determine if this is a good cycle estimate. const int cycle_estimate = 1000; context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( num_programs, cycle_estimate, DoWork); return Status::OK(); } Status GetProgramsAndProgramsToAppend( OpKernelContext* context, std::vector<Program>* programs, std::vector<Program>* programs_to_append) { Status status = ParsePrograms(context, "programs", programs); if (!status.ok()) { return status; } status = ParsePrograms(context, "programs_to_append", programs_to_append); if (!status.ok()) { return status; } if (programs->size() != programs_to_append->size()) { return Status(tensorflow::error::INVALID_ARGUMENT, "programs and programs_to_append must have matching sizes."); } return Status::OK(); } Status GetProgramsAndNumQubits( OpKernelContext* context, std::vector<Program>* programs, std::vector<int>* num_qubits, std::vector<std::vector<PauliSum>>* p_sums /*=nullptr*/) { // 1. Parse input programs // 2. (Optional) Parse input PauliSums // 3. Convert GridQubit locations to integers. Status status = ParsePrograms(context, "programs", programs); if (!status.ok()) { return status; } if (p_sums) { status = GetPauliSums(context, p_sums); if (!status.ok()) { return status; } } // Resolve qubit ID's in parallel. num_qubits->assign(programs->size(), -1); auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { Program& program = (*programs)[i]; unsigned int this_num_qubits; if (p_sums) { OP_REQUIRES_OK(context, ResolveQubitIds(&program, &this_num_qubits, &(p_sums->at(i)))); } else { OP_REQUIRES_OK(context, ResolveQubitIds(&program, &this_num_qubits)); } (*num_qubits)[i] = this_num_qubits; } }; // TODO(mbbrough): Determine if this is a good cycle estimate. const int cycle_estimate = 1000; context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( num_qubits->size(), cycle_estimate, DoWork); return Status::OK(); } Status GetPauliSums(OpKernelContext* context, std::vector<std::vector<PauliSum>>* p_sums) { // 1. Parses PauliSum proto. const Tensor* input; Status status = context->input("pauli_sums", &input); if (!status.ok()) { return status; } if (input->dims() != 2) { return Status(tensorflow::error::INVALID_ARGUMENT, absl::StrCat("pauli_sums must be rank 2. Got rank ", input->dims(), ".")); } const auto sum_specs = input->matrix<tensorflow::tstring>(); p_sums->assign(sum_specs.dimension(0), std::vector<PauliSum>(sum_specs.dimension(1), PauliSum())); auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { for (int j = 0; j < sum_specs.dimension(1); j++) { PauliSum p; OP_REQUIRES_OK(context, ParseProto(sum_specs(i, j), &p)); (*p_sums)[i][j] = p; } } }; // TODO(mbbrough): Determine if this is a good cycle estimate. const int cycle_estimate = 1000; context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( sum_specs.dimension(0), cycle_estimate, DoWork); return Status::OK(); } Status GetSymbolMaps(OpKernelContext* context, std::vector<SymbolMap>* maps) { // 1. Convert to dictionary representation for param resolution. const Tensor* input_names; Status status = context->input("symbol_names", &input_names); if (!status.ok()) { return status; } if (input_names->dims() != 1) { return Status(tensorflow::error::INVALID_ARGUMENT, absl::StrCat("symbol_names must be rank 1. Got rank ", input_names->dims(), ".")); } const Tensor* input_values; status = context->input("symbol_values", &input_values); if (!status.ok()) { return status; } if (input_values->dims() != 2) { return Status(tensorflow::error::INVALID_ARGUMENT, absl::StrCat("symbol_values must be rank 2. Got rank ", input_values->dims(), ".")); } const auto symbol_names = input_names->vec<tensorflow::tstring>(); const auto symbol_values = input_values->matrix<float>(); if (symbol_names.dimension(0) != symbol_values.dimension(1)) { return Status(tensorflow::error::INVALID_ARGUMENT, "Input symbol names and value sizes do not match."); } maps->assign(symbol_values.dimension(0), SymbolMap()); auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { for (int j = 0; j < symbol_values.dimension(1); j++) { const std::string& name = symbol_names(j); const float value = symbol_values(i, j); (*maps)[i][name] = {j, value}; } } }; // TODO(mbbrough): Determine if this is a good cycle estimate. const int cycle_estimate = 1000; context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( symbol_values.dimension(0), cycle_estimate, DoWork); return Status::OK(); } // TODO (mbbrough/pmassey/jaeyoo): Should grads return an EigenMatrixXd instead // of a vector of vectors ? Status GetGradients(OpKernelContext* context, std::vector<std::vector<float>>* grads) { const Tensor* input; const Status status = context->input("grad", &input); if (!status.ok()) { return status; } const auto input_grads = input->matrix<float>(); grads->reserve(input_grads.dimension(0)); for (int i = 0; i < input_grads.dimension(0); i++) { std::vector<float> sub_grads; sub_grads.reserve(input_grads.dimension(1)); for (int j = 0; j < input_grads.dimension(1); j++) { sub_grads.push_back(input_grads(i, j)); } grads->push_back(sub_grads); } return Status::OK(); } tensorflow::Status GetNumSamples( tensorflow::OpKernelContext* context, std::vector<std::vector<int>>* parsed_num_samples) { const Tensor* input_num_samples; Status status = context->input("num_samples", &input_num_samples); if (!status.ok()) { return status; } if (input_num_samples->dims() != 2) { return Status(tensorflow::error::INVALID_ARGUMENT, absl::StrCat("num_samples must be rank 2. Got rank ", input_num_samples->dims(), ".")); } const auto matrix_num_samples = input_num_samples->matrix<int>(); parsed_num_samples->reserve(matrix_num_samples.dimension(0)); for (unsigned int i = 0; i < matrix_num_samples.dimension(0); i++) { std::vector<int> sub_parsed_num_samples; sub_parsed_num_samples.reserve(matrix_num_samples.dimension(1)); for (unsigned int j = 0; j < matrix_num_samples.dimension(1); j++) { const int num_samples = matrix_num_samples(i, j); if (num_samples < 1) { return Status(tensorflow::error::INVALID_ARGUMENT, "Each element of num_samples must be greater than 0."); } sub_parsed_num_samples.push_back(num_samples); } parsed_num_samples->push_back(sub_parsed_num_samples); } return Status::OK(); } } // namespace tfq <commit_msg>More robust parallelization on doubly nested loops.<commit_after>/* Copyright 2020 The TensorFlow Quantum 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 "tensorflow_quantum/core/ops/parse_context.h" #include <google/protobuf/text_format.h> #include <string> #include <vector> #include "cirq/google/api/v2/program.pb.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/error_codes.pb.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow_quantum/core/ops/tfq_simulate_utils.h" #include "tensorflow_quantum/core/proto/pauli_sum.pb.h" #include "tensorflow_quantum/core/src/program_resolution.h" namespace tfq { namespace { using ::cirq::google::api::v2::Program; using ::tensorflow::OpKernelContext; using ::tensorflow::Status; using ::tensorflow::Tensor; using ::tfq::proto::PauliSum; template <typename T> Status ParseProto(const std::string& text, T* proto) { // First attempt to parse from the binary representation. if (proto->ParseFromString(text)) { return Status::OK(); } // If that fails, then try to parse from the human readable representation. if (google::protobuf::TextFormat::ParseFromString(text, proto)) { return Status::OK(); } return Status(tensorflow::error::INVALID_ARGUMENT, "Unparseable proto: " + text); } } // namespace Status ParsePrograms(OpKernelContext* context, const std::string& input_name, std::vector<Program>* programs) { const tensorflow::Tensor* input; Status status = context->input(input_name, &input); if (!status.ok()) { return status; } if (input->dims() != 1) { // Never parse anything other than a 1d list of circuits. return Status( tensorflow::error::INVALID_ARGUMENT, absl::StrCat("programs must be rank 1. Got rank ", input->dims(), ".")); } const auto program_strings = input->vec<tensorflow::tstring>(); const int num_programs = program_strings.dimension(0); programs->assign(num_programs, Program()); auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { OP_REQUIRES_OK(context, ParseProto(program_strings(i), &programs->at(i))); } }; // TODO(mbbrough): Determine if this is a good cycle estimate. const int cycle_estimate = 1000; context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( num_programs, cycle_estimate, DoWork); return Status::OK(); } Status GetProgramsAndProgramsToAppend( OpKernelContext* context, std::vector<Program>* programs, std::vector<Program>* programs_to_append) { Status status = ParsePrograms(context, "programs", programs); if (!status.ok()) { return status; } status = ParsePrograms(context, "programs_to_append", programs_to_append); if (!status.ok()) { return status; } if (programs->size() != programs_to_append->size()) { return Status(tensorflow::error::INVALID_ARGUMENT, "programs and programs_to_append must have matching sizes."); } return Status::OK(); } Status GetProgramsAndNumQubits( OpKernelContext* context, std::vector<Program>* programs, std::vector<int>* num_qubits, std::vector<std::vector<PauliSum>>* p_sums /*=nullptr*/) { // 1. Parse input programs // 2. (Optional) Parse input PauliSums // 3. Convert GridQubit locations to integers. Status status = ParsePrograms(context, "programs", programs); if (!status.ok()) { return status; } if (p_sums) { status = GetPauliSums(context, p_sums); if (!status.ok()) { return status; } } // Resolve qubit ID's in parallel. num_qubits->assign(programs->size(), -1); auto DoWork = [&](int start, int end) { for (int i = start; i < end; i++) { Program& program = (*programs)[i]; unsigned int this_num_qubits; if (p_sums) { OP_REQUIRES_OK(context, ResolveQubitIds(&program, &this_num_qubits, &(p_sums->at(i)))); } else { OP_REQUIRES_OK(context, ResolveQubitIds(&program, &this_num_qubits)); } (*num_qubits)[i] = this_num_qubits; } }; // TODO(mbbrough): Determine if this is a good cycle estimate. const int cycle_estimate = 1000; context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( num_qubits->size(), cycle_estimate, DoWork); return Status::OK(); } Status GetPauliSums(OpKernelContext* context, std::vector<std::vector<PauliSum>>* p_sums) { // 1. Parses PauliSum proto. const Tensor* input; Status status = context->input("pauli_sums", &input); if (!status.ok()) { return status; } if (input->dims() != 2) { return Status(tensorflow::error::INVALID_ARGUMENT, absl::StrCat("pauli_sums must be rank 2. Got rank ", input->dims(), ".")); } const auto sum_specs = input->matrix<tensorflow::tstring>(); p_sums->assign(sum_specs.dimension(0), std::vector<PauliSum>(sum_specs.dimension(1), PauliSum())); const int op_dim = sum_specs.dimension(1); auto DoWork = [&](int start, int end) { for (int ii = start; ii < end; ii++) { const int i = ii / op_dim; const int j = ii % op_dim; PauliSum p; OP_REQUIRES_OK(context, ParseProto(sum_specs(i, j), &p)); (*p_sums)[i][j] = p; } }; // TODO(mbbrough): Determine if this is a good cycle estimate. const int cycle_estimate = 1000; context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( sum_specs.dimension(0) * sum_specs.dimension(1), cycle_estimate, DoWork); return Status::OK(); } Status GetSymbolMaps(OpKernelContext* context, std::vector<SymbolMap>* maps) { // 1. Convert to dictionary representation for param resolution. const Tensor* input_names; Status status = context->input("symbol_names", &input_names); if (!status.ok()) { return status; } if (input_names->dims() != 1) { return Status(tensorflow::error::INVALID_ARGUMENT, absl::StrCat("symbol_names must be rank 1. Got rank ", input_names->dims(), ".")); } const Tensor* input_values; status = context->input("symbol_values", &input_values); if (!status.ok()) { return status; } if (input_values->dims() != 2) { return Status(tensorflow::error::INVALID_ARGUMENT, absl::StrCat("symbol_values must be rank 2. Got rank ", input_values->dims(), ".")); } const auto symbol_names = input_names->vec<tensorflow::tstring>(); const auto symbol_values = input_values->matrix<float>(); if (symbol_names.dimension(0) != symbol_values.dimension(1)) { return Status(tensorflow::error::INVALID_ARGUMENT, "Input symbol names and value sizes do not match."); } maps->assign(symbol_values.dimension(0), SymbolMap()); const int symbol_dim = symbol_values.dimension(1); auto DoWork = [&](int start, int end) { for (int ii = start; ii < end; ii++) { const int i = ii / symbol_dim; const int j = ii % symbol_dim; const std::string& name = symbol_names(j); const float value = symbol_values(i, j); (*maps)[i][name] = {j, value}; } }; // TODO(mbbrough): Determine if this is a good cycle estimate. const int cycle_estimate = 1000; context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( symbol_values.dimension(0) * symbol_values.dimension(1), cycle_estimate, DoWork); return Status::OK(); } // TODO (mbbrough/pmassey/jaeyoo): Should grads return an EigenMatrixXd instead // of a vector of vectors ? Status GetGradients(OpKernelContext* context, std::vector<std::vector<float>>* grads) { const Tensor* input; const Status status = context->input("grad", &input); if (!status.ok()) { return status; } const auto input_grads = input->matrix<float>(); grads->reserve(input_grads.dimension(0)); for (int i = 0; i < input_grads.dimension(0); i++) { std::vector<float> sub_grads; sub_grads.reserve(input_grads.dimension(1)); for (int j = 0; j < input_grads.dimension(1); j++) { sub_grads.push_back(input_grads(i, j)); } grads->push_back(sub_grads); } return Status::OK(); } tensorflow::Status GetNumSamples( tensorflow::OpKernelContext* context, std::vector<std::vector<int>>* parsed_num_samples) { const Tensor* input_num_samples; Status status = context->input("num_samples", &input_num_samples); if (!status.ok()) { return status; } if (input_num_samples->dims() != 2) { return Status(tensorflow::error::INVALID_ARGUMENT, absl::StrCat("num_samples must be rank 2. Got rank ", input_num_samples->dims(), ".")); } const auto matrix_num_samples = input_num_samples->matrix<int>(); parsed_num_samples->reserve(matrix_num_samples.dimension(0)); for (unsigned int i = 0; i < matrix_num_samples.dimension(0); i++) { std::vector<int> sub_parsed_num_samples; sub_parsed_num_samples.reserve(matrix_num_samples.dimension(1)); for (unsigned int j = 0; j < matrix_num_samples.dimension(1); j++) { const int num_samples = matrix_num_samples(i, j); if (num_samples < 1) { return Status(tensorflow::error::INVALID_ARGUMENT, "Each element of num_samples must be greater than 0."); } sub_parsed_num_samples.push_back(num_samples); } parsed_num_samples->push_back(sub_parsed_num_samples); } return Status::OK(); } } // namespace tfq <|endoftext|>
<commit_before>/*Copyright 2011 George Karagoulis 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 "bst_node.h" #include "gutil_globals.h" #include "Core/exception.h" GUTIL_USING_CORE_NAMESPACE(DataObjects); bst_node::bst_node() :Parent(0), LChild(0), RChild(0), LeftmostChild(this), RightmostChild(this), Height(0), Data(0) { } bst_node::~bst_node() { if(LChild) delete LChild; if(RChild) delete RChild; } int bst_node::HeightDifference() const { int sum(0); if(LChild) sum += (1 + LChild->Height); if(RChild) sum -= (1 + RChild->Height); return sum; } bool bst_node::Balanced() const { return gAbs(HeightDifference()) <= 1; } void bst_node::rebalance(bst_node *n) { int height_difference = n->HeightDifference(); if(height_difference > 1) { // The node is left-heavy // Check if it's LR imbalance so we can resolve that first. if(n->LChild->HeightDifference() < 0) rotate_left(n->LChild); // Now that the LR imbalance is fixed, do the LL rebalance. rotate_right(n); } else if(height_difference < -1) { // The node is right-heavy // Check if it's RL imbalance so we can resolve that first. if(n->RChild->HeightDifference() > 0) rotate_right(n->RChild); // Now that the RL imbalance is fixed, do the RR rebalance. rotate_left(n); } } void bst_node::rotate_right(bst_node *n) { bst_node *parent(n->Parent); if(parent) { if(parent->LChild == n) parent->LChild = n->LChild; else parent->RChild = n->LChild; } n->LChild->Parent = parent; bst_node *tmp(n->LChild->RChild); n->Parent = n->LChild; n->LChild->RChild = n; n->LChild = tmp; if(tmp) tmp->Parent = n; // Have to refresh the node we just rotated, the other one will be refreshed // automatically when we walk up the tree refresh_node_state(n); } void bst_node::rotate_left(bst_node *n) { bst_node *parent(n->Parent); if(parent) { if(parent->LChild == n) parent->LChild = n->RChild; else parent->RChild = n->RChild; } n->RChild->Parent = parent; bst_node *tmp(n->RChild->LChild); n->Parent = n->RChild; n->RChild->LChild = n; n->RChild = tmp; if(tmp) tmp->Parent = n; // Have to refresh the node we just rotated, the other one will be refreshed // automatically when we walk up the tree refresh_node_state(n); } void bst_node::Insert(bst_node *parent, bst_node *new_node, bst_node::SideEnum side) { bst_node **node_ref(0); switch(side) { case LeftSide: node_ref = &parent->LChild; break; case RightSide: node_ref = &parent->RChild; break; default: return; } *node_ref = new_node; new_node->Parent = parent; // Now we need to ascend the tree to the root and update the heights walk_parents_update_heights_rebalance(parent); } void bst_node::Delete(bst_node *node, bst_node *replacement) { // This variable determines where to start adjusting the node height after deletion. bst_node *start_height_adjustment(0); if(replacement) { // If the replacement has a child (at most 1) then we move it into the replacement's place bst_node *replacement_child(0); if(replacement->RChild) replacement_child = replacement->RChild; else if(replacement->LChild) replacement_child = replacement->LChild; if(node == replacement->Parent) start_height_adjustment = replacement; else { start_height_adjustment = replacement->Parent; switch(replacement->SideOfParent()) { case RightSide: replacement->Parent->RChild = replacement_child; case LeftSide: replacement->Parent->LChild = replacement_child; break; default: break; } if(replacement_child) replacement_child->Parent = replacement->Parent; } replacement->Parent = node->Parent; if(replacement != node->RChild) replacement->RChild = node->RChild; if(replacement != node->LChild) replacement->LChild = node->LChild; } else { start_height_adjustment = node->Parent; } if(node->RChild && node->RChild != replacement) node->RChild->Parent = replacement; if(node->LChild && node->LChild != replacement) node->LChild->Parent = replacement; if(node->Parent) { switch(node->SideOfParent()) { case RightSide: node->Parent->RChild = replacement; break; case LeftSide: node->Parent->LChild = replacement; break; default: break; } } // Delete the node (set children to 0 so to not delete them) node->LChild = 0; node->RChild = 0; delete node; // Walk up the tree and update the height variables. walk_parents_update_heights_rebalance(start_height_adjustment); } bst_node::SideEnum bst_node::SideOfParent() const { SideEnum ret(NoSide); if(Parent) { if(Parent->LChild == this) ret = LeftSide; else if(Parent->RChild == this) ret = RightSide; } return ret; } void bst_node::refresh_node_state(bst_node *n) { // Update the node's height cache if(!n->LChild && !n->RChild) n->Height = 0; else { const int lheight(n->LChild ? n->LChild->Height : 0); const int rheight(n->RChild ? n->RChild->Height : 0); n->Height = gMax(lheight, rheight) + 1; } // Update the left-most and right-most child caches n->LeftmostChild = n->LChild ? n->LChild->LeftmostChild : n; n->RightmostChild = n->RChild ? n->RChild->RightmostChild : n; } void bst_node::walk_parents_update_heights_rebalance(bst_node *n) { if(n) { refresh_node_state(n); // Rebalance the node if it's unbalanced if(!n->Balanced()) rebalance(n); walk_parents_update_heights_rebalance(n->Parent); } } bst_node_df_iterator::bst_node_df_iterator(bst_node *n) :current(n), mem_begin(0), mem_end(0) {} bst_node_df_iterator::bst_node_df_iterator(const bst_node_df_iterator &o) :current(o.current), mem_begin(o.mem_begin), mem_end(o.mem_end) {} bool bst_node_df_iterator::operator == (const bst_node_df_iterator &o) const { return current == o.current && (current != 0 || ((mem_begin == 0 && mem_end == 0) || (o.mem_begin == 0 && o.mem_end == 0) || (mem_begin == o.mem_begin && mem_end == o.mem_end))); } bool bst_node_df_iterator::operator != (const bst_node_df_iterator &o) const { return !(*this == o); } void bst_node_df_iterator::advance() { if(current) { if(current->RChild) current = current->RChild->LeftmostChild; else { // Ascend current's parents to find the next greater element bst_node *cur(current); do { if(cur->SideOfParent() == bst_node::LeftSide) { current = cur->Parent; break; } }while((cur = cur->Parent)); if(!cur) { // We've hit the end of the BST mem_end = current; current = 0; } } } else if(mem_begin) { current = mem_begin; mem_begin = 0; } else THROW_NEW_GUTIL_EXCEPTION2(GUtil::Core::Exception, "Can't move iterator past the end of the container."); } void bst_node_df_iterator::retreat() { if(current) { if(current->LChild) current = current->LChild->RightmostChild; else { // Ascend current's parents to find the next lesser element bst_node *cur(current); do { if(cur->SideOfParent() == bst_node::RightSide) { current = cur->Parent; break; } }while((cur = cur->Parent)); if(!cur) { // We've hit the beginning of the BST mem_begin = current; current = 0; } } } else if(mem_end) { current = mem_end; mem_end = 0; } else THROW_NEW_GUTIL_EXCEPTION2(GUtil::Core::Exception, "Can't move iterator before the beginning of the container."); } <commit_msg>Fixed the last major deletion bug, now all test cases pass.<commit_after>/*Copyright 2011 George Karagoulis 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 "bst_node.h" #include "gutil_globals.h" #include "Core/exception.h" GUTIL_USING_CORE_NAMESPACE(DataObjects); bst_node::bst_node() :Parent(0), LChild(0), RChild(0), LeftmostChild(this), RightmostChild(this), Height(0), Data(0) { } bst_node::~bst_node() { if(LChild) delete LChild; if(RChild) delete RChild; } int bst_node::HeightDifference() const { int sum(0); if(LChild) sum += (1 + LChild->Height); if(RChild) sum -= (1 + RChild->Height); return sum; } bool bst_node::Balanced() const { return gAbs(HeightDifference()) <= 1; } void bst_node::rebalance(bst_node *n) { int height_difference = n->HeightDifference(); if(height_difference > 1) { // The node is left-heavy // Check if it's LR imbalance so we can resolve that first. if(n->LChild->HeightDifference() < 0) rotate_left(n->LChild); // Now that the LR imbalance is fixed, do the LL rebalance. rotate_right(n); } else if(height_difference < -1) { // The node is right-heavy // Check if it's RL imbalance so we can resolve that first. if(n->RChild->HeightDifference() > 0) rotate_right(n->RChild); // Now that the RL imbalance is fixed, do the RR rebalance. rotate_left(n); } } void bst_node::rotate_right(bst_node *n) { bst_node *parent(n->Parent); if(parent) { if(parent->LChild == n) parent->LChild = n->LChild; else parent->RChild = n->LChild; } n->LChild->Parent = parent; bst_node *tmp(n->LChild->RChild); n->Parent = n->LChild; n->LChild->RChild = n; n->LChild = tmp; if(tmp) tmp->Parent = n; // Have to refresh the node we just rotated, the other one will be refreshed // automatically when we walk up the tree refresh_node_state(n); } void bst_node::rotate_left(bst_node *n) { bst_node *parent(n->Parent); if(parent) { if(parent->LChild == n) parent->LChild = n->RChild; else parent->RChild = n->RChild; } n->RChild->Parent = parent; bst_node *tmp(n->RChild->LChild); n->Parent = n->RChild; n->RChild->LChild = n; n->RChild = tmp; if(tmp) tmp->Parent = n; // Have to refresh the node we just rotated, the other one will be refreshed // automatically when we walk up the tree refresh_node_state(n); } void bst_node::Insert(bst_node *parent, bst_node *new_node, bst_node::SideEnum side) { bst_node **node_ref(0); switch(side) { case LeftSide: node_ref = &parent->LChild; break; case RightSide: node_ref = &parent->RChild; break; default: return; } *node_ref = new_node; new_node->Parent = parent; // Now we need to ascend the tree to the root and update the heights walk_parents_update_heights_rebalance(parent); } void bst_node::Delete(bst_node *node, bst_node *replacement) { // This variable determines where to start adjusting the node height after deletion. bst_node *start_height_adjustment(0); if(replacement) { // If the replacement has a child (at most 1) then we move it into the replacement's place bst_node *replacement_child(0); if(replacement->RChild) replacement_child = replacement->RChild; else if(replacement->LChild) replacement_child = replacement->LChild; if(node == replacement->Parent) start_height_adjustment = replacement; else { start_height_adjustment = replacement->Parent; switch(replacement->SideOfParent()) { case RightSide: replacement->Parent->RChild = replacement_child; break; case LeftSide: replacement->Parent->LChild = replacement_child; break; default: break; } if(replacement_child) replacement_child->Parent = replacement->Parent; } replacement->Parent = node->Parent; if(replacement != node->RChild) replacement->RChild = node->RChild; if(replacement != node->LChild) replacement->LChild = node->LChild; } else { start_height_adjustment = node->Parent; } if(node->RChild && node->RChild != replacement) node->RChild->Parent = replacement; if(node->LChild && node->LChild != replacement) node->LChild->Parent = replacement; if(node->Parent) { switch(node->SideOfParent()) { case RightSide: node->Parent->RChild = replacement; break; case LeftSide: node->Parent->LChild = replacement; break; default: break; } } // Delete the node (set children to 0 so to not delete them) node->LChild = 0; node->RChild = 0; delete node; // Walk up the tree and update the height variables. walk_parents_update_heights_rebalance(start_height_adjustment); } bst_node::SideEnum bst_node::SideOfParent() const { SideEnum ret(NoSide); if(Parent) { if(Parent->LChild == this) ret = LeftSide; else if(Parent->RChild == this) ret = RightSide; } return ret; } void bst_node::refresh_node_state(bst_node *n) { // Update the node's height cache if(!n->LChild && !n->RChild) n->Height = 0; else { const int lheight(n->LChild ? n->LChild->Height : 0); const int rheight(n->RChild ? n->RChild->Height : 0); n->Height = gMax(lheight, rheight) + 1; } // Update the left-most and right-most child caches n->LeftmostChild = n->LChild ? n->LChild->LeftmostChild : n; n->RightmostChild = n->RChild ? n->RChild->RightmostChild : n; } void bst_node::walk_parents_update_heights_rebalance(bst_node *n) { if(n) { refresh_node_state(n); // Rebalance the node if it's unbalanced if(!n->Balanced()) rebalance(n); walk_parents_update_heights_rebalance(n->Parent); } } bst_node_df_iterator::bst_node_df_iterator(bst_node *n) :current(n), mem_begin(0), mem_end(0) {} bst_node_df_iterator::bst_node_df_iterator(const bst_node_df_iterator &o) :current(o.current), mem_begin(o.mem_begin), mem_end(o.mem_end) {} bool bst_node_df_iterator::operator == (const bst_node_df_iterator &o) const { return current == o.current && (current != 0 || ((mem_begin == 0 && mem_end == 0) || (o.mem_begin == 0 && o.mem_end == 0) || (mem_begin == o.mem_begin && mem_end == o.mem_end))); } bool bst_node_df_iterator::operator != (const bst_node_df_iterator &o) const { return !(*this == o); } void bst_node_df_iterator::advance() { if(current) { if(current->RChild) current = current->RChild->LeftmostChild; else { // Ascend current's parents to find the next greater element bst_node *cur(current); do { if(cur->SideOfParent() == bst_node::LeftSide) { current = cur->Parent; break; } }while((cur = cur->Parent)); if(!cur) { // We've hit the end of the BST mem_end = current; current = 0; } } } else if(mem_begin) { current = mem_begin; mem_begin = 0; } else THROW_NEW_GUTIL_EXCEPTION2(GUtil::Core::Exception, "Can't move iterator past the end of the container."); } void bst_node_df_iterator::retreat() { if(current) { if(current->LChild) current = current->LChild->RightmostChild; else { // Ascend current's parents to find the next lesser element bst_node *cur(current); do { if(cur->SideOfParent() == bst_node::RightSide) { current = cur->Parent; break; } }while((cur = cur->Parent)); if(!cur) { // We've hit the beginning of the BST mem_begin = current; current = 0; } } } else if(mem_end) { current = mem_end; mem_end = 0; } else THROW_NEW_GUTIL_EXCEPTION2(GUtil::Core::Exception, "Can't move iterator before the beginning of the container."); } <|endoftext|>
<commit_before>#include "mitkOpenGLRenderer.h" #include "Mapper.h" #include "mitkImageMapper2D.h" #include "BaseVtkMapper2D.h" #include "BaseVtkMapper3D.h" #include "LevelWindow.h" #include "mitkVtkInteractorCameraController.h" #include "mitkVtkRenderWindow.h" #include "mitkRenderWindow.h" #include <vtkRenderer.h> #include <vtkLight.h> #include <vtkLightKit.h> #include <vtkRenderWindow.h> #include <vtkTransform.h> #include "PlaneGeometry.h" #include "mitkProperties.h" #include <queue> #include <utility> //##ModelId=3E33ECF301AD mitk::OpenGLRenderer::OpenGLRenderer() : m_VtkMapperPresent(false) { m_CameraController=NULL; m_CameraController = VtkInteractorCameraController::New(); m_CameraController->AddRenderer(this); } //##ModelId=3E3D28AB0018 void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator) { if(iterator!=GetData()) { BaseRenderer::SetData(iterator); if (iterator != NULL) { //initialize world geometry: use first slice of first node containing an image mitk::DataTreeIterator* it=m_DataTreeIterator->clone(); while(it->hasNext()) { it->next(); BaseData::Pointer data=it->get()->GetData(); if(data.IsNotNull()) { Image::Pointer image = dynamic_cast<Image*>(data.GetPointer()); if(image.IsNotNull()) { SetWorldGeometry(image->GetGeometry2D(0, 0)); break; } } } delete it; } //update the vtk-based mappers Update(); //this is only called to check, whether we have vtk-based mappers! UpdateVtkActors(); Modified(); } } //##ModelId=3ED91D060305 void mitk::OpenGLRenderer::UpdateVtkActors() { VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer()); if (m_VtkMapperPresent == false) { if(vicc!=NULL) vicc->GetVtkInteractor()->Disable(); return; } if(vicc!=NULL) vicc->GetVtkInteractor()->Enable(); // m_LightKit->RemoveLightsFromRenderer(this->m_VtkRenderer); // m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer); // m_VtkRenderer->Delete(); if(m_VtkRenderer==NULL) { m_VtkRenderer = vtkRenderer::New(); m_VtkRenderer->SetLayer(0); m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer ); } m_VtkRenderer->RemoveAllProps(); //strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers) //m_Light->Delete(); //m_Light = vtkLight::New(); //m_VtkRenderer->AddLight( m_Light ); if(m_LightKit!=NULL) { m_LightKit = vtkLightKit::New(); m_LightKit->AddLightsToRenderer(m_VtkRenderer); } // try if (m_DataTreeIterator != NULL) { mitk::DataTreeIterator* it=m_DataTreeIterator->clone(); while(it->hasNext()) { it->next(); mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID); if(mapper.IsNotNull()) { BaseVtkMapper2D* anVtkMapper2D; anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer()); if(anVtkMapper2D != NULL) { anVtkMapper2D->Update(this); m_VtkRenderer->AddProp(anVtkMapper2D->GetProp()); } else { BaseVtkMapper3D* anVtkMapper3D; anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()); if(anVtkMapper3D != NULL) { anVtkMapper3D->Update(this); m_VtkRenderer->AddProp(anVtkMapper3D->GetProp()); } } } } delete it; } // catch( ::itk::ExceptionObject ee) // { // printf("%s\n",ee.what()); //// itkGenericOutputMacro(ee->what()); // } // catch( ...) // { // printf("test\n"); // } } //##ModelId=3E330D260255 void mitk::OpenGLRenderer::Update() { if(m_DataTreeIterator == NULL) return; m_VtkMapperPresent=false; mitk::DataTreeIterator* it=m_DataTreeIterator->clone(); while(it->hasNext()) { it->next(); // mitk::LevelWindow lw; unsigned int dummy[] = {10,10,10}; //Geometry3D geometry(3,dummy); mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID); if(mapper.IsNotNull()) { Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer()); if(mapper2d != NULL) { BaseVtkMapper2D* vtkmapper2d=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer()); if(vtkmapper2d != NULL) { vtkmapper2d->Update(this); m_VtkMapperPresent=true; } else mapper2d->Update(); ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer()); } else { BaseVtkMapper3D* vtkmapper3d=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()); if(vtkmapper3d != NULL) { vtkmapper3d->Update(this); m_VtkMapperPresent=true; } } } } delete it; Modified(); m_LastUpdateTime=GetMTime(); } //##ModelId=3E330D2903CC void mitk::OpenGLRenderer::Render() { //if we do not have any data, we do nothing else but clearing our window if(GetData() == NULL) { glClear(GL_COLOR_BUFFER_BIT); return; } //has someone transformed our worldgeometry-node? if so, incorporate this transform into //the worldgeometry itself and reset the transform of the node to identity /* if(m_WorldGeometryTransformTime<m_WorldGeometryNode->GetVtkTransform()->GetMTime()) { vtkTransform *i; m_WorldGeometry->TransformGeometry(m_WorldGeometryNode->GetVtkTransform()); m_WorldGeometryNode->GetVtkTransform()->Identity(); m_WorldGeometryTransformTime=GetWorldGeometryNode()->GetVtkTransform()->GetMTime(); } */ //has the data tree been changed? if(dynamic_cast<mitk::DataTree*>(GetData()->getTree()) == NULL ) return; // if(m_LastUpdateTime<((mitk::DataTree*)GetData()->getTree())->GetMTime()) if(m_LastUpdateTime < dynamic_cast<mitk::DataTree*>(GetData()->getTree())->GetMTime() ) { //yes: update vtk-actors Update(); UpdateVtkActors(); } else //has anything else changed (geometry to display, etc.)? if (m_LastUpdateTime<GetMTime() || m_LastUpdateTime<GetDisplayGeometry()->GetMTime() || m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime()) { //std::cout << "OpenGLRenderer calling its update..." << std::endl; Update(); } else if(m_MapperID==2) { //@todo in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!! Update(); } glClear(GL_COLOR_BUFFER_BIT); PlaneGeometry* myPlaneGeom = dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry())); glViewport (0, 0, m_Size[0], m_Size[1]); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] ); glMatrixMode( GL_MODELVIEW ); mitk::DataTreeIterator* it=m_DataTreeIterator->clone(); mitk::DataTree::Pointer tree = dynamic_cast <mitk::DataTree *> (it->getTree()); // std::cout << "Render:: tree: " << *tree << std::endl; typedef std::pair<int, GLMapper2D*> LayerMapperPair; std::priority_queue<LayerMapperPair> layers; while(it->hasNext()) { it->next(); mitk::DataTreeNode::Pointer node = it->get(); mitk::Mapper::Pointer mapper = node->GetMapper(m_MapperID); if(mapper.IsNotNull()) { GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer()); if(mapper2d!=NULL) { int layer; IntegerProperty::Pointer layerprop = dynamic_cast<IntegerProperty*>(node->GetProperty("layer",this).GetPointer()); if (layerprop.IsNotNull()) { layer = layerprop->GetValue(); } else { // mapper without a layer property are painted first layer = -1; } // pushing negative layer value, since default sort for // priority_queue is lessthan layers.push(LayerMapperPair(-layer,mapper2d)); } } } delete it; while (!layers.empty()) { layers.top().second->Paint(this); layers.pop(); } if(m_VtkMapperPresent) { m_MitkVtkRenderWindow->MitkRender(); } } /*! \brief Initialize the OpenGLRenderer This method is called from the two Constructors */ void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow) { BaseRenderer::InitRenderer(renderwindow); m_InitNeeded = true; m_ResizeNeeded = true; m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New(); m_MitkVtkRenderWindow->SetMitkRenderer(this); /**@todo SetNumberOfLayers commented out, because otherwise the backface of the planes are not shown (only, when a light is added). * But we need SetNumberOfLayers(2) later, when we want to prevent vtk to clear the widget before it renders (i.e., when we render something in the scene before vtk). */ //m_MitkVtkRenderWindow->SetNumberOfLayers(2); m_VtkRenderer = vtkRenderer::New(); m_MitkVtkRenderWindow->AddRenderer( m_VtkRenderer ); //strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers) //m_Light = vtkLight::New(); //m_VtkRenderer->AddLight( m_Light ); m_LightKit = vtkLightKit::New(); m_LightKit->AddLightsToRenderer(m_VtkRenderer); if(m_CameraController) ((VtkInteractorCameraController*)m_CameraController.GetPointer())->SetRenderWindow(m_MitkVtkRenderWindow); //we should disable vtk doublebuffering, but then it doesn't work //m_MitkVtkRenderWindow->SwapBuffersOff(); } /*! \brief Destructs the OpenGLRenderer. */ //##ModelId=3E33ECF301B7 mitk::OpenGLRenderer::~OpenGLRenderer() { m_VtkRenderer->Delete(); m_MitkVtkRenderWindow->Delete(); } /*! \brief Initialize the OpenGL Window */ //##ModelId=3E33145B0096 void mitk::OpenGLRenderer::Initialize( ) { glClearColor(0.0, 0.0, 0.0, 1.0); glColor3f(1.0, 0.0, 0.0); } /*! \brief Resize the OpenGL Window */ //##ModelId=3E33145B00D2 void mitk::OpenGLRenderer::Resize(int w, int h) { BaseRenderer::Resize(w, h); glViewport (0, 0, w, h); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluOrtho2D( 0.0, w, 0.0, h ); glMatrixMode( GL_MODELVIEW ); GetDisplayGeometry()->SetSizeInDisplayUnits(w, h); GetDisplayGeometry()->Fit(); Update(); // m_MitkVtkRenderWindow->SetSize(w,h); //FIXME? } /*! \brief Render the scene */ //##ModelId=3E33145B005A void mitk::OpenGLRenderer::Paint( ) { Render(); glFlush(); } //##ModelId=3E3314B0005C void mitk::OpenGLRenderer::SetWindowId(void * id) { m_MitkVtkRenderWindow->SetWindowId( id ); } //##ModelId=3E3799420227 void mitk::OpenGLRenderer::InitSize(int w, int h) { m_MitkVtkRenderWindow->SetSize(w,h); GetDisplayGeometry()->Fit(); Modified(); Update(); } //##ModelId=3EF59AD20235 void mitk::OpenGLRenderer::SetMapperID(const MapperSlotId mapperId) { Superclass::SetMapperID(mapperId); Update(); UpdateVtkActors(); } //##ModelId=3EF162760271 void mitk::OpenGLRenderer::MakeCurrent() { if(m_RenderWindow!=NULL) { m_RenderWindow->MakeCurrent(); } } <commit_msg>now using order of Mappers in the tree as second criteria for rendering order<commit_after>#include "mitkOpenGLRenderer.h" #include "Mapper.h" #include "mitkImageMapper2D.h" #include "BaseVtkMapper2D.h" #include "BaseVtkMapper3D.h" #include "LevelWindow.h" #include "mitkVtkInteractorCameraController.h" #include "mitkVtkRenderWindow.h" #include "mitkRenderWindow.h" #include <vtkRenderer.h> #include <vtkLight.h> #include <vtkLightKit.h> #include <vtkRenderWindow.h> #include <vtkTransform.h> #include "PlaneGeometry.h" #include "mitkProperties.h" #include <queue> #include <utility> //##ModelId=3E33ECF301AD mitk::OpenGLRenderer::OpenGLRenderer() : m_VtkMapperPresent(false) { m_CameraController=NULL; m_CameraController = VtkInteractorCameraController::New(); m_CameraController->AddRenderer(this); } //##ModelId=3E3D28AB0018 void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator) { if(iterator!=GetData()) { BaseRenderer::SetData(iterator); if (iterator != NULL) { //initialize world geometry: use first slice of first node containing an image mitk::DataTreeIterator* it=m_DataTreeIterator->clone(); while(it->hasNext()) { it->next(); BaseData::Pointer data=it->get()->GetData(); if(data.IsNotNull()) { Image::Pointer image = dynamic_cast<Image*>(data.GetPointer()); if(image.IsNotNull()) { SetWorldGeometry(image->GetGeometry2D(0, 0)); break; } } } delete it; } //update the vtk-based mappers Update(); //this is only called to check, whether we have vtk-based mappers! UpdateVtkActors(); Modified(); } } //##ModelId=3ED91D060305 void mitk::OpenGLRenderer::UpdateVtkActors() { VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer()); if (m_VtkMapperPresent == false) { if(vicc!=NULL) vicc->GetVtkInteractor()->Disable(); return; } if(vicc!=NULL) vicc->GetVtkInteractor()->Enable(); // m_LightKit->RemoveLightsFromRenderer(this->m_VtkRenderer); // m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer); // m_VtkRenderer->Delete(); if(m_VtkRenderer==NULL) { m_VtkRenderer = vtkRenderer::New(); m_VtkRenderer->SetLayer(0); m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer ); } m_VtkRenderer->RemoveAllProps(); //strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers) //m_Light->Delete(); //m_Light = vtkLight::New(); //m_VtkRenderer->AddLight( m_Light ); if(m_LightKit!=NULL) { m_LightKit = vtkLightKit::New(); m_LightKit->AddLightsToRenderer(m_VtkRenderer); } // try if (m_DataTreeIterator != NULL) { mitk::DataTreeIterator* it=m_DataTreeIterator->clone(); while(it->hasNext()) { it->next(); mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID); if(mapper.IsNotNull()) { BaseVtkMapper2D* anVtkMapper2D; anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer()); if(anVtkMapper2D != NULL) { anVtkMapper2D->Update(this); m_VtkRenderer->AddProp(anVtkMapper2D->GetProp()); } else { BaseVtkMapper3D* anVtkMapper3D; anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()); if(anVtkMapper3D != NULL) { anVtkMapper3D->Update(this); m_VtkRenderer->AddProp(anVtkMapper3D->GetProp()); } } } } delete it; } // catch( ::itk::ExceptionObject ee) // { // printf("%s\n",ee.what()); //// itkGenericOutputMacro(ee->what()); // } // catch( ...) // { // printf("test\n"); // } } //##ModelId=3E330D260255 void mitk::OpenGLRenderer::Update() { if(m_DataTreeIterator == NULL) return; m_VtkMapperPresent=false; mitk::DataTreeIterator* it=m_DataTreeIterator->clone(); while(it->hasNext()) { it->next(); // mitk::LevelWindow lw; unsigned int dummy[] = {10,10,10}; //Geometry3D geometry(3,dummy); mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID); if(mapper.IsNotNull()) { Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer()); if(mapper2d != NULL) { BaseVtkMapper2D* vtkmapper2d=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer()); if(vtkmapper2d != NULL) { vtkmapper2d->Update(this); m_VtkMapperPresent=true; } else mapper2d->Update(); ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer()); } else { BaseVtkMapper3D* vtkmapper3d=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer()); if(vtkmapper3d != NULL) { vtkmapper3d->Update(this); m_VtkMapperPresent=true; } } } } delete it; Modified(); m_LastUpdateTime=GetMTime(); } //##ModelId=3E330D2903CC void mitk::OpenGLRenderer::Render() { //if we do not have any data, we do nothing else but clearing our window if(GetData() == NULL) { glClear(GL_COLOR_BUFFER_BIT); return; } //has someone transformed our worldgeometry-node? if so, incorporate this transform into //the worldgeometry itself and reset the transform of the node to identity /* if(m_WorldGeometryTransformTime<m_WorldGeometryNode->GetVtkTransform()->GetMTime()) { vtkTransform *i; m_WorldGeometry->TransformGeometry(m_WorldGeometryNode->GetVtkTransform()); m_WorldGeometryNode->GetVtkTransform()->Identity(); m_WorldGeometryTransformTime=GetWorldGeometryNode()->GetVtkTransform()->GetMTime(); } */ //has the data tree been changed? if(dynamic_cast<mitk::DataTree*>(GetData()->getTree()) == NULL ) return; // if(m_LastUpdateTime<((mitk::DataTree*)GetData()->getTree())->GetMTime()) if(m_LastUpdateTime < dynamic_cast<mitk::DataTree*>(GetData()->getTree())->GetMTime() ) { //yes: update vtk-actors Update(); UpdateVtkActors(); } else //has anything else changed (geometry to display, etc.)? if (m_LastUpdateTime<GetMTime() || m_LastUpdateTime<GetDisplayGeometry()->GetMTime() || m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime()) { //std::cout << "OpenGLRenderer calling its update..." << std::endl; Update(); } else if(m_MapperID==2) { //@todo in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!! Update(); } glClear(GL_COLOR_BUFFER_BIT); PlaneGeometry* myPlaneGeom = dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry())); glViewport (0, 0, m_Size[0], m_Size[1]); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] ); glMatrixMode( GL_MODELVIEW ); mitk::DataTreeIterator* it=m_DataTreeIterator->clone(); mitk::DataTree::Pointer tree = dynamic_cast <mitk::DataTree *> (it->getTree()); // std::cout << "Render:: tree: " << *tree << std::endl; typedef std::pair<int, GLMapper2D*> LayerMapperPair; std::priority_queue<LayerMapperPair> layers; int mapperNo = 0; while(it->hasNext()) { it->next(); mitk::DataTreeNode::Pointer node = it->get(); mitk::Mapper::Pointer mapper = node->GetMapper(m_MapperID); if(mapper.IsNotNull()) { GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer()); if(mapper2d!=NULL) { int layer; IntegerProperty::Pointer layerprop = dynamic_cast<IntegerProperty*>(node->GetProperty("layer",this).GetPointer()); if (layerprop.IsNotNull()) { layer = layerprop->GetValue(); } else { // mapper without a layer property are painted first layer = -1; } // pushing negative layer value, since default sort for // priority_queue is lessthan layers.push(LayerMapperPair(- (layer<<16) - mapperNo ,mapper2d)); mapperNo++; } } } delete it; while (!layers.empty()) { layers.top().second->Paint(this); layers.pop(); } if(m_VtkMapperPresent) { m_MitkVtkRenderWindow->MitkRender(); } } /*! \brief Initialize the OpenGLRenderer This method is called from the two Constructors */ void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow) { BaseRenderer::InitRenderer(renderwindow); m_InitNeeded = true; m_ResizeNeeded = true; m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New(); m_MitkVtkRenderWindow->SetMitkRenderer(this); /**@todo SetNumberOfLayers commented out, because otherwise the backface of the planes are not shown (only, when a light is added). * But we need SetNumberOfLayers(2) later, when we want to prevent vtk to clear the widget before it renders (i.e., when we render something in the scene before vtk). */ //m_MitkVtkRenderWindow->SetNumberOfLayers(2); m_VtkRenderer = vtkRenderer::New(); m_MitkVtkRenderWindow->AddRenderer( m_VtkRenderer ); //strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers) //m_Light = vtkLight::New(); //m_VtkRenderer->AddLight( m_Light ); m_LightKit = vtkLightKit::New(); m_LightKit->AddLightsToRenderer(m_VtkRenderer); if(m_CameraController) ((VtkInteractorCameraController*)m_CameraController.GetPointer())->SetRenderWindow(m_MitkVtkRenderWindow); //we should disable vtk doublebuffering, but then it doesn't work //m_MitkVtkRenderWindow->SwapBuffersOff(); } /*! \brief Destructs the OpenGLRenderer. */ //##ModelId=3E33ECF301B7 mitk::OpenGLRenderer::~OpenGLRenderer() { m_VtkRenderer->Delete(); m_MitkVtkRenderWindow->Delete(); } /*! \brief Initialize the OpenGL Window */ //##ModelId=3E33145B0096 void mitk::OpenGLRenderer::Initialize( ) { glClearColor(0.0, 0.0, 0.0, 1.0); glColor3f(1.0, 0.0, 0.0); } /*! \brief Resize the OpenGL Window */ //##ModelId=3E33145B00D2 void mitk::OpenGLRenderer::Resize(int w, int h) { BaseRenderer::Resize(w, h); glViewport (0, 0, w, h); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluOrtho2D( 0.0, w, 0.0, h ); glMatrixMode( GL_MODELVIEW ); GetDisplayGeometry()->SetSizeInDisplayUnits(w, h); GetDisplayGeometry()->Fit(); Update(); // m_MitkVtkRenderWindow->SetSize(w,h); //FIXME? } /*! \brief Render the scene */ //##ModelId=3E33145B005A void mitk::OpenGLRenderer::Paint( ) { Render(); glFlush(); } //##ModelId=3E3314B0005C void mitk::OpenGLRenderer::SetWindowId(void * id) { m_MitkVtkRenderWindow->SetWindowId( id ); } //##ModelId=3E3799420227 void mitk::OpenGLRenderer::InitSize(int w, int h) { m_MitkVtkRenderWindow->SetSize(w,h); GetDisplayGeometry()->Fit(); Modified(); Update(); } //##ModelId=3EF59AD20235 void mitk::OpenGLRenderer::SetMapperID(const MapperSlotId mapperId) { Superclass::SetMapperID(mapperId); Update(); UpdateVtkActors(); } //##ModelId=3EF162760271 void mitk::OpenGLRenderer::MakeCurrent() { if(m_RenderWindow!=NULL) { m_RenderWindow->MakeCurrent(); } } <|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 "itkImageRegistrationMethodv4.h" #include "itkTranslationTransform.h" #include "itkMeanSquaresImageToImageMetricv4.h" #include "itkRegularStepGradientDescentOptimizerv4.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkSubtractImageFilter.h" int main( int argc, char *argv[] ) { if( argc != 6 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile [differenceImageAfter]"; std::cerr << "[differenceImageBefore]" << std::endl; return EXIT_FAILURE; } const char * fixedImageFile = argv[1]; const char * movingImageFile = argv[2]; const char * outputImageFile = argv[3]; const char * differenceImageAfterFile = argv[4]; const char * differenceImageBeforeFile = argv[5]; constexpr unsigned int Dimension = 2; using PixelType = float; using FixedImageType = itk::Image< PixelType, Dimension >; using MovingImageType = itk::Image< PixelType, Dimension >; using TransformType = itk::TranslationTransform< double, Dimension >; using OptimizerType = itk::RegularStepGradientDescentOptimizerv4<double>; using MetricType = itk::MeanSquaresImageToImageMetricv4< FixedImageType, MovingImageType >; using RegistrationType = itk::ImageRegistrationMethodv4< FixedImageType, MovingImageType >; MetricType::Pointer metric = MetricType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); RegistrationType::Pointer registration = RegistrationType::New(); TransformType::Pointer initialTransform = TransformType::New(); registration->SetInitialTransform( initialTransform ); registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); using FixedLinearInterpolatorType = itk::LinearInterpolateImageFunction< FixedImageType, double >; using MovingLinearInterpolatorType = itk::LinearInterpolateImageFunction< MovingImageType, double >; FixedLinearInterpolatorType::Pointer fixedInterpolator = FixedLinearInterpolatorType::New(); MovingLinearInterpolatorType::Pointer movingInterpolator = MovingLinearInterpolatorType::New(); metric->SetFixedInterpolator( fixedInterpolator ); metric->SetMovingInterpolator( movingInterpolator ); using FixedImageReaderType = itk::ImageFileReader< FixedImageType >; using MovingImageReaderType = itk::ImageFileReader< MovingImageType >; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( fixedImageFile ); movingImageReader->SetFileName( movingImageFile ); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); TransformType::Pointer movingInitialTransform = TransformType::New(); TransformType::ParametersType initialParameters( movingInitialTransform->GetNumberOfParameters() ); initialParameters[0] = 0.0; initialParameters[1] = 0.0; movingInitialTransform->SetParameters( initialParameters ); registration->SetMovingInitialTransform( movingInitialTransform ); TransformType::Pointer identityTransform = TransformType::New(); identityTransform->SetIdentity(); registration->SetFixedInitialTransform( identityTransform ); optimizer->SetLearningRate( 4 ); optimizer->SetMinimumStepLength( 0.001 ); optimizer->SetRelaxationFactor( 0.5 ); optimizer->SetNumberOfIterations( 200 ); constexpr unsigned int numberOfLevels = 1; RegistrationType::ShrinkFactorsArrayType shrinkFactorsPerLevel; shrinkFactorsPerLevel.SetSize( 1 ); shrinkFactorsPerLevel[0] = 1; RegistrationType::SmoothingSigmasArrayType smoothingSigmasPerLevel; smoothingSigmasPerLevel.SetSize( 1 ); smoothingSigmasPerLevel[0] = 0; registration->SetNumberOfLevels ( numberOfLevels ); registration->SetSmoothingSigmasPerLevel( smoothingSigmasPerLevel ); registration->SetShrinkFactorsPerLevel( shrinkFactorsPerLevel ); try { registration->Update(); std::cout << "Optimizer stop condition: " << registration->GetOptimizer()->GetStopConditionDescription() << std::endl; } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } TransformType::ConstPointer transform = dynamic_cast< const TransformType *> ( registration->GetTransform() ); TransformType::ParametersType finalParameters = transform->GetParameters(); const double TranslationAlongX = finalParameters[0]; const double TranslationAlongY = finalParameters[1]; const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); const 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; using CompositeTransformType = itk::CompositeTransform< double, Dimension >; CompositeTransformType::Pointer outputCompositeTransform = CompositeTransformType::New(); outputCompositeTransform->AddTransform( movingInitialTransform ); outputCompositeTransform->AddTransform( registration->GetModifiableTransform() ); using ResampleFilterType = itk::ResampleImageFilter< MovingImageType, FixedImageType >; ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetInput( movingImageReader->GetOutput() ); resampler->SetTransform( outputCompositeTransform ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resampler->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resampler->SetOutputOrigin( fixedImage->GetOrigin() ); resampler->SetOutputSpacing( fixedImage->GetSpacing() ); resampler->SetOutputDirection( fixedImage->GetDirection() ); resampler->SetDefaultPixelValue( 100 ); using OutputPixelType = unsigned char; using OutputImageType = itk::Image< OutputPixelType, Dimension >; using CastFilterType = itk::CastImageFilter< FixedImageType, OutputImageType >; using WriterType = itk::ImageFileWriter< OutputImageType >; WriterType::Pointer writer = WriterType::New(); CastFilterType::Pointer caster = CastFilterType::New(); writer->SetFileName( outputImageFile ); caster->SetInput( resampler->GetOutput() ); writer->SetInput( caster->GetOutput() ); writer->Update(); using DifferenceFilterType = itk::SubtractImageFilter< FixedImageType, FixedImageType, FixedImageType >; DifferenceFilterType::Pointer difference = DifferenceFilterType::New(); difference->SetInput1( fixedImageReader->GetOutput() ); difference->SetInput2( resampler->GetOutput() ); using RescalerType = itk::RescaleIntensityImageFilter< FixedImageType, OutputImageType >; RescalerType::Pointer intensityRescaler = RescalerType::New(); intensityRescaler->SetInput( difference->GetOutput() ); intensityRescaler->SetOutputMinimum( itk::NumericTraits< OutputPixelType >::min() ); intensityRescaler->SetOutputMaximum( itk::NumericTraits< OutputPixelType >::max() ); resampler->SetDefaultPixelValue( 1 ); WriterType::Pointer writer2 = WriterType::New(); writer2->SetInput( intensityRescaler->GetOutput() ); writer2->SetFileName( differenceImageAfterFile ); writer2->Update(); resampler->SetTransform( identityTransform ); writer2->SetFileName( differenceImageBeforeFile ); writer2->Update(); return EXIT_SUCCESS; } <commit_msg>STYLE: Improve Perform2DTranslationRegistrationWithMeanSquares/Code.cxx<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 "itkImageRegistrationMethodv4.h" #include "itkTranslationTransform.h" #include "itkMeanSquaresImageToImageMetricv4.h" #include "itkRegularStepGradientDescentOptimizerv4.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkSubtractImageFilter.h" int main( int argc, char *argv[] ) { if( argc != 6 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile [differenceImageAfter]"; std::cerr << "[differenceImageBefore]" << std::endl; return EXIT_FAILURE; } const char * fixedImageFile = argv[1]; const char * movingImageFile = argv[2]; const char * outputImageFile = argv[3]; const char * differenceImageAfterFile = argv[4]; const char * differenceImageBeforeFile = argv[5]; constexpr unsigned int Dimension = 2; using PixelType = float; using FixedImageType = itk::Image< PixelType, Dimension >; using MovingImageType = itk::Image< PixelType, Dimension >; using FixedImageReaderType = itk::ImageFileReader< FixedImageType >; auto fixedImageReader = FixedImageReaderType::New(); fixedImageReader->SetFileName( fixedImageFile ); using MovingImageReaderType = itk::ImageFileReader< MovingImageType >; auto movingImageReader = MovingImageReaderType::New(); movingImageReader->SetFileName( movingImageFile ); using TransformType = itk::TranslationTransform< double, Dimension >; auto initialTransform = TransformType::New(); using OptimizerType = itk::RegularStepGradientDescentOptimizerv4<double>; auto optimizer = OptimizerType::New(); optimizer->SetLearningRate( 4 ); optimizer->SetMinimumStepLength( 0.001 ); optimizer->SetRelaxationFactor( 0.5 ); optimizer->SetNumberOfIterations( 200 ); using MetricType = itk::MeanSquaresImageToImageMetricv4< FixedImageType, MovingImageType >; auto metric = MetricType::New(); using RegistrationType = itk::ImageRegistrationMethodv4< FixedImageType, MovingImageType >; auto registration = RegistrationType::New(); registration->SetInitialTransform( initialTransform ); registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); auto movingInitialTransform = TransformType::New(); TransformType::ParametersType initialParameters( movingInitialTransform->GetNumberOfParameters() ); initialParameters[0] = 0.0; initialParameters[1] = 0.0; movingInitialTransform->SetParameters( initialParameters ); registration->SetMovingInitialTransform( movingInitialTransform ); auto identityTransform = TransformType::New(); identityTransform->SetIdentity(); registration->SetFixedInitialTransform( identityTransform ); constexpr unsigned int numberOfLevels = 1; registration->SetNumberOfLevels( numberOfLevels ); RegistrationType::ShrinkFactorsArrayType shrinkFactorsPerLevel; shrinkFactorsPerLevel.SetSize( 1 ); shrinkFactorsPerLevel[0] = 1; registration->SetShrinkFactorsPerLevel( shrinkFactorsPerLevel ); RegistrationType::SmoothingSigmasArrayType smoothingSigmasPerLevel; smoothingSigmasPerLevel.SetSize( 1 ); smoothingSigmasPerLevel[0] = 0; registration->SetSmoothingSigmasPerLevel( smoothingSigmasPerLevel ); try { registration->Update(); std::cout << "Optimizer stop condition: " << registration->GetOptimizer()->GetStopConditionDescription() << std::endl; } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } auto transform = registration->GetTransform(); auto finalParameters = transform->GetParameters(); auto translationAlongX = finalParameters[0]; auto translationAlongY = finalParameters[1]; auto numberOfIterations = optimizer->GetCurrentIteration(); auto 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; using CompositeTransformType = itk::CompositeTransform< double, Dimension >; auto outputCompositeTransform = CompositeTransformType::New(); outputCompositeTransform->AddTransform( movingInitialTransform ); outputCompositeTransform->AddTransform( registration->GetModifiableTransform() ); using ResampleFilterType = itk::ResampleImageFilter< MovingImageType, FixedImageType >; auto resampler = ResampleFilterType::New(); resampler->SetInput( movingImageReader->GetOutput() ); resampler->SetTransform( outputCompositeTransform ); auto fixedImage = fixedImageReader->GetOutput(); resampler->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resampler->SetOutputOrigin( fixedImage->GetOrigin() ); resampler->SetOutputSpacing( fixedImage->GetSpacing() ); resampler->SetOutputDirection( fixedImage->GetDirection() ); resampler->SetDefaultPixelValue( 100 ); using OutputPixelType = unsigned char; using OutputImageType = itk::Image< OutputPixelType, Dimension >; using CastFilterType = itk::CastImageFilter< FixedImageType, OutputImageType >; auto caster = CastFilterType::New(); caster->SetInput( resampler->GetOutput() ); using WriterType = itk::ImageFileWriter< OutputImageType >; auto writer = WriterType::New(); writer->SetFileName( outputImageFile ); writer->SetInput( caster->GetOutput() ); writer->Update(); using DifferenceFilterType = itk::SubtractImageFilter< FixedImageType, FixedImageType, FixedImageType >; auto difference = DifferenceFilterType::New(); difference->SetInput1( fixedImageReader->GetOutput() ); difference->SetInput2( resampler->GetOutput() ); using RescalerType = itk::RescaleIntensityImageFilter< FixedImageType, OutputImageType >; auto intensityRescaler = RescalerType::New(); intensityRescaler->SetInput( difference->GetOutput() ); intensityRescaler->SetOutputMinimum( itk::NumericTraits< OutputPixelType >::min() ); intensityRescaler->SetOutputMaximum( itk::NumericTraits< OutputPixelType >::max() ); resampler->SetDefaultPixelValue( 1 ); writer->SetInput( intensityRescaler->GetOutput() ); writer->SetFileName( differenceImageAfterFile ); writer->Update(); resampler->SetTransform( identityTransform ); writer->SetFileName( differenceImageBeforeFile ); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/network_state_notifier.h" #include "base/message_loop.h" #include "base/time.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" namespace chromeos { using base::Time; using base::TimeDelta; // static NetworkStateNotifier* NetworkStateNotifier::Get() { return Singleton<NetworkStateNotifier>::get(); } // static TimeDelta NetworkStateNotifier::GetOfflineDuration() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(oshima): make this instance method so that // we can mock this for ui_tests. // http://crbug.com/4825 . return base::Time::Now() - Get()->offline_start_time_; } NetworkStateNotifier::NetworkStateNotifier() : ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)), state_(RetrieveState()), offline_start_time_(Time::Now()) { } void NetworkStateNotifier::NetworkChanged(NetworkLibrary* cros) { DCHECK(CrosLibrary::Get()->EnsureLoaded()); // Update the state 2 seconds later using UI thread. // See http://crosbug.com/4558 BrowserThread::PostDelayedTask( BrowserThread::UI, FROM_HERE, task_factory_.NewRunnableMethod( &NetworkStateNotifier::UpdateNetworkState, RetrieveState()), 2000); } void NetworkStateNotifier::UpdateNetworkState( NetworkStateDetails::State new_state) { DLOG(INFO) << "UpdateNetworkState: new=" << new_state << ", old=" << state_; if (state_ == NetworkStateDetails::CONNECTED && new_state != NetworkStateDetails::CONNECTED) { offline_start_time_ = Time::Now(); } state_ = new_state; NetworkStateDetails details(state_); NotificationService::current()->Notify( NotificationType::NETWORK_STATE_CHANGED, NotificationService::AllSources(), Details<NetworkStateDetails>(&details)); }; // static NetworkStateDetails::State NetworkStateNotifier::RetrieveState() { // Running on desktop means always connected, for now. if (!CrosLibrary::Get()->EnsureLoaded()) return NetworkStateDetails::CONNECTED; NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary(); if (cros->Connected()) { return NetworkStateDetails::CONNECTED; } else if (cros->Connecting()) { return NetworkStateDetails::CONNECTING; } else { return NetworkStateDetails::DISCONNECTED; } } } // namespace chromeos <commit_msg>Remove 2s delay before start loading page when network becomes available. crosbug.com/4558 is fixed and 2s delay is no longer necessary.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/network_state_notifier.h" #include "base/message_loop.h" #include "base/time.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" namespace chromeos { using base::Time; using base::TimeDelta; // static NetworkStateNotifier* NetworkStateNotifier::Get() { return Singleton<NetworkStateNotifier>::get(); } // static TimeDelta NetworkStateNotifier::GetOfflineDuration() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(oshima): make this instance method so that // we can mock this for ui_tests. // http://crbug.com/4825 . return base::Time::Now() - Get()->offline_start_time_; } NetworkStateNotifier::NetworkStateNotifier() : ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)), state_(RetrieveState()), offline_start_time_(Time::Now()) { } void NetworkStateNotifier::NetworkChanged(NetworkLibrary* cros) { DCHECK(CrosLibrary::Get()->EnsureLoaded()); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, task_factory_.NewRunnableMethod( &NetworkStateNotifier::UpdateNetworkState, RetrieveState())); } void NetworkStateNotifier::UpdateNetworkState( NetworkStateDetails::State new_state) { DLOG(INFO) << "UpdateNetworkState: new=" << new_state << ", old=" << state_; if (state_ == NetworkStateDetails::CONNECTED && new_state != NetworkStateDetails::CONNECTED) { offline_start_time_ = Time::Now(); } state_ = new_state; NetworkStateDetails details(state_); NotificationService::current()->Notify( NotificationType::NETWORK_STATE_CHANGED, NotificationService::AllSources(), Details<NetworkStateDetails>(&details)); }; // static NetworkStateDetails::State NetworkStateNotifier::RetrieveState() { // Running on desktop means always connected, for now. if (!CrosLibrary::Get()->EnsureLoaded()) return NetworkStateDetails::CONNECTED; NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary(); if (cros->Connected()) { return NetworkStateDetails::CONNECTED; } else if (cros->Connecting()) { return NetworkStateDetails::CONNECTING; } else { return NetworkStateDetails::DISCONNECTED; } } } // namespace chromeos <|endoftext|>
<commit_before><commit_msg>fdo#78921 save embedded fonts in Flat ODF<commit_after><|endoftext|>
<commit_before>///Created: Daniel Turcanu @ IPDevel #include "util/singleton.h" #include "zorba_api.h" #include "store/api/item_factory.h" #include "store/api/store.h" #include "xquerybinary.h" #include "util/zorba.h" #include "errors/Error_impl.h" ///temporary stuff #include "store/naive/basic_item_factory.h" #include "store/naive/simple_store.h" namespace xqp{ ZorbaFactory *g_ZorbaFactory = NULL; ZorbaFactory& ZorbaFactory::getInstance() { if(!g_ZorbaFactory) { g_ZorbaFactory = new ZorbaFactory; zorba::initializeZorbaEngine(Store::getInstance()); } return *g_ZorbaFactory; } ItemFactory& ZorbaFactory::getItemFactory() { return Store::getInstance().getItemFactory(); } void ZorbaFactory::shutdownZorbaEngine() { zorba::uninitializeZorbaEngine(); delete g_ZorbaFactory; g_ZorbaFactory = NULL; } ZorbaFactory::ZorbaFactory() { } /* ZorbaFactory::ZorbaFactory(ItemFactory *item_factory, Store *theStore) { zorba::initializeZorbaEngine(item_factory, theStore); } ZorbaFactory::~ZorbaFactory() { zorba::uninitializeZorbaEngine(); g_ZorbaFactory = NULL;///kind of thread-unsafe } */ void ZorbaFactory::InitThread( error_messages *em,//=NULL const char *collator_name,// = "root", ::Collator::ECollationStrength collator_strength)// = Collator::PRIMARY) { zorba* zorp = zorba::allocateZorbaForCurrentThread(); if(!em) { errors_english *err_messages = new errors_english;///the english error messages zorp->m_error_manager->err_messages = err_messages; } else zorp->m_error_manager->err_messages = em; zorp->coll_string = collator_name; zorp->coll_strength = collator_strength; } void ZorbaFactory::UninitThread() { zorba::destroyZorbaForCurrentThread(); } XQuery_t ZorbaFactory::createQuery(const char* aQueryString, StaticQueryContext* sctx, bool routing_mode) { Zorba_XQueryBinary *xq = new Zorba_XQueryBinary( aQueryString ); if(!xq->compile(sctx, routing_mode)) { delete xq; return NULL; } return xq; } /* void ZorbaFactory::destroyQuery( XQuery *query ) { query->removeReference(); } */ Zorba_AlertsManager& ZorbaFactory::getAlertsManagerForCurrentThread() { zorba *z = zorba::getZorbaForCurrentThread(); return *z->getErrorManager(); } }//end namespace xqp <commit_msg>made Store a singleton<commit_after>///Created: Daniel Turcanu @ IPDevel #include "zorba_api.h" #include "store/api/item_factory.h" #include "store/api/store.h" #include "xquerybinary.h" #include "util/zorba.h" #include "errors/Error_impl.h" ///temporary stuff #include "store/naive/basic_item_factory.h" #include "store/naive/simple_store.h" namespace xqp{ ZorbaFactory *g_ZorbaFactory = NULL; ZorbaFactory& ZorbaFactory::getInstance() { if(!g_ZorbaFactory) { g_ZorbaFactory = new ZorbaFactory; zorba::initializeZorbaEngine(Store::getInstance()); } return *g_ZorbaFactory; } ItemFactory& ZorbaFactory::getItemFactory() { return Store::getInstance().getItemFactory(); } void ZorbaFactory::shutdownZorbaEngine() { zorba::uninitializeZorbaEngine(); delete g_ZorbaFactory; g_ZorbaFactory = NULL; } ZorbaFactory::ZorbaFactory() { } /* ZorbaFactory::ZorbaFactory(ItemFactory *item_factory, Store *theStore) { zorba::initializeZorbaEngine(item_factory, theStore); } ZorbaFactory::~ZorbaFactory() { zorba::uninitializeZorbaEngine(); g_ZorbaFactory = NULL;///kind of thread-unsafe } */ void ZorbaFactory::InitThread( error_messages *em,//=NULL const char *collator_name,// = "root", ::Collator::ECollationStrength collator_strength)// = Collator::PRIMARY) { zorba* zorp = zorba::allocateZorbaForCurrentThread(); if(!em) { errors_english *err_messages = new errors_english;///the english error messages zorp->m_error_manager->err_messages = err_messages; } else zorp->m_error_manager->err_messages = em; zorp->coll_string = collator_name; zorp->coll_strength = collator_strength; } void ZorbaFactory::UninitThread() { zorba::destroyZorbaForCurrentThread(); } XQuery_t ZorbaFactory::createQuery(const char* aQueryString, StaticQueryContext* sctx, bool routing_mode) { Zorba_XQueryBinary *xq = new Zorba_XQueryBinary( aQueryString ); if(!xq->compile(sctx, routing_mode)) { delete xq; return NULL; } return xq; } /* void ZorbaFactory::destroyQuery( XQuery *query ) { query->removeReference(); } */ Zorba_AlertsManager& ZorbaFactory::getAlertsManagerForCurrentThread() { zorba *z = zorba::getZorbaForCurrentThread(); return *z->getErrorManager(); } }//end namespace xqp <|endoftext|>
<commit_before>/* * PrimeSieveGUI.cpp -- This file is part of primesieve * * Copyright (C) 2012 Kim Walisch, <kim.walisch@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "PrimeSieveGUI.hpp" #include "ui_PrimeSieveGUI.h" #include "PrimeSieveProcess.hpp" #include "calculator.hpp" #include <primesieve.hpp> #include <primesieve/ParallelPrimeSieve.hpp> #if QT_VERSION >= 0x050000 #include <QtGlobal> #include <QCoreApplication> #include <QByteArray> #include <QTextStream> #include <QFile> #include <QSize> #include <QtWidgets/QMessageBox> #include <QTextCursor> #include <stdexcept> #else #include <QtGlobal> #include <QCoreApplication> #include <QByteArray> #include <QTextStream> #include <QFile> #include <QSize> #include <QMessageBox> #include <QTextCursor> #include <stdexcept> #endif using primesieve::ParallelPrimeSieve; int get_l1d_cache_size(); PrimeSieveGUI::PrimeSieveGUI(QWidget *parent) : QMainWindow(parent), ui(new Ui::PrimeSieveGUI), validator_(0), primeSieveProcess_(0), saveAct_(0), quitAct_(0), aboutAct_(0), alignmentGroup_(0) { ui->setupUi(this); primeText_.push_back("Prime numbers"); primeText_.push_back("Twin primes"); primeText_.push_back("Prime triplets"); primeText_.push_back("Prime quadruplets"); primeText_.push_back("Prime quintuplets"); primeText_.push_back("Prime sextuplets"); this->initGUI(); this->initConnections(); } PrimeSieveGUI::~PrimeSieveGUI() { this->cleanUp(); delete validator_; delete saveAct_; delete quitAct_; delete aboutAct_; delete alignmentGroup_; for (; !countAct_.isEmpty(); countAct_.pop_back()) delete countAct_.back(); for (; !printAct_.isEmpty(); printAct_.pop_back()) delete printAct_.back(); // Qt code delete ui; } void PrimeSieveGUI::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void PrimeSieveGUI::initGUI() { this->setWindowTitle(APPLICATION_NAME + " " + PRIMESIEVE_VERSION); this->createMenu(primeText_); // fill the sieveSizeComboBox with power of 2 values <= "2048 KB" for (int i = MINIMUM_SIEVE_SIZE; i <= MAXIMUM_SIEVE_SIZE; i *= 2) ui->sieveSizeComboBox->addItem(QString::number(i) + " KB"); int l1d_cache_size = get_l1d_cache_size(); if (l1d_cache_size < 16 || l1d_cache_size > 1024) l1d_cache_size = DEFAULT_L1D_CACHE_SIZE; this->setTo(ui->sieveSizeComboBox, QString::number(l1d_cache_size) + " KB"); // fill the threadsComboBox with power of 2 values <= maxThreads_ maxThreads_ = ParallelPrimeSieve::getMaxThreads(); for (int i = 1; i < maxThreads_; i *= 2) ui->threadsComboBox->addItem(QString::number(i)); ui->threadsComboBox->addItem(QString::number(maxThreads_)); this->setTo(ui->threadsComboBox, "1"); // set an ideal ComboBox width int width = ui->sieveSizeComboBox->minimumSizeHint().width(); ui->sieveSizeComboBox->setFixedWidth(width); ui->threadsComboBox->setFixedWidth(width); // set a nice GUI size QSize size = this->sizeHint(); size.setWidth(this->minimumSizeHint().width()); #if defined(Q_OS_WIN) size.setHeight(size.height() - size.height() / 10); #endif this->resize(size); // limit input for arithmetic expressions QRegExp rx("[0-9\\+\\-\\*\\/\\%\\^\\(\\)\\e\\E]*"); validator_ = new QRegExpValidator(rx, this); ui->lowerBoundLineEdit->setValidator(validator_); ui->upperBoundLineEdit->setValidator(validator_); } void PrimeSieveGUI::initConnections() { connect(&progressBarTimer_, SIGNAL(timeout()), this, SLOT(advanceProgressBar())); connect(ui->lowerBoundLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(autoSetThreads())); connect(ui->upperBoundLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(autoSetThreads())); connect(ui->autoSetCheckBox, SIGNAL(toggled(bool)), this, SLOT(autoSetThreads())); connect(saveAct_, SIGNAL(triggered()), this, SLOT(saveToFile())); connect(quitAct_, SIGNAL(triggered()), qApp, SLOT(closeAllWindows())); connect(alignmentGroup_, SIGNAL(triggered(QAction*)), this, SLOT(printMenuClicked(QAction*))); connect(aboutAct_, SIGNAL(triggered()), this, SLOT(showAboutDialog())); } /** * Get the sieve size in kilobytes from the sieveSizeComboBox. * @post sieveSize >= 1 && sieveSize <= 2048. */ int PrimeSieveGUI::getSieveSize() { QString sieveSize(ui->sieveSizeComboBox->currentText()); // remove " KB" sieveSize.chop(3); return sieveSize.toInt(); } /** * Get the number of threads from the threadsComboBox. */ int PrimeSieveGUI::getThreads() { return ui->threadsComboBox->currentText().toInt(); } quint64 PrimeSieveGUI::getNumber(const QString& str) { if (str.isEmpty()) throw std::invalid_argument("Please enter a lower and upper bound for prime sieving."); quint64 result = 0; try { result = calculator::eval<quint64>(str.toLatin1().data()); } catch (calculator::error& e) { throw std::invalid_argument(e.what()); } int digits = str.count(QRegExp("[0-9]")); if (result >= UPPER_BOUND_LIMIT || ( digits == str.size() && ( digits > UPPER_BOUND_STR.size() || ( digits == UPPER_BOUND_STR.size() && str >= UPPER_BOUND_STR)))) throw std::invalid_argument("Please use positive integers < 2^64 - 2^32*10."); return result; } void PrimeSieveGUI::setTo(QComboBox* comboBox, const QString& text) { comboBox->setCurrentIndex(comboBox->findText(text)); } /** * If "Auto set" is enabled set an ideal number of threads for the * current lower bound, upper bound in the threadsComboBox. */ void PrimeSieveGUI::autoSetThreads() { if (ui->autoSetCheckBox->isEnabled() && ui->autoSetCheckBox->isChecked()) { try { quint64 lowerBound = this->getNumber(ui->lowerBoundLineEdit->text()); quint64 upperBound = this->getNumber(ui->upperBoundLineEdit->text()); ParallelPrimeSieve pps; pps.setStart(lowerBound); pps.setStop(upperBound); int idealNumThreads = pps.getNumThreads(); if (idealNumThreads < maxThreads_) { // floor to the next power of 2 value int p = 1; for (; p <= idealNumThreads; p *= 2) ; idealNumThreads = p / 2; } this->setTo(ui->threadsComboBox, QString::number(idealNumThreads)); } catch (...) { this->setTo(ui->threadsComboBox, "1"); } } } /** * The user has chosen a custom number of threads, disable "Auto set". */ void PrimeSieveGUI::on_threadsComboBox_activated() { ui->autoSetCheckBox->setChecked(false); } /** * Start sieving primes. */ void PrimeSieveGUI::on_sieveButton_clicked() { // invert buttons, reset upon cleanUp() ui->sieveButton->setDisabled(true); ui->cancelButton->setEnabled(true); try { flags_ = this->getMenuSettings() | CALCULATE_STATUS; if ((flags_ & (COUNT_FLAGS | PRINT_FLAGS)) == 0) throw std::invalid_argument("Nothing to do, no count or print options selected."); quint64 lowerBound = this->getNumber(ui->lowerBoundLineEdit->text()); quint64 upperBound = this->getNumber(ui->upperBoundLineEdit->text()); if (lowerBound > upperBound) throw std::invalid_argument("The lower bound must not be greater than the upper bound."); // reset the GUI widgets ui->progressBar->setValue(ui->progressBar->minimum()); ui->textEdit->clear(); progressBarTimer_.start(25); // start a new process for sieving (avoids cancel // trouble with multiple threads) primeSieveProcess_ = new PrimeSieveProcess(this); if (flags_ & PRINT_FLAGS) connect(primeSieveProcess_, SIGNAL(readyReadStandardOutput()), this, SLOT(printProcessOutput())); connect(primeSieveProcess_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(processFinished(int, QProcess::ExitStatus))); primeSieveProcess_->start(lowerBound, upperBound, this->getSieveSize(), flags_, this->getThreads()); } catch (std::invalid_argument& ex) { this->cleanUp(); QMessageBox::warning(this, APPLICATION_NAME, ex.what()); } catch (std::exception& ex) { this->cleanUp(); QMessageBox::critical(this, APPLICATION_NAME, ex.what()); } } void PrimeSieveGUI::advanceProgressBar() { int permil = static_cast<int>(primeSieveProcess_->getStatus() * 10.0); ui->progressBar->setValue(permil); } /** * Redirects the standard output (prime numbers or prime k-tuplets) of * the primeSieveProcess_ to the TextEdit. */ void PrimeSieveGUI::printProcessOutput() { QByteArray buffer; buffer.reserve(PRINT_BUFFER_SIZE + 256); while (ui->cancelButton->isEnabled() && primeSieveProcess_->canReadLine()) { buffer.clear(); while (primeSieveProcess_->canReadLine() && buffer.size() < PRINT_BUFFER_SIZE) buffer.append(primeSieveProcess_->readLine(256)); // remove "\r\n" or '\n', '\r' at the back while (buffer.endsWith('\n') || buffer.endsWith('\r')) buffer.chop(1); if (!buffer.isEmpty()) ui->textEdit->appendPlainText(buffer); /// @brief Keep the GUI responsive. /// @bug processEvents() crashes on Windows with MSVC 2010 and Qt 5 beta. /// @warning QApplication::processEvents() must not be used on /// operating systems that use signal recursion (like Linux /// X11) otherwise the stack will explode! #if defined(Q_OS_WIN) || defined(Q_OS_MAC) || defined(Q_OS_IOS) QApplication::processEvents(); #else ui->textEdit->repaint(); #endif } } /** * Is executed when the primeSieveProcess_ finishes, checks for * process errors and calls this->printResults(). */ void PrimeSieveGUI::processFinished(int exitCode, QProcess::ExitStatus exitStatus) { // the process did not exit normally, i.e. threw and exception if (exitCode != 0) { // Qt uses '/' internally, even for Windows QString path = QCoreApplication::applicationDirPath() + "/" + APPLICATION_NAME + "_error.txt"; QFile error_log(path); if (error_log.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { QTextStream out(&error_log); out << primeSieveProcess_->readAllStandardError(); error_log.close(); } this->cleanUp(); QMessageBox::critical(this, APPLICATION_NAME, "The PrimeSieveProcess reported an error (see primesieve_error.txt), sieving has been aborted."); } // the PrimeSieveProcess has been interrupted by a signal (SIGTERM, // SIGKILL, ...) or a segmentation fault else if (exitStatus == QProcess::CrashExit) { this->cleanUp(); QMessageBox::critical(this, APPLICATION_NAME, "The PrimeSieveProcess crashed, sieving has been aborted."); } // the PrimeSieveProcess has finished correctly else { ui->progressBar->setValue(ui->progressBar->maximum()); // print results if not canceled lately if (ui->cancelButton->isEnabled()) this->printResults(); this->cleanUp(); } } /** * Print the sieving results. */ void PrimeSieveGUI::printResults() { if (!ui->textEdit->toPlainText().isEmpty()) ui->textEdit->appendPlainText(""); // hack to get the count results aligned using tabs QString maxSizeText; for (int i = 0; i < primeText_.size(); i++) { if ((flags_ & (COUNT_PRIMES << i)) && maxSizeText.size() < primeText_[i].size()) maxSizeText = primeText_[i]; } ui->textEdit->insertPlainText(maxSizeText + ": "); int maxWidth = ui->textEdit->cursorRect().left(); ui->textEdit->moveCursor(QTextCursor::StartOfLine, QTextCursor::KeepAnchor); ui->textEdit->textCursor().removeSelectedText(); ui->textEdit->setTabStopWidth(maxWidth); // print prime counts & time elapsed for (int i = 0; i < primeText_.size(); i++) { if (flags_ & (COUNT_PRIMES << i)) ui->textEdit->appendPlainText(primeText_[i] + ":\t" + QString::number(primeSieveProcess_->getCount(i))); } if (flags_ & COUNT_KTUPLETS) ui->textEdit->appendPlainText(""); QString time("Elapsed time:\t" + QString::number(primeSieveProcess_->getSeconds(), 'f', 2) + " sec"); ui->textEdit->appendPlainText(time); } /** * Cancel sieving. */ void PrimeSieveGUI::on_cancelButton_clicked() { ui->cancelButton->setDisabled(true); ui->progressBar->setValue(0); // too late to abort if ((flags_ & PRINT_FLAGS) && primeSieveProcess_->isFinished()) return; this->cleanUp(); } /** * Clean up after sieving is finished or canceled (abort the * PrimeSieveProcess if still running). */ void PrimeSieveGUI::cleanUp() { progressBarTimer_.stop(); if (primeSieveProcess_ != 0) delete primeSieveProcess_; primeSieveProcess_ = 0; // invert buttons ui->cancelButton->setDisabled(true); ui->sieveButton->setEnabled(true); // force repainting widgets this->repaint(); } <commit_msg>Fix L1 cache size bug in GUI app<commit_after>/* * PrimeSieveGUI.cpp -- This file is part of primesieve * * Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "PrimeSieveGUI.hpp" #include "ui_PrimeSieveGUI.h" #include "PrimeSieveProcess.hpp" #include "calculator.hpp" #include <primesieve.hpp> #include <primesieve/ParallelPrimeSieve.hpp> #include <primesieve/pmath.hpp> #if QT_VERSION >= 0x050000 #include <QtGlobal> #include <QCoreApplication> #include <QByteArray> #include <QTextStream> #include <QFile> #include <QSize> #include <QtWidgets/QMessageBox> #include <QTextCursor> #include <stdexcept> #else #include <QtGlobal> #include <QCoreApplication> #include <QByteArray> #include <QTextStream> #include <QFile> #include <QSize> #include <QMessageBox> #include <QTextCursor> #include <stdexcept> #endif int get_l1d_cache_size(); using namespace primesieve; PrimeSieveGUI::PrimeSieveGUI(QWidget *parent) : QMainWindow(parent), ui(new Ui::PrimeSieveGUI), validator_(0), primeSieveProcess_(0), saveAct_(0), quitAct_(0), aboutAct_(0), alignmentGroup_(0) { ui->setupUi(this); primeText_.push_back("Prime numbers"); primeText_.push_back("Twin primes"); primeText_.push_back("Prime triplets"); primeText_.push_back("Prime quadruplets"); primeText_.push_back("Prime quintuplets"); primeText_.push_back("Prime sextuplets"); this->initGUI(); this->initConnections(); } PrimeSieveGUI::~PrimeSieveGUI() { this->cleanUp(); delete validator_; delete saveAct_; delete quitAct_; delete aboutAct_; delete alignmentGroup_; for (; !countAct_.isEmpty(); countAct_.pop_back()) delete countAct_.back(); for (; !printAct_.isEmpty(); printAct_.pop_back()) delete printAct_.back(); // Qt code delete ui; } void PrimeSieveGUI::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void PrimeSieveGUI::initGUI() { this->setWindowTitle(APPLICATION_NAME + " " + PRIMESIEVE_VERSION); this->createMenu(primeText_); // fill the sieveSizeComboBox with power of 2 values <= "2048 KB" for (int i = MINIMUM_SIEVE_SIZE; i <= MAXIMUM_SIEVE_SIZE; i *= 2) ui->sieveSizeComboBox->addItem(QString::number(i) + " KB"); int l1dCacheSize = get_l1d_cache_size(); if (l1dCacheSize < 16 || l1dCacheSize > 1024) l1dCacheSize = DEFAULT_L1D_CACHE_SIZE; int defaultSieveSize = floorPowerOf2(l1dCacheSize); // default sieve size = CPU L1 data cache size this->setTo(ui->sieveSizeComboBox, QString::number(defaultSieveSize) + " KB"); // fill the threadsComboBox with power of 2 values <= maxThreads_ maxThreads_ = ParallelPrimeSieve::getMaxThreads(); for (int i = 1; i < maxThreads_; i *= 2) ui->threadsComboBox->addItem(QString::number(i)); ui->threadsComboBox->addItem(QString::number(maxThreads_)); this->setTo(ui->threadsComboBox, "1"); // set an ideal ComboBox width int width = ui->sieveSizeComboBox->minimumSizeHint().width(); ui->sieveSizeComboBox->setFixedWidth(width); ui->threadsComboBox->setFixedWidth(width); // set a nice GUI size QSize size = this->sizeHint(); size.setWidth(this->minimumSizeHint().width()); #if defined(Q_OS_WIN) size.setHeight(size.height() - size.height() / 10); #endif this->resize(size); // limit input for arithmetic expressions QRegExp rx("[0-9\\+\\-\\*\\/\\%\\^\\(\\)\\e\\E]*"); validator_ = new QRegExpValidator(rx, this); ui->lowerBoundLineEdit->setValidator(validator_); ui->upperBoundLineEdit->setValidator(validator_); } void PrimeSieveGUI::initConnections() { connect(&progressBarTimer_, SIGNAL(timeout()), this, SLOT(advanceProgressBar())); connect(ui->lowerBoundLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(autoSetThreads())); connect(ui->upperBoundLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(autoSetThreads())); connect(ui->autoSetCheckBox, SIGNAL(toggled(bool)), this, SLOT(autoSetThreads())); connect(saveAct_, SIGNAL(triggered()), this, SLOT(saveToFile())); connect(quitAct_, SIGNAL(triggered()), qApp, SLOT(closeAllWindows())); connect(alignmentGroup_, SIGNAL(triggered(QAction*)), this, SLOT(printMenuClicked(QAction*))); connect(aboutAct_, SIGNAL(triggered()), this, SLOT(showAboutDialog())); } /** * Get the sieve size in kilobytes from the sieveSizeComboBox. * @post sieveSize >= 1 && sieveSize <= 2048. */ int PrimeSieveGUI::getSieveSize() { QString sieveSize(ui->sieveSizeComboBox->currentText()); // remove " KB" sieveSize.chop(3); return sieveSize.toInt(); } /** * Get the number of threads from the threadsComboBox. */ int PrimeSieveGUI::getThreads() { return ui->threadsComboBox->currentText().toInt(); } quint64 PrimeSieveGUI::getNumber(const QString& str) { if (str.isEmpty()) throw std::invalid_argument("Please enter a lower and upper bound for prime sieving."); quint64 result = 0; try { result = calculator::eval<quint64>(str.toLatin1().data()); } catch (calculator::error& e) { throw std::invalid_argument(e.what()); } int digits = str.count(QRegExp("[0-9]")); if (result >= UPPER_BOUND_LIMIT || ( digits == str.size() && ( digits > UPPER_BOUND_STR.size() || ( digits == UPPER_BOUND_STR.size() && str >= UPPER_BOUND_STR)))) throw std::invalid_argument("Please use positive integers < 2^64 - 2^32*10."); return result; } void PrimeSieveGUI::setTo(QComboBox* comboBox, const QString& text) { comboBox->setCurrentIndex(comboBox->findText(text)); } /** * If "Auto set" is enabled set an ideal number of threads for the * current lower bound, upper bound in the threadsComboBox. */ void PrimeSieveGUI::autoSetThreads() { if (ui->autoSetCheckBox->isEnabled() && ui->autoSetCheckBox->isChecked()) { try { quint64 lowerBound = this->getNumber(ui->lowerBoundLineEdit->text()); quint64 upperBound = this->getNumber(ui->upperBoundLineEdit->text()); ParallelPrimeSieve pps; pps.setStart(lowerBound); pps.setStop(upperBound); int idealNumThreads = pps.getNumThreads(); if (idealNumThreads < maxThreads_) { // floor to the next power of 2 value int p = 1; for (; p <= idealNumThreads; p *= 2) ; idealNumThreads = p / 2; } this->setTo(ui->threadsComboBox, QString::number(idealNumThreads)); } catch (...) { this->setTo(ui->threadsComboBox, "1"); } } } /** * The user has chosen a custom number of threads, disable "Auto set". */ void PrimeSieveGUI::on_threadsComboBox_activated() { ui->autoSetCheckBox->setChecked(false); } /** * Start sieving primes. */ void PrimeSieveGUI::on_sieveButton_clicked() { // invert buttons, reset upon cleanUp() ui->sieveButton->setDisabled(true); ui->cancelButton->setEnabled(true); try { flags_ = this->getMenuSettings() | CALCULATE_STATUS; if ((flags_ & (COUNT_FLAGS | PRINT_FLAGS)) == 0) throw std::invalid_argument("Nothing to do, no count or print options selected."); quint64 lowerBound = this->getNumber(ui->lowerBoundLineEdit->text()); quint64 upperBound = this->getNumber(ui->upperBoundLineEdit->text()); if (lowerBound > upperBound) throw std::invalid_argument("The lower bound must not be greater than the upper bound."); // reset the GUI widgets ui->progressBar->setValue(ui->progressBar->minimum()); ui->textEdit->clear(); progressBarTimer_.start(25); // start a new process for sieving (avoids cancel // trouble with multiple threads) primeSieveProcess_ = new PrimeSieveProcess(this); if (flags_ & PRINT_FLAGS) connect(primeSieveProcess_, SIGNAL(readyReadStandardOutput()), this, SLOT(printProcessOutput())); connect(primeSieveProcess_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(processFinished(int, QProcess::ExitStatus))); primeSieveProcess_->start(lowerBound, upperBound, this->getSieveSize(), flags_, this->getThreads()); } catch (std::invalid_argument& ex) { this->cleanUp(); QMessageBox::warning(this, APPLICATION_NAME, ex.what()); } catch (std::exception& ex) { this->cleanUp(); QMessageBox::critical(this, APPLICATION_NAME, ex.what()); } } void PrimeSieveGUI::advanceProgressBar() { int permil = static_cast<int>(primeSieveProcess_->getStatus() * 10.0); ui->progressBar->setValue(permil); } /** * Redirects the standard output (prime numbers or prime k-tuplets) of * the primeSieveProcess_ to the TextEdit. */ void PrimeSieveGUI::printProcessOutput() { QByteArray buffer; buffer.reserve(PRINT_BUFFER_SIZE + 256); while (ui->cancelButton->isEnabled() && primeSieveProcess_->canReadLine()) { buffer.clear(); while (primeSieveProcess_->canReadLine() && buffer.size() < PRINT_BUFFER_SIZE) buffer.append(primeSieveProcess_->readLine(256)); // remove "\r\n" or '\n', '\r' at the back while (buffer.endsWith('\n') || buffer.endsWith('\r')) buffer.chop(1); if (!buffer.isEmpty()) ui->textEdit->appendPlainText(buffer); /// @brief Keep the GUI responsive. /// @bug processEvents() crashes on Windows with MSVC 2010 and Qt 5 beta. /// @warning QApplication::processEvents() must not be used on /// operating systems that use signal recursion (like Linux /// X11) otherwise the stack will explode! #if defined(Q_OS_WIN) || defined(Q_OS_MAC) || defined(Q_OS_IOS) QApplication::processEvents(); #else ui->textEdit->repaint(); #endif } } /** * Is executed when the primeSieveProcess_ finishes, checks for * process errors and calls this->printResults(). */ void PrimeSieveGUI::processFinished(int exitCode, QProcess::ExitStatus exitStatus) { // the process did not exit normally, i.e. threw and exception if (exitCode != 0) { // Qt uses '/' internally, even for Windows QString path = QCoreApplication::applicationDirPath() + "/" + APPLICATION_NAME + "_error.txt"; QFile error_log(path); if (error_log.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { QTextStream out(&error_log); out << primeSieveProcess_->readAllStandardError(); error_log.close(); } this->cleanUp(); QMessageBox::critical(this, APPLICATION_NAME, "The PrimeSieveProcess reported an error (see primesieve_error.txt), sieving has been aborted."); } // the PrimeSieveProcess has been interrupted by a signal (SIGTERM, // SIGKILL, ...) or a segmentation fault else if (exitStatus == QProcess::CrashExit) { this->cleanUp(); QMessageBox::critical(this, APPLICATION_NAME, "The PrimeSieveProcess crashed, sieving has been aborted."); } // the PrimeSieveProcess has finished correctly else { ui->progressBar->setValue(ui->progressBar->maximum()); // print results if not canceled lately if (ui->cancelButton->isEnabled()) this->printResults(); this->cleanUp(); } } /** * Print the sieving results. */ void PrimeSieveGUI::printResults() { if (!ui->textEdit->toPlainText().isEmpty()) ui->textEdit->appendPlainText(""); // hack to get the count results aligned using tabs QString maxSizeText; for (int i = 0; i < primeText_.size(); i++) { if ((flags_ & (COUNT_PRIMES << i)) && maxSizeText.size() < primeText_[i].size()) maxSizeText = primeText_[i]; } ui->textEdit->insertPlainText(maxSizeText + ": "); int maxWidth = ui->textEdit->cursorRect().left(); ui->textEdit->moveCursor(QTextCursor::StartOfLine, QTextCursor::KeepAnchor); ui->textEdit->textCursor().removeSelectedText(); ui->textEdit->setTabStopWidth(maxWidth); // print prime counts & time elapsed for (int i = 0; i < primeText_.size(); i++) { if (flags_ & (COUNT_PRIMES << i)) ui->textEdit->appendPlainText(primeText_[i] + ":\t" + QString::number(primeSieveProcess_->getCount(i))); } if (flags_ & COUNT_KTUPLETS) ui->textEdit->appendPlainText(""); QString time("Elapsed time:\t" + QString::number(primeSieveProcess_->getSeconds(), 'f', 2) + " sec"); ui->textEdit->appendPlainText(time); } /** * Cancel sieving. */ void PrimeSieveGUI::on_cancelButton_clicked() { ui->cancelButton->setDisabled(true); ui->progressBar->setValue(0); // too late to abort if ((flags_ & PRINT_FLAGS) && primeSieveProcess_->isFinished()) return; this->cleanUp(); } /** * Clean up after sieving is finished or canceled (abort the * PrimeSieveProcess if still running). */ void PrimeSieveGUI::cleanUp() { progressBarTimer_.stop(); if (primeSieveProcess_ != 0) delete primeSieveProcess_; primeSieveProcess_ = 0; // invert buttons ui->cancelButton->setDisabled(true); ui->sieveButton->setEnabled(true); // force repainting widgets this->repaint(); } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/Core/Stopwatch.h> #include <vw/Core/Log.h> #include <vw/Plate/Rpc.h> #include <vw/Plate/HTTPUtils.h> #include <vw/Plate/IndexService.h> #include <asp/PhotometryTK/ProjectService.h> #include <asp/Core/Macros.h> #include <signal.h> #include <google/protobuf/descriptor.h> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; namespace fs = boost::filesystem; using namespace vw; using namespace vw::platefile; using namespace asp::pho; // -- Signal Handler --------------------- volatile bool process_messages = true; volatile bool force_sync = false; void sig_unexpected_shutdown( int sig_num ) { signal(sig_num, SIG_IGN); process_messages = false; signal(sig_num, sig_unexpected_shutdown); } void sig_sync( int sig_num ) { signal(sig_num, SIG_IGN); force_sync = true; signal(sig_num, sig_sync); } struct Options { Url url, index_url; std::string ptk_file; float sync_interval; bool debug, help; }; // -- Main Loop -------------------------- void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options("Runs a mosaicking daemon that listens for mosaicking requests coming in over the AMQP bus..\n\nGeneral Options:"); general_options.add_options() ("url", po::value(&opt.url), "Url to listen in on") ("sync-interval,s", po::value(&opt.sync_interval)->default_value(60), "Specify the time interval (in minutes) for automatically synchronizing the index to disk.") ("debug", po::bool_switch(&opt.debug)->default_value(false), "Output debug messages.") ("help,h", po::bool_switch(&opt.help)->default_value(false), "Display this help message"); po::options_description hidden_options(""); hidden_options.add_options() ("ptk-file", po::value(&opt.ptk_file)); po::options_description options("Allowed Options"); options.add(general_options).add(hidden_options); po::positional_options_description p; p.add("ptk-file", -1); po::variables_map vm; po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm ); po::notify( vm ); std::ostringstream usage; usage << "Usage: " << argv[0] << " <ptk file> --url <url>" << std::endl << std::endl; usage << general_options << std::endl; if ( opt.help ) vw_throw( ArgumentErr() << usage.str() ); if ( opt.ptk_file.size() < 5 ) vw_throw( ArgumentErr() << "Error: must specify a ptk file to be servering!\n\n" << usage.str() ); } int main(int argc, char** argv) { Options opt; try { handle_arguments( argc, argv, opt ); // Install Unix Signal Handlers. These will help us to gracefully // recover and salvage the index under most unexpected error // conditions. signal(SIGINT, sig_unexpected_shutdown); signal(SIGUSR1, sig_sync); // Clean & Create new url if ( opt.ptk_file.substr(opt.ptk_file.size()-4,4) != ".ptk" ) vw_throw( ArgumentErr() << "Failed to provide input ptk file." ); std::string scheme = opt.url.scheme(); if ( scheme == "pf" || scheme == "amqp" ) { #if defined(VW_HAVE_PKG_RABBITMQ_C) && VW_HAVE_PKG_RABBITMQ_C==1 opt.index_url = opt.url; opt.index_url.path( opt.url.path()+"_index" ); #else vw_throw( ArgumentErr() << "ptk_server: This build does not support AMQP.\n" ); #endif } else if ( scheme == "zmq" || scheme == "zmq+ipc" || scheme == "zmq+tcp" || scheme == "zmq+inproc" ) { #if defined(VW_HAVE_PKG_ZEROMQ) && VW_HAVE_PKG_ZEROMQ==1 opt.index_url = Url( opt.url.scheme() + "://" + opt.url.hostname() + ":" + boost::lexical_cast<std::string>(opt.url.port()+1) ); #else vw_throw( ArgumentErr() << "ptk_server: This build does not support ZeroMQ.\n" ); #endif } else { vw_throw( ArgumentErr() << "ptk_server: Unknown URL scheme \"" << scheme << "\".\n" ); } fs::path ptk_path( opt.ptk_file ); // Start the ptk server task in another thread RpcServer<ProjectServiceImpl> server_1(opt.url, new ProjectServiceImpl(ptk_path.string())); RpcServer<IndexServiceImpl> server_2(opt.index_url, new IndexServiceImpl(ptk_path.string())); vw_out(InfoMessage) << "Starting ptk server\n"; vw_out(InfoMessage) << "\tw/ URL: " << opt.url << "\n"; vw_out(InfoMessage) << "Starting index server\n"; vw_out(InfoMessage) << "\tw/ URL: " << opt.index_url << "\n"; uint64 sync_interval_us = uint64(opt.sync_interval * 60000000); uint64 t0 = Stopwatch::microtime(), t1; uint64 next_sync = t0 + sync_interval_us; size_t success = 0, fail = 0, calls = 0; while(process_messages) { bool should_sync = force_sync || (Stopwatch::microtime() >= next_sync); if ( should_sync ) { vw_out(InfoMessage) << "\nStarting sync to disk. (" << (force_sync ? "auto" : "manual") << ")\n"; uint64 s0 = Stopwatch::microtime(); server_1.impl()->sync(); server_2.impl()->sync(); uint64 s1 = Stopwatch::microtime(); next_sync = s1 + sync_interval_us; vw_out(InfoMessage) << "Sync complete (took " << float(s1-s0) / 1e6 << " seconds).\n"; force_sync = false; } t1 = Stopwatch::microtime(); size_t success_dt, fail_dt, calls_dt; { ThreadMap::Locked stats = server_2.stats(); success_dt = stats.get("msgs"); fail_dt = stats.get("server_error") + stats.get("client_error"); calls_dt = success_dt + fail_dt; stats.clear(); } success += success_dt; fail += fail_dt; calls += calls_dt; float dt = float(t1 - t0) / 1e6f; t0 = t1; vw_out(InfoMessage) << "[ptk_server] : " << float(calls_dt)/dt << " qps " << "(" << (100. * success / (calls ? calls : 1)) << "% success) \r" << std::flush; Thread::sleep_ms(1000); } server_2.stop(); vw_out(InfoMessage) << "\nShutting down the index service safely.\n"; server_2.impl()->sync(); server_1.stop(); vw_out(InfoMessage) << "\nShutting down the ptk service safely.\n"; server_1.impl()->sync(); } ASP_STANDARD_CATCHES; return 0; } <commit_msg>Added error checking to PTK_server<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/Core/Stopwatch.h> #include <vw/Core/Log.h> #include <vw/Plate/Rpc.h> #include <vw/Plate/HTTPUtils.h> #include <vw/Plate/IndexService.h> #include <asp/PhotometryTK/ProjectService.h> #include <asp/Core/Macros.h> #include <signal.h> #include <google/protobuf/descriptor.h> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; namespace fs = boost::filesystem; using namespace vw; using namespace vw::platefile; using namespace asp::pho; // -- Signal Handler --------------------- volatile bool process_messages = true; volatile bool force_sync = false; void sig_unexpected_shutdown( int sig_num ) { signal(sig_num, SIG_IGN); process_messages = false; signal(sig_num, sig_unexpected_shutdown); } void sig_sync( int sig_num ) { signal(sig_num, SIG_IGN); force_sync = true; signal(sig_num, sig_sync); } struct Options { Url url, index_url; std::string ptk_file; float sync_interval; bool debug, help; }; // -- Main Loop -------------------------- void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options("Runs a mosaicking daemon that listens for mosaicking requests coming in over the AMQP bus..\n\nGeneral Options:"); general_options.add_options() ("url", po::value(&opt.url), "Url to listen in on") ("sync-interval,s", po::value(&opt.sync_interval)->default_value(60), "Specify the time interval (in minutes) for automatically synchronizing the index to disk.") ("debug", po::bool_switch(&opt.debug)->default_value(false), "Output debug messages.") ("help,h", po::bool_switch(&opt.help)->default_value(false), "Display this help message"); po::options_description hidden_options(""); hidden_options.add_options() ("ptk-file", po::value(&opt.ptk_file)); po::options_description options("Allowed Options"); options.add(general_options).add(hidden_options); po::positional_options_description p; p.add("ptk-file", -1); po::variables_map vm; po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm ); po::notify( vm ); std::ostringstream usage; usage << "Usage: " << argv[0] << " <ptk file> --url <url>" << std::endl << std::endl; usage << general_options << std::endl; if ( opt.help ) vw_throw( ArgumentErr() << usage.str() ); if ( opt.ptk_file.size() < 5 ) vw_throw( ArgumentErr() << "Error: must specify a ptk file to be servering!\n\n" << usage.str() ); } int main(int argc, char** argv) { Options opt; try { handle_arguments( argc, argv, opt ); // Install Unix Signal Handlers. These will help us to gracefully // recover and salvage the index under most unexpected error // conditions. signal(SIGINT, sig_unexpected_shutdown); signal(SIGUSR1, sig_sync); // Clean & Create new url if ( opt.ptk_file.substr(opt.ptk_file.size()-4,4) != ".ptk" ) vw_throw( ArgumentErr() << "Failed to provide input ptk file." ); std::string scheme = opt.url.scheme(); if ( scheme == "pf" || scheme == "amqp" ) { #if defined(VW_HAVE_PKG_RABBITMQ_C) && VW_HAVE_PKG_RABBITMQ_C==1 opt.index_url = opt.url; opt.index_url.path( opt.url.path()+"_index" ); #else vw_throw( ArgumentErr() << "ptk_server: This build does not support AMQP.\n" ); #endif } else if ( scheme == "zmq" || scheme == "zmq+ipc" || scheme == "zmq+tcp" || scheme == "zmq+inproc" ) { #if defined(VW_HAVE_PKG_ZEROMQ) && VW_HAVE_PKG_ZEROMQ==1 opt.index_url = Url( opt.url.scheme() + "://" + opt.url.hostname() + ":" + boost::lexical_cast<std::string>(opt.url.port()+1) ); #else vw_throw( ArgumentErr() << "ptk_server: This build does not support ZeroMQ.\n" ); #endif } else { vw_throw( ArgumentErr() << "ptk_server: Unknown URL scheme \"" << scheme << "\".\n" ); } fs::path ptk_path( opt.ptk_file ); // Start the ptk server task in another thread RpcServer<ProjectServiceImpl> server_1(opt.url, new ProjectServiceImpl(ptk_path.string())); RpcServer<IndexServiceImpl> server_2(opt.index_url, new IndexServiceImpl(ptk_path.string())); vw_out(InfoMessage) << "Starting ptk server\n"; vw_out(InfoMessage) << "\tw/ URL: " << opt.url << "\n"; vw_out(InfoMessage) << "Starting index server\n"; vw_out(InfoMessage) << "\tw/ URL: " << opt.index_url << "\n"; uint64 sync_interval_us = uint64(opt.sync_interval * 60000000); uint64 t0 = Stopwatch::microtime(), t1; uint64 next_sync = t0 + sync_interval_us; size_t success = 0, fail = 0, calls = 0; while(process_messages) { if ( server_1.error() ) { vw_out(InfoMessage) << "PTK Service has terminated with message: " << server_1.error() << "\n"; break; } else if ( server_2.error() ) { vw_out(InfoMessage) << "Index Service has terminated with message: " << server_2.error() << "\n"; break; } bool should_sync = force_sync || (Stopwatch::microtime() >= next_sync); if ( should_sync ) { vw_out(InfoMessage) << "\nStarting sync to disk. (" << (force_sync ? "auto" : "manual") << ")\n"; uint64 s0 = Stopwatch::microtime(); server_1.impl()->sync(); server_2.impl()->sync(); uint64 s1 = Stopwatch::microtime(); next_sync = s1 + sync_interval_us; vw_out(InfoMessage) << "Sync complete (took " << float(s1-s0) / 1e6 << " seconds).\n"; force_sync = false; } t1 = Stopwatch::microtime(); size_t success_dt, fail_dt, calls_dt; { ThreadMap::Locked stats = server_2.stats(); success_dt = stats.get("msgs"); fail_dt = stats.get("server_error") + stats.get("client_error"); calls_dt = success_dt + fail_dt; stats.clear(); } success += success_dt; fail += fail_dt; calls += calls_dt; float dt = float(t1 - t0) / 1e6f; t0 = t1; vw_out(InfoMessage) << "[ptk_server] : " << float(calls_dt)/dt << " qps " << "(" << (100. * success / (calls ? calls : 1)) << "% success) \r" << std::flush; Thread::sleep_ms(1000); } server_2.stop(); vw_out(InfoMessage) << "\nShutting down the index service safely.\n"; server_2.impl()->sync(); server_1.stop(); vw_out(InfoMessage) << "\nShutting down the ptk service safely.\n"; server_1.impl()->sync(); } ASP_STANDARD_CATCHES; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <cppunit/TestRunner.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> //#include <cppunit/BriefTestProgressListener.h> #include <cppunit/TextOutputter.h> //#include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> int main( int argc, char **argv ) { // Cxg}l[W쐬 CPPUNIT_NS::TestResult controller; // eXgʂWIuWFNg쐬 CPPUNIT_NS::TestResultCollector result; controller.addListener( &result ); // eXgsɐis󋵂\IuWFNg쐬 //CPPUNIT_NS::BriefTestProgressListener progress; //controller.addListener( &progress ); // eXgi[ɃeXgݒ肷 CPPUNIT_NS::TestRunner runner; runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry( ).makeTest( ) ); runner.run( controller ); // eXgʂo͂ CPPUNIT_NS::TextOutputter *outputter = new CPPUNIT_NS::TextOutputter( &result, std::cout ); outputter->write( ); // eXgɐꍇ 0 ԂCs 1 Ԃ return( result.wasSuccessful( ) ? 0 : 1 ); } <commit_msg>ポインタを使用しないように修正した.<commit_after>#include <iostream> #include <cppunit/TestRunner.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> //#include <cppunit/BriefTestProgressListener.h> #include <cppunit/TextOutputter.h> //#include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> int main( int argc, char **argv ) { // Cxg}l[W쐬 CPPUNIT_NS::TestResult controller; // eXgʂWIuWFNg쐬 CPPUNIT_NS::TestResultCollector result; controller.addListener( &result ); // eXgsɐis󋵂\IuWFNg쐬 //CPPUNIT_NS::BriefTestProgressListener progress; //controller.addListener( &progress ); // eXgi[ɃeXgݒ肷 CPPUNIT_NS::TestRunner runner; runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry( ).makeTest( ) ); runner.run( controller ); // eXgʂo͂ CPPUNIT_NS::TextOutputter outputter( &result, std::cout ); outputter.write( ); // eXgɐꍇ 0 ԂCs 1 Ԃ return( result.wasSuccessful( ) ? 0 : 1 ); } <|endoftext|>
<commit_before>#include <QtSerialPort/QSerialPort> #include <QUdpSocket> #include "InfrastructureLayer/InfrastructureContainer.h" #include "DataLayer/DataContainer.h" #include "CommDeviceControl/RadioCommDevice.h" #include "CommDeviceControl/UdpMessageForwarder.h" #include "CommunicationContainer.h" #include "DataPopulators/BatteryPopulator.h" #include "DataPopulators/CmuPopulator.h" #include "DataPopulators/DriverDetailsPopulator.h" #include "DataPopulators/FaultsPopulator.h" #include "DataPopulators/KeyDriverControlPopulator.h" #include "PacketChecksumChecker/PacketChecksumChecker.h" #include "PacketDecoder/PacketDecoder.h" #include "PacketSynchronizer/PacketSynchronizer.h" #include "PacketUnstuffer/PacketUnstuffer.h" class CommunicationContainerPrivate { public: CommunicationContainerPrivate(DataContainer& dataContainer, InfrastructureContainer& infrastructureContainer) : radioCommDevice(serialPort, infrastructureContainer.settings()) , messageForwarder(infrastructureContainer.settings()) , packetSynchronizer(radioCommDevice) , packetUnstuffer(packetSynchronizer) , packetChecksumChecker(packetUnstuffer) , packetDecoder(packetChecksumChecker) , keyDriverControlPopulator( packetDecoder, dataContainer.vehicleData(), dataContainer.powerData()) , driverDetailsPopulator( packetDecoder, dataContainer.vehicleData(), dataContainer.powerData()) , faultsPopulator( packetDecoder, dataContainer.faultsData()) , batteryPopulator( packetDecoder, dataContainer.batteryData()) , cmuPopulator( packetDecoder, dataContainer.batteryData()) { } QSerialPort serialPort; RadioCommDevice radioCommDevice; UdpMessageForwarder messageForwarder; PacketSynchronizer packetSynchronizer; PacketUnstuffer packetUnstuffer; PacketChecksumChecker packetChecksumChecker; PacketDecoder packetDecoder; KeyDriverControlPopulator keyDriverControlPopulator; DriverDetailsPopulator driverDetailsPopulator; FaultsPopulator faultsPopulator; BatteryPopulator batteryPopulator; CmuPopulator cmuPopulator; }; CommunicationContainer::CommunicationContainer(DataContainer& dataContainer, InfrastructureContainer& infrastructureContainer) : impl_(new CommunicationContainerPrivate(dataContainer, infrastructureContainer)) { } CommunicationContainer::~CommunicationContainer() { } I_CommDevice& CommunicationContainer::commDevice() { return impl_->radioCommDevice; } I_PacketSynchronizer& CommunicationContainer::packetSynchronizer() { return impl_->packetSynchronizer; } I_DataInjectionService& CommunicationContainer::dataInjectionService() { return impl_->packetUnstuffer; } I_PacketDecoder& CommunicationContainer::packetDecoder() { return impl_->packetDecoder; } I_PacketChecksumChecker& CommunicationContainer::packetChecksumChecker() { return impl_->packetChecksumChecker; } I_MessageForwarder& CommunicationContainer::udpMessageForwarder() { return impl_->messageForwarder; } <commit_msg>Implementing CommunicationContainerPrivate<commit_after>#include <QtSerialPort/QSerialPort> #include <QUdpSocket> #include "InfrastructureLayer/InfrastructureContainer.h" #include "DataLayer/DataContainer.h" #include "CommDeviceControl/RadioCommDevice.h" #include "CommDeviceControl/UdpMessageForwarder.h" #include "CommunicationContainer.h" #include "DataPopulators/BatteryFaultsPopulator.h" #include "DataPopulators/BatteryPopulator.h" #include "DataPopulators/CmuPopulator.h" #include "DataPopulators/DriverControlsPopulator.h" #include "DataPopulators/KeyMotorPopulator.h" #include "DataPopulators/LightsPopulator.h" #include "DataPopulators/MotorDetailsPopulator.h" #include "DataPopulators/MotorFaultsPopulator.h" #include "DataPopulators/MpptPopulator.h" #include "DataPopulators/OtherPopulator.h" #include "PacketChecksumChecker/PacketChecksumChecker.h" #include "PacketDecoder/PacketDecoder.h" #include "PacketSynchronizer/PacketSynchronizer.h" #include "PacketUnstuffer/PacketUnstuffer.h" class CommunicationContainerPrivate { public: CommunicationContainerPrivate(DataContainer& dataContainer, InfrastructureContainer& infrastructureContainer) : radioCommDevice(serialPort, infrastructureContainer.settings()) , messageForwarder(infrastructureContainer.settings()) , packetSynchronizer(radioCommDevice) , packetUnstuffer(packetSynchronizer) , packetChecksumChecker(packetUnstuffer) , packetDecoder(packetChecksumChecker) , BatteryFaultsPopulator(packetDecoder, dataContainer.batteryFaultsData()) , batteryPopulator(packetDecoder, dataContainer.batteryData()) , cmuPopulator(packetDecoder, dataContainer.cmuData()) , driverControlsPopulator(packetDecoder, dataContainer.driverControlsData()) , keyMotorPopulator(packetDecoder, dataContainer.keyMotorData()) , lightsPopulator(packetDecoder, dataContainer.lightsData()) , motorDetailsPopulator(packetDecoder, dataContainer.motorDetailsData()) , motorFaultsPopulator(packetDecoder, dataContainer.motorFaultsData()) , mpptPopulator(packetDecoder, dataContainer.mpptData()) , otherPopulator(packetDecoder, dataContainer.otherData()) { } QSerialPort serialPort; RadioCommDevice radioCommDevice; UdpMessageForwarder messageForwarder; PacketSynchronizer packetSynchronizer; PacketUnstuffer packetUnstuffer; PacketChecksumChecker packetChecksumChecker; PacketDecoder packetDecoder; BatteryFaultsPopulator batteryFaultsPopulator; BatteryPopulator batteryPopulator; CmuPopulator cmuPopulator; DriverControlsPopulator driverControlsPopulator; KeyMotorPopulator keyMotorPopulator; LightsPopulator lightsPopulator; MotorDetailsPopulator motorDetailsPopulator; MotorFaultsPopulator motorFaultsPopulator; MpptPopulator mpptPopulator; OtherPopulator otherPopulator; }; CommunicationContainer::CommunicationContainer(DataContainer& dataContainer, InfrastructureContainer& infrastructureContainer) : impl_(new CommunicationContainerPrivate(dataContainer, infrastructureContainer)) { } CommunicationContainer::~CommunicationContainer() { } I_CommDevice& CommunicationContainer::commDevice() { return impl_->radioCommDevice; } I_PacketSynchronizer& CommunicationContainer::packetSynchronizer() { return impl_->packetSynchronizer; } I_DataInjectionService& CommunicationContainer::dataInjectionService() { return impl_->packetUnstuffer; } I_PacketDecoder& CommunicationContainer::packetDecoder() { return impl_->packetDecoder; } I_PacketChecksumChecker& CommunicationContainer::packetChecksumChecker() { return impl_->packetChecksumChecker; } I_MessageForwarder& CommunicationContainer::udpMessageForwarder() { return impl_->messageForwarder; } <|endoftext|>
<commit_before>/* * File: tlos.hpp * Author: Barath Kannan * Implementation of thread-local variables with object-scoped access. * Created on 13 February 2017 7:46 PM */ #ifndef BK_CONQ_TLOS_HPP #define BK_CONQ_TLOS_HPP #include <mutex> #include <vector> #include <set> #include <thread> namespace bk_conq{ namespace details{ template <typename T, typename OWNER = void> class tlos { public: tlos(std::function<T()> defaultvalfunc = nullptr, std::function<void(T&&)> returnfunc = nullptr) : _defaultvalfunc(defaultvalfunc), _returnfunc(returnfunc), _myid(_id++), _myindx(get_index(_myid)) {} static size_t get_index(size_t myid) { std::lock_guard<std::mutex> lock(_m); size_t myindx; //check if a previous owner returned their index if (!_available.empty()) { //use that index if available myindx = _available.back(); _owners[myindx] = myid; _available.pop_back(); } else { //otherwise generate a new one myindx = _owners.size(); _owners.push_back(myid); } return myindx; } virtual ~tlos() { std::lock_guard<std::mutex> lock(_m); //invoke the returner for all thread local boxes corresponding to this index for (returner* ret : _thread_locals) { std::vector<box>& vec = (*ret)(); //if the size is not greater than the index, the thread-local object was never accessed //and hence it was never initialized if (_myindx < vec.size()) { auto& box_instance = vec.at(_myindx); //check if we've used that box if (box_instance.owner_id == _myid) { if (box_instance.returnfunc) box_instance.returnfunc(std::move(box_instance.value)); //mark as unused box_instance.owner_id = 0; } } } //relinquish the index and mark it as available for others _available.push_back(_myindx); //mark the index as unused _owners[_myindx] = 0; //if this is the last tlos instance of this type, clear some of the static space if (_available.size() == _owners.size()) { _available.clear(); _owners.clear(); } } //Returns a reference to the thread local variable corresponding to the tlos object T& get() { auto& vec = get_returner(); //resize if accessed by a class with a higher counter if (vec.size() <= _myindx) { std::lock_guard<std::mutex> lock(_m); //check again now that we're sync'd if (vec.size() <= _myindx) { vec.resize(_myindx + 1); } } //retrieve the item owned by this object instance auto& ret = vec[_myindx]; //if the owner is not set, need to apply the default value if (!ret.owner_id) { //if a default value function has been provided, use that to assign the initial value if (_defaultvalfunc) ret.value = _defaultvalfunc(); //reconfigure the id and returner //the returnerfunc is only invoked if the thread is joined and the thread_local vector has its dtor invoked //it is not necessary to invoke it here as the previous owner has already been destroyed ret.owner_id = _myid; ret.returnfunc = _returnfunc; } return ret.value; } //manually invokes the returning function for the calling thread //return value indicates that the returner was successfully invoked bool relinquish() { std::lock_guard<std::mutex> lock(_m); auto& vec = get_returner(); //if the index is not valid yet, the object was never assigned from this thread in the first place if (vec.size() <= _myindx) return false; auto& ret = vec[_myindx]; //we only want to invoke the returner if we are the owner if (ret.owner_id != _myid) return false; //check if it has been initialized if (!ret.returnfunc) return false; ret.returnfunc(std::move(ret.value)); //reset the owner id so if get() is ever called after this point, it will call the defaultvalfunc again ret.owner_id = 0; return true; } private: struct box { size_t owner_id; T value; std::function<void(T&&)> returnfunc{ nullptr }; }; class returner { private: std::vector<box> _v; public: returner() { std::lock_guard<std::mutex> lock(_m); _thread_locals.insert(this); } std::vector<box>& get() { return _v; } std::vector<box>& operator()() { return get(); } //This thread local object's dtor invokes the returnfunc for all thread-local items //whose owning object has not already gone out of scope and who have defined a _returnfunc. //It also removes the returner from the tracked set of thread local returners ~returner() { std::lock_guard<std::mutex> lock(_m); //owners size will only be less if it was flushed by a tlos dtor for (size_t i = 0; i < _v.size() && i < _owners.size(); ++i) { auto& current_id = _v.at(i); //check if a returnfunc has been defined, and //check if the object who owns the item is still valid if (current_id.returnfunc && current_id.owner_id && _owners[i] == current_id.owner_id) { current_id.returnfunc(std::move(current_id.value)); } } _thread_locals.erase(this); } }; std::vector<box>& get_returner() { //the vector of thread_local variables thread_local returner vec; return vec(); } //defines a function to assign the initial value to the retrieved value, when it is first retrieved in a unique thread in a unique object std::function<T()> _defaultvalfunc{ nullptr }; //defines a function to notify the owning object that a thread owning a thread-local instance has gone out of scope std::function<void(T&&)> _returnfunc{ nullptr }; //identifies the index of this objects U item in the thread const size_t _myindx; //uniquely identifies this object (prefer using this to pointer as another object of the same type can be given the same address) const size_t _myid; //counter for assigning the objects unique id, starting at 1 static std::atomic<size_t> _id; //vector of released box indexes static std::vector<size_t> _available; //maps box indexes to their owners id static std::vector<size_t> _owners; //provides global access to the thread local vectors static std::set<returner*> _thread_locals; static std::mutex _m; }; template <typename T, typename OWNER> std::atomic<size_t> tlos<T, OWNER>::_id = 1; template <typename T, typename OWNER> std::vector<size_t> tlos<T, OWNER>::_available; template <typename T, typename OWNER> std::vector<size_t> tlos<T, OWNER>::_owners; template <typename T, typename OWNER> std::set<typename tlos<T, OWNER>::returner*> tlos<T, OWNER>::_thread_locals; template <typename T, typename OWNER> std::mutex tlos<T, OWNER>::_m; }//namespace details }//namespace bk_conq #endif // BK_CONQ_TLOS_HPP <commit_msg>const the tlos functions<commit_after>/* * File: tlos.hpp * Author: Barath Kannan * Implementation of thread-local variables with object-scoped access. * Created on 13 February 2017 7:46 PM */ #ifndef BK_CONQ_TLOS_HPP #define BK_CONQ_TLOS_HPP #include <mutex> #include <vector> #include <set> #include <thread> namespace bk_conq{ namespace details{ template <typename T, typename OWNER = void> class tlos { public: tlos(std::function<T()> defaultvalfunc = nullptr, std::function<void(T&&)> returnfunc = nullptr) : _defaultvalfunc(defaultvalfunc), _returnfunc(returnfunc), _myid(_id++), _myindx(get_index(_myid)) {} static size_t get_index(size_t myid) { std::lock_guard<std::mutex> lock(_m); size_t myindx; //check if a previous owner returned their index if (!_available.empty()) { //use that index if available myindx = _available.back(); _owners[myindx] = myid; _available.pop_back(); } else { //otherwise generate a new one myindx = _owners.size(); _owners.push_back(myid); } return myindx; } virtual ~tlos() { std::lock_guard<std::mutex> lock(_m); //invoke the returner for all thread local boxes corresponding to this index for (returner* ret : _thread_locals) { std::vector<box>& vec = (*ret)(); //if the size is not greater than the index, the thread-local object was never accessed //and hence it was never initialized if (_myindx < vec.size()) { auto& box_instance = vec.at(_myindx); //check if we've used that box if (box_instance.owner_id == _myid) { if (box_instance.returnfunc) box_instance.returnfunc(std::move(box_instance.value)); //mark as unused box_instance.owner_id = 0; } } } //relinquish the index and mark it as available for others _available.push_back(_myindx); //mark the index as unused _owners[_myindx] = 0; //if this is the last tlos instance of this type, clear some of the static space if (_available.size() == _owners.size()) { _available.clear(); _owners.clear(); } } //Returns a reference to the thread local variable corresponding to the tlos object T& get() { auto& vec = get_returner(); //resize if accessed by a class with a higher counter if (vec.size() <= _myindx) { std::lock_guard<std::mutex> lock(_m); //check again now that we're sync'd if (vec.size() <= _myindx) { vec.resize(_myindx + 1); } } //retrieve the item owned by this object instance auto& ret = vec[_myindx]; //if the owner is not set, need to apply the default value if (!ret.owner_id) { //if a default value function has been provided, use that to assign the initial value if (_defaultvalfunc) ret.value = _defaultvalfunc(); //reconfigure the id and returner //the returnerfunc is only invoked if the thread is joined and the thread_local vector has its dtor invoked //it is not necessary to invoke it here as the previous owner has already been destroyed ret.owner_id = _myid; ret.returnfunc = _returnfunc; } return ret.value; } //manually invokes the returning function for the calling thread //return value indicates that the returner was successfully invoked bool relinquish() { std::lock_guard<std::mutex> lock(_m); auto& vec = get_returner(); //if the index is not valid yet, the object was never assigned from this thread in the first place if (vec.size() <= _myindx) return false; auto& ret = vec[_myindx]; //we only want to invoke the returner if we are the owner if (ret.owner_id != _myid) return false; //check if it has been initialized if (!ret.returnfunc) return false; ret.returnfunc(std::move(ret.value)); //reset the owner id so if get() is ever called after this point, it will call the defaultvalfunc again ret.owner_id = 0; return true; } private: struct box { size_t owner_id; T value; std::function<void(T&&)> returnfunc{ nullptr }; }; class returner { private: std::vector<box> _v; public: returner() { std::lock_guard<std::mutex> lock(_m); _thread_locals.insert(this); } std::vector<box>& get() { return _v; } std::vector<box>& operator()() { return get(); } //This thread local object's dtor invokes the returnfunc for all thread-local items //whose owning object has not already gone out of scope and who have defined a _returnfunc. //It also removes the returner from the tracked set of thread local returners ~returner() { std::lock_guard<std::mutex> lock(_m); //owners size will only be less if it was flushed by a tlos dtor for (size_t i = 0; i < _v.size() && i < _owners.size(); ++i) { auto& current_id = _v.at(i); //check if a returnfunc has been defined, and //check if the object who owns the item is still valid if (current_id.returnfunc && current_id.owner_id && _owners[i] == current_id.owner_id) { current_id.returnfunc(std::move(current_id.value)); } } _thread_locals.erase(this); } }; std::vector<box>& get_returner() { //the vector of thread_local variables thread_local returner vec; return vec(); } //defines a function to assign the initial value to the retrieved value, when it is first retrieved in a unique thread in a unique object const std::function<T()> _defaultvalfunc{ nullptr }; //defines a function to notify the owning object that a thread owning a thread-local instance has gone out of scope const std::function<void(T&&)> _returnfunc{ nullptr }; //identifies the index of this objects U item in the thread const size_t _myindx; //uniquely identifies this object (prefer using this to pointer as another object of the same type can be given the same address) const size_t _myid; //counter for assigning the objects unique id, starting at 1 static std::atomic<size_t> _id; //vector of released box indexes static std::vector<size_t> _available; //maps box indexes to their owners id static std::vector<size_t> _owners; //provides global access to the thread local vectors static std::set<returner*> _thread_locals; static std::mutex _m; }; template <typename T, typename OWNER> std::atomic<size_t> tlos<T, OWNER>::_id = 1; template <typename T, typename OWNER> std::vector<size_t> tlos<T, OWNER>::_available; template <typename T, typename OWNER> std::vector<size_t> tlos<T, OWNER>::_owners; template <typename T, typename OWNER> std::set<typename tlos<T, OWNER>::returner*> tlos<T, OWNER>::_thread_locals; template <typename T, typename OWNER> std::mutex tlos<T, OWNER>::_m; }//namespace details }//namespace bk_conq #endif // BK_CONQ_TLOS_HPP <|endoftext|>
<commit_before>#include "pattern_posture_generator_node.hpp" #include <sstream> void dumpMap(std::map<std::string, double>& map) { std::stringstream map_info; for (std::map<std::string, double>::iterator it = map.begin(), end_it = map.end(); it != end_it; it++) map_info << it->second << ':'; ROS_INFO("%s", map_info.str().c_str()); } void dumpVector(std::vector<std::string> vec) { std::string vec_info; for (std::vector<std::string>::iterator it = vec.begin(), end_it = vec.end(); it != end_it; it++) { vec_info.append(*it); vec_info.push_back(':'); } ROS_INFO("%s", vec_info.c_str()); } int main(int argc, char* argv[]) { ros::init(argc, argv, "pattern_posture_generator"); ros::NodeHandle nh("~"); PatternPostureGenerator ppg(nh); ROS_INFO("Ready getPosture and reload service."); ros::spin(); return 0; } PatternPostureGenerator::PatternPostureGenerator(){} PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) : nh(nh) { key_srv = nh.advertiseService("getPosture", &PatternPostureGenerator::getPosture, this); reload_srv = nh.advertiseService("reload", &PatternPostureGenerator::reload, this); reload(); } bool PatternPostureGenerator::reload() { if (!nh.hasParam("pattern_names")) return false; std::string pattern_names; nh.getParam("pattern_names", pattern_names); dumpVector(pattern_names); posture_datas.clear(); for (std::vector<std::string>::iterator it = pattern_names.begin(), end_it = pattern_names.end(); it != end_it; it++) { if (!nh.hasParam(*it)) continue; std::vector<double> posture; nh.getParam(*it, posture); std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[*it])); ROS_INFO("Found posture of [%s]", it->c_str()); } return true; } bool PatternPostureGenerator::reload(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res) { return reload(); } bool PatternPostureGenerator::getPosture(pattern_posture_generator::PatternPosture::Request& req, pattern_posture_generator::PatternPosture::Response& res) { if (posture_datas.find(req.name) == posture_datas.end()) return false; std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture)); return true; } <commit_msg>Fix wrong variable type of pattern_name.<commit_after>#include "pattern_posture_generator_node.hpp" #include <sstream> void dumpMap(std::map<std::string, double>& map) { std::stringstream map_info; for (std::map<std::string, double>::iterator it = map.begin(), end_it = map.end(); it != end_it; it++) map_info << it->second << ':'; ROS_INFO("%s", map_info.str().c_str()); } void dumpVector(std::vector<std::string> vec) { std::string vec_info; for (std::vector<std::string>::iterator it = vec.begin(), end_it = vec.end(); it != end_it; it++) { vec_info.append(*it); vec_info.push_back(':'); } ROS_INFO("%s", vec_info.c_str()); } int main(int argc, char* argv[]) { ros::init(argc, argv, "pattern_posture_generator"); ros::NodeHandle nh("~"); PatternPostureGenerator ppg(nh); ROS_INFO("Ready getPosture and reload service."); ros::spin(); return 0; } PatternPostureGenerator::PatternPostureGenerator(){} PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) : nh(nh) { key_srv = nh.advertiseService("getPosture", &PatternPostureGenerator::getPosture, this); reload_srv = nh.advertiseService("reload", &PatternPostureGenerator::reload, this); reload(); } bool PatternPostureGenerator::reload() { if (!nh.hasParam("pattern_names")) return false; std::vector<std::string> pattern_names; nh.getParam("pattern_names", pattern_names); dumpVector(pattern_names); posture_datas.clear(); for (std::vector<std::string>::iterator it = pattern_names.begin(), end_it = pattern_names.end(); it != end_it; it++) { if (!nh.hasParam(*it)) continue; std::vector<double> posture; nh.getParam(*it, posture); std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[*it])); ROS_INFO("Found posture of [%s]", it->c_str()); } return true; } bool PatternPostureGenerator::reload(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res) { return reload(); } bool PatternPostureGenerator::getPosture(pattern_posture_generator::PatternPosture::Request& req, pattern_posture_generator::PatternPosture::Response& res) { if (posture_datas.find(req.name) == posture_datas.end()) return false; std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture)); return true; } <|endoftext|>
<commit_before>#include "ros/ros.h" #include "pattern_posture_generator_node.hpp" int main(int argc, char* argv[]) { ros::init(argc, argv, "pattern_posture_generator"); ros::NodeHandle nh; PatternPostureGenerator ppg(nh); ROS_INFO("Ready. getPostureKey"); ros::spin(); return 0; } PatternPostureGenerator::PatternPostureGenerator(){} PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) { if (!nh.getParam("pattern", pattern_names)) return; ROS_INFO("Get map of patterns parent"); for (std::map<std::string, std::string >::iterator it = pattern_names.begin(); it != pattern_names.end(); it++) { std::vector<double> posture; if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return; std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second])); ROS_INFO(std::string("Found posture of ").append(it->second).c_str()); } key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this); } bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request& req, pattern_posture_generator::PatternKeyPosture::Response& res) { std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture)); return true; } <commit_msg>Fix presence check param & Add ehco more info<commit_after>#include "ros/ros.h" #include "pattern_posture_generator_node.hpp" void dumpMap(std::map<std::string, std::string>& map) { std::string map_info; for (std::map<std::string, std::string>::iterator it = map.begin(), end_it = map.end(); it != end_it; it++) { map_info.append(it->second); map_info.push_back(':'); } ROS_INFO("%s", map_info.c_str()); } int main(int argc, char* argv[]) { ros::init(argc, argv, "pattern_posture_generator"); ros::NodeHandle nh; PatternPostureGenerator ppg(nh); ROS_INFO("Ready. getPostureKey"); ros::spin(); return 0; } PatternPostureGenerator::PatternPostureGenerator(){} PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) { if (!nh.hasParam("pattern")) throw; nh.getParam("pattern", pattern_names); ROS_INFO("Get map of patterns parent"); dumpMap(pattern_names); for (std::map<std::string, std::string>::iterator it = pattern_names.begin(), end_it = pattern_names.end(); it != end_it; it++) { std::vector<double> posture; std::string posture_param_name = std::string("pattern/").append(it->second); nh.getParam(posture_param_name, posture); std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second])); ROS_INFO("Found posture of [%s]", it->second.c_str()); } key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this); } bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request& req, pattern_posture_generator::PatternKeyPosture::Response& res) { std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture)); return true; } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // type_traits // extension // template <typename _Tp> struct __has_operator_addressof #include <type_traits> #ifndef _LIBCPP_HAS_NO_CONSTEXPR struct A { }; struct B { constexpr B* operator&() const; }; struct D; struct C { template <class U> D operator,(U&&); }; struct E { constexpr C operator&() const; }; struct F {}; constexpr F* operator&(F const &) { return nullptr; } struct G {}; constexpr G* operator&(G &&) { return nullptr; } struct H {}; constexpr H* operator&(H const &&) { return nullptr; } struct J { constexpr J* operator&() &&; }; #endif // _LIBCPP_HAS_NO_CONSTEXPR int main() { #ifndef _LIBCPP_HAS_NO_CONSTEXPR static_assert(std::__has_operator_addressof<int>::value == false, ""); static_assert(std::__has_operator_addressof<A>::value == false, ""); static_assert(std::__has_operator_addressof<B>::value == true, ""); static_assert(std::__has_operator_addressof<E>::value == true, ""); static_assert(std::__has_operator_addressof<F>::value == true, ""); static_assert(std::__has_operator_addressof<G>::value == true, ""); static_assert(std::__has_operator_addressof<H>::value == true, ""); static_assert(std::__has_operator_addressof<J>::value == true, ""); #endif // _LIBCPP_HAS_NO_CONSTEXPR } <commit_msg>Fix a warning in the test; no functionality change<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // type_traits // extension // template <typename _Tp> struct __has_operator_addressof #include <type_traits> #ifndef _LIBCPP_HAS_NO_CONSTEXPR struct A { }; struct B { constexpr B* operator&() const; }; struct D; struct C { template <class U> D operator,(U&&); }; struct E { constexpr C operator&() const; }; struct F {}; constexpr F* operator&(F const &) { return nullptr; } struct G {}; constexpr G* operator&(G &&) { return nullptr; } struct H {}; constexpr H* operator&(H const &&) { return nullptr; } struct J { constexpr J* operator&() const &&; }; #endif // _LIBCPP_HAS_NO_CONSTEXPR int main() { #ifndef _LIBCPP_HAS_NO_CONSTEXPR static_assert(std::__has_operator_addressof<int>::value == false, ""); static_assert(std::__has_operator_addressof<A>::value == false, ""); static_assert(std::__has_operator_addressof<B>::value == true, ""); static_assert(std::__has_operator_addressof<E>::value == true, ""); static_assert(std::__has_operator_addressof<F>::value == true, ""); static_assert(std::__has_operator_addressof<G>::value == true, ""); static_assert(std::__has_operator_addressof<H>::value == true, ""); static_assert(std::__has_operator_addressof<J>::value == true, ""); #endif // _LIBCPP_HAS_NO_CONSTEXPR } <|endoftext|>
<commit_before>// FIXME: run this (and other) UBSan tests in both 32- and 64-bit modes (?). // RUN: %clangxx -fsanitize=float-cast-overflow %s -o %t // RUN: %run %t _ // RUN: %run %t 0 2>&1 | FileCheck %s --check-prefix=CHECK-0 // RUN: %run %t 1 2>&1 | FileCheck %s --check-prefix=CHECK-1 // RUN: %run %t 2 2>&1 | FileCheck %s --check-prefix=CHECK-2 // RUN: %run %t 3 2>&1 | FileCheck %s --check-prefix=CHECK-3 // RUN: %run %t 4 2>&1 | FileCheck %s --check-prefix=CHECK-4 // RUN: %run %t 5 2>&1 | FileCheck %s --check-prefix=CHECK-5 // RUN: %run %t 6 2>&1 | FileCheck %s --check-prefix=CHECK-6 // FIXME: %run %t 7 2>&1 | FileCheck %s --check-prefix=CHECK-7 // RUN: not %run %t 8 2>&1 | FileCheck %s --check-prefix=CHECK-8 // RUN: not %run %t 9 2>&1 | FileCheck %s --check-prefix=CHECK-9 // This test assumes float and double are IEEE-754 single- and double-precision. // XFAIL: armv7l-unknown-linux-gnueabihf #if defined(__APPLE__) # include <machine/endian.h> # define BYTE_ORDER __DARWIN_BYTE_ORDER # define BIG_ENDIAN __DARWIN_BIG_ENDIAN # define LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN #else # include <endian.h> # define BYTE_ORDER __BYTE_ORDER # define BIG_ENDIAN __BIG_ENDIAN # define LITTLE_ENDIAN __LITTLE_ENDIAN #endif // __APPLE__ #include <stdint.h> #include <stdio.h> #include <string.h> float Inf; float NaN; int main(int argc, char **argv) { float MaxFloatRepresentableAsInt = 0x7fffff80; (int)MaxFloatRepresentableAsInt; // ok (int)-MaxFloatRepresentableAsInt; // ok float MinFloatRepresentableAsInt = -0x7fffffff - 1; (int)MinFloatRepresentableAsInt; // ok float MaxFloatRepresentableAsUInt = 0xffffff00u; (unsigned int)MaxFloatRepresentableAsUInt; // ok #ifdef __SIZEOF_INT128__ unsigned __int128 FloatMaxAsUInt128 = -((unsigned __int128)1 << 104); (void)(float)FloatMaxAsUInt128; // ok #endif float NearlyMinusOne = -0.99999; unsigned Zero = NearlyMinusOne; // ok // Build a '+Inf'. #if BYTE_ORDER == LITTLE_ENDIAN char InfVal[] = { 0x00, 0x00, 0x80, 0x7f }; #else char InfVal[] = { 0x7f, 0x80, 0x00, 0x00 }; #endif float Inf; memcpy(&Inf, InfVal, 4); // Build a 'NaN'. #if BYTE_ORDER == LITTLE_ENDIAN char NaNVal[] = { 0x01, 0x00, 0x80, 0x7f }; #else char NaNVal[] = { 0x7f, 0x80, 0x00, 0x01 }; #endif float NaN; memcpy(&NaN, NaNVal, 4); double DblInf = (double)Inf; // ok switch (argv[1][0]) { // FIXME: Produce a source location for these checks and test for it here. // Floating point -> integer overflow. case '0': // Note that values between 0x7ffffe00 and 0x80000000 may or may not // successfully round-trip, depending on the rounding mode. // CHECK-0: runtime error: value 2.14748{{.*}} is outside the range of representable values of type 'int' return MaxFloatRepresentableAsInt + 0x80; case '1': // CHECK-1: runtime error: value -2.14748{{.*}} is outside the range of representable values of type 'int' return MinFloatRepresentableAsInt - 0x100; case '2': // CHECK-2: runtime error: value -1 is outside the range of representable values of type 'unsigned int' return (unsigned)-1.0; case '3': // CHECK-3: runtime error: value 4.2949{{.*}} is outside the range of representable values of type 'unsigned int' return (unsigned)(MaxFloatRepresentableAsUInt + 0x100); case '4': // CHECK-4: runtime error: value {{.*}} is outside the range of representable values of type 'int' return Inf; case '5': // CHECK-5: runtime error: value {{.*}} is outside the range of representable values of type 'int' return NaN; // Integer -> floating point overflow. case '6': // CHECK-6: {{runtime error: value 0xffffff00000000000000000000000001 is outside the range of representable values of type 'float'|__int128 not supported}} #ifdef __SIZEOF_INT128__ return (float)(FloatMaxAsUInt128 + 1); #else puts("__int128 not supported"); return 0; #endif // FIXME: The backend cannot lower __fp16 operations on x86 yet. //case '7': // (__fp16)65504; // ok // // CHECK-7: runtime error: value 65505 is outside the range of representable values of type '__fp16' // return (__fp16)65505; // Floating point -> floating point overflow. case '8': // CHECK-8: runtime error: value 1e+39 is outside the range of representable values of type 'float' return (float)1e39; case '9': volatile long double ld = 300.0; // CHECK-9: runtime error: value 300 is outside the range of representable values of type 'char' char c = ld; return c; } } <commit_msg>[UBSan] Fix UBSan testcase for float->int conversion after LLVM r219542.<commit_after>// FIXME: run this (and other) UBSan tests in both 32- and 64-bit modes (?). // RUN: %clangxx -fsanitize=float-cast-overflow %s -o %t // RUN: %run %t _ // RUN: %run %t 0 2>&1 | FileCheck %s --check-prefix=CHECK-0 // RUN: %run %t 1 2>&1 | FileCheck %s --check-prefix=CHECK-1 // RUN: %run %t 2 2>&1 | FileCheck %s --check-prefix=CHECK-2 // RUN: %run %t 3 2>&1 | FileCheck %s --check-prefix=CHECK-3 // RUN: %run %t 4 2>&1 | FileCheck %s --check-prefix=CHECK-4 // RUN: %run %t 5 2>&1 | FileCheck %s --check-prefix=CHECK-5 // RUN: %run %t 6 2>&1 | FileCheck %s --check-prefix=CHECK-6 // FIXME: %run %t 7 2>&1 | FileCheck %s --check-prefix=CHECK-7 // RUN: not %run %t 8 2>&1 | FileCheck %s --check-prefix=CHECK-8 // RUN: not %run %t 9 2>&1 | FileCheck %s --check-prefix=CHECK-9 // This test assumes float and double are IEEE-754 single- and double-precision. // XFAIL: armv7l-unknown-linux-gnueabihf #if defined(__APPLE__) # include <machine/endian.h> # define BYTE_ORDER __DARWIN_BYTE_ORDER # define BIG_ENDIAN __DARWIN_BIG_ENDIAN # define LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN #else # include <endian.h> # define BYTE_ORDER __BYTE_ORDER # define BIG_ENDIAN __BIG_ENDIAN # define LITTLE_ENDIAN __LITTLE_ENDIAN #endif // __APPLE__ #include <stdint.h> #include <stdio.h> #include <string.h> float Inf; float NaN; int main(int argc, char **argv) { float MaxFloatRepresentableAsInt = 0x7fffff80; (int)MaxFloatRepresentableAsInt; // ok (int)-MaxFloatRepresentableAsInt; // ok float MinFloatRepresentableAsInt = -0x7fffffff - 1; (int)MinFloatRepresentableAsInt; // ok float MaxFloatRepresentableAsUInt = 0xffffff00u; (unsigned int)MaxFloatRepresentableAsUInt; // ok #ifdef __SIZEOF_INT128__ unsigned __int128 FloatMaxAsUInt128 = -((unsigned __int128)1 << 104); (void)(float)FloatMaxAsUInt128; // ok #endif float NearlyMinusOne = -0.99999; unsigned Zero = NearlyMinusOne; // ok // Build a '+Inf'. #if BYTE_ORDER == LITTLE_ENDIAN char InfVal[] = { 0x00, 0x00, 0x80, 0x7f }; #else char InfVal[] = { 0x7f, 0x80, 0x00, 0x00 }; #endif float Inf; memcpy(&Inf, InfVal, 4); // Build a 'NaN'. #if BYTE_ORDER == LITTLE_ENDIAN char NaNVal[] = { 0x01, 0x00, 0x80, 0x7f }; #else char NaNVal[] = { 0x7f, 0x80, 0x00, 0x01 }; #endif float NaN; memcpy(&NaN, NaNVal, 4); double DblInf = (double)Inf; // ok switch (argv[1][0]) { // FIXME: Produce a source location for these checks and test for it here. // Floating point -> integer overflow. case '0': // Note that values between 0x7ffffe00 and 0x80000000 may or may not // successfully round-trip, depending on the rounding mode. // CHECK-0: runtime error: value 2.14748{{.*}} is outside the range of representable values of type 'int' return MaxFloatRepresentableAsInt + 0x80; case '1': // CHECK-1: runtime error: value -2.14748{{.*}} is outside the range of representable values of type 'int' return MinFloatRepresentableAsInt - 0x100; case '2': { // CHECK-2: runtime error: value -1 is outside the range of representable values of type 'unsigned int' volatile float f = -1.0; volatile unsigned u = (unsigned)f; return 0; } case '3': // CHECK-3: runtime error: value 4.2949{{.*}} is outside the range of representable values of type 'unsigned int' return (unsigned)(MaxFloatRepresentableAsUInt + 0x100); case '4': // CHECK-4: runtime error: value {{.*}} is outside the range of representable values of type 'int' return Inf; case '5': // CHECK-5: runtime error: value {{.*}} is outside the range of representable values of type 'int' return NaN; // Integer -> floating point overflow. case '6': // CHECK-6: {{runtime error: value 0xffffff00000000000000000000000001 is outside the range of representable values of type 'float'|__int128 not supported}} #ifdef __SIZEOF_INT128__ return (float)(FloatMaxAsUInt128 + 1); #else puts("__int128 not supported"); return 0; #endif // FIXME: The backend cannot lower __fp16 operations on x86 yet. //case '7': // (__fp16)65504; // ok // // CHECK-7: runtime error: value 65505 is outside the range of representable values of type '__fp16' // return (__fp16)65505; // Floating point -> floating point overflow. case '8': // CHECK-8: runtime error: value 1e+39 is outside the range of representable values of type 'float' return (float)1e39; case '9': volatile long double ld = 300.0; // CHECK-9: runtime error: value 300 is outside the range of representable values of type 'char' char c = ld; return c; } } <|endoftext|>
<commit_before>// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // All Rights Reserved. // // Author: Daniel Ford #include "sampler.h" #include <algorithm> // For min() #include <cmath> using std::min; // The approximate gap in bytes between sampling actions. // I.e., we take one sample approximately once every // tcmalloc_sample_parameter bytes of allocation // i.e. about once every 512KB. #ifdef NO_TCMALLOC_SAMPLES DEFINE_int64(tcmalloc_sample_parameter, 0, "Unused: code is compiled with NO_TCMALLOC_SAMPLES"); #else DEFINE_int64(tcmalloc_sample_parameter, EnvToInt64("TCMALLOC_SAMPLE_PARAMETER", 1<<19), "The approximate gap in bytes between sampling actions. " "This must be between 1 and 1<<58."); // Note: there are other places in this file where the number 19 occurs. #endif namespace tcmalloc { // Statics for Sampler double Sampler::log_table_[1<<kFastlogNumBits]; // Populate the lookup table for FastLog2. // This approximates the log2 curve with a step function. // Steps have height equal to log2 of the mid-point of the step. void Sampler::PopulateFastLog2Table() { for (int i = 0; i < (1<<kFastlogNumBits); i++) { log_table_[i] = (log(1.0 + static_cast<double>(i+0.5)/(1<<kFastlogNumBits)) / log(2.0)); } } int Sampler::GetSamplePeriod() { return FLAGS_tcmalloc_sample_parameter; } // Run this before using your sampler void Sampler::Init(uint32_t seed) { // Initialize PRNG if (seed != 0) { rnd_ = seed; } else { rnd_ = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this)); if (rnd_ == 0) { rnd_ = 1; } } // Step it forward 20 times for good measure for (int i = 0; i < 20; i++) { rnd_ = NextRandom(rnd_); } // Initialize counter bytes_until_sample_ = PickNextSamplingPoint(); } // Initialize the Statics for the Sampler class void Sampler::InitStatics() { PopulateFastLog2Table(); } // Generates a geometric variable with the specified mean (512K by default). // This is done by generating a random number between 0 and 1 and applying // the inverse cumulative distribution function for an exponential. // Specifically: Let m be the inverse of the sample period, then // the probability distribution function is m*exp(-mx) so the CDF is // p = 1 - exp(-mx), so // q = 1 - p = exp(-mx) // log_e(q) = -mx // -log_e(q)/m = x // log_2(q) * (-log_e(2) * 1/m) = x // In the code, q is actually in the range 1 to 2**26, hence the -26 below size_t Sampler::PickNextSamplingPoint() { rnd_ = NextRandom(rnd_); // Take the top 26 bits as the random number // (This plus the 1<<58 sampling bound give a max possible step of // 5194297183973780480 bytes.) const uint64_t prng_mod_power = 48; // Number of bits in prng // The uint32_t cast is to prevent a (hard-to-reproduce) NAN // under piii debug for some binaries. double q = static_cast<uint32_t>(rnd_ >> (prng_mod_power - 26)) + 1.0; // Put the computed p-value through the CDF of a geometric. // For faster performance (save ~1/20th exec time), replace // min(0.0, FastLog2(q) - 26) by (Fastlog2(q) - 26.000705) // The value 26.000705 is used rather than 26 to compensate // for inaccuracies in FastLog2 which otherwise result in a // negative answer. return static_cast<size_t>(min(0.0, (FastLog2(q) - 26)) * (-log(2.0) * FLAGS_tcmalloc_sample_parameter) + 1); } } // namespace tcmalloc <commit_msg>Disable TCMalloc heap sampling. BUG=38960,40149<commit_after>// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // All Rights Reserved. // // Author: Daniel Ford #include "sampler.h" #include <algorithm> // For min() #include <cmath> using std::min; // The approximate gap in bytes between sampling actions. // I.e., we take one sample approximately once every // tcmalloc_sample_parameter bytes of allocation // i.e. about once every 512KB. #ifdef NO_TCMALLOC_SAMPLES DEFINE_int64(tcmalloc_sample_parameter, 0, "Unused: code is compiled with NO_TCMALLOC_SAMPLES"); #else DEFINE_int64(tcmalloc_sample_parameter, EnvToInt64("TCMALLOC_SAMPLE_PARAMETER", 0), "The approximate gap in bytes between sampling actions. " "This must be between 1 and 1<<58."); // Note: there are other places in this file where the number 19 occurs. #endif namespace tcmalloc { // Statics for Sampler double Sampler::log_table_[1<<kFastlogNumBits]; // Populate the lookup table for FastLog2. // This approximates the log2 curve with a step function. // Steps have height equal to log2 of the mid-point of the step. void Sampler::PopulateFastLog2Table() { for (int i = 0; i < (1<<kFastlogNumBits); i++) { log_table_[i] = (log(1.0 + static_cast<double>(i+0.5)/(1<<kFastlogNumBits)) / log(2.0)); } } int Sampler::GetSamplePeriod() { return FLAGS_tcmalloc_sample_parameter; } // Run this before using your sampler void Sampler::Init(uint32_t seed) { // Initialize PRNG if (seed != 0) { rnd_ = seed; } else { rnd_ = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this)); if (rnd_ == 0) { rnd_ = 1; } } // Step it forward 20 times for good measure for (int i = 0; i < 20; i++) { rnd_ = NextRandom(rnd_); } // Initialize counter bytes_until_sample_ = PickNextSamplingPoint(); } // Initialize the Statics for the Sampler class void Sampler::InitStatics() { PopulateFastLog2Table(); } // Generates a geometric variable with the specified mean (512K by default). // This is done by generating a random number between 0 and 1 and applying // the inverse cumulative distribution function for an exponential. // Specifically: Let m be the inverse of the sample period, then // the probability distribution function is m*exp(-mx) so the CDF is // p = 1 - exp(-mx), so // q = 1 - p = exp(-mx) // log_e(q) = -mx // -log_e(q)/m = x // log_2(q) * (-log_e(2) * 1/m) = x // In the code, q is actually in the range 1 to 2**26, hence the -26 below size_t Sampler::PickNextSamplingPoint() { rnd_ = NextRandom(rnd_); // Take the top 26 bits as the random number // (This plus the 1<<58 sampling bound give a max possible step of // 5194297183973780480 bytes.) const uint64_t prng_mod_power = 48; // Number of bits in prng // The uint32_t cast is to prevent a (hard-to-reproduce) NAN // under piii debug for some binaries. double q = static_cast<uint32_t>(rnd_ >> (prng_mod_power - 26)) + 1.0; // Put the computed p-value through the CDF of a geometric. // For faster performance (save ~1/20th exec time), replace // min(0.0, FastLog2(q) - 26) by (Fastlog2(q) - 26.000705) // The value 26.000705 is used rather than 26 to compensate // for inaccuracies in FastLog2 which otherwise result in a // negative answer. return static_cast<size_t>(min(0.0, (FastLog2(q) - 26)) * (-log(2.0) * FLAGS_tcmalloc_sample_parameter) + 1); } } // namespace tcmalloc <|endoftext|>
<commit_before>/* * * Copyright 2008-2010 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrust/random/normal_distribution.h> #include <thrust/random/uniform_real_distribution.h> #include <thrust/detail/cstdint.h> #include <thrust/detail/integer_traits.h> namespace thrust { namespace random { namespace experimental { template<typename RealType> normal_distribution<RealType> ::normal_distribution(RealType a, RealType b) :m_param(a,b) { } // end normal_distribution::normal_distribution() template<typename RealType> normal_distribution<RealType> ::normal_distribution(const param_type &parm) :m_param(parm) { } // end normal_distribution::normal_distribution() template<typename RealType> void normal_distribution<RealType> ::reset(void) { } // end normal_distribution::reset() template<typename RealType> template<typename UniformRandomNumberGenerator> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::operator()(UniformRandomNumberGenerator &urng) { return operator()(urng, m_param); } // end normal_distribution::operator()() template<typename RealType> template<typename UniformRandomNumberGenerator> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::operator()(UniformRandomNumberGenerator &urng, const param_type &parm) { typedef typename UniformRandomNumberGenerator::result_type uint_type; const uint_type urng_range = UniformRandomNumberGenerator::max - UniformRandomNumberGenerator::min; // Constants for conversion const result_type S1 = static_cast<result_type>(1) / urng_range; const result_type S2 = S1 / 2; result_type S3 = static_cast<result_type>(-1.4142135623730950488016887242097); // -sqrt(2) // Get the integer value uint_type u = urng() - UniformRandomNumberGenerator::min; // Ensure the conversion to float will give a value in the range [0,0.5) if(u > (urng_range / 2)) { u = urng_range - u; S3 = -S3; } // Convert to floating point in [0,0.5) result_type p = u*S1 + S2; // Apply inverse error function return parm.first + parm.second * S3 * erfcinv(2 * p); // // sample [0,1) // thrust::uniform_real_distribution<result_type> u01; // result_type z = u01(urng); // // result_type S3 = static_cast<result_type>(-1.4142135623730950488016887242097); // -sqrt(2) // // if(z > 0.5) // { // z = 1.0f - z; // S3 = -S3; // } // // // Apply inverse error function // return parm.first + parm.second * S3 * erfcinv(2 * z); } // end normal_distribution::operator()() template<typename RealType> typename normal_distribution<RealType>::param_type normal_distribution<RealType> ::param(void) const { return m_param; } // end normal_distribution::param() template<typename RealType> void normal_distribution<RealType> ::param(const param_type &parm) { m_param = parm; } // end normal_distribution::param() template<typename RealType> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::min(void) const { // XXX this solution is pretty terrible const thrust::detail::uint32_t inf_as_int = 0x7f800000u; const float inf = *reinterpret_cast<const float*>(&inf_as_int); return result_type(-inf); } // end normal_distribution::min() template<typename RealType> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::max(void) const { // XXX this solution is pretty terrible const thrust::detail::uint32_t inf_as_int = 0x7f800000u; const float inf = *reinterpret_cast<const float*>(&inf_as_int); return result_type(inf); } // end normal_distribution::max() template<typename RealType> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::mean(void) const { return m_param.first; } // end normal_distribution::mean() template<typename RealType> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::stddev(void) const { return m_param.second; } // end normal_distribution::stddev() template<typename RealType> bool normal_distribution<RealType> ::equal(const normal_distribution &rhs) const { return m_param == rhs.param(); } template<typename RealType> template<typename CharT, typename Traits> std::basic_ostream<CharT,Traits>& normal_distribution<RealType> ::stream_out(std::basic_ostream<CharT,Traits> &os) const { typedef std::basic_ostream<CharT,Traits> ostream_type; typedef typename ostream_type::ios_base ios_base; // save old flags and fill character const typename ios_base::fmtflags flags = os.flags(); const CharT fill = os.fill(); const CharT space = os.widen(' '); os.flags(ios_base::dec | ios_base::fixed | ios_base::left); os.fill(space); os << mean() << space << stddev(); // restore old flags and fill character os.flags(flags); os.fill(fill); return os; } template<typename RealType> template<typename CharT, typename Traits> std::basic_istream<CharT,Traits>& normal_distribution<RealType> ::stream_in(std::basic_istream<CharT,Traits> &is) { typedef std::basic_istream<CharT,Traits> istream_type; typedef typename istream_type::ios_base ios_base; // save old flags const typename ios_base::fmtflags flags = is.flags(); is.flags(ios_base::skipws); is >> m_param.first >> m_param.second; // restore old flags is.flags(flags); return is; } template<typename RealType> bool operator==(const normal_distribution<RealType> &lhs, const normal_distribution<RealType> &rhs) { return thrust::random::detail::random_core_access::equal(lhs,rhs); } template<typename RealType> bool operator!=(const normal_distribution<RealType> &lhs, const normal_distribution<RealType> &rhs) { return !(lhs == rhs); } template<typename RealType, typename CharT, typename Traits> std::basic_ostream<CharT,Traits>& operator<<(std::basic_ostream<CharT,Traits> &os, const normal_distribution<RealType> &d) { return thrust::random::detail::random_core_access::stream_out(os,d); } template<typename RealType, typename CharT, typename Traits> std::basic_istream<CharT,Traits>& operator>>(std::basic_istream<CharT,Traits> &is, normal_distribution<RealType> &d) { return thrust::random::detail::random_core_access::stream_in(is,d); } } // end experimental } // end random } // end thrust <commit_msg>Eliminate commented-out code from normal_distribution's generation function.<commit_after>/* * * Copyright 2008-2010 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrust/random/normal_distribution.h> #include <thrust/random/uniform_real_distribution.h> #include <thrust/detail/cstdint.h> #include <thrust/detail/integer_traits.h> namespace thrust { namespace random { namespace experimental { template<typename RealType> normal_distribution<RealType> ::normal_distribution(RealType a, RealType b) :m_param(a,b) { } // end normal_distribution::normal_distribution() template<typename RealType> normal_distribution<RealType> ::normal_distribution(const param_type &parm) :m_param(parm) { } // end normal_distribution::normal_distribution() template<typename RealType> void normal_distribution<RealType> ::reset(void) { } // end normal_distribution::reset() template<typename RealType> template<typename UniformRandomNumberGenerator> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::operator()(UniformRandomNumberGenerator &urng) { return operator()(urng, m_param); } // end normal_distribution::operator()() template<typename RealType> template<typename UniformRandomNumberGenerator> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::operator()(UniformRandomNumberGenerator &urng, const param_type &parm) { typedef typename UniformRandomNumberGenerator::result_type uint_type; const uint_type urng_range = UniformRandomNumberGenerator::max - UniformRandomNumberGenerator::min; // Constants for conversion const result_type S1 = static_cast<result_type>(1) / urng_range; const result_type S2 = S1 / 2; result_type S3 = static_cast<result_type>(-1.4142135623730950488016887242097); // -sqrt(2) // Get the integer value uint_type u = urng() - UniformRandomNumberGenerator::min; // Ensure the conversion to float will give a value in the range [0,0.5) if(u > (urng_range / 2)) { u = urng_range - u; S3 = -S3; } // Convert to floating point in [0,0.5) result_type p = u*S1 + S2; // Apply inverse error function return parm.first + parm.second * S3 * erfcinv(2 * p); } // end normal_distribution::operator()() template<typename RealType> typename normal_distribution<RealType>::param_type normal_distribution<RealType> ::param(void) const { return m_param; } // end normal_distribution::param() template<typename RealType> void normal_distribution<RealType> ::param(const param_type &parm) { m_param = parm; } // end normal_distribution::param() template<typename RealType> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::min(void) const { // XXX this solution is pretty terrible const thrust::detail::uint32_t inf_as_int = 0x7f800000u; const float inf = *reinterpret_cast<const float*>(&inf_as_int); return result_type(-inf); } // end normal_distribution::min() template<typename RealType> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::max(void) const { // XXX this solution is pretty terrible const thrust::detail::uint32_t inf_as_int = 0x7f800000u; const float inf = *reinterpret_cast<const float*>(&inf_as_int); return result_type(inf); } // end normal_distribution::max() template<typename RealType> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::mean(void) const { return m_param.first; } // end normal_distribution::mean() template<typename RealType> typename normal_distribution<RealType>::result_type normal_distribution<RealType> ::stddev(void) const { return m_param.second; } // end normal_distribution::stddev() template<typename RealType> bool normal_distribution<RealType> ::equal(const normal_distribution &rhs) const { return m_param == rhs.param(); } template<typename RealType> template<typename CharT, typename Traits> std::basic_ostream<CharT,Traits>& normal_distribution<RealType> ::stream_out(std::basic_ostream<CharT,Traits> &os) const { typedef std::basic_ostream<CharT,Traits> ostream_type; typedef typename ostream_type::ios_base ios_base; // save old flags and fill character const typename ios_base::fmtflags flags = os.flags(); const CharT fill = os.fill(); const CharT space = os.widen(' '); os.flags(ios_base::dec | ios_base::fixed | ios_base::left); os.fill(space); os << mean() << space << stddev(); // restore old flags and fill character os.flags(flags); os.fill(fill); return os; } template<typename RealType> template<typename CharT, typename Traits> std::basic_istream<CharT,Traits>& normal_distribution<RealType> ::stream_in(std::basic_istream<CharT,Traits> &is) { typedef std::basic_istream<CharT,Traits> istream_type; typedef typename istream_type::ios_base ios_base; // save old flags const typename ios_base::fmtflags flags = is.flags(); is.flags(ios_base::skipws); is >> m_param.first >> m_param.second; // restore old flags is.flags(flags); return is; } template<typename RealType> bool operator==(const normal_distribution<RealType> &lhs, const normal_distribution<RealType> &rhs) { return thrust::random::detail::random_core_access::equal(lhs,rhs); } template<typename RealType> bool operator!=(const normal_distribution<RealType> &lhs, const normal_distribution<RealType> &rhs) { return !(lhs == rhs); } template<typename RealType, typename CharT, typename Traits> std::basic_ostream<CharT,Traits>& operator<<(std::basic_ostream<CharT,Traits> &os, const normal_distribution<RealType> &d) { return thrust::random::detail::random_core_access::stream_out(os,d); } template<typename RealType, typename CharT, typename Traits> std::basic_istream<CharT,Traits>& operator>>(std::basic_istream<CharT,Traits> &is, normal_distribution<RealType> &d) { return thrust::random::detail::random_core_access::stream_in(is,d); } } // end experimental } // end random } // end thrust <|endoftext|>
<commit_before>/* * */ #include <stdio.h> #include "sync.h" #include "topo.h" #include "mp.h" #include "measurement_framework.h" #include <pthread.h> #include <unistd.h> #include <vector> #include "model_defs.h" #include "barrier.h" #ifdef PARLIB #include "mcs.h" #endif //#define SEND7 #ifdef BARRELFISH #include <barrelfish/barrelfish.h> #include <posixcompat.h> #endif __thread struct sk_measurement m; __thread struct sk_measurement m2; unsigned num_threads; #define NUM_RUNS 100000 //50 // 10000 // Tested up to 1.000.000 #define NUM_RESULTS 1000 pthread_barrier_t ab_barrier; #define TOPO_NAME(x,y) sprintf(x, "%s_%s", y, topo_get_name()); mcs_barrier_t mcs_b; static void* mcs_barrier(void* a) { coreid_t tid = *((int*) a); __thread_init(tid, num_threads); // will bind threads cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS); char outname[1024]; TOPO_NAME(outname, "mcs-barrier"); sk_m_init(&m, NUM_RESULTS, outname, buf); sk_m_restart_tsc(&m); for (unsigned i=0; i<NUM_RUNS; i++) { mcs_barrier_wait(&mcs_b, tid); } sk_m_add(&m); if (get_thread_id() == get_sequentializer()) { sk_m_print(&m); } return NULL; } static void* barrier(void* a) { coreid_t tid = *((int*) a); __thread_init(tid, num_threads); cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS); char outname[1024]; TOPO_NAME(outname, "syc-barrier"); sk_m_init(&m, NUM_RESULTS, outname, buf); sk_m_restart_tsc(&m); for (int epoch=0; epoch<NUM_RUNS; epoch++) { shl_hybrid_barrier(NULL); } sk_m_add(&m); if (get_thread_id() == get_sequentializer()) { sk_m_print(&m); } __thread_end(); return NULL; } static void* barrier0(void* a) { coreid_t tid = *((int*) a); __thread_init(tid, num_threads); cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS); char outname[1024]; TOPO_NAME(outname, "syc-barrier0"); sk_m_init(&m, NUM_RESULTS, outname, buf); sk_m_restart_tsc(&m); for (int epoch=0; epoch<NUM_RUNS; epoch++) { shl_hybrid_barrier0(NULL); } sk_m_add(&m); if (get_thread_id() == get_sequentializer()) { sk_m_print(&m); } __thread_end(); return NULL; } #define NUM_EXP 3 #define max(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a > _b ? _a : _b; }) int main(int argc, char **argv) { unsigned nthreads = sysconf(_SC_NPROCESSORS_CONF); __sync_init(nthreads, true); num_threads = get_num_threads(); mcs_barrier_init(&mcs_b, num_threads); pthread_barrier_init(&ab_barrier, NULL, num_threads); typedef void* (worker_func_t)(void*); worker_func_t* workers[NUM_EXP] = { &mcs_barrier, &barrier, &barrier0, }; const char *labels[NUM_EXP] = { "MCS barrier", "libsync barrier", "libsync barrier0" }; pthread_t ptds[num_threads]; int tids[num_threads]; printf("%d models\n", max(1U, (topo_num_topos()-1))); for (unsigned e=0; e<max(1U, (topo_num_topos()-1)); e++) { for (int j=0; j<NUM_EXP; j++) { printf("----------------------------------------\n"); printf("Executing experiment %d - %s\n", (j+1), labels[j]); printf("----------------------------------------\n"); // Yield to reduce the risk of getting de-scheduled later sched_yield(); // Create for (unsigned i=1; i<num_threads; i++) { tids[i] = i; pthread_create(ptds+i, NULL, workers[j], (void*) (tids+i)); } // Master thread executes work for node 0 tids[0] = 0; workers[j]((void*) (tids+0)); // Join for (unsigned i=1; i<num_threads; i++) { pthread_join(ptds[i], NULL); } } if( e<topo_num_topos()-1) switch_topo(); } pthread_barrier_destroy(&ab_barrier); } <commit_msg>bench: Don't use hybrid barriers, they are slower<commit_after>/* * */ #include <stdio.h> #include "sync.h" #include "topo.h" #include "mp.h" #include "measurement_framework.h" #include <pthread.h> #include <unistd.h> #include <vector> #include "model_defs.h" #include "barrier.h" #ifdef PARLIB #include "mcs.h" #endif //#define SEND7 #ifdef BARRELFISH #include <barrelfish/barrelfish.h> #include <posixcompat.h> #endif __thread struct sk_measurement m; __thread struct sk_measurement m2; unsigned num_threads; #define NUM_RUNS 100000 //50 // 10000 // Tested up to 1.000.000 #define NUM_RESULTS 1000 pthread_barrier_t ab_barrier; #define TOPO_NAME(x,y) sprintf(x, "%s_%s", y, topo_get_name()); mcs_barrier_t mcs_b; static void* mcs_barrier(void* a) { coreid_t tid = *((int*) a); __thread_init(tid, num_threads); // will bind threads cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS); char outname[1024]; TOPO_NAME(outname, "mcs-barrier"); sk_m_init(&m, NUM_RESULTS, outname, buf); sk_m_restart_tsc(&m); for (unsigned i=0; i<NUM_RUNS; i++) { mcs_barrier_wait(&mcs_b, tid); } sk_m_add(&m); if (get_thread_id() == get_sequentializer()) { sk_m_print(&m); } return NULL; } static void* barrier(void* a) { coreid_t tid = *((int*) a); __thread_init(tid, num_threads); cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS); char outname[1024]; TOPO_NAME(outname, "syc-barrier"); sk_m_init(&m, NUM_RESULTS, outname, buf); sk_m_restart_tsc(&m); for (int epoch=0; epoch<NUM_RUNS; epoch++) { #ifdef HYB shl_hybrid_barrier(NULL); #else mp_barrier(NULL); #endif } sk_m_add(&m); if (get_thread_id() == get_sequentializer()) { sk_m_print(&m); } __thread_end(); return NULL; } static void* barrier0(void* a) { coreid_t tid = *((int*) a); __thread_init(tid, num_threads); cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS); char outname[1024]; TOPO_NAME(outname, "syc-barrier0"); sk_m_init(&m, NUM_RESULTS, outname, buf); sk_m_restart_tsc(&m); for (int epoch=0; epoch<NUM_RUNS; epoch++) { #ifdef HYB shl_hybrid_barrier0(NULL); #else mp_barrier0(); #endif } sk_m_add(&m); if (get_thread_id() == get_sequentializer()) { sk_m_print(&m); } __thread_end(); return NULL; } #define NUM_EXP 3 #define max(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a > _b ? _a : _b; }) int main(int argc, char **argv) { unsigned nthreads = sysconf(_SC_NPROCESSORS_CONF); __sync_init(nthreads, true); num_threads = get_num_threads(); mcs_barrier_init(&mcs_b, num_threads); pthread_barrier_init(&ab_barrier, NULL, num_threads); typedef void* (worker_func_t)(void*); worker_func_t* workers[NUM_EXP] = { &mcs_barrier, &barrier, &barrier0, }; const char *labels[NUM_EXP] = { "MCS barrier", "libsync barrier", "libsync barrier0" }; pthread_t ptds[num_threads]; int tids[num_threads]; printf("%d models\n", max(1U, (topo_num_topos()-1))); for (unsigned e=0; e<max(1U, (topo_num_topos()-1)); e++) { for (int j=0; j<NUM_EXP; j++) { printf("----------------------------------------\n"); printf("Executing experiment %d - %s\n", (j+1), labels[j]); printf("----------------------------------------\n"); // Yield to reduce the risk of getting de-scheduled later sched_yield(); // Create for (unsigned i=1; i<num_threads; i++) { tids[i] = i; pthread_create(ptds+i, NULL, workers[j], (void*) (tids+i)); } // Master thread executes work for node 0 tids[0] = 0; workers[j]((void*) (tids+0)); // Join for (unsigned i=1; i<num_threads; i++) { pthread_join(ptds[i], NULL); } } if( e<topo_num_topos()-1) switch_topo(); } pthread_barrier_destroy(&ab_barrier); } <|endoftext|>
<commit_before>#include <string> #include <cstring> #include <cassert> #include <cmath> #include <unordered_map> #include <unordered_set> #include <algorithm> #include <iostream> #include <fstream> #include <sstream> #include <getopt.h> #include "rolling.h" #include "city.h" /* as per instructions at top of stb_image_write.h */ #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" using namespace std; #define PROGRAM "collision" static const char USAGE_MESSAGE[] = "Usage:" PROGRAM " [OPTIONS] [FASTA]...\n" "Measure number of hash collisions using CityHash64 or rolling hash.\n" "K-mers from [FASTA] are hashed to positions within a fixed-size\n" "window (using the modulus operator).\n" "\n" "Options:\n" " -d, --max-density N stop hashing k-mers when\n" " DISTINCT_KMERS / WINDOW_SIZE > N [0.05]\n" " -h, --help show this message\n" " -H, --hash HASH hash function to use ('city' or 'rolling')\n" " [rolling]\n" " -k, --kmer-size size of k-mer [20]\n" " -p, --png FILE write bitmap of hash positions\n" " to FILE; dimensions of output PNG are\n" " approximately sqrt(WINDOW_SIZE) by \n" " sqrt(WINDOW_SIZE)\n" " -P, --progress-step N show progress message after hashing\n" " every N k-mers [10000]\n" " -v, --verbose show progress messages\n" " -w, --window-size N window size; this should normally\n" " be a prime number [1048573]\n"; namespace opt { static float maxDensity = 0.05f; static int help = 0; static string hashFunc("rolling"); static unsigned k = 20; static string pngPath; static size_t progressStep = 10000; static int verbose = 0; static size_t windowSize = 1048573; } static const char shortopts[] = "d:hH:k:p:P:vw:"; static const struct option longopts[] = { { "max-density", required_argument, NULL, 'd' }, { "help", no_argument, NULL, 'h' }, { "hash", required_argument, NULL, 'H' }, { "kmer-size", required_argument, NULL, 'k' }, { "png", required_argument, NULL, 'p' }, { "progress-step", required_argument, NULL, 'P' }, { "verbose", no_argument, NULL, 'v' }, { "window-size", required_argument, NULL, 'w' }, { NULL, 0, NULL, 0 } }; #define RGB_FORMAT 3 #define BYTES_PER_PIXEL 3 /** Dimensions and pixel data for output PNG file */ struct PNG { int width; int height; /* 3 bytes per pixel: R,G,B */ void* data; void setPixel(unsigned x, unsigned y, uint8_t r, uint8_t g, uint8_t b) { size_t offset = (y * width + x) * BYTES_PER_PIXEL; uint8_t* bytes = (uint8_t*)data; bytes[offset] = r; bytes[offset + 1] = g; bytes[offset + 2] = b; } }; typedef unordered_map<uint64_t, uint8_t> HashCountMap; static inline bool hashSeq(string seq, unordered_set<string>& kmers, HashCountMap& hashCounts) { transform(seq.begin(), seq.end(), seq.begin(), ::toupper); uint64_t fwdHash, rcHash, hash; string prevKmer; for (unsigned i = 0; i < seq.length() - opt::k + 1; ++i) { string kmer = seq.substr(i, opt::k); size_t pos = kmer.find_first_not_of("ACGT"); if (pos != string::npos) { i += pos; prevKmer.clear(); continue; } if (opt::hashFunc == "city") { hash = CityHash64(kmer.c_str(), kmer.length()); } else { /* hashFunc == "rolling" */ if (prevKmer.empty()) { hash = initHashes(kmer, fwdHash, rcHash); } else { hash = rollHashesRight(fwdHash, rcHash, prevKmer.at(0), kmer.at(opt::k-1), opt::k); } } hash %= opt::windowSize; kmers.insert(kmer); hashCounts[hash]++; prevKmer = kmer; if ((float)kmers.size() / opt::windowSize > opt::maxDensity) return false; if (opt::verbose && kmers.size() % opt::progressStep == 0) { cerr << "hashed " << kmers.size() << " k-mers" << endl; } } return true; } static inline void drawPNG(HashCountMap& hashCounts, PNG& png) { /* white background */ memset(png.data, 255, png.width * png.height * BYTES_PER_PIXEL); for(HashCountMap::iterator it = hashCounts.begin(); it != hashCounts.end(); ++it) { uint64_t hash = it->first; uint8_t count = it->second; unsigned x = hash % png.width; unsigned y = hash / png.width; if (y >= png.height) { cerr << "y >= png.height!" << endl; cerr << "hash: " << hash << endl; cerr << "y: " << y << endl; cerr << "png.width: " << png.width << endl; cerr << "png.height: " << png.height << endl; } assert(y < png.height); assert(count > 0); if (count > 1) { /* red to indicate collision */ png.setPixel(x, y, 255, 0, 0); } else { /* black to indicate non-collision */ png.setPixel(x, y, 0, 0, 0); } } } int main(int argc, char** argv) { bool die = false; for (int c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) { istringstream arg(optarg != NULL ? optarg : ""); switch (c) { case 'd': arg >> opt::maxDensity; break; case 'h': cout << USAGE_MESSAGE; exit(EXIT_SUCCESS); case 'H': arg >> opt::hashFunc; break; case 'k': arg >> opt::k; break; case 'p': arg >> opt::pngPath; break; case 'P': arg >> opt::progressStep; break; case 'v': opt::verbose++; break; case 'w': arg >> opt::windowSize; break; case '?': die = true; break; } if (optarg != NULL && !arg.eof()) { cerr << PROGRAM ": invalid option: `-" << (char)c << optarg << "'\n"; exit(EXIT_FAILURE); } } if (opt::maxDensity < 0.0f || opt::maxDensity > 1.0f) { cerr << "error: value for -d (--max-density) must be in " " range [0,1]" << endl; die = true; } if (opt::hashFunc != "rolling" && opt::hashFunc != "city") { cerr << "error: unrecognized argument for -h (--hash); " " legal values are: 'rolling', 'city'" << endl; } if (die) { cerr << USAGE_MESSAGE; exit(EXIT_FAILURE); } ifstream fin; if (argc > optind) fin.open(argv[optind]); istream& in = (argc > optind) ? fin : cin; assert(in); /* k-mers inserted so far */ unordered_set<string> kmers; /* number of occurrences of each hash value (usually 1) */ HashCountMap hashCounts; /* read and hash FASTA sequences */ string line; while(getline(in, line)) { if (line.empty() || line.at(0) == '>') continue; /* return false when window exceeds opt::maxDensity */ if(!hashSeq(line, kmers, hashCounts)) break; } /* count collisions */ uint64_t collisions = kmers.size() - hashCounts.size(); cout << "distinct_kmers\tcollisions\n"; cout << kmers.size() << "\t" << collisions << "\n"; /* create PNG image */ if (!opt::pngPath.empty()) { PNG png; png.width = (int)ceil(sqrt(opt::windowSize)); png.height = (int)ceil((double)opt::windowSize / png.width); png.data = malloc(png.width * png.height * BYTES_PER_PIXEL); drawPNG(hashCounts, png); stbi_write_png(opt::pngPath.c_str(), png.width, png.height, RGB_FORMAT, png.data, png.width*BYTES_PER_PIXEL); } return 0; } <commit_msg>collision.cpp: add example prime numbers to --help<commit_after>#include <string> #include <cstring> #include <cassert> #include <cmath> #include <unordered_map> #include <unordered_set> #include <algorithm> #include <iostream> #include <fstream> #include <sstream> #include <getopt.h> #include "rolling.h" #include "city.h" /* as per instructions at top of stb_image_write.h */ #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" using namespace std; #define PROGRAM "collision" static const char USAGE_MESSAGE[] = "Usage:" PROGRAM " [OPTIONS] [FASTA]...\n" "Measure number of hash collisions using CityHash64 or rolling hash.\n" "K-mers from [FASTA] are hashed to positions within a fixed-size\n" "window (using the modulus operator).\n" "\n" "Options:\n" " -d, --max-density N stop hashing k-mers when\n" " DISTINCT_KMERS / WINDOW_SIZE > N [0.05]\n" " -h, --help show this message\n" " -H, --hash HASH hash function to use ('city' or 'rolling')\n" " [rolling]\n" " -k, --kmer-size size of k-mer [20]\n" " -p, --png FILE write bitmap of hash positions\n" " to FILE; dimensions of output PNG are\n" " approximately sqrt(WINDOW_SIZE) by \n" " sqrt(WINDOW_SIZE)\n" " -P, --progress-step N show progress message after hashing\n" " every N k-mers [10000]\n" " -v, --verbose show progress messages\n" " -w, --window-size N window size; this should normally\n" " be a prime number [1048573]\n" "\n" "Sample Prime Numbers (for window size):\n" "\n" " 1048573\n" " 2047541\n" " 3055471\n" " 4051051\n" " 5051143\n"; namespace opt { static float maxDensity = 0.05f; static int help = 0; static string hashFunc("rolling"); static unsigned k = 20; static string pngPath; static size_t progressStep = 10000; static int verbose = 0; static size_t windowSize = 1048573; } static const char shortopts[] = "d:hH:k:p:P:vw:"; static const struct option longopts[] = { { "max-density", required_argument, NULL, 'd' }, { "help", no_argument, NULL, 'h' }, { "hash", required_argument, NULL, 'H' }, { "kmer-size", required_argument, NULL, 'k' }, { "png", required_argument, NULL, 'p' }, { "progress-step", required_argument, NULL, 'P' }, { "verbose", no_argument, NULL, 'v' }, { "window-size", required_argument, NULL, 'w' }, { NULL, 0, NULL, 0 } }; #define RGB_FORMAT 3 #define BYTES_PER_PIXEL 3 /** Dimensions and pixel data for output PNG file */ struct PNG { int width; int height; /* 3 bytes per pixel: R,G,B */ void* data; void setPixel(unsigned x, unsigned y, uint8_t r, uint8_t g, uint8_t b) { size_t offset = (y * width + x) * BYTES_PER_PIXEL; uint8_t* bytes = (uint8_t*)data; bytes[offset] = r; bytes[offset + 1] = g; bytes[offset + 2] = b; } }; typedef unordered_map<uint64_t, uint8_t> HashCountMap; static inline bool hashSeq(string seq, unordered_set<string>& kmers, HashCountMap& hashCounts) { transform(seq.begin(), seq.end(), seq.begin(), ::toupper); uint64_t fwdHash, rcHash, hash; string prevKmer; for (unsigned i = 0; i < seq.length() - opt::k + 1; ++i) { string kmer = seq.substr(i, opt::k); size_t pos = kmer.find_first_not_of("ACGT"); if (pos != string::npos) { i += pos; prevKmer.clear(); continue; } if (opt::hashFunc == "city") { hash = CityHash64(kmer.c_str(), kmer.length()); } else { /* hashFunc == "rolling" */ if (prevKmer.empty()) { hash = initHashes(kmer, fwdHash, rcHash); } else { hash = rollHashesRight(fwdHash, rcHash, prevKmer.at(0), kmer.at(opt::k-1), opt::k); } } hash %= opt::windowSize; kmers.insert(kmer); hashCounts[hash]++; prevKmer = kmer; if ((float)kmers.size() / opt::windowSize > opt::maxDensity) return false; if (opt::verbose && kmers.size() % opt::progressStep == 0) { cerr << "hashed " << kmers.size() << " k-mers" << endl; } } return true; } static inline void drawPNG(HashCountMap& hashCounts, PNG& png) { /* white background */ memset(png.data, 255, png.width * png.height * BYTES_PER_PIXEL); for(HashCountMap::iterator it = hashCounts.begin(); it != hashCounts.end(); ++it) { uint64_t hash = it->first; uint8_t count = it->second; unsigned x = hash % png.width; unsigned y = hash / png.width; if (y >= png.height) { cerr << "y >= png.height!" << endl; cerr << "hash: " << hash << endl; cerr << "y: " << y << endl; cerr << "png.width: " << png.width << endl; cerr << "png.height: " << png.height << endl; } assert(y < png.height); assert(count > 0); if (count > 1) { /* red to indicate collision */ png.setPixel(x, y, 255, 0, 0); } else { /* black to indicate non-collision */ png.setPixel(x, y, 0, 0, 0); } } } int main(int argc, char** argv) { bool die = false; for (int c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) { istringstream arg(optarg != NULL ? optarg : ""); switch (c) { case 'd': arg >> opt::maxDensity; break; case 'h': cout << USAGE_MESSAGE; exit(EXIT_SUCCESS); case 'H': arg >> opt::hashFunc; break; case 'k': arg >> opt::k; break; case 'p': arg >> opt::pngPath; break; case 'P': arg >> opt::progressStep; break; case 'v': opt::verbose++; break; case 'w': arg >> opt::windowSize; break; case '?': die = true; break; } if (optarg != NULL && !arg.eof()) { cerr << PROGRAM ": invalid option: `-" << (char)c << optarg << "'\n"; exit(EXIT_FAILURE); } } if (opt::maxDensity < 0.0f || opt::maxDensity > 1.0f) { cerr << "error: value for -d (--max-density) must be in " " range [0,1]" << endl; die = true; } if (opt::hashFunc != "rolling" && opt::hashFunc != "city") { cerr << "error: unrecognized argument for -h (--hash); " " legal values are: 'rolling', 'city'" << endl; } if (die) { cerr << USAGE_MESSAGE; exit(EXIT_FAILURE); } ifstream fin; if (argc > optind) fin.open(argv[optind]); istream& in = (argc > optind) ? fin : cin; assert(in); /* k-mers inserted so far */ unordered_set<string> kmers; /* number of occurrences of each hash value (usually 1) */ HashCountMap hashCounts; /* read and hash FASTA sequences */ string line; while(getline(in, line)) { if (line.empty() || line.at(0) == '>') continue; /* return false when window exceeds opt::maxDensity */ if(!hashSeq(line, kmers, hashCounts)) break; } /* count collisions */ uint64_t collisions = kmers.size() - hashCounts.size(); cout << "distinct_kmers\tcollisions\n"; cout << kmers.size() << "\t" << collisions << "\n"; /* create PNG image */ if (!opt::pngPath.empty()) { PNG png; png.width = (int)ceil(sqrt(opt::windowSize)); png.height = (int)ceil((double)opt::windowSize / png.width); png.data = malloc(png.width * png.height * BYTES_PER_PIXEL); drawPNG(hashCounts, png); stbi_write_png(opt::pngPath.c_str(), png.width, png.height, RGB_FORMAT, png.data, png.width*BYTES_PER_PIXEL); } return 0; } <|endoftext|>
<commit_before>/* nowlisteningplugin.cpp Kopete Now Listening To plugin Copyright (c) 2002,2003 by Will Stephenson <will@stevello.free-online.co.uk> Kopete (c) 2002,2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include <qtimer.h> #include <kdebug.h> #include <kgenericfactory.h> #include <kapplication.h> #include <dcopclient.h> #include <kaction.h> #include "config.h" #include "kopetemessagemanagerfactory.h" #include "kopetemetacontact.h" #include "nowlisteningpreferences.h" #include "nowlisteningplugin.h" #include "nlmediaplayer.h" #include "nlkscd.h" #include "nlnoatun.h" #include "nljuk.h" #include "nowlisteningguiclient.h" #ifdef HAVE_XMMS #include "nlxmms.h" #endif typedef KGenericFactory<NowListeningPlugin> NowListeningPluginFactory; K_EXPORT_COMPONENT_FACTORY( kopete_nowlistening, NowListeningPluginFactory( "kopete_nowlistening" ) ); NowListeningPlugin::NowListeningPlugin( QObject *parent, const char *name, const QStringList & /*args*/ ) : KopetePlugin( NowListeningPlugin::instance(), parent, name ) { if ( pluginStatic_ ) kdDebug(14307)<<"####"<<"Now Listening already initialized"<<endl; else pluginStatic_ = this; kdDebug(14307) << k_funcinfo << endl; // make these pointers safe until init'd m_actionCollection = 0L; m_actionWantsAdvert = 0L; m_currentMetaContact = 0L; m_currentMessageManager = 0L; // initialise preferences m_prefs = new NowListeningPreferences( "kaboodle", this ); connect( KopeteMessageManagerFactory::factory(), SIGNAL( messageManagerCreated( KopeteMessageManager * )) , SLOT( slotNewKMM( KopeteMessageManager * ) ) ); QIntDict<KopeteMessageManager> sessions = KopeteMessageManagerFactory::factory()->sessions(); QIntDictIterator<KopeteMessageManager> it( sessions ); for ( ; it.current() ; ++it ) slotNewKMM( it.current() ); // get a pointer to the dcop client m_client = kapp->dcopClient(); //new DCOPClient(); // set up known media players m_mediaPlayer = new QPtrList<NLMediaPlayer>; m_mediaPlayer->setAutoDelete( true ); m_mediaPlayer->append( new NLKscd( m_client ) ); m_mediaPlayer->append( new NLNoatun( m_client ) ); m_mediaPlayer->append( new NLJuk( m_client ) ); #ifdef HAVE_XMMS m_mediaPlayer->append( new NLXmms() ); #endif // watch for '/media' getting typed connect( KopeteMessageManagerFactory::factory(), SIGNAL( aboutToSend( KopeteMessage & ) ), SLOT( slotOutgoingMessage( KopeteMessage & ) ) ); } NowListeningPlugin::~NowListeningPlugin() { kdDebug(14307) << k_funcinfo << endl; delete m_mediaPlayer; pluginStatic_ = 0L; } void NowListeningPlugin::slotNewKMM(KopeteMessageManager *KMM) { new NowListeningGUIClient(KMM); } NowListeningPlugin* NowListeningPlugin::plugin() { return pluginStatic_ ; } void NowListeningPlugin::slotOutgoingMessage( KopeteMessage& msg ) { QString originalBody = msg.plainBody(); // look for messages that we've generated and ignore them if ( !originalBody.startsWith( m_prefs->header() ) ) { // look for the string '/media' if ( originalBody.startsWith( "/media" ) ) { // replace it with media advert QString newBody = allPlayerAdvert() + originalBody.right( originalBody.length() - 6 ); msg.setBody( newBody, KopeteMessage::RichText ); } return; } } QString NowListeningPlugin::allPlayerAdvert() const { // generate message for all players QString message = ""; QString perTrack = m_prefs->perTrack(); for ( NLMediaPlayer* i = m_mediaPlayer->first(); i; i = m_mediaPlayer->next() ) { i->update(); if ( i->playing() ) { kdDebug(14307) << k_funcinfo << i->name() << " is playing" << endl; if ( message.isEmpty() ) message = m_prefs->header(); if ( message != m_prefs->header() ) // > 1 track playing! message = message + m_prefs->conjunction(); message = message + substDepthFirst( i, perTrack, false ); } } kdDebug(14307) << k_funcinfo << message << endl; return message; } QString NowListeningPlugin::substDepthFirst( NLMediaPlayer *player, QString in, bool inBrackets ) const { QString track = player->track(); QString artist = player->artist(); QString album = player->album(); QString playerName = player->name(); for ( unsigned int i = 0; i < in.length(); i++ ) { QChar c = in.at( i ); //kdDebug(14307) << "Now working on:" << in << " char is: " << c << endl; if ( c == '(' ) { // find matching bracket int depth = 0; //kdDebug(14307) << "Looking for ')'" << endl; for ( unsigned int j = i + 1; j < in.length(); j++ ) { QChar d = in.at( j ); //kdDebug(14307) << "Got " << d << endl; if ( d == '(' ) depth++; if ( d == ')' ) { // have we found the match? if ( depth == 0 ) { // recursively replace contents of matching () QString substitution = substDepthFirst( player, in.mid( i + 1, j - i - 1), true ) ; in.replace ( i, j - i + 1, substitution ); // perform substitution and return the result i = i + substitution.length() - 1; break; } else depth--; } } } } // no () found, perform substitution! // get each string (to) to substitute for (from) bool done = false; if ( in.contains ( "%track" ) ) { if ( track.isEmpty() ) track = i18n("Unknown track"); in.replace( "%track", track ); done = true; } if ( in.contains ( "%artist" ) && !artist.isEmpty() ) { if ( artist.isEmpty() ) artist = i18n("Unknown artist"); in.replace( "%artist", artist ); done = true; } if ( in.contains ( "%album" ) && !album.isEmpty() ) { if ( album.isEmpty() ) album = i18n("Unknown album"); in.replace( "%album", album ); done = true; } if ( in.contains ( "%player" ) && !playerName.isEmpty() ) { if ( playerName.isEmpty() ) playerName = i18n("Unknown player"); in.replace( "%player", playerName ); done = true; } // make whether we return anything dependent on whether we // were in brackets and if we were, if a substitution was made. if ( inBrackets && !done ) return ""; else return in; } void NowListeningPlugin::advertiseToChat( KopeteMessageManager *theChat, QString message ) { KopeteContactPtrList pl = theChat->members(); // get on with it kdDebug(14307) << "NowListeningPlugin::advertiseNewTracks() - " << ( pl.isEmpty() ? "has no " : "has " ) << "interested recipients: " << endl; for ( pl.first(); pl.current(); pl.next() ) kdDebug(14307) << "NowListeningPlugin::advertiseNewTracks() " << pl.current()->displayName() << endl; // if no-one in this KMM wants to be advertised to, don't send // any message if ( pl.isEmpty() ) return; KopeteMessage msg( theChat->user(), pl, message, KopeteMessage::Outbound, KopeteMessage::RichText ); theChat->sendMessage( msg ); } NowListeningPlugin* NowListeningPlugin::pluginStatic_ = 0L; #include "nowlisteningplugin.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>fix bug 63689 - Kopete segfaults on startup<commit_after>/* nowlisteningplugin.cpp Kopete Now Listening To plugin Copyright (c) 2002,2003 by Will Stephenson <will@stevello.free-online.co.uk> Kopete (c) 2002,2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include <qtimer.h> #include <kdebug.h> #include <kgenericfactory.h> #include <kapplication.h> #include <dcopclient.h> #include <kaction.h> #include "config.h" #include "kopetemessagemanagerfactory.h" #include "kopetemetacontact.h" #include "nowlisteningpreferences.h" #include "nowlisteningplugin.h" #include "nlmediaplayer.h" #include "nlkscd.h" #include "nlnoatun.h" #include "nljuk.h" #include "nowlisteningguiclient.h" #ifdef HAVE_XMMS #include "nlxmms.h" #endif typedef KGenericFactory<NowListeningPlugin> NowListeningPluginFactory; K_EXPORT_COMPONENT_FACTORY( kopete_nowlistening, NowListeningPluginFactory( "kopete_nowlistening" ) ); NowListeningPlugin::NowListeningPlugin( QObject *parent, const char* name, const QStringList& /*args*/ ) : KopetePlugin( NowListeningPluginFactory::instance(), parent, name ) { if ( pluginStatic_ ) kdDebug(14307)<<"####"<<"Now Listening already initialized"<<endl; else pluginStatic_ = this; kdDebug(14307) << k_funcinfo << endl; // make these pointers safe until init'd m_actionCollection = 0L; m_actionWantsAdvert = 0L; m_currentMetaContact = 0L; m_currentMessageManager = 0L; // initialise preferences m_prefs = new NowListeningPreferences( "kaboodle", this ); connect( KopeteMessageManagerFactory::factory(), SIGNAL( messageManagerCreated( KopeteMessageManager * )) , SLOT( slotNewKMM( KopeteMessageManager * ) ) ); QIntDict<KopeteMessageManager> sessions = KopeteMessageManagerFactory::factory()->sessions(); QIntDictIterator<KopeteMessageManager> it( sessions ); for ( ; it.current() ; ++it ) slotNewKMM( it.current() ); // get a pointer to the dcop client m_client = kapp->dcopClient(); //new DCOPClient(); // set up known media players m_mediaPlayer = new QPtrList<NLMediaPlayer>; m_mediaPlayer->setAutoDelete( true ); m_mediaPlayer->append( new NLKscd( m_client ) ); m_mediaPlayer->append( new NLNoatun( m_client ) ); m_mediaPlayer->append( new NLJuk( m_client ) ); #ifdef HAVE_XMMS m_mediaPlayer->append( new NLXmms() ); #endif // watch for '/media' getting typed connect( KopeteMessageManagerFactory::factory(), SIGNAL( aboutToSend( KopeteMessage & ) ), SLOT( slotOutgoingMessage( KopeteMessage & ) ) ); } NowListeningPlugin::~NowListeningPlugin() { kdDebug(14307) << k_funcinfo << endl; delete m_mediaPlayer; pluginStatic_ = 0L; } void NowListeningPlugin::slotNewKMM(KopeteMessageManager *KMM) { new NowListeningGUIClient(KMM); } NowListeningPlugin* NowListeningPlugin::plugin() { return pluginStatic_ ; } void NowListeningPlugin::slotOutgoingMessage( KopeteMessage& msg ) { QString originalBody = msg.plainBody(); // look for messages that we've generated and ignore them if ( !originalBody.startsWith( m_prefs->header() ) ) { // look for the string '/media' if ( originalBody.startsWith( "/media" ) ) { // replace it with media advert QString newBody = allPlayerAdvert() + originalBody.right( originalBody.length() - 6 ); msg.setBody( newBody, KopeteMessage::RichText ); } return; } } QString NowListeningPlugin::allPlayerAdvert() const { // generate message for all players QString message = ""; QString perTrack = m_prefs->perTrack(); for ( NLMediaPlayer* i = m_mediaPlayer->first(); i; i = m_mediaPlayer->next() ) { i->update(); if ( i->playing() ) { kdDebug(14307) << k_funcinfo << i->name() << " is playing" << endl; if ( message.isEmpty() ) message = m_prefs->header(); if ( message != m_prefs->header() ) // > 1 track playing! message = message + m_prefs->conjunction(); message = message + substDepthFirst( i, perTrack, false ); } } kdDebug(14307) << k_funcinfo << message << endl; return message; } QString NowListeningPlugin::substDepthFirst( NLMediaPlayer *player, QString in, bool inBrackets ) const { QString track = player->track(); QString artist = player->artist(); QString album = player->album(); QString playerName = player->name(); for ( unsigned int i = 0; i < in.length(); i++ ) { QChar c = in.at( i ); //kdDebug(14307) << "Now working on:" << in << " char is: " << c << endl; if ( c == '(' ) { // find matching bracket int depth = 0; //kdDebug(14307) << "Looking for ')'" << endl; for ( unsigned int j = i + 1; j < in.length(); j++ ) { QChar d = in.at( j ); //kdDebug(14307) << "Got " << d << endl; if ( d == '(' ) depth++; if ( d == ')' ) { // have we found the match? if ( depth == 0 ) { // recursively replace contents of matching () QString substitution = substDepthFirst( player, in.mid( i + 1, j - i - 1), true ) ; in.replace ( i, j - i + 1, substitution ); // perform substitution and return the result i = i + substitution.length() - 1; break; } else depth--; } } } } // no () found, perform substitution! // get each string (to) to substitute for (from) bool done = false; if ( in.contains ( "%track" ) ) { if ( track.isEmpty() ) track = i18n("Unknown track"); in.replace( "%track", track ); done = true; } if ( in.contains ( "%artist" ) && !artist.isEmpty() ) { if ( artist.isEmpty() ) artist = i18n("Unknown artist"); in.replace( "%artist", artist ); done = true; } if ( in.contains ( "%album" ) && !album.isEmpty() ) { if ( album.isEmpty() ) album = i18n("Unknown album"); in.replace( "%album", album ); done = true; } if ( in.contains ( "%player" ) && !playerName.isEmpty() ) { if ( playerName.isEmpty() ) playerName = i18n("Unknown player"); in.replace( "%player", playerName ); done = true; } // make whether we return anything dependent on whether we // were in brackets and if we were, if a substitution was made. if ( inBrackets && !done ) return ""; else return in; } void NowListeningPlugin::advertiseToChat( KopeteMessageManager *theChat, QString message ) { KopeteContactPtrList pl = theChat->members(); // get on with it kdDebug(14307) << "NowListeningPlugin::advertiseNewTracks() - " << ( pl.isEmpty() ? "has no " : "has " ) << "interested recipients: " << endl; for ( pl.first(); pl.current(); pl.next() ) kdDebug(14307) << "NowListeningPlugin::advertiseNewTracks() " << pl.current()->displayName() << endl; // if no-one in this KMM wants to be advertised to, don't send // any message if ( pl.isEmpty() ) return; KopeteMessage msg( theChat->user(), pl, message, KopeteMessage::Outbound, KopeteMessage::RichText ); theChat->sendMessage( msg ); } NowListeningPlugin* NowListeningPlugin::pluginStatic_ = 0L; #include "nowlisteningplugin.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/service/service_process_control.h" #include "app/app_switches.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/process_util.h" #include "base/stl_util-inl.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/io_thread.h" #include "chrome/browser/upgrade_detector.h" #include "chrome/common/child_process_host.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/common/service_messages.h" #include "chrome/common/service_process_util.h" // ServiceProcessControl::Launcher implementation. // This class is responsible for launching the service process on the // PROCESS_LAUNCHER thread. class ServiceProcessControl::Launcher : public base::RefCountedThreadSafe<ServiceProcessControl::Launcher> { public: Launcher(ServiceProcessControl* process, CommandLine* cmd_line) : process_(process), cmd_line_(cmd_line), launched_(false), retry_count_(0) { } // Execute the command line to start the process asynchronously. // After the comamnd is executed |task| is called with the process handle on // the UI thread. void Run(Task* task) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); notify_task_.reset(task); BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER, FROM_HERE, NewRunnableMethod(this, &Launcher::DoRun)); } bool launched() const { return launched_; } private: void DoRun() { DCHECK(notify_task_.get()); base::LaunchApp(*cmd_line_.get(), false, true, NULL); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &Launcher::DoDetectLaunched)); } void DoDetectLaunched() { DCHECK(notify_task_.get()); const uint32 kMaxLaunchDetectRetries = 10; { // We should not be doing blocking disk IO from this thread! // Temporarily allowed until we fix // http://code.google.com/p/chromium/issues/detail?id=60207 base::ThreadRestrictions::ScopedAllowIO allow_io; launched_ = CheckServiceProcessReady(); } if (launched_ || (retry_count_ >= kMaxLaunchDetectRetries)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &Launcher::Notify)); return; } retry_count_++; // If the service process is not launched yet then check again in 2 seconds. const int kDetectLaunchRetry = 2000; MessageLoop::current()->PostDelayedTask( FROM_HERE, NewRunnableMethod(this, &Launcher::DoDetectLaunched), kDetectLaunchRetry); } void Notify() { DCHECK(notify_task_.get()); notify_task_->Run(); notify_task_.reset(); } ServiceProcessControl* process_; scoped_ptr<CommandLine> cmd_line_; scoped_ptr<Task> notify_task_; bool launched_; uint32 retry_count_; }; // ServiceProcessControl implementation. ServiceProcessControl::ServiceProcessControl(Profile* profile) : profile_(profile) { } ServiceProcessControl::~ServiceProcessControl() { STLDeleteElements(&connect_done_tasks_); STLDeleteElements(&connect_success_tasks_); STLDeleteElements(&connect_failure_tasks_); } void ServiceProcessControl::ConnectInternal() { // If the channel has already been established then we run the task // and return. if (channel_.get()) { RunConnectDoneTasks(); return; } // Actually going to connect. VLOG(1) << "Connecting to Service Process IPC Server"; // Run the IPC channel on the shared IO thread. base::Thread* io_thread = g_browser_process->io_thread(); // TODO(hclam): Handle error connecting to channel. const std::string channel_id = GetServiceProcessChannelName(); channel_.reset( new IPC::SyncChannel(channel_id, IPC::Channel::MODE_CLIENT, this, io_thread->message_loop(), true, g_browser_process->shutdown_event())); channel_->set_sync_messages_with_no_timeout_allowed(false); // We just established a channel with the service process. Notify it if an // upgrade is available. if (UpgradeDetector::GetInstance()->notify_upgrade()) { Send(new ServiceMsg_UpdateAvailable); } else { if (registrar_.IsEmpty()) registrar_.Add(this, NotificationType::UPGRADE_RECOMMENDED, NotificationService::AllSources()); } } void ServiceProcessControl::RunConnectDoneTasks() { RunAllTasksHelper(&connect_done_tasks_); DCHECK(connect_done_tasks_.empty()); if (is_connected()) { RunAllTasksHelper(&connect_success_tasks_); DCHECK(connect_success_tasks_.empty()); STLDeleteElements(&connect_failure_tasks_); } else { RunAllTasksHelper(&connect_failure_tasks_); DCHECK(connect_failure_tasks_.empty()); STLDeleteElements(&connect_success_tasks_); } } // static void ServiceProcessControl::RunAllTasksHelper(TaskList* task_list) { TaskList::iterator index = task_list->begin(); while (index != task_list->end()) { (*index)->Run(); delete (*index); index = task_list->erase(index); } } void ServiceProcessControl::Launch(Task* success_task, Task* failure_task) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (success_task) { if (success_task == failure_task) { // If the tasks are the same, then the same task needs to be invoked // for success and failure. failure_task = NULL; connect_done_tasks_.push_back(success_task); } else { connect_success_tasks_.push_back(success_task); } } if (failure_task) connect_failure_tasks_.push_back(failure_task); // If the service process is already running then connects to it. if (CheckServiceProcessReady()) { ConnectInternal(); return; } // If we already in the process of launching, then we are done. if (launcher_) { return; } // A service process should have a different mechanism for starting, but now // we start it as if it is a child process. FilePath exe_path = ChildProcessHost::GetChildPath(true); if (exe_path.empty()) { NOTREACHED() << "Unable to get service process binary name."; } CommandLine* cmd_line = new CommandLine(exe_path); cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kServiceProcess); const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); FilePath user_data_dir = browser_command_line.GetSwitchValuePath(switches::kUserDataDir); if (!user_data_dir.empty()) cmd_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir); std::string logging_level = browser_command_line.GetSwitchValueASCII( switches::kLoggingLevel); if (!logging_level.empty()) cmd_line->AppendSwitchASCII(switches::kLoggingLevel, logging_level); if (browser_command_line.HasSwitch(switches::kWaitForDebuggerChildren)) { cmd_line->AppendSwitch(switches::kWaitForDebugger); } std::string locale = g_browser_process->GetApplicationLocale(); cmd_line->AppendSwitchASCII(switches::kLang, locale); // And then start the process asynchronously. launcher_ = new Launcher(this, cmd_line); launcher_->Run( NewRunnableMethod(this, &ServiceProcessControl::OnProcessLaunched)); } void ServiceProcessControl::OnProcessLaunched() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (launcher_->launched()) { // After we have successfully created the service process we try to connect // to it. The launch task is transfered to a connect task. ConnectInternal(); } else { // If we don't have process handle that means launching the service process // has failed. RunConnectDoneTasks(); } // We don't need the launcher anymore. launcher_ = NULL; } bool ServiceProcessControl::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ServiceProcessControl, message) IPC_MESSAGE_HANDLER(ServiceHostMsg_CloudPrintProxy_IsEnabled, OnCloudPrintProxyIsEnabled) IPC_MESSAGE_HANDLER(ServiceHostMsg_RemotingHost_HostInfo, OnRemotingHostInfo) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void ServiceProcessControl::OnChannelConnected(int32 peer_pid) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); RunConnectDoneTasks(); } void ServiceProcessControl::OnChannelError() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); channel_.reset(); RunConnectDoneTasks(); } bool ServiceProcessControl::Send(IPC::Message* message) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!channel_.get()) return false; return channel_->Send(message); } // NotificationObserver implementation. void ServiceProcessControl::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::UPGRADE_RECOMMENDED) { Send(new ServiceMsg_UpdateAvailable); } } void ServiceProcessControl::OnCloudPrintProxyIsEnabled(bool enabled, std::string email) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (cloud_print_status_callback_ != NULL) { cloud_print_status_callback_->Run(enabled, email); cloud_print_status_callback_.reset(); } } void ServiceProcessControl::OnRemotingHostInfo( remoting::ChromotingHostInfo host_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); for (std::set<MessageHandler*>::iterator it = message_handlers_.begin(); it != message_handlers_.end(); ++it) { (*it)->OnRemotingHostInfo(host_info); } } bool ServiceProcessControl::GetCloudPrintProxyStatus( Callback2<bool, std::string>::Type* cloud_print_status_callback) { DCHECK(cloud_print_status_callback); cloud_print_status_callback_.reset(cloud_print_status_callback); return Send(new ServiceMsg_IsCloudPrintProxyEnabled); } bool ServiceProcessControl::Shutdown() { bool ret = Send(new ServiceMsg_Shutdown()); channel_.reset(); return ret; } bool ServiceProcessControl::SetRemotingHostCredentials( const std::string& user, const std::string& talk_token) { return Send( new ServiceMsg_SetRemotingHostCredentials(user, talk_token)); } bool ServiceProcessControl::EnableRemotingHost() { return Send(new ServiceMsg_EnableRemotingHost()); } bool ServiceProcessControl::DisableRemotingHost() { return Send(new ServiceMsg_DisableRemotingHost()); } bool ServiceProcessControl::RequestRemotingHostStatus() { return Send(new ServiceMsg_GetRemotingHostInfo); } void ServiceProcessControl::AddMessageHandler( MessageHandler* message_handler) { message_handlers_.insert(message_handler); } void ServiceProcessControl::RemoveMessageHandler( MessageHandler* message_handler) { message_handlers_.erase(message_handler); } DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControl); <commit_msg>Update another include path<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/service/service_process_control.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/process_util.h" #include "base/stl_util-inl.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/io_thread.h" #include "chrome/browser/upgrade_detector.h" #include "chrome/common/child_process_host.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/common/service_messages.h" #include "chrome/common/service_process_util.h" #include "ui/base/ui_base_switches.h" // ServiceProcessControl::Launcher implementation. // This class is responsible for launching the service process on the // PROCESS_LAUNCHER thread. class ServiceProcessControl::Launcher : public base::RefCountedThreadSafe<ServiceProcessControl::Launcher> { public: Launcher(ServiceProcessControl* process, CommandLine* cmd_line) : process_(process), cmd_line_(cmd_line), launched_(false), retry_count_(0) { } // Execute the command line to start the process asynchronously. // After the comamnd is executed |task| is called with the process handle on // the UI thread. void Run(Task* task) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); notify_task_.reset(task); BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER, FROM_HERE, NewRunnableMethod(this, &Launcher::DoRun)); } bool launched() const { return launched_; } private: void DoRun() { DCHECK(notify_task_.get()); base::LaunchApp(*cmd_line_.get(), false, true, NULL); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &Launcher::DoDetectLaunched)); } void DoDetectLaunched() { DCHECK(notify_task_.get()); const uint32 kMaxLaunchDetectRetries = 10; { // We should not be doing blocking disk IO from this thread! // Temporarily allowed until we fix // http://code.google.com/p/chromium/issues/detail?id=60207 base::ThreadRestrictions::ScopedAllowIO allow_io; launched_ = CheckServiceProcessReady(); } if (launched_ || (retry_count_ >= kMaxLaunchDetectRetries)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &Launcher::Notify)); return; } retry_count_++; // If the service process is not launched yet then check again in 2 seconds. const int kDetectLaunchRetry = 2000; MessageLoop::current()->PostDelayedTask( FROM_HERE, NewRunnableMethod(this, &Launcher::DoDetectLaunched), kDetectLaunchRetry); } void Notify() { DCHECK(notify_task_.get()); notify_task_->Run(); notify_task_.reset(); } ServiceProcessControl* process_; scoped_ptr<CommandLine> cmd_line_; scoped_ptr<Task> notify_task_; bool launched_; uint32 retry_count_; }; // ServiceProcessControl implementation. ServiceProcessControl::ServiceProcessControl(Profile* profile) : profile_(profile) { } ServiceProcessControl::~ServiceProcessControl() { STLDeleteElements(&connect_done_tasks_); STLDeleteElements(&connect_success_tasks_); STLDeleteElements(&connect_failure_tasks_); } void ServiceProcessControl::ConnectInternal() { // If the channel has already been established then we run the task // and return. if (channel_.get()) { RunConnectDoneTasks(); return; } // Actually going to connect. VLOG(1) << "Connecting to Service Process IPC Server"; // Run the IPC channel on the shared IO thread. base::Thread* io_thread = g_browser_process->io_thread(); // TODO(hclam): Handle error connecting to channel. const std::string channel_id = GetServiceProcessChannelName(); channel_.reset( new IPC::SyncChannel(channel_id, IPC::Channel::MODE_CLIENT, this, io_thread->message_loop(), true, g_browser_process->shutdown_event())); channel_->set_sync_messages_with_no_timeout_allowed(false); // We just established a channel with the service process. Notify it if an // upgrade is available. if (UpgradeDetector::GetInstance()->notify_upgrade()) { Send(new ServiceMsg_UpdateAvailable); } else { if (registrar_.IsEmpty()) registrar_.Add(this, NotificationType::UPGRADE_RECOMMENDED, NotificationService::AllSources()); } } void ServiceProcessControl::RunConnectDoneTasks() { RunAllTasksHelper(&connect_done_tasks_); DCHECK(connect_done_tasks_.empty()); if (is_connected()) { RunAllTasksHelper(&connect_success_tasks_); DCHECK(connect_success_tasks_.empty()); STLDeleteElements(&connect_failure_tasks_); } else { RunAllTasksHelper(&connect_failure_tasks_); DCHECK(connect_failure_tasks_.empty()); STLDeleteElements(&connect_success_tasks_); } } // static void ServiceProcessControl::RunAllTasksHelper(TaskList* task_list) { TaskList::iterator index = task_list->begin(); while (index != task_list->end()) { (*index)->Run(); delete (*index); index = task_list->erase(index); } } void ServiceProcessControl::Launch(Task* success_task, Task* failure_task) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (success_task) { if (success_task == failure_task) { // If the tasks are the same, then the same task needs to be invoked // for success and failure. failure_task = NULL; connect_done_tasks_.push_back(success_task); } else { connect_success_tasks_.push_back(success_task); } } if (failure_task) connect_failure_tasks_.push_back(failure_task); // If the service process is already running then connects to it. if (CheckServiceProcessReady()) { ConnectInternal(); return; } // If we already in the process of launching, then we are done. if (launcher_) { return; } // A service process should have a different mechanism for starting, but now // we start it as if it is a child process. FilePath exe_path = ChildProcessHost::GetChildPath(true); if (exe_path.empty()) { NOTREACHED() << "Unable to get service process binary name."; } CommandLine* cmd_line = new CommandLine(exe_path); cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kServiceProcess); const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); FilePath user_data_dir = browser_command_line.GetSwitchValuePath(switches::kUserDataDir); if (!user_data_dir.empty()) cmd_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir); std::string logging_level = browser_command_line.GetSwitchValueASCII( switches::kLoggingLevel); if (!logging_level.empty()) cmd_line->AppendSwitchASCII(switches::kLoggingLevel, logging_level); if (browser_command_line.HasSwitch(switches::kWaitForDebuggerChildren)) { cmd_line->AppendSwitch(switches::kWaitForDebugger); } std::string locale = g_browser_process->GetApplicationLocale(); cmd_line->AppendSwitchASCII(switches::kLang, locale); // And then start the process asynchronously. launcher_ = new Launcher(this, cmd_line); launcher_->Run( NewRunnableMethod(this, &ServiceProcessControl::OnProcessLaunched)); } void ServiceProcessControl::OnProcessLaunched() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (launcher_->launched()) { // After we have successfully created the service process we try to connect // to it. The launch task is transfered to a connect task. ConnectInternal(); } else { // If we don't have process handle that means launching the service process // has failed. RunConnectDoneTasks(); } // We don't need the launcher anymore. launcher_ = NULL; } bool ServiceProcessControl::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ServiceProcessControl, message) IPC_MESSAGE_HANDLER(ServiceHostMsg_CloudPrintProxy_IsEnabled, OnCloudPrintProxyIsEnabled) IPC_MESSAGE_HANDLER(ServiceHostMsg_RemotingHost_HostInfo, OnRemotingHostInfo) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void ServiceProcessControl::OnChannelConnected(int32 peer_pid) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); RunConnectDoneTasks(); } void ServiceProcessControl::OnChannelError() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); channel_.reset(); RunConnectDoneTasks(); } bool ServiceProcessControl::Send(IPC::Message* message) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!channel_.get()) return false; return channel_->Send(message); } // NotificationObserver implementation. void ServiceProcessControl::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::UPGRADE_RECOMMENDED) { Send(new ServiceMsg_UpdateAvailable); } } void ServiceProcessControl::OnCloudPrintProxyIsEnabled(bool enabled, std::string email) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (cloud_print_status_callback_ != NULL) { cloud_print_status_callback_->Run(enabled, email); cloud_print_status_callback_.reset(); } } void ServiceProcessControl::OnRemotingHostInfo( remoting::ChromotingHostInfo host_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); for (std::set<MessageHandler*>::iterator it = message_handlers_.begin(); it != message_handlers_.end(); ++it) { (*it)->OnRemotingHostInfo(host_info); } } bool ServiceProcessControl::GetCloudPrintProxyStatus( Callback2<bool, std::string>::Type* cloud_print_status_callback) { DCHECK(cloud_print_status_callback); cloud_print_status_callback_.reset(cloud_print_status_callback); return Send(new ServiceMsg_IsCloudPrintProxyEnabled); } bool ServiceProcessControl::Shutdown() { bool ret = Send(new ServiceMsg_Shutdown()); channel_.reset(); return ret; } bool ServiceProcessControl::SetRemotingHostCredentials( const std::string& user, const std::string& talk_token) { return Send( new ServiceMsg_SetRemotingHostCredentials(user, talk_token)); } bool ServiceProcessControl::EnableRemotingHost() { return Send(new ServiceMsg_EnableRemotingHost()); } bool ServiceProcessControl::DisableRemotingHost() { return Send(new ServiceMsg_DisableRemotingHost()); } bool ServiceProcessControl::RequestRemotingHostStatus() { return Send(new ServiceMsg_GetRemotingHostInfo); } void ServiceProcessControl::AddMessageHandler( MessageHandler* message_handler) { message_handlers_.insert(message_handler); } void ServiceProcessControl::RemoveMessageHandler( MessageHandler* message_handler) { message_handlers_.erase(message_handler); } DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControl); <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- $Id$ This file is part of Crystal Space Virtual Object System Abstract 3D Layer plugin (csvosa3dl). Copyright (C) 2004 Peter Amstutz This program 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 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 program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "cssysdef.h" #include "csgfx/memimage.h" #include "csgfx/xorpat.h" #include "iutil/objreg.h" #include "ivideo/graph3d.h" #include "ivideo/material.h" #include "ivideo/txtmgr.h" #include "vosmaterial.h" #include "vostexture.h" #include "vosobject3d.h" csRef<iMaterialWrapper> csMetaMaterial::checkerboard; iObjectRegistry* csMetaMaterial::object_reg; using namespace VOS; class ConstructMaterialTask : public Task { public: vRef<csMetaTexture> base; std::vector<csMetaTexture*> layers; csTextureLayer* coords; vRef<csMetaMaterial> metamaterial; iObjectRegistry *object_reg; bool iscolor; float R, G, B; ConstructMaterialTask(iObjectRegistry *objreg, csMetaMaterial* mm); virtual ~ConstructMaterialTask(); virtual void doTask(); }; ConstructMaterialTask::ConstructMaterialTask(iObjectRegistry *objreg, csMetaMaterial* mm) : coords(0), metamaterial(mm, true), object_reg(objreg) { } ConstructMaterialTask::~ConstructMaterialTask() { } void ConstructMaterialTask::doTask() { csRef<iEngine> engine = CS_QUERY_REGISTRY (object_reg, iEngine); csRef<iGraphics3D> g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D); csRef<iTextureManager> txtmgr = g3d->GetTextureManager(); csRef<iMaterial> imat; if(base.isValid()) { csRef<iTextureWrapper> basetw = base->GetTextureWrapper(); if(layers.size() > 0) { iTextureWrapper** layertws = (iTextureWrapper**)malloc(layers.size() * sizeof(iTextureWrapper*)); for(unsigned int i = 0; i < layers.size(); i++) { layertws[i] = layers[i]->GetTextureWrapper(); layers[i]->release(); } imat = engine->CreateBaseMaterial(basetw, layers.size(), layertws, coords); free(layertws); free(coords); } else { imat = engine->CreateBaseMaterial(basetw); } } else { if(iscolor) { // we tried some alternate ways of doing colors! /* csRef<iMaterial> color = engine->CreateBaseMaterial(0); int red = strtol(newproperty.substr(1, 2).c_str(), 0, 16); int green = strtol(newproperty.substr(3, 2).c_str(), 0, 16); int blue = strtol(newproperty.substr(5, 2).c_str(), 0, 16); color->SetFlatColor(csRGBcolor(red, green, blue)); if(!material) { material = engine->GetMaterialList()->NewMaterial(color); material->QueryObject()->SetName(p.getURL().getString().c_str()); } material->SetMaterial(color); material->Register(txtmgr); material->GetMaterialHandle()->Prepare (); */ /* csRef<iMaterial> color = engine->CreateBaseMaterial(0); color->SetFlatColor(csRGBcolor((int)(r*255), (int)(g*255), (int)(b*255))); if(!material) { material = engine->GetMaterialList()->NewMaterial(color); material->QueryObject()->SetName(p.getURL().getString().c_str()); } material->SetMaterial(color); material->Register(txtmgr); material->GetMaterialHandle()->Prepare (); */ iTextureWrapper* txtwrap; txtwrap = engine->CreateBlackTexture("", 2, 2, 0, CS_TEXTURE_3D); csImageMemory* img = new csImageMemory(1, 1); csRGBpixel px((int)(R*255.0), (int)(G*255.0), (int)(B*255.0)); img->Clear(px); txtwrap->SetImageFile(img); txtwrap->Register(txtmgr); txtwrap->GetTextureHandle()->Prepare (); imat = engine->CreateBaseMaterial(txtwrap); } } if(imat.IsValid()) { csRef<iMaterialWrapper> material = engine->GetMaterialList()->NewMaterial(imat); if(!material) return; material->Register(txtmgr); material->GetMaterialHandle()->Prepare(); metamaterial->materialwrapper = material; } } csMetaMaterial::csMetaMaterial(VobjectBase* superobject) : A3DL::Material(superobject), alreadyLoaded(false) { } csMetaMaterial::~csMetaMaterial() { } void csMetaMaterial::CreateCheckerboard() { csRef<iEngine> engine = CS_QUERY_REGISTRY (object_reg, iEngine); csRef<iGraphics3D> g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D); csRef<iImage> im = csCreateXORPatternImage(64, 64, 6); csRef<iTextureManager> txtmgr = g3d->GetTextureManager(); csRef<iTextureHandle> th = txtmgr->RegisterTexture (im, CS_TEXTURE_3D); csRef<iTextureWrapper> tw = engine->GetTextureList()->NewTexture(th); tw->SetImageFile(im); csRef<iMaterial> mat = engine->CreateBaseMaterial(tw); checkerboard = engine->GetMaterialList()->NewMaterial(mat); th->Prepare(); checkerboard->Register(txtmgr); checkerboard->GetMaterialHandle()->Prepare(); } /** Return CS iMaterialWrapper interface for this object */ csRef<iMaterialWrapper> csMetaMaterial::GetCheckerboard() { if(! checkerboard.IsValid()) CreateCheckerboard(); return checkerboard; } void csMetaMaterial::Setup(csVosA3DL* vosa3dl) { LOG("csMetaMaterial", 3, "setting up material"); ConstructMaterialTask* cmt = new ConstructMaterialTask(vosa3dl->GetObjectRegistry(), this); A3DL::TextureIterator txt = getTextureLayers(); if(txt.hasMore()) { vRef<csMetaTexture> base = meta_cast<csMetaTexture>(*txt); if(base.isValid()) { base->Setup(vosa3dl); cmt->base = base; } txt++; if(txt.hasMore()) { cmt->coords = (csTextureLayer*)malloc(txt.remaining() * sizeof(csTextureLayer)); float uscale = 1, vscale = 1, ushift = 0, vshift = 0; for(int i = 0; txt.hasMore(); txt++, i++) { vRef<csMetaTexture> mt = meta_cast<csMetaTexture>(*txt); if(mt.isValid()) { mt->Setup(vosa3dl); mt->acquire(); cmt->layers.push_back(&mt); try { mt->getUVScaleAndShift(uscale, vscale, ushift, vshift); } catch(std::runtime_error& e) { uscale = 1; vscale = 1; ushift = 0; vshift = 0; } cmt->coords[i].uscale = uscale; cmt->coords[i].vscale = vscale; cmt->coords[i].ushift = ushift; cmt->coords[i].vshift = vshift; switch(mt->getBlendMode()) { case A3DL::Material::BLEND_NORMAL: try { double transparency = mt->getTransparency(); if(transparency == 1.0) cmt->coords[i].mode = CS_FX_TRANSPARENT; else if(transparency == 0.0) cmt->coords[i].mode = CS_FX_COPY; else cmt->coords[i].mode = CS_FX_SETALPHA(1.0-transparency); } catch(...) { cmt->coords[i].mode = CS_FX_COPY; } break; case A3DL::Material::BLEND_ADD: cmt->coords[i].mode = CS_FX_ADD; break; case A3DL::Material::BLEND_MULTIPLY: cmt->coords[i].mode = CS_FX_MULTIPLY; break; case A3DL::Material::BLEND_DOUBLE_MULTIPLY: cmt->coords[i].mode = CS_FX_MULTIPLY2; break; } try { if(mt->getShaded()) cmt->coords[i].mode |= CS_FX_GOURAUD; } catch(...) { } cmt->coords[i].mode |= CS_FX_TILING; // for software renderer :P } } } cmt->iscolor = false; } else { getColor(cmt->R, cmt->G, cmt->B); cmt->iscolor = true; } vosa3dl->mainThreadTasks.push(cmt); #if 0 // now go through our parents and let them know that this material is ready const ParentSet& parents = getParents(); for(ParentSet::const_iterator i = parents.begin(); i != parents.end(); i++) { Object3D* obj3d = meta_cast<Object3D*>((*i)->parent); if(obj3d) obj3d->setupMaterial(); } #endif return; } void csMetaMaterial::notifyPropertyChange(const PropertyEvent& event) { try { vRef<ParentChildRelation> pcr = event.getProperty()->findParent(*this); if(pcr->getContextualName() == "a3dl:color") { // XXX } } catch(NoSuchObjectError) { } catch(AccessControlError) { } catch(RemoteError) { } } csRef<iMaterialWrapper> csMetaMaterial::GetMaterialWrapper() { if(! materialwrapper.IsValid()) return GetCheckerboard(); return materialwrapper; } void csMetaMaterial::notifyChildInserted(VobjectEvent& event) { if(event.getContextualName() == "a3dl:texture") { // TODO: can we just modify the material's texture list? //clearMaterial(); //loadMaterial(); } vRef<Property> p = meta_cast<Property>(event.getNewChild()); if(p.isValid()) p->addPropertyListener(this); } void csMetaMaterial::notifyChildReplaced(VobjectEvent& event) { notifyChildRemoved(event); notifyChildInserted(event); } void csMetaMaterial::notifyChildRemoved(VobjectEvent& event) { if(event.getContextualName() == "a3dl:texture") { // TODO: can we just modify the material's texture list? //clearMaterial(); //loadMaterial(); } vRef<Property> p = meta_cast<Property>(event.getOldChild()); if(p.isValid()) p->removePropertyListener(this); } MetaObject* csMetaMaterial::new_csMetaMaterial(VobjectBase* superobject, const std::string& type) { return new csMetaMaterial(superobject); } <commit_msg>Fixed for API change (uses A3DL::Material::getAlpha now())<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- $Id$ This file is part of Crystal Space Virtual Object System Abstract 3D Layer plugin (csvosa3dl). Copyright (C) 2004 Peter Amstutz This program 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 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 program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "cssysdef.h" #include "csgfx/memimage.h" #include "csgfx/xorpat.h" #include "iutil/objreg.h" #include "ivideo/graph3d.h" #include "ivideo/material.h" #include "ivideo/txtmgr.h" #include "vosmaterial.h" #include "vostexture.h" #include "vosobject3d.h" csRef<iMaterialWrapper> csMetaMaterial::checkerboard; iObjectRegistry* csMetaMaterial::object_reg; using namespace VOS; class ConstructMaterialTask : public Task { public: vRef<csMetaTexture> base; std::vector<csMetaTexture*> layers; csTextureLayer* coords; vRef<csMetaMaterial> metamaterial; iObjectRegistry *object_reg; bool iscolor; float R, G, B; ConstructMaterialTask(iObjectRegistry *objreg, csMetaMaterial* mm); virtual ~ConstructMaterialTask(); virtual void doTask(); }; ConstructMaterialTask::ConstructMaterialTask(iObjectRegistry *objreg, csMetaMaterial* mm) : coords(0), metamaterial(mm, true), object_reg(objreg) { } ConstructMaterialTask::~ConstructMaterialTask() { } void ConstructMaterialTask::doTask() { csRef<iEngine> engine = CS_QUERY_REGISTRY (object_reg, iEngine); csRef<iGraphics3D> g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D); csRef<iTextureManager> txtmgr = g3d->GetTextureManager(); csRef<iMaterial> imat; if(base.isValid()) { csRef<iTextureWrapper> basetw = base->GetTextureWrapper(); if(layers.size() > 0) { iTextureWrapper** layertws = (iTextureWrapper**)malloc(layers.size() * sizeof(iTextureWrapper*)); for(unsigned int i = 0; i < layers.size(); i++) { layertws[i] = layers[i]->GetTextureWrapper(); layers[i]->release(); } imat = engine->CreateBaseMaterial(basetw, layers.size(), layertws, coords); free(layertws); free(coords); } else { imat = engine->CreateBaseMaterial(basetw); } } else { if(iscolor) { // we tried some alternate ways of doing colors! /* csRef<iMaterial> color = engine->CreateBaseMaterial(0); int red = strtol(newproperty.substr(1, 2).c_str(), 0, 16); int green = strtol(newproperty.substr(3, 2).c_str(), 0, 16); int blue = strtol(newproperty.substr(5, 2).c_str(), 0, 16); color->SetFlatColor(csRGBcolor(red, green, blue)); if(!material) { material = engine->GetMaterialList()->NewMaterial(color); material->QueryObject()->SetName(p.getURL().getString().c_str()); } material->SetMaterial(color); material->Register(txtmgr); material->GetMaterialHandle()->Prepare (); */ /* csRef<iMaterial> color = engine->CreateBaseMaterial(0); color->SetFlatColor(csRGBcolor((int)(r*255), (int)(g*255), (int)(b*255))); if(!material) { material = engine->GetMaterialList()->NewMaterial(color); material->QueryObject()->SetName(p.getURL().getString().c_str()); } material->SetMaterial(color); material->Register(txtmgr); material->GetMaterialHandle()->Prepare (); */ iTextureWrapper* txtwrap; txtwrap = engine->CreateBlackTexture("", 2, 2, 0, CS_TEXTURE_3D); csImageMemory* img = new csImageMemory(1, 1); csRGBpixel px((int)(R*255.0), (int)(G*255.0), (int)(B*255.0)); img->Clear(px); txtwrap->SetImageFile(img); txtwrap->Register(txtmgr); txtwrap->GetTextureHandle()->Prepare (); imat = engine->CreateBaseMaterial(txtwrap); } } if(imat.IsValid()) { csRef<iMaterialWrapper> material = engine->GetMaterialList()->NewMaterial(imat); if(!material) return; material->Register(txtmgr); material->GetMaterialHandle()->Prepare(); metamaterial->materialwrapper = material; } } csMetaMaterial::csMetaMaterial(VobjectBase* superobject) : A3DL::Material(superobject), alreadyLoaded(false) { } csMetaMaterial::~csMetaMaterial() { } void csMetaMaterial::CreateCheckerboard() { csRef<iEngine> engine = CS_QUERY_REGISTRY (object_reg, iEngine); csRef<iGraphics3D> g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D); csRef<iImage> im = csCreateXORPatternImage(64, 64, 6); csRef<iTextureManager> txtmgr = g3d->GetTextureManager(); csRef<iTextureHandle> th = txtmgr->RegisterTexture (im, CS_TEXTURE_3D); csRef<iTextureWrapper> tw = engine->GetTextureList()->NewTexture(th); tw->SetImageFile(im); csRef<iMaterial> mat = engine->CreateBaseMaterial(tw); checkerboard = engine->GetMaterialList()->NewMaterial(mat); th->Prepare(); checkerboard->Register(txtmgr); checkerboard->GetMaterialHandle()->Prepare(); } /** Return CS iMaterialWrapper interface for this object */ csRef<iMaterialWrapper> csMetaMaterial::GetCheckerboard() { if(! checkerboard.IsValid()) CreateCheckerboard(); return checkerboard; } void csMetaMaterial::Setup(csVosA3DL* vosa3dl) { LOG("csMetaMaterial", 3, "setting up material"); ConstructMaterialTask* cmt = new ConstructMaterialTask(vosa3dl->GetObjectRegistry(), this); A3DL::TextureIterator txt = getTextureLayers(); if(txt.hasMore()) { vRef<csMetaTexture> base = meta_cast<csMetaTexture>(*txt); if(base.isValid()) { base->Setup(vosa3dl); cmt->base = base; } txt++; if(txt.hasMore()) { cmt->coords = (csTextureLayer*)malloc(txt.remaining() * sizeof(csTextureLayer)); float uscale = 1, vscale = 1, ushift = 0, vshift = 0; for(int i = 0; txt.hasMore(); txt++, i++) { vRef<csMetaTexture> mt = meta_cast<csMetaTexture>(*txt); if(mt.isValid()) { mt->Setup(vosa3dl); mt->acquire(); cmt->layers.push_back(&mt); try { mt->getUVScaleAndShift(uscale, vscale, ushift, vshift); } catch(std::runtime_error& e) { uscale = 1; vscale = 1; ushift = 0; vshift = 0; } cmt->coords[i].uscale = uscale; cmt->coords[i].vscale = vscale; cmt->coords[i].ushift = ushift; cmt->coords[i].vshift = vshift; switch(mt->getBlendMode()) { case A3DL::Material::BLEND_NORMAL: try { double alpha = mt->getAlpha(); if(alpha == 0.0) cmt->coords[i].mode = CS_FX_TRANSPARENT; else if(alpha == 1.0) cmt->coords[i].mode = CS_FX_COPY; else cmt->coords[i].mode = CS_FX_SETALPHA(alpha); } catch(...) { cmt->coords[i].mode = CS_FX_COPY; } break; case A3DL::Material::BLEND_ADD: cmt->coords[i].mode = CS_FX_ADD; break; case A3DL::Material::BLEND_MULTIPLY: cmt->coords[i].mode = CS_FX_MULTIPLY; break; case A3DL::Material::BLEND_DOUBLE_MULTIPLY: cmt->coords[i].mode = CS_FX_MULTIPLY2; break; } try { if(mt->getShaded()) cmt->coords[i].mode |= CS_FX_GOURAUD; } catch(...) { } cmt->coords[i].mode |= CS_FX_TILING; // for software renderer :P } } } cmt->iscolor = false; } else { getColor(cmt->R, cmt->G, cmt->B); cmt->iscolor = true; } vosa3dl->mainThreadTasks.push(cmt); #if 0 // now go through our parents and let them know that this material is ready const ParentSet& parents = getParents(); for(ParentSet::const_iterator i = parents.begin(); i != parents.end(); i++) { Object3D* obj3d = meta_cast<Object3D*>((*i)->parent); if(obj3d) obj3d->setupMaterial(); } #endif return; } void csMetaMaterial::notifyPropertyChange(const PropertyEvent& event) { try { vRef<ParentChildRelation> pcr = event.getProperty()->findParent(*this); if(pcr->getContextualName() == "a3dl:color") { // XXX } } catch(NoSuchObjectError) { } catch(AccessControlError) { } catch(RemoteError) { } } csRef<iMaterialWrapper> csMetaMaterial::GetMaterialWrapper() { if(! materialwrapper.IsValid()) return GetCheckerboard(); return materialwrapper; } void csMetaMaterial::notifyChildInserted(VobjectEvent& event) { if(event.getContextualName() == "a3dl:texture") { // TODO: can we just modify the material's texture list? //clearMaterial(); //loadMaterial(); } vRef<Property> p = meta_cast<Property>(event.getNewChild()); if(p.isValid()) p->addPropertyListener(this); } void csMetaMaterial::notifyChildReplaced(VobjectEvent& event) { notifyChildRemoved(event); notifyChildInserted(event); } void csMetaMaterial::notifyChildRemoved(VobjectEvent& event) { if(event.getContextualName() == "a3dl:texture") { // TODO: can we just modify the material's texture list? //clearMaterial(); //loadMaterial(); } vRef<Property> p = meta_cast<Property>(event.getOldChild()); if(p.isValid()) p->removePropertyListener(this); } MetaObject* csMetaMaterial::new_csMetaMaterial(VobjectBase* superobject, const std::string& type) { return new csMetaMaterial(superobject); } <|endoftext|>
<commit_before>#include <primitives/command.h> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/nowide/convert.hpp> #include <boost/process.hpp> #include <iostream> namespace primitives { namespace bp = boost::process; struct CommandData { std::unique_ptr<boost::asio::io_service> ios; std::unique_ptr<boost::process::async_pipe> pout, perr; std::unique_ptr<boost::process::child> c; using cb_func = std::function<void(const boost::system::error_code &, std::size_t)>; cb_func out_cb, err_cb; std::function<void(int, const std::error_code &)> on_exit; std::function<void(const boost::system::error_code &ec, std::size_t s, Command::Stream &out, boost::process::async_pipe &p, Command::Buffer &out_buf, cb_func &out_cb, std::ostream &stream)> async_read; Command::Buffer out_buf, err_buf; }; path resolve_executable(const path &p) { return bp::search_path(p); } path resolve_executable(const std::vector<path> &paths) { for (auto &p : paths) { auto e = resolve_executable(p); if (!e.empty()) return e; } return path(); } Command::Command() { } Command::~Command() { } void Command::execute1(std::error_code *ec_in) { // setup // try to use first arg as a program if (program.empty()) { if (args.empty()) throw std::runtime_error("No program was set"); program = args[0]; auto t = std::move(args); args.assign(t.begin() + 1, t.end()); } // resolve exe { auto p = resolve_executable(program); if (p.empty()) { if (!ec_in) throw std::runtime_error("Cannot resolve executable: " + program.string()); *ec_in = std::make_error_code(std::errc::no_such_file_or_directory); return; } program = p; } if (working_directory.empty()) working_directory = fs::current_path(); d = std::make_unique<CommandData>(); boost::asio::io_service *ios_ptr; if (io_service) ios_ptr = io_service; else { d->ios = std::make_unique<boost::asio::io_service>(); ios_ptr = d->ios.get(); } d->pout = std::make_unique<bp::async_pipe>(*ios_ptr); d->perr = std::make_unique<bp::async_pipe>(*ios_ptr); d->on_exit = [this, ec_in](int exit, const std::error_code &ec) { exit_code = exit; // return if ok if (exit_code == 0) return; // set ec, if passed if (ec_in) { if (ec) *ec_in = ec; else ec_in->assign(1, std::generic_category()); return; } // throw now String s; s += "\"" + program.string() + "\" "; for (auto &a : args) s += "\"" + a + "\" "; s.resize(s.size() - 1); throw std::runtime_error("Last command failed: " + s + ", exit code = " + std::to_string(exit_code)); }; d->async_read = [this](const boost::system::error_code &ec, std::size_t s, auto &out, auto &p, auto &out_buf, auto &&out_cb, auto &stream) { if (s) { String str(out_buf.begin(), out_buf.begin() + s); out.text += str; if (inherit || out.inherit) stream << str; if (out.action) out.action(str, ec); } if (!ec) boost::asio::async_read(p, boost::asio::buffer(out_buf), out_cb); else p.async_close(); }; // setup buffers also before child creation d->out_buf.resize(buf_size); d->err_buf.resize(buf_size); d->out_cb = [this](const boost::system::error_code &ec, std::size_t s) { d->async_read(ec, s, out, *d->pout.get(), d->out_buf, d->out_cb, std::cout); }; d->err_cb = [this](const boost::system::error_code &ec, std::size_t s) { d->async_read(ec, s, err, *d->perr.get(), d->err_buf, d->err_cb, std::cerr); }; boost::asio::async_read(*d->pout.get(), boost::asio::buffer(d->out_buf), d->out_cb); boost::asio::async_read(*d->perr.get(), boost::asio::buffer(d->err_buf), d->err_cb); #ifdef _WIN32 // widen args std::vector<std::wstring> wargs; for (auto &a : args) wargs.push_back(boost::nowide::widen(a)); #else const Strings &wargs = args; #endif // run if (ec_in) { d->c = std::make_unique<bp::child>( program , bp::args = wargs , bp::start_dir = working_directory , bp::std_in < stdin , bp::std_out > *d->pout.get() , bp::std_err > *d->perr.get() , bp::on_exit(d->on_exit) , *ios_ptr , *ec_in ); } else { d->c = std::make_unique<bp::child>( program , bp::args = wargs , bp::start_dir = working_directory , bp::std_in < stdin , bp::std_out > *d->pout.get() , bp::std_err > *d->perr.get() , bp::on_exit(d->on_exit) , *ios_ptr ); } // perform io only in case we didn't get external io_service if (d->ios) ios_ptr->run(); } void Command::write(path p) const { auto fn = p.filename().string(); p = p.parent_path(); write_file(p / (fn + "_out.txt"), out.text); write_file(p / (fn + "_err.txt"), err.text); } void Command::execute1(const path &p, const Strings &args, std::error_code *ec) { Command c; c.program = p; c.args = args; c.execute1(ec); } void Command::execute(const path &p) { execute1(p); } void Command::execute(const path &p, std::error_code &ec) { execute1(p, Strings(), &ec); } void Command::execute(const path &p, const Strings &args) { execute1(p, args); } void Command::execute(const path &p, const Strings &args, std::error_code &ec) { execute1(p, args, &ec); } void Command::execute(const Strings &args) { Command c; c.args = args; c.execute(); } void Command::execute(const Strings &args, std::error_code &ec) { Command c; c.args = args; c.execute(ec); } void Command::execute(const std::initializer_list<String> &args) { execute(Strings(args.begin(), args.end())); } void Command::execute(const std::initializer_list<String> &args, std::error_code &ec) { execute(Strings(args.begin(), args.end()), ec); } } <commit_msg>Throw error only after pipes are closed.<commit_after>#include <primitives/command.h> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/nowide/convert.hpp> #include <boost/process.hpp> #include <iostream> namespace primitives { namespace bp = boost::process; struct CommandData { std::unique_ptr<boost::asio::io_service> ios; std::unique_ptr<boost::process::async_pipe> pout, perr; std::unique_ptr<boost::process::child> c; using cb_func = std::function<void(const boost::system::error_code &, std::size_t)>; cb_func out_cb, err_cb; std::function<void(int, const std::error_code &)> on_exit; std::function<void(void)> on_error; std::function<void(const boost::system::error_code &ec, std::size_t s, Command::Stream &out, boost::process::async_pipe &p, Command::Buffer &out_buf, cb_func &out_cb, std::ostream &stream)> async_read; std::atomic_int pipes_closed{ 0 }; Command::Buffer out_buf, err_buf; }; path resolve_executable(const path &p) { return bp::search_path(p); } path resolve_executable(const std::vector<path> &paths) { for (auto &p : paths) { auto e = resolve_executable(p); if (!e.empty()) return e; } return path(); } Command::Command() { } Command::~Command() { } void Command::execute1(std::error_code *ec_in) { // setup // try to use first arg as a program if (program.empty()) { if (args.empty()) throw std::runtime_error("No program was set"); program = args[0]; auto t = std::move(args); args.assign(t.begin() + 1, t.end()); } // resolve exe { auto p = resolve_executable(program); if (p.empty()) { if (!ec_in) throw std::runtime_error("Cannot resolve executable: " + program.string()); *ec_in = std::make_error_code(std::errc::no_such_file_or_directory); return; } program = p; } if (working_directory.empty()) working_directory = fs::current_path(); d = std::make_unique<CommandData>(); boost::asio::io_service *ios_ptr; if (io_service) ios_ptr = io_service; else { d->ios = std::make_unique<boost::asio::io_service>(); ios_ptr = d->ios.get(); } d->pout = std::make_unique<bp::async_pipe>(*ios_ptr); d->perr = std::make_unique<bp::async_pipe>(*ios_ptr); d->on_error = [this, &ios_ptr]() { if (d->pipes_closed != 2) { ios_ptr->post([this] {d->on_error(); }); return; } // throw now String s; s += "\"" + program.string() + "\" "; for (auto &a : args) s += "\"" + a + "\" "; s.resize(s.size() - 1); throw std::runtime_error("Last command failed: " + s + ", exit code = " + std::to_string(exit_code)); }; d->on_exit = [this, ec_in](int exit, const std::error_code &ec) { exit_code = exit; // return if ok if (exit_code == 0) return; // set ec, if passed if (ec_in) { if (ec) *ec_in = ec; else ec_in->assign(1, std::generic_category()); return; } d->on_error(); }; d->async_read = [this](const boost::system::error_code &ec, std::size_t s, auto &out, auto &p, auto &out_buf, auto &&out_cb, auto &stream) { if (s) { String str(out_buf.begin(), out_buf.begin() + s); out.text += str; if (inherit || out.inherit) stream << str; if (out.action) out.action(str, ec); } if (!ec) boost::asio::async_read(p, boost::asio::buffer(out_buf), out_cb); else { p.async_close(); d->pipes_closed++; } }; // setup buffers also before child creation d->out_buf.resize(buf_size); d->err_buf.resize(buf_size); d->out_cb = [this](const boost::system::error_code &ec, std::size_t s) { d->async_read(ec, s, out, *d->pout.get(), d->out_buf, d->out_cb, std::cout); }; d->err_cb = [this](const boost::system::error_code &ec, std::size_t s) { d->async_read(ec, s, err, *d->perr.get(), d->err_buf, d->err_cb, std::cerr); }; boost::asio::async_read(*d->pout.get(), boost::asio::buffer(d->out_buf), d->out_cb); boost::asio::async_read(*d->perr.get(), boost::asio::buffer(d->err_buf), d->err_cb); #ifdef _WIN32 // widen args std::vector<std::wstring> wargs; for (auto &a : args) wargs.push_back(boost::nowide::widen(a)); #else const Strings &wargs = args; #endif // run if (ec_in) { d->c = std::make_unique<bp::child>( program , bp::args = wargs , bp::start_dir = working_directory , bp::std_in < stdin , bp::std_out > *d->pout.get() , bp::std_err > *d->perr.get() , bp::on_exit(d->on_exit) , *ios_ptr , *ec_in ); } else { d->c = std::make_unique<bp::child>( program , bp::args = wargs , bp::start_dir = working_directory , bp::std_in < stdin , bp::std_out > *d->pout.get() , bp::std_err > *d->perr.get() , bp::on_exit(d->on_exit) , *ios_ptr ); } // perform io only in case we didn't get external io_service if (d->ios) { ios_ptr->run(); } } void Command::write(path p) const { auto fn = p.filename().string(); p = p.parent_path(); write_file(p / (fn + "_out.txt"), out.text); write_file(p / (fn + "_err.txt"), err.text); } void Command::execute1(const path &p, const Strings &args, std::error_code *ec) { Command c; c.program = p; c.args = args; c.execute1(ec); } void Command::execute(const path &p) { execute1(p); } void Command::execute(const path &p, std::error_code &ec) { execute1(p, Strings(), &ec); } void Command::execute(const path &p, const Strings &args) { execute1(p, args); } void Command::execute(const path &p, const Strings &args, std::error_code &ec) { execute1(p, args, &ec); } void Command::execute(const Strings &args) { Command c; c.args = args; c.execute(); } void Command::execute(const Strings &args, std::error_code &ec) { Command c; c.args = args; c.execute(ec); } void Command::execute(const std::initializer_list<String> &args) { execute(Strings(args.begin(), args.end())); } void Command::execute(const std::initializer_list<String> &args, std::error_code &ec) { execute(Strings(args.begin(), args.end()), ec); } } <|endoftext|>
<commit_before><commit_msg>`scene_must_bind_to_worlds_appropriately`: more assertions.<commit_after><|endoftext|>
<commit_before><commit_msg>Fixed a typo in a weather description.<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef QUEUEDITEM_HH #define QUEUEDITEM_HH 1 #include "common.hh" #include "item.hh" #include "stats.hh" enum queue_operation { queue_op_set, queue_op_del, queue_op_flush, queue_op_empty, queue_op_commit, queue_op_checkpoint_start, queue_op_checkpoint_end }; typedef enum { vbucket_del_success, vbucket_del_fail, vbucket_del_invalid } vbucket_del_result; /** * Representation of an item queued for persistence or tap. */ class QueuedItem { public: QueuedItem(const std::string &k, const uint16_t vb, enum queue_operation o, const uint16_t vb_version = -1, const int64_t rid = -1, const uint32_t f = 0, const time_t expiry_time = 0, const uint64_t cv = 0) : op(o),vbucket_version(vb_version), queued(ep_current_time()), dirtied(ep_current_time()), item(new Item(k, f, expiry_time, NULL, 0, cv, rid, vb)) { // Exclude the value size as it is included in the kv memory overhead. stats->memOverhead.incr(size() - getValue()->length()); assert(stats->memOverhead.get() < GIGANTOR); } QueuedItem(const std::string &k, value_t v, const uint16_t vb, enum queue_operation o, const uint16_t vb_version = -1, const int64_t rid = -1, const uint32_t f = 0, const time_t expiry_time = 0, const uint64_t cv = 0) : op(o), vbucket_version(vb_version), queued(ep_current_time()), dirtied(ep_current_time()), item(new Item(k, f, expiry_time, v, cv, rid, vb)) { // Exclude the value size as it is included in the kv memory overhead. stats->memOverhead.incr(size() - getValue()->length()); assert(stats->memOverhead.get() < GIGANTOR); } ~QueuedItem() { // Exclude the value size as it is included in the kv memory overhead. stats->memOverhead.decr(size() - getValue()->length()); assert(stats->memOverhead.get() < GIGANTOR); } const std::string &getKey(void) const { return item->getKey(); } uint16_t getVBucketId(void) const { return item->getVBucketId(); } uint16_t getVBucketVersion(void) const { return vbucket_version; } uint32_t getQueuedTime(void) const { return queued; } enum queue_operation getOperation(void) const { return op; } int64_t getRowId() const { return item->getId(); } uint32_t getDirtiedTime() const { return dirtied; } uint32_t getFlags() const { return item->getFlags(); } time_t getExpiryTime() const { return item->getExptime(); } uint64_t getCas() const { return item->getCas(); } value_t getValue() const { return item->getValue(); } Item &getItem() { return *item; } void setQueuedTime(uint32_t queued_time) { queued = queued_time; } bool operator <(const QueuedItem &other) const { return getVBucketId() == other.getVBucketId() ? getKey() < other.getKey() : getVBucketId() < other.getVBucketId(); } size_t size() const { return sizeof(QueuedItem) + item->size(); } static void init(EPStats * st) { stats = st; } private: enum queue_operation op; uint16_t vbucket_version; uint32_t queued; // Additional variables below are required to support the checkpoint and cursors // as memory hashtable always contains the latest value and latest meta data for each key. uint32_t dirtied; shared_ptr<Item> item; static EPStats *stats; DISALLOW_COPY_AND_ASSIGN(QueuedItem); }; typedef shared_ptr<QueuedItem> queued_item; /** * Order QueuedItem objects pointed by shared_ptr by their keys. */ class CompareQueuedItemsByKey { public: CompareQueuedItemsByKey() {} bool operator()(const queued_item &i1, const queued_item &i2) { return i1->getKey() < i2->getKey(); } }; /** * Order QueuedItem objects by their row ids. */ class CompareQueuedItemsByRowId { public: CompareQueuedItemsByRowId() {} bool operator()(const queued_item &i1, const queued_item &i2) { return i1->getRowId() < i2->getRowId(); } }; /** * Order QueuedItem objects by their vbucket then row ids. */ class CompareQueuedItemsByVBAndRowId { public: CompareQueuedItemsByVBAndRowId() {} bool operator()(const queued_item &i1, const queued_item &i2) { return i1->getVBucketId() == i2->getVBucketId() ? i1->getRowId() < i2->getRowId() : i1->getVBucketId() < i2->getVBucketId(); } }; /** * Compare two Schwartzian-transformed QueuedItems. */ template <typename T> class TaggedQueuedItemComparator { public: TaggedQueuedItemComparator() {} bool operator()(std::pair<T, queued_item> i1, std::pair<T, queued_item> i2) { return (i1.first == i2.first) ? (i1.second->getRowId() < i2.second->getRowId()) : (i1 < i2); } }; #endif /* QUEUEDITEM_HH */ <commit_msg>Do not use shared_ptr for Item instance in QueuedItem class.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef QUEUEDITEM_HH #define QUEUEDITEM_HH 1 #include "common.hh" #include "item.hh" #include "stats.hh" enum queue_operation { queue_op_set, queue_op_del, queue_op_flush, queue_op_empty, queue_op_commit, queue_op_checkpoint_start, queue_op_checkpoint_end }; typedef enum { vbucket_del_success, vbucket_del_fail, vbucket_del_invalid } vbucket_del_result; /** * Representation of an item queued for persistence or tap. */ class QueuedItem { public: QueuedItem(const std::string &k, const uint16_t vb, enum queue_operation o, const uint16_t vb_version = -1, const int64_t rid = -1, const uint32_t f = 0, const time_t expiry_time = 0, const uint64_t cv = 0) : op(o),vbucket_version(vb_version), queued(ep_current_time()), dirtied(ep_current_time()), item(k, f, expiry_time, NULL, 0, cv, rid, vb) { // Exclude the value size as it is included in the kv memory overhead. stats->memOverhead.incr(size() - getValue()->length()); assert(stats->memOverhead.get() < GIGANTOR); } QueuedItem(const std::string &k, value_t v, const uint16_t vb, enum queue_operation o, const uint16_t vb_version = -1, const int64_t rid = -1, const uint32_t f = 0, const time_t expiry_time = 0, const uint64_t cv = 0) : op(o), vbucket_version(vb_version), queued(ep_current_time()), dirtied(ep_current_time()), item(k, f, expiry_time, v, cv, rid, vb) { // Exclude the value size as it is included in the kv memory overhead. stats->memOverhead.incr(size() - getValue()->length()); assert(stats->memOverhead.get() < GIGANTOR); } ~QueuedItem() { // Exclude the value size as it is included in the kv memory overhead. stats->memOverhead.decr(size() - getValue()->length()); assert(stats->memOverhead.get() < GIGANTOR); } const std::string &getKey(void) const { return item.getKey(); } uint16_t getVBucketId(void) const { return item.getVBucketId(); } uint16_t getVBucketVersion(void) const { return vbucket_version; } uint32_t getQueuedTime(void) const { return queued; } enum queue_operation getOperation(void) const { return op; } int64_t getRowId() const { return item.getId(); } uint32_t getDirtiedTime() const { return dirtied; } uint32_t getFlags() const { return item.getFlags(); } time_t getExpiryTime() const { return item.getExptime(); } uint64_t getCas() const { return item.getCas(); } value_t getValue() const { return item.getValue(); } Item &getItem() { return item; } void setQueuedTime(uint32_t queued_time) { queued = queued_time; } bool operator <(const QueuedItem &other) const { return getVBucketId() == other.getVBucketId() ? getKey() < other.getKey() : getVBucketId() < other.getVBucketId(); } size_t size() { return sizeof(QueuedItem) + getKey().size() + getValue()->length(); } static void init(EPStats * st) { stats = st; } private: enum queue_operation op; uint16_t vbucket_version; uint32_t queued; // Additional variables below are required to support the checkpoint and cursors // as memory hashtable always contains the latest value and latest meta data for each key. uint32_t dirtied; Item item; static EPStats *stats; DISALLOW_COPY_AND_ASSIGN(QueuedItem); }; typedef shared_ptr<QueuedItem> queued_item; /** * Order QueuedItem objects pointed by shared_ptr by their keys. */ class CompareQueuedItemsByKey { public: CompareQueuedItemsByKey() {} bool operator()(const queued_item &i1, const queued_item &i2) { return i1->getKey() < i2->getKey(); } }; /** * Order QueuedItem objects by their row ids. */ class CompareQueuedItemsByRowId { public: CompareQueuedItemsByRowId() {} bool operator()(const queued_item &i1, const queued_item &i2) { return i1->getRowId() < i2->getRowId(); } }; /** * Order QueuedItem objects by their vbucket then row ids. */ class CompareQueuedItemsByVBAndRowId { public: CompareQueuedItemsByVBAndRowId() {} bool operator()(const queued_item &i1, const queued_item &i2) { return i1->getVBucketId() == i2->getVBucketId() ? i1->getRowId() < i2->getRowId() : i1->getVBucketId() < i2->getVBucketId(); } }; /** * Compare two Schwartzian-transformed QueuedItems. */ template <typename T> class TaggedQueuedItemComparator { public: TaggedQueuedItemComparator() {} bool operator()(std::pair<T, queued_item> i1, std::pair<T, queued_item> i2) { return (i1.first == i2.first) ? (i1.second->getRowId() < i2.second->getRowId()) : (i1 < i2); } }; #endif /* QUEUEDITEM_HH */ <|endoftext|>