text
stringlengths
54
60.6k
<commit_before>#include "Browser.h" #include "Log.h" #include <map> #include <cstdio> #include <cstring> #include <cstdlib> #include <cassert> typedef std::map<const char*, Browser::factory_callback> factory_map; typedef std::pair<const char*, Browser::factory_callback> pair; typedef factory_map::iterator iterator; factory_map* factories = NULL; Browser::Browser(const browser_context_t& context): _bin(0), _username(NULL), _password(NULL), _database(NULL), _hostname(NULL){ set_username(context.user); set_password(context.pass); set_hostname(context.host); set_database(context.name); } Browser::~Browser(){ set_username(NULL); set_password(NULL); set_hostname(NULL); set_database(NULL); } void Browser::set_username(const char* username){ set_string(_username, username); } void Browser::set_password(const char* password){ set_string(_password, password); } void Browser::set_database(const char* database){ set_string(_database, database); } void Browser::set_hostname(const char* hostname){ set_string(_hostname, hostname); } void Browser::set_string(char*& dst, const char* src){ free(dst); dst = NULL; if ( !src ){ return; } dst = (char*)malloc( strlen(src) + 1 ); strcpy(dst, src); } void Browser::register_factory(factory_callback callback, const char* name){ if ( !factories ){ factories = new factory_map; } factories->insert(pair(name, callback)); } Browser* Browser::factory(const char* string, const char* password){ if ( !(factories && string) ){ return NULL; } browser_context_t context = get_context(string); // If the contex doesn't contain a password and a password was passed from stdin (arg password) // we set that as the password in the context. if ( !context.pass && password ){ context.pass = (char*)malloc( strlen(password) + 1 ); strcpy(context.pass, password); } for ( iterator it = factories->begin(); it != factories->end(); ++it ){ if ( strcmp(context.provider, it->first) == 0){ Browser* browser = it->second(context); free_context(context); return browser; } } Log::message(Log::Warning, "Unknown database provider '%s'\n", context.provider); free_context(context); return NULL; } <commit_msg>Removed some includes<commit_after>#include "Browser.h" #include "Log.h" #include <map> #include <cstring> #include <cstdlib> typedef std::map<const char*, Browser::factory_callback> factory_map; typedef std::pair<const char*, Browser::factory_callback> pair; typedef factory_map::iterator iterator; factory_map* factories = NULL; Browser::Browser(const browser_context_t& context): _bin(0), _username(NULL), _password(NULL), _database(NULL), _hostname(NULL){ set_username(context.user); set_password(context.pass); set_hostname(context.host); set_database(context.name); } Browser::~Browser(){ set_username(NULL); set_password(NULL); set_hostname(NULL); set_database(NULL); } void Browser::set_username(const char* username){ set_string(_username, username); } void Browser::set_password(const char* password){ set_string(_password, password); } void Browser::set_database(const char* database){ set_string(_database, database); } void Browser::set_hostname(const char* hostname){ set_string(_hostname, hostname); } void Browser::set_string(char*& dst, const char* src){ free(dst); dst = NULL; if ( !src ){ return; } dst = (char*)malloc( strlen(src) + 1 ); strcpy(dst, src); } void Browser::register_factory(factory_callback callback, const char* name){ if ( !factories ){ factories = new factory_map; } factories->insert(pair(name, callback)); } Browser* Browser::factory(const char* string, const char* password){ if ( !(factories && string) ){ return NULL; } browser_context_t context = get_context(string); // If the contex doesn't contain a password and a password was passed from stdin (arg password) // we set that as the password in the context. if ( !context.pass && password ){ context.pass = (char*)malloc( strlen(password) + 1 ); strcpy(context.pass, password); } for ( iterator it = factories->begin(); it != factories->end(); ++it ){ if ( strcmp(context.provider, it->first) == 0){ Browser* browser = it->second(context); free_context(context); return browser; } } Log::message(Log::Warning, "Unknown database provider '%s'\n", context.provider); free_context(context); return NULL; } <|endoftext|>
<commit_before>#include "Context.h" #include <cmath> #include <iostream> #ifdef OPENGL #include <glm/glm.hpp> #endif using namespace std; using namespace canvas; void Context::resize(unsigned int _width, unsigned int _height) { width = _width; height = _height; getDefaultSurface().resize(_width, _height); } void Context::rect(double x, double y, double w, double h) { moveTo(x, y); lineTo(x + w, y); lineTo(x + w, y + h); lineTo(x, y + h); closePath(); } void Context::fillRect(double x, double y, double w, double h) { save(); beginPath(); rect(x, y, w, h); fill(); beginPath(); // tmp fix restore(); } void Context::strokeRect(double x, double y, double w, double h) { beginPath(); rect(x, y, w, h); stroke(); } void Context::fillText(const std::string & text, double x, double y) { if (hasShadow()) { float bx = shadowBlurX ? shadowBlurX : shadowBlur, by = shadowBlurY ? shadowBlurY : shadowBlur; auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * bx, getDefaultSurface().getHeight() + 2 * by); Style shadow_style = shadowColor; shadow->fillText(font, shadow_style, textBaseline, textAlign, text, x + shadowOffsetX + bx, y + shadowOffsetY + by); shadow->gaussianBlur(bx, by); getDefaultSurface().drawImage(*shadow, -bx, -by, shadow->getWidth(), shadow->getHeight()); } getDefaultSurface().fillText(font, fillStyle, textBaseline, textAlign, text, x, y); } void Context::strokeText(const std::string & text, double x, double y) { if (hasShadow()) { float bx = shadowBlurX ? shadowBlurX : shadowBlur, by = shadowBlurY ? shadowBlurY : shadowBlur; auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * bx, getDefaultSurface().getHeight() + 2 * by); Style shadow_style = shadowColor; shadow->strokeText(font, shadow_style, textBaseline, textAlign, text, x + shadowOffsetX + bx, y + shadowOffsetY + by); shadow->gaussianBlur(bx, by); getDefaultSurface().drawImage(*shadow, -bx, -by, shadow->getWidth(), shadow->getHeight()); } getDefaultSurface().strokeText(font, strokeStyle, textBaseline, textAlign, text, x, y); } void Context::fill() { if (hasShadow()) { float bx = shadowBlurX ? shadowBlurX : shadowBlur, by = shadowBlurY ? shadowBlurY : shadowBlur; auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * bx, getDefaultSurface().getHeight() + 2 * by); Style shadow_style = shadowColor; Path tmp_path = current_path; tmp_path.offset(shadowOffsetX + bx, shadowOffsetY + by); shadow->fill(tmp_path, shadow_style); shadow->gaussianBlur(bx, by); getDefaultSurface().drawImage(*shadow, -bx, -by, shadow->getWidth(), shadow->getHeight()); } getDefaultSurface().fill(current_path, fillStyle); } void Context::stroke() { if (hasShadow()) { float bx = shadowBlurX ? shadowBlurX : shadowBlur, by = shadowBlurY ? shadowBlurY : shadowBlur; auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * bx, getDefaultSurface().getHeight() + 2 * by); Style shadow_style = shadowColor; Path tmp_path = current_path; tmp_path.offset(shadowOffsetX + bx, shadowOffsetY + by); shadow->stroke(tmp_path, shadow_style, lineWidth); shadow->gaussianBlur(bx, by); getDefaultSurface().drawImage(*shadow, -bx, -by, shadow->getWidth(), shadow->getHeight()); } getDefaultSurface().stroke(current_path, strokeStyle, lineWidth); } void Context::drawImage(Surface & img, double x, double y, double w, double h) { if (hasShadow()) { float bx = shadowBlurX ? shadowBlurX : shadowBlur, by = shadowBlurY ? shadowBlurY : shadowBlur; auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * bx, getDefaultSurface().getHeight() + 2 * by); shadow->drawImage(img, x + shadowOffsetX + bx, y + shadowOffsetY + by, w, h, globalAlpha); shadow->colorFill(shadowColor); shadow->gaussianBlur(bx, by); getDefaultSurface().drawImage(*shadow, -bx, -by, shadow->getWidth(), shadow->getHeight()); } getDefaultSurface().drawImage(img, x, y, w, h, globalAlpha); } <commit_msg>cast floats to int<commit_after>#include "Context.h" #include <cmath> #include <iostream> #ifdef OPENGL #include <glm/glm.hpp> #endif using namespace std; using namespace canvas; void Context::resize(unsigned int _width, unsigned int _height) { width = _width; height = _height; getDefaultSurface().resize(_width, _height); } void Context::rect(double x, double y, double w, double h) { moveTo(x, y); lineTo(x + w, y); lineTo(x + w, y + h); lineTo(x, y + h); closePath(); } void Context::fillRect(double x, double y, double w, double h) { save(); beginPath(); rect(x, y, w, h); fill(); beginPath(); // tmp fix restore(); } void Context::strokeRect(double x, double y, double w, double h) { beginPath(); rect(x, y, w, h); stroke(); } void Context::fillText(const std::string & text, double x, double y) { if (hasShadow()) { float bx = shadowBlurX ? shadowBlurX : shadowBlur, by = shadowBlurY ? shadowBlurY : shadowBlur; auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * int(ceil(bx)), getDefaultSurface().getHeight() + 2 * int(ceil(by))); Style shadow_style = shadowColor; shadow->fillText(font, shadow_style, textBaseline, textAlign, text, x + shadowOffsetX + bx, y + shadowOffsetY + by); shadow->gaussianBlur(bx, by); getDefaultSurface().drawImage(*shadow, -bx, -by, shadow->getWidth(), shadow->getHeight()); } getDefaultSurface().fillText(font, fillStyle, textBaseline, textAlign, text, x, y); } void Context::strokeText(const std::string & text, double x, double y) { if (hasShadow()) { float bx = shadowBlurX ? shadowBlurX : shadowBlur, by = shadowBlurY ? shadowBlurY : shadowBlur; auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * int(ceil(bx)), getDefaultSurface().getHeight() + 2 * int(ceil(by))); Style shadow_style = shadowColor; shadow->strokeText(font, shadow_style, textBaseline, textAlign, text, x + shadowOffsetX + bx, y + shadowOffsetY + by); shadow->gaussianBlur(bx, by); getDefaultSurface().drawImage(*shadow, -bx, -by, shadow->getWidth(), shadow->getHeight()); } getDefaultSurface().strokeText(font, strokeStyle, textBaseline, textAlign, text, x, y); } void Context::fill() { if (hasShadow()) { float bx = shadowBlurX ? shadowBlurX : shadowBlur, by = shadowBlurY ? shadowBlurY : shadowBlur; auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * int(ceil(bx)), getDefaultSurface().getHeight() + 2 * int(ceil(by))); Style shadow_style = shadowColor; Path tmp_path = current_path; tmp_path.offset(shadowOffsetX + bx, shadowOffsetY + by); shadow->fill(tmp_path, shadow_style); shadow->gaussianBlur(bx, by); getDefaultSurface().drawImage(*shadow, -bx, -by, shadow->getWidth(), shadow->getHeight()); } getDefaultSurface().fill(current_path, fillStyle); } void Context::stroke() { if (hasShadow()) { float bx = shadowBlurX ? shadowBlurX : shadowBlur, by = shadowBlurY ? shadowBlurY : shadowBlur; auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * int(ceil(bx)), getDefaultSurface().getHeight() + 2 * int(ceil(by))); Style shadow_style = shadowColor; Path tmp_path = current_path; tmp_path.offset(shadowOffsetX + bx, shadowOffsetY + by); shadow->stroke(tmp_path, shadow_style, lineWidth); shadow->gaussianBlur(bx, by); getDefaultSurface().drawImage(*shadow, -bx, -by, shadow->getWidth(), shadow->getHeight()); } getDefaultSurface().stroke(current_path, strokeStyle, lineWidth); } void Context::drawImage(Surface & img, double x, double y, double w, double h) { if (hasShadow()) { float bx = shadowBlurX ? shadowBlurX : shadowBlur, by = shadowBlurY ? shadowBlurY : shadowBlur; auto shadow = createSurface(getDefaultSurface().getWidth() + 2 * int(ceil(bx)), getDefaultSurface().getHeight() + 2 * int(ceil(by))); shadow->drawImage(img, x + shadowOffsetX + bx, y + shadowOffsetY + by, w, h, globalAlpha); shadow->colorFill(shadowColor); shadow->gaussianBlur(bx, by); getDefaultSurface().drawImage(*shadow, -bx, -by, shadow->getWidth(), shadow->getHeight()); } getDefaultSurface().drawImage(img, x, y, w, h, globalAlpha); } <|endoftext|>
<commit_before>#include "gtest/gtest.h" TEST(Test, FIRST) { EXPECT_EQ(2,1+1); } TEST(Test, SECOND) { EXPECT_EQ(2,1); }<commit_msg>[NSTL]fix a test care<commit_after>#include "gtest/gtest.h" TEST(Test, FIRST) { EXPECT_EQ(2,1+1); } TEST(Test, SECOND) { EXPECT_EQ(2,2*1); }<|endoftext|>
<commit_before>#include <isl/set.h> #include <isl/union_map.h> #include <isl/union_set.h> #include <isl/ast_build.h> #include <isl/schedule.h> #include <isl/schedule_node.h> #include <coli/debug.h> #include <coli/core.h> #include <string.h> #include <Halide.h> /* Halide code. Func blurxy(Func input, Func blur_y) { Func blur_x; Var x, y, xi, yi; // The algorithm - no storage or order blur_x(x, y) = input(x, y) + input(x, y); blur_y(x, y) = blur_x(x, y) + blur_x(x, y); // The schedule - defines order, locality; implies storage blur_y.tile(x, y, xi, yi, 256, 32) .vectorize(xi, 8).parallel(y); blur_x.compute_at(blur_y, x).vectorize(x, 8); } */ int main(int argc, char **argv) { // Set default coli options. coli::global::set_default_coli_options(); /* * Declare a function fct. * Declare two arguments (coli buffers) for the function: input and blur_y * Declare an invariant for the function. */ coli::function fct("blurxy"); coli::argument a_input(coli::inputarg, "a_input", 2, {100,100}, Halide::Int(8), NULL, &fct); coli::argument a_blury(coli::outputarg, "a_blury", 2, {100,100}, Halide::Int(8), NULL, &fct); coli::invariant p0("N", Halide::Expr((int32_t) 100), &fct); // Declare the computations of the function fct. coli::computation computation0("[N]->{c_input[i,j]: 0<=i<N and 0<=j<N}", &a_input, &fct); coli::computation computation1("[N]->{c_blurx[i,j]: 0<=i<N and 0<=j<N}", Halide::Expr((uint8_t) 3), &fct); coli::computation computation2("[N]->{c_blury[i,j]: 0<=i<N and 0<=j<N}", Halide::Expr((uint8_t) 7), &a_blury, &fct); // Create a memory buffer (2 dimensional). coli::buffer buf0("b_blurx", 2, {100,100}, Halide::Int(8), NULL, &fct); // Map the computations to a buffer (i.e. where each computation // should be stored in the buffer). // This mapping will be updated automaticall when the schedule // is applied. To disable automatic data mapping updates use // coli::global::set_auto_data_mapping(false). computation0.set_access("{c_input[i,j]->b_input[i,j]}"); computation0.set_access("{c_blurx[i,j]->b_blurx[i,j]}"); computation0.set_access("{c_blury[i,j]->b_blury[i,j]}"); // Dump the iteration domain (input) for the function. fct.dump_iteration_domain(); // Set the schedule of each computation. // The identity schedule means that the program order is not modified // (i.e. no optimization is applied). c_blurx.tile(0,1,2,2); c_blurx.tag_parallel_dimension(0); c_blury.set_schedule("{blury[i,j]->[i,j]}"); c_blury.after(c_blurx, coli::computation::root_dimension); // Generate the time-processor domain of the computation // and dump it on stdout. fct.gen_time_processor_domain(); fct.dump_time_processor_domain(); // Generate an AST (abstract Syntax Tree) fct.gen_isl_ast(); // Generate Halide statement for the function. fct.gen_halide_stmt(); // If you want to get the generated halide statements, call // fct.get_halide_stmts(). // Dump the Halide stmt generated by gen_halide_stmt() // for the function. fct.dump_halide_stmt(); // Generate an object file from the function. fct.gen_halide_obj("build/generated_lib_tutorial_01.o"); return 0; } <commit_msg>Update tutorial<commit_after>#include <isl/set.h> #include <isl/union_map.h> #include <isl/union_set.h> #include <isl/ast_build.h> #include <isl/schedule.h> #include <isl/schedule_node.h> #include <coli/debug.h> #include <coli/core.h> #include <string.h> #include <Halide.h> /* Halide code. Func blurxy(Func input, Func blur_y) { Func blur_x; Var x, y, xi, yi; // The algorithm - no storage or order blur_x(x, y) = input(x, y) + input(x, y); blur_y(x, y) = blur_x(x, y) + blur_x(x, y); // The schedule - defines order, locality; implies storage blur_y.tile(x, y, xi, yi, 256, 32) .vectorize(xi, 8).parallel(y); blur_x.compute_at(blur_y, x).vectorize(x, 8); } */ int main(int argc, char **argv) { // Set default coli options. coli::global::set_default_coli_options(); /* * Declare a function fct. * Declare two arguments (coli buffers) for the function: input and blur_y * Declare an invariant for the function. */ coli::function blurxy("blurxy"); coli::argument a_input(coli::inputarg, "a_input", 2, {100,100}, Halide::Int(8), NULL, &fct); coli::argument a_blury(coli::outputarg, "a_blury", 2, {100,100}, Halide::Int(8), NULL, &fct); coli::invariant N("N", Halide::Expr((int32_t) 100), &fct); // Declare the computations of the function fct. coli::computation computation0("[N]->{c_input[i,j]: 0<=i<N and 0<=j<N}", &a_input, &fct); coli::computation computation1("[N]->{c_blurx[i,j]: 0<=i<N and 0<=j<N}", Halide::Expr((uint8_t) 3), &fct); coli::computation computation2("[N]->{c_blury[i,j]: 0<=i<N and 0<=j<N}", Halide::Expr((uint8_t) 7), &a_blury, &fct); // Create a memory buffer (2 dimensional). coli::buffer buf0("b_blurx", 2, {100,100}, Halide::Int(8), NULL, &fct); // Map the computations to a buffer (i.e. where each computation // should be stored in the buffer). // This mapping will be updated automaticall when the schedule // is applied. To disable automatic data mapping updates use // coli::global::set_auto_data_mapping(false). computation0.set_access("{c_input[i,j]->b_input[i,j]}"); computation0.set_access("{c_blurx[i,j]->b_blurx[i,j]}"); computation0.set_access("{c_blury[i,j]->b_blury[i,j]}"); // Dump the iteration domain (input) for the function. fct.dump_iteration_domain(); // Set the schedule of each computation. // The identity schedule means that the program order is not modified // (i.e. no optimization is applied). c_blurx.tile(0,1,2,2); c_blurx.tag_parallel_dimension(0); c_blury.set_schedule("{blury[i,j]->[i,j]}"); c_blury.after(c_blurx, coli::computation::root_dimension); // Generate the time-processor domain of the computation // and dump it on stdout. fct.gen_time_processor_domain(); fct.dump_time_processor_domain(); // Generate an AST (abstract Syntax Tree) fct.gen_isl_ast(); // Generate Halide statement for the function. fct.gen_halide_stmt(); // If you want to get the generated halide statements, call // fct.get_halide_stmts(). // Dump the Halide stmt generated by gen_halide_stmt() // for the function. fct.dump_halide_stmt(); // Generate an object file from the function. fct.gen_halide_obj("build/generated_lib_tutorial_01.o"); return 0; } <|endoftext|>
<commit_before>#include <climits> #include <elevator/elevator.h> #include <elevator/restartwrapper.h> #include <elevator/test.h> #include <wibble/raii.h> namespace elevator { std::vector< Button > genFloorButtons( const BasicDriverInfo &bi ) { std::vector< Button > btns; for ( int i = bi.minFloor(); i <= bi.maxFloor(); ++i ) { btns.push_back( Button( ButtonType::TargetFloor, i ) ); if ( i < bi.maxFloor() ) btns.push_back( Button( ButtonType::CallUp, i ) ); if ( i > bi.minFloor() ) btns.push_back( Button( ButtonType::CallDown, i ) ); } return btns; } Elevator::Elevator( int id, HeartBeat &heartbeat, ConcurrentQueue< Command > &inCommands, ConcurrentQueue< StateChange > &outState ) : _terminate( false ), _inCommands( inCommands ), _outState( outState ), _heartbeat( heartbeat ), _previousDirection( Direction::None ), _lastStateUpdate( 0 ), _floorButtons( genFloorButtons( _driver ) ) { _elevState.lastFloor = _driver.minFloor(); _elevState.id = id; } Elevator::~Elevator() { if ( _thread.joinable() ) terminate(); } void Elevator::terminate() { assert( _thread.joinable(), "control loop not running" ); _terminate = true; _thread.join(); } void Elevator::run() { _thread = std::thread( restartWrapper( &Elevator::_loop ), this ); } void Elevator::_addTargetFloor( int floor ) { _elevState.insideButtons.set( true, floor, _driver ); } void Elevator::_removeTargetFloor( int floor ) { _elevState.insideButtons.set( false, floor, _driver ); } void Elevator::assertConsistency() { assert_lt( _driver.minFloor(), _driver.maxFloor(), "invalid floor bounds" ); assert( _previousDirection == Direction::Up || _previousDirection == Direction::Down || _previousDirection == Direction::None, "invalid direction" ); _elevState.assertConsistency( _driver ); assert_leq( _driver.minFloor(), _elevState.lastFloor, "last floor out of bounds" ); assert_leq( _elevState.lastFloor, _driver.maxFloor(), "last floor out of bounds" ); } Button buttonByDirection( Direction dir, int floor ) { assert_neq( dir, Direction::None, "Need direction" ); return dir == Direction::Down ? Button( ButtonType::CallDown, floor ) : Button( ButtonType::CallUp, floor ); } int Elevator::_updateAndGetFloor() { int f = _driver.getFloor(); if ( f != INT_MIN ) _elevState.lastFloor = f; return f; } void Elevator::_stopElevator() { if ( _elevState.direction != Direction::None ) _previousDirection = _elevState.direction; _elevState.direction = Direction::None; _driver.stopElevator(); } void Elevator::_startElevator() { _startElevator( Direction::None ); } void Elevator::_startElevator( Direction direction ) { _elevState.direction = direction; // we may not have current information in _elevState.lastFloor, on the other hand // sensor never lies but may not know _updateAndGetFloor(); // update information if sensor senses floor if ( _elevState.lastFloor == _driver.minFloor() ) _elevState.direction = Direction::Up; else if ( _elevState.lastFloor == _driver.maxFloor() ) _elevState.direction = Direction::Down; // if we have no clue select direction by requests if ( _elevState.direction == Direction::None ) _elevState.direction = _optimalDirection(); _driver.setMotorSpeed( _elevState.direction, _speed ); _driver.setDoorOpenLamp( false ); } Direction Elevator::_optimalDirection() const { int lowerThan{ 0 }, higherThan { 0 }; FloorSet floorsToServe = _elevState.insideButtons; if ( !floorsToServe.hasAny() ) { floorsToServe |= _elevState.upButtons; floorsToServe |= _elevState.downButtons; } for ( int i = _driver.minFloor(); i <= _driver.maxFloor(); ++i ) { if ( floorsToServe.get( i, _driver ) ) { if ( i > _elevState.lastFloor ) ++higherThan; if ( i < _elevState.lastFloor ) ++lowerThan; } } return higherThan >= lowerThan ? Direction::Up : Direction::Down; } /* we want to prioritize inside buttons, imagine: * - elevator is on floor 3 and last went up, inside is pressed 2, outside 4 * normally we preffer continuing withing last direction to avoid malicious * co-travellers from calling elevator to other direction from inside, * but this must work only for inside buttons, we don't want elevator * to be called to floor 4 in this situation */ bool Elevator::_priorityFloorsInDirection( Direction direction ) const { if ( direction == Direction::Down ) return _elevState.insideButtons.anyLower( _elevState.lastFloor, _driver ); if ( direction == Direction::Up ) return _elevState.insideButtons.anyHigher( _elevState.lastFloor, _driver ); return false; } void Elevator::_emitStateChange( ChangeType type, int floor ) { StateChange change; change.state = _elevState; change.changeType = type; change.changeFloor = floor; _lastStateUpdate = change.state.timestamp = now(); _outState.enqueue( change ); } void Elevator::_setButtonLampAndFlag( Button btn, bool val ) { _driver.setButtonLamp( btn, val ); if ( btn.type() == ButtonType::TargetFloor ) _elevState.insideButtons.set( val, btn.floor(), _driver ); } ChangeType changeTypeByButton( ButtonType btnt ) { switch ( btnt ) { case ButtonType::CallUp: return ChangeType::ButtonDownPressed; case ButtonType::CallDown: return ChangeType::ButtonUpPressed; case ButtonType::TargetFloor: return ChangeType::InsideButtonPresed; default: assert_unreachable(); } } FloorSet Elevator::_allButtons() const { return _elevState.insideButtons | _elevState.upButtons | _elevState.downButtons; } bool Elevator::_shouldStop( int currentFloor ) const { /* stop if this floor was requested from inside or if we are moving * in direction of pressed outside button * the special case of topmost/bottommost floor need not to be * handled as elevator stops there anyway */ return _elevState.insideButtons.get( currentFloor, _driver ) || ( _elevState.direction == Direction::Up && _elevState.upButtons.get( currentFloor, _driver ) ) || ( _elevState.direction == Direction::Down && _elevState.downButtons.get( currentFloor, _driver ) ); } void Elevator::_clearDirectionButtonLamp() { Button b; if ( _elevState.lastFloor == _driver.maxFloor() ) b = Button{ ButtonType::CallDown, _driver.maxFloor() }; else if ( _elevState.lastFloor == _driver.minFloor() ) b = Button{ ButtonType::CallUp, _driver.minFloor() }; else b = buttonByDirection( _elevState.direction, _elevState.lastFloor ); if ( b.type() == ButtonType::CallUp ) { if ( _elevState.upButtons.set( false, b.floor(), _driver ) ) _emitStateChange( ChangeType::ServedUp, b.floor() ); } else { if ( _elevState.downButtons.set( false, b.floor(), _driver ) ) _emitStateChange( ChangeType::ServedDown, b.floor() ); } _driver.setButtonLamp( b, false ); } void Elevator::_initializeElevator() { // initialize according to lights for ( auto b : _floorButtons ) { if ( _driver.getButtonLamp( b ) ) { if ( b.type() == ButtonType::TargetFloor ) _addTargetFloor( b.floor() ); else if ( b.type() == ButtonType::CallDown ) _elevState.downButtons.set( true, b.floor(), _driver ); else if ( b.type() == ButtonType::CallUp ) _elevState.upButtons.set( true, b.floor(), _driver ); } } } void Elevator::_loop() { // no matter whether exit is caused by terminate flag or exception // we want to stop elevator (ok, it works only for exceptions caught somewhere // above, but nothing better exists and we are catching assertions and // restarting) auto d_stop = wibble::raii::defer( [&]() { _stopElevator(); } ); // for some buttons, we need to keep track about changes, so that we // can detect button press/release event no just the fact that button // is now activated FloorSet inFloorButtons, inFloorButtonsLast; bool stopLast{ false }, stopNow{ false }; int prevFloor{ INT_MIN }; // to keep track when to send state update MillisecondTime doorWaitingStarted{ 0 }; // for closing doors enum class State { Normal, WaitingForInButton, Stopped }; State state = State::Normal; _initializeElevator(); if ( _driver.getStopLamp() ) state = State::Stopped; while ( !_terminate.load( std::memory_order::memory_order_relaxed ) ) { // initialize cycle inFloorButtonsLast = inFloorButtons; inFloorButtons.reset(); stopLast = stopNow; assertConsistency(); // handle buttons and lamps for ( auto b : _floorButtons ) { if ( _driver.getButtonSignal( b ) ) { if ( !_driver.getButtonLamp( b ) ) { // new press _setButtonLampAndFlag( b, true ); if ( b.type() == ButtonType::TargetFloor ) { // we need to serve this one on this elevator _addTargetFloor( b.floor() ); } _emitStateChange( changeTypeByButton( b.type() ), b.floor() ); } // furthermore we need to keep track of pressed inside buttons // regardless if they were already lit, this is for the purpose // of detection re-pressing inside button to get elevator moving // after entering if ( b.type() == ButtonType::TargetFloor ) { inFloorButtons.set( true, b.floor(), _driver ); } } } if ( (stopNow = _driver.getStop()) && stopNow != stopLast ) { _elevState.stopped = !_driver.getStopLamp(); _driver.setStopLamp( _elevState.stopped ); /* stop button will (surprise) stop the elevator right where it is * movement is resumed once button is presses again */ if ( _elevState.stopped ) { _stopElevator(); state = State::Stopped; _emitStateChange( ChangeType::OtherChange, _updateAndGetFloor() ); } else { _startElevator( _previousDirection ); state = State::Normal; _emitStateChange( ChangeType::OtherChange, _updateAndGetFloor() ); } } if ( _driver.getObstruction() ) { _driver.shutdown(); while ( _driver.getObstruction() ) { /* obstruction causes infinite loop which it turn causes * heartbeat timeout and terminates whole process */ } } // must be nonblocking auto maybeCommand = _inCommands.tryDequeue(); if ( !maybeCommand.isNothing() ) { auto command = maybeCommand.value(); assert( command.targetElevatorId == _elevState.id || command.targetElevatorId == Command::ANY_ID, "command to other elevator" ); switch ( command.commandType ) { case CommandType::Empty: break; case CommandType::CallToFloorAndGoUp: _elevState.upButtons.set( true, command.targetFloor, _driver ); _driver.setButtonLamp( Button{ ButtonType::CallUp, command.targetFloor }, true ); break; case CommandType::CallToFloorAndGoDown: _elevState.downButtons.set( true, command.targetFloor, _driver ); _driver.setButtonLamp( Button{ ButtonType::CallDown, command.targetFloor }, true ); break; case CommandType::TurnOnLightUp: _driver.setButtonLamp( Button{ ButtonType::CallUp, command.targetFloor }, true ); break; case CommandType::TurnOffLightUp: _driver.setButtonLamp( Button{ ButtonType::CallUp, command.targetFloor }, false ); break; case CommandType::TurnOnLightDown: _driver.setButtonLamp( Button{ ButtonType::CallDown, command.targetFloor }, true ); break; case CommandType::TurnOffLightDown: _driver.setButtonLamp( Button{ ButtonType::CallDown, command.targetFloor }, false ); break; } } int currentFloor = _updateAndGetFloor(); // safety precautions if ( currentFloor == _driver.maxFloor() && _elevState.direction == Direction::Up ) _stopElevator(); if ( currentFloor == _driver.minFloor() && _elevState.direction == Direction::Down ) _stopElevator(); if ( currentFloor != INT_MIN ) _driver.setFloorIndicator( currentFloor ); if ( currentFloor != prevFloor ) _emitStateChange( ChangeType::OtherChange, currentFloor ); // note: we are here working wich _floorsToServe shared atomic variable // it can change between subsequent loads, but only this thread // ever removes any floor from it, so there is nothing dangerous in this // now do what is needed depending on state if ( state == State::Normal ) { // check if we arrived at any floor which was scheduled for us if ( currentFloor != INT_MIN && _shouldStop( currentFloor ) ) { // turn off button lights _setButtonLampAndFlag( Button( ButtonType::TargetFloor, currentFloor ), false ); // open doors _driver.setDoorOpenLamp( true ); state = State::WaitingForInButton; doorWaitingStarted = now(); _stopElevator(); // this floor is served _removeTargetFloor( currentFloor ); _emitStateChange( ChangeType::Served, currentFloor ); } else if ( _elevState.direction == Direction::None && _allButtons().hasAny() ) { // we are not moving but we can if ( _priorityFloorsInDirection( _previousDirection ) ) _startElevator( _previousDirection ); else _startElevator(); // decides which direction is better itself _emitStateChange( ChangeType::OtherChange, currentFloor ); _clearDirectionButtonLamp(); } } else if ( state == State::WaitingForInButton ) { if ( FloorSet::hasAdditional( inFloorButtonsLast, inFloorButtons ) || (doorWaitingStarted + _waitThreshold) < now() ) { _driver.setDoorOpenLamp( false ); state = State::Normal; } } else if ( state == State::Stopped ) { // nothing to do } else { assert_unreachable(); } if ( _lastStateUpdate + _keepAlive <= now() ) _emitStateChange( ChangeType::KeepAlive, currentFloor ); // it is important to do heartbeat at the end so that we don't end up // beating even in case we are repeatedlay auto-restarted due to assertion // we don't need to care about beating too often, it is cheap and safe _heartbeat.beat(); prevFloor = currentFloor; } } } <commit_msg>elevator: Tweak outside button turnoff contidions.<commit_after>#include <climits> #include <elevator/elevator.h> #include <elevator/restartwrapper.h> #include <elevator/test.h> #include <wibble/raii.h> namespace elevator { std::vector< Button > genFloorButtons( const BasicDriverInfo &bi ) { std::vector< Button > btns; for ( int i = bi.minFloor(); i <= bi.maxFloor(); ++i ) { btns.push_back( Button( ButtonType::TargetFloor, i ) ); if ( i < bi.maxFloor() ) btns.push_back( Button( ButtonType::CallUp, i ) ); if ( i > bi.minFloor() ) btns.push_back( Button( ButtonType::CallDown, i ) ); } return btns; } Elevator::Elevator( int id, HeartBeat &heartbeat, ConcurrentQueue< Command > &inCommands, ConcurrentQueue< StateChange > &outState ) : _terminate( false ), _inCommands( inCommands ), _outState( outState ), _heartbeat( heartbeat ), _previousDirection( Direction::None ), _lastStateUpdate( 0 ), _floorButtons( genFloorButtons( _driver ) ) { _elevState.lastFloor = _driver.minFloor(); _elevState.id = id; } Elevator::~Elevator() { if ( _thread.joinable() ) terminate(); } void Elevator::terminate() { assert( _thread.joinable(), "control loop not running" ); _terminate = true; _thread.join(); } void Elevator::run() { _thread = std::thread( restartWrapper( &Elevator::_loop ), this ); } void Elevator::_addTargetFloor( int floor ) { _elevState.insideButtons.set( true, floor, _driver ); } void Elevator::_removeTargetFloor( int floor ) { _elevState.insideButtons.set( false, floor, _driver ); } void Elevator::assertConsistency() { assert_lt( _driver.minFloor(), _driver.maxFloor(), "invalid floor bounds" ); assert( _previousDirection == Direction::Up || _previousDirection == Direction::Down || _previousDirection == Direction::None, "invalid direction" ); _elevState.assertConsistency( _driver ); assert_leq( _driver.minFloor(), _elevState.lastFloor, "last floor out of bounds" ); assert_leq( _elevState.lastFloor, _driver.maxFloor(), "last floor out of bounds" ); } Button buttonByDirection( Direction dir, int floor ) { assert_neq( dir, Direction::None, "Need direction" ); return dir == Direction::Down ? Button( ButtonType::CallDown, floor ) : Button( ButtonType::CallUp, floor ); } int Elevator::_updateAndGetFloor() { int f = _driver.getFloor(); if ( f != INT_MIN ) _elevState.lastFloor = f; return f; } void Elevator::_stopElevator() { if ( _elevState.direction != Direction::None ) _previousDirection = _elevState.direction; _elevState.direction = Direction::None; _driver.stopElevator(); } void Elevator::_startElevator() { _startElevator( Direction::None ); } void Elevator::_startElevator( Direction direction ) { _elevState.direction = direction; // we may not have current information in _elevState.lastFloor, on the other hand // sensor never lies but may not know _updateAndGetFloor(); // update information if sensor senses floor if ( _elevState.lastFloor == _driver.minFloor() ) _elevState.direction = Direction::Up; else if ( _elevState.lastFloor == _driver.maxFloor() ) _elevState.direction = Direction::Down; // if we have no clue select direction by requests if ( _elevState.direction == Direction::None ) _elevState.direction = _optimalDirection(); _driver.setMotorSpeed( _elevState.direction, _speed ); _driver.setDoorOpenLamp( false ); } Direction Elevator::_optimalDirection() const { int lowerThan{ 0 }, higherThan { 0 }; FloorSet floorsToServe = _elevState.insideButtons; if ( !floorsToServe.hasAny() ) { floorsToServe |= _elevState.upButtons; floorsToServe |= _elevState.downButtons; } for ( int i = _driver.minFloor(); i <= _driver.maxFloor(); ++i ) { if ( floorsToServe.get( i, _driver ) ) { if ( i > _elevState.lastFloor ) ++higherThan; if ( i < _elevState.lastFloor ) ++lowerThan; } } return higherThan >= lowerThan ? Direction::Up : Direction::Down; } /* we want to prioritize inside buttons, imagine: * - elevator is on floor 3 and last went up, inside is pressed 2, outside 4 * normally we preffer continuing withing last direction to avoid malicious * co-travellers from calling elevator to other direction from inside, * but this must work only for inside buttons, we don't want elevator * to be called to floor 4 in this situation */ bool Elevator::_priorityFloorsInDirection( Direction direction ) const { if ( direction == Direction::Down ) return _elevState.insideButtons.anyLower( _elevState.lastFloor, _driver ); if ( direction == Direction::Up ) return _elevState.insideButtons.anyHigher( _elevState.lastFloor, _driver ); return false; } void Elevator::_emitStateChange( ChangeType type, int floor ) { StateChange change; change.state = _elevState; change.changeType = type; change.changeFloor = floor; _lastStateUpdate = change.state.timestamp = now(); _outState.enqueue( change ); } void Elevator::_setButtonLampAndFlag( Button btn, bool val ) { _driver.setButtonLamp( btn, val ); if ( btn.type() == ButtonType::TargetFloor ) _elevState.insideButtons.set( val, btn.floor(), _driver ); } ChangeType changeTypeByButton( ButtonType btnt ) { switch ( btnt ) { case ButtonType::CallUp: return ChangeType::ButtonDownPressed; case ButtonType::CallDown: return ChangeType::ButtonUpPressed; case ButtonType::TargetFloor: return ChangeType::InsideButtonPresed; default: assert_unreachable(); } } FloorSet Elevator::_allButtons() const { return _elevState.insideButtons | _elevState.upButtons | _elevState.downButtons; } bool Elevator::_shouldStop( int currentFloor ) const { /* stop if this floor was requested from inside or if we are moving * in direction of pressed outside button * the special case of topmost/bottommost floor need not to be * handled as elevator stops there anyway */ return _elevState.insideButtons.get( currentFloor, _driver ) || ( _elevState.direction == Direction::Up && _elevState.upButtons.get( currentFloor, _driver ) ) || ( _elevState.direction == Direction::Down && _elevState.downButtons.get( currentFloor, _driver ) ); } void Elevator::_clearDirectionButtonLamp() { Button b; if ( _elevState.lastFloor == _driver.maxFloor() ) b = Button{ ButtonType::CallDown, _driver.maxFloor() }; else if ( _elevState.lastFloor == _driver.minFloor() ) b = Button{ ButtonType::CallUp, _driver.minFloor() }; else b = buttonByDirection( _elevState.direction, _elevState.lastFloor ); if ( b.type() == ButtonType::CallUp ) { if ( _elevState.upButtons.set( false, b.floor(), _driver ) ) _emitStateChange( ChangeType::ServedUp, b.floor() ); } else { if ( _elevState.downButtons.set( false, b.floor(), _driver ) ) _emitStateChange( ChangeType::ServedDown, b.floor() ); } _driver.setButtonLamp( b, false ); } void Elevator::_initializeElevator() { // initialize according to lights for ( auto b : _floorButtons ) { if ( _driver.getButtonLamp( b ) ) { if ( b.type() == ButtonType::TargetFloor ) _addTargetFloor( b.floor() ); else if ( b.type() == ButtonType::CallDown ) _elevState.downButtons.set( true, b.floor(), _driver ); else if ( b.type() == ButtonType::CallUp ) _elevState.upButtons.set( true, b.floor(), _driver ); } } } void Elevator::_loop() { // no matter whether exit is caused by terminate flag or exception // we want to stop elevator (ok, it works only for exceptions caught somewhere // above, but nothing better exists and we are catching assertions and // restarting) auto d_stop = wibble::raii::defer( [&]() { _stopElevator(); } ); // for some buttons, we need to keep track about changes, so that we // can detect button press/release event no just the fact that button // is now activated FloorSet inFloorButtons, inFloorButtonsLast; bool stopLast{ false }, stopNow{ false }; int prevFloor{ INT_MIN }; // to keep track when to send state update MillisecondTime doorWaitingStarted{ 0 }; // for closing doors enum class State { Normal, WaitingForInButton, Stopped }; State state = State::Normal; _initializeElevator(); if ( _driver.getStopLamp() ) state = State::Stopped; while ( !_terminate.load( std::memory_order::memory_order_relaxed ) ) { // initialize cycle inFloorButtonsLast = inFloorButtons; inFloorButtons.reset(); stopLast = stopNow; assertConsistency(); // handle buttons and lamps for ( auto b : _floorButtons ) { if ( _driver.getButtonSignal( b ) ) { if ( !_driver.getButtonLamp( b ) ) { // new press _setButtonLampAndFlag( b, true ); if ( b.type() == ButtonType::TargetFloor ) { // we need to serve this one on this elevator _addTargetFloor( b.floor() ); } _emitStateChange( changeTypeByButton( b.type() ), b.floor() ); } // furthermore we need to keep track of pressed inside buttons // regardless if they were already lit, this is for the purpose // of detection re-pressing inside button to get elevator moving // after entering if ( b.type() == ButtonType::TargetFloor ) { inFloorButtons.set( true, b.floor(), _driver ); } } } if ( (stopNow = _driver.getStop()) && stopNow != stopLast ) { _elevState.stopped = !_driver.getStopLamp(); _driver.setStopLamp( _elevState.stopped ); /* stop button will (surprise) stop the elevator right where it is * movement is resumed once button is presses again */ if ( _elevState.stopped ) { _stopElevator(); state = State::Stopped; _emitStateChange( ChangeType::OtherChange, _updateAndGetFloor() ); } else { _startElevator( _previousDirection ); state = State::Normal; _emitStateChange( ChangeType::OtherChange, _updateAndGetFloor() ); } } if ( _driver.getObstruction() ) { _driver.shutdown(); while ( _driver.getObstruction() ) { /* obstruction causes infinite loop which it turn causes * heartbeat timeout and terminates whole process */ } } // must be nonblocking auto maybeCommand = _inCommands.tryDequeue(); if ( !maybeCommand.isNothing() ) { auto command = maybeCommand.value(); assert( command.targetElevatorId == _elevState.id || command.targetElevatorId == Command::ANY_ID, "command to other elevator" ); switch ( command.commandType ) { case CommandType::Empty: break; case CommandType::CallToFloorAndGoUp: _elevState.upButtons.set( true, command.targetFloor, _driver ); _driver.setButtonLamp( Button{ ButtonType::CallUp, command.targetFloor }, true ); break; case CommandType::CallToFloorAndGoDown: _elevState.downButtons.set( true, command.targetFloor, _driver ); _driver.setButtonLamp( Button{ ButtonType::CallDown, command.targetFloor }, true ); break; case CommandType::TurnOnLightUp: _driver.setButtonLamp( Button{ ButtonType::CallUp, command.targetFloor }, true ); break; case CommandType::TurnOffLightUp: _driver.setButtonLamp( Button{ ButtonType::CallUp, command.targetFloor }, false ); break; case CommandType::TurnOnLightDown: _driver.setButtonLamp( Button{ ButtonType::CallDown, command.targetFloor }, true ); break; case CommandType::TurnOffLightDown: _driver.setButtonLamp( Button{ ButtonType::CallDown, command.targetFloor }, false ); break; } } int currentFloor = _updateAndGetFloor(); // safety precautions if ( currentFloor == _driver.maxFloor() && _elevState.direction == Direction::Up ) _stopElevator(); if ( currentFloor == _driver.minFloor() && _elevState.direction == Direction::Down ) _stopElevator(); if ( currentFloor != INT_MIN ) _driver.setFloorIndicator( currentFloor ); if ( currentFloor != prevFloor ) _emitStateChange( ChangeType::OtherChange, currentFloor ); // note: we are here working wich _floorsToServe shared atomic variable // it can change between subsequent loads, but only this thread // ever removes any floor from it, so there is nothing dangerous in this // now do what is needed depending on state if ( state == State::Normal ) { // check if we arrived at any floor which was scheduled for us if ( currentFloor != INT_MIN && _shouldStop( currentFloor ) ) { // turn off button lights _setButtonLampAndFlag( Button( ButtonType::TargetFloor, currentFloor ), false ); // open doors _driver.setDoorOpenLamp( true ); state = State::WaitingForInButton; doorWaitingStarted = now(); _stopElevator(); // this floor is served _removeTargetFloor( currentFloor ); _emitStateChange( ChangeType::Served, currentFloor ); } else if ( _elevState.direction == Direction::None ) { if ( _allButtons().hasAny() ) { // we are not moving but we can if ( _priorityFloorsInDirection( _previousDirection ) ) _startElevator( _previousDirection ); else _startElevator(); // decides which direction is better itself _emitStateChange( ChangeType::OtherChange, currentFloor ); } _clearDirectionButtonLamp(); } } else if ( state == State::WaitingForInButton ) { bool timeout = (doorWaitingStarted + _waitThreshold) < now(); if ( FloorSet::hasAdditional( inFloorButtonsLast, inFloorButtons ) || timeout ) { _driver.setDoorOpenLamp( false ); state = State::Normal; if ( timeout ) { _elevState.downButtons.set( false, currentFloor, _driver ); _elevState.upButtons.set( false, currentFloor, _driver ); _driver.setButtonLamp( Button{ ButtonType::CallUp, currentFloor }, false ); _driver.setButtonLamp( Button{ ButtonType::CallDown, currentFloor }, false ); } } } else if ( state == State::Stopped ) { // nothing to do } else { assert_unreachable(); } if ( _lastStateUpdate + _keepAlive <= now() ) _emitStateChange( ChangeType::KeepAlive, currentFloor ); // it is important to do heartbeat at the end so that we don't end up // beating even in case we are repeatedlay auto-restarted due to assertion // we don't need to care about beating too often, it is cheap and safe _heartbeat.beat(); prevFloor = currentFloor; } } } <|endoftext|>
<commit_before>/* * $Id$ * * Copyright(C) 1998-2005 Satoshi Nakamura * All rights reserved. * */ #include <qsconv.h> #include <qsstream.h> using namespace qs; /**************************************************************************** * * Writer * */ qs::Writer::~Writer() { } /**************************************************************************** * * OutputStreamWriterImpl * */ struct qs::OutputStreamWriterImpl { enum { BUFFER_SIZE = 8192 }; bool flushBuffer(); bool write(const WCHAR* p, size_t nSize); OutputStream* pOutputStream_; bool bDelete_; std::auto_ptr<Converter> pConverter_; WCHAR* pBuf_; WCHAR* pBufEnd_; WCHAR* pCurrent_; }; bool qs::OutputStreamWriterImpl::flushBuffer() { if (pCurrent_ != pBuf_) { size_t nLen = pCurrent_ - pBuf_; xstring_size_ptr encoded(pConverter_->encode(pBuf_, &nLen)); if (!encoded.get()) return false; if (pOutputStream_->write( reinterpret_cast<unsigned char*>(encoded.get()), encoded.size()) == -1) return false; if (nLen != static_cast<size_t>(pCurrent_ - pBuf_)) memmove(pBuf_, pCurrent_, (pCurrent_ - pBuf_ - nLen)*sizeof(WCHAR)); pCurrent_ -= nLen; } return true; } bool qs::OutputStreamWriterImpl::write(const WCHAR* p, size_t nSize) { assert(p); assert(nSize > static_cast<size_t>(pBufEnd_ - pCurrent_)); while (nSize != 0) { if (pCurrent_ == pBuf_) { size_t nLen = nSize; xstring_size_ptr encoded(pConverter_->encode(p, &nLen)); if (!encoded.get()) return false; assert(nSize - nLen < BUFFER_SIZE); if (pOutputStream_->write( reinterpret_cast<unsigned char*>(encoded.get()), encoded.size()) == -1) return false; if (nLen != nSize) memcpy(pBuf_, p + nLen, nSize - nLen); pCurrent_ = pBuf_ + (nSize - nLen); nSize = 0; } else { size_t nRest = pCurrent_ - pBuf_; size_t nLen = QSMAX(static_cast<size_t>(pBufEnd_ - pCurrent_), nSize); memcpy(pCurrent_, p, nLen); WCHAR* pCurrentOld = pCurrent_; if (!flushBuffer()) return false; if (pCurrent_ != pBuf_ && static_cast<size_t>(pCurrentOld - pCurrent_) >= nRest) { p += pCurrentOld - pCurrent_ - nRest; nSize -= pCurrentOld - pCurrent_ - nRest; pCurrent_ = pBuf_; } else { p += nLen; nSize -= nLen; } } } return true; } /**************************************************************************** * * OutputStreamWriter * */ qs::OutputStreamWriter::OutputStreamWriter(OutputStream* pOutputStream, bool bDelete, const WCHAR* pwszEncoding) : pImpl_(0) { assert(pOutputStream); malloc_ptr<WCHAR> pBuf(static_cast<WCHAR*>( malloc(OutputStreamWriterImpl::BUFFER_SIZE*sizeof(WCHAR)))); if (!pBuf.get()) return; if (!pwszEncoding) pwszEncoding = getSystemEncoding(); std::auto_ptr<Converter> pConverter(ConverterFactory::getInstance(pwszEncoding)); if (!pConverter.get()) return; pImpl_ = new OutputStreamWriterImpl(); pImpl_->pOutputStream_ = pOutputStream; pImpl_->bDelete_ = bDelete; pImpl_->pConverter_ = pConverter; pImpl_->pBuf_ = pBuf.release(); pImpl_->pBufEnd_ = pImpl_->pBuf_ + OutputStreamWriterImpl::BUFFER_SIZE; pImpl_->pCurrent_ = pImpl_->pBuf_; } qs::OutputStreamWriter::~OutputStreamWriter() { if (pImpl_) { if (pImpl_->bDelete_) delete pImpl_->pOutputStream_; free(pImpl_->pBuf_); delete pImpl_; pImpl_ = 0; } } bool qs::OutputStreamWriter::operator!() const { return pImpl_ == 0; } bool qs::OutputStreamWriter::close() { if (!pImpl_->flushBuffer()) return false; return pImpl_->pOutputStream_->close(); } size_t qs::OutputStreamWriter::write(const WCHAR* p, size_t nWrite) { assert(p); if (static_cast<size_t>(pImpl_->pBufEnd_ - pImpl_->pCurrent_) >= nWrite) { memcpy(pImpl_->pCurrent_, p, nWrite*sizeof(WCHAR)); pImpl_->pCurrent_ += nWrite; } else { if (!pImpl_->flushBuffer()) return -1; if (nWrite > static_cast<size_t>(pImpl_->pBufEnd_ - pImpl_->pCurrent_)) { if (!pImpl_->write(p, nWrite)) return -1; } else { memcpy(pImpl_->pCurrent_, p, nWrite*sizeof(WCHAR)); pImpl_->pCurrent_ += nWrite; } } return nWrite; } /**************************************************************************** * * StringWriterImpl * */ struct qs::StringWriterImpl { enum { BUFFER_SIZE = 256 }; bool allocBuffer(size_t nSize); wxstring_ptr wstr_; WCHAR* pEnd_; WCHAR* pCurrent_; }; bool qs::StringWriterImpl::allocBuffer(size_t nSize) { size_t nNewSize = 0; if (!wstr_.get()) { nNewSize = QSMAX(static_cast<size_t>(BUFFER_SIZE), nSize); } else { nNewSize = pEnd_ - wstr_.get(); nNewSize += QSMAX(nNewSize, nSize); } size_t nLen = pCurrent_ - wstr_.get(); if (!wstr_.get()) wstr_ = allocWXString(nNewSize); else wstr_ = reallocWXString(wstr_, nNewSize); if (!wstr_.get()) return false; pEnd_ = wstr_.get() + nNewSize; pCurrent_ = wstr_.get() + nLen; return true; } /**************************************************************************** * * StringWriter * */ qs::StringWriter::StringWriter() : pImpl_(0) { pImpl_ = new StringWriterImpl(); pImpl_->pEnd_ = 0; pImpl_->pCurrent_ = 0; } qs::StringWriter::~StringWriter() { delete pImpl_; pImpl_ = 0; } bool qs::StringWriter::close() { return true; } size_t qs::StringWriter::write(const WCHAR* p, size_t nWrite) { if (static_cast<size_t>(pImpl_->pEnd_ - pImpl_->pCurrent_) < nWrite) { if (!pImpl_->allocBuffer(nWrite)) return -1; } memcpy(pImpl_->pCurrent_, p, nWrite*sizeof(WCHAR)); pImpl_->pCurrent_ += nWrite; return nWrite; } /**************************************************************************** * * BufferedWriterImpl * */ struct qs::BufferedWriterImpl { enum { BUFFER_SIZE = 4096 }; bool flushBuffer(); Writer* pWriter_; bool bDelete_; auto_ptr_array<WCHAR> pBuf_; WCHAR* pBufEnd_; WCHAR* pCurrent_; }; bool qs::BufferedWriterImpl::flushBuffer() { if (pCurrent_ != pBuf_.get()) { if (pWriter_->write(pBuf_.get(), pCurrent_ - pBuf_.get()) == -1) return false; pCurrent_ = pBuf_.get(); } return true; } /**************************************************************************** * * BufferedWriter * */ qs::BufferedWriter::BufferedWriter(Writer* pWriter, bool bDelete) : pImpl_(0) { auto_ptr_array<WCHAR> pBuf(new WCHAR[BufferedWriterImpl::BUFFER_SIZE]); pImpl_ = new BufferedWriterImpl(); pImpl_->pWriter_ = pWriter; pImpl_->bDelete_ = bDelete; pImpl_->pBuf_ = pBuf; pImpl_->pBufEnd_ = pImpl_->pBuf_.get() + BufferedWriterImpl::BUFFER_SIZE; pImpl_->pCurrent_ = pImpl_->pBuf_.get(); } qs::BufferedWriter::~BufferedWriter() { if (pImpl_) { if (pImpl_->bDelete_) delete pImpl_->pWriter_; delete pImpl_; pImpl_ = 0; } } bool qs::BufferedWriter::newLine() { return write(L"\r\n", 2) == 2; } bool qs::BufferedWriter::close() { if (!pImpl_->flushBuffer()) return false; return pImpl_->pWriter_->close(); } size_t qs::BufferedWriter::write(const WCHAR* p, size_t nWrite) { assert(p); if (static_cast<size_t>(pImpl_->pBufEnd_ - pImpl_->pCurrent_) >= nWrite) { memcpy(pImpl_->pCurrent_, p, nWrite*sizeof(WCHAR)); pImpl_->pCurrent_ += nWrite; } else { if (!pImpl_->flushBuffer()) return -1; if (nWrite > BufferedWriterImpl::BUFFER_SIZE/2) { if (pImpl_->pWriter_->write(p, nWrite) == -1) return -1; } else { memcpy(pImpl_->pCurrent_, p, nWrite*sizeof(WCHAR)); pImpl_->pCurrent_ += nWrite; } } return nWrite; } <commit_msg>OutputStreamWriter converts new lines.<commit_after>/* * $Id$ * * Copyright(C) 1998-2005 Satoshi Nakamura * All rights reserved. * */ #include <qsconv.h> #include <qsstream.h> using namespace qs; /**************************************************************************** * * Writer * */ qs::Writer::~Writer() { } /**************************************************************************** * * OutputStreamWriterImpl * */ struct qs::OutputStreamWriterImpl { enum { BUFFER_SIZE = 8192 }; bool flushBuffer(); bool write(const WCHAR* p, size_t nSize); bool writeToStream(const unsigned char* p, size_t nLen); OutputStream* pOutputStream_; bool bDelete_; std::auto_ptr<Converter> pConverter_; WCHAR* pBuf_; WCHAR* pBufEnd_; WCHAR* pCurrent_; }; bool qs::OutputStreamWriterImpl::flushBuffer() { if (pCurrent_ != pBuf_) { size_t nLen = pCurrent_ - pBuf_; xstring_size_ptr encoded(pConverter_->encode(pBuf_, &nLen)); if (!encoded.get()) return false; if (!writeToStream(reinterpret_cast<unsigned char*>(encoded.get()), encoded.size())) return false; if (nLen != static_cast<size_t>(pCurrent_ - pBuf_)) memmove(pBuf_, pCurrent_, (pCurrent_ - pBuf_ - nLen)*sizeof(WCHAR)); pCurrent_ -= nLen; } return true; } bool qs::OutputStreamWriterImpl::write(const WCHAR* p, size_t nSize) { assert(p); assert(nSize > static_cast<size_t>(pBufEnd_ - pCurrent_)); while (nSize != 0) { if (pCurrent_ == pBuf_) { size_t nLen = nSize; xstring_size_ptr encoded(pConverter_->encode(p, &nLen)); if (!encoded.get()) return false; assert(nSize - nLen < BUFFER_SIZE); if (!writeToStream(reinterpret_cast<unsigned char*>(encoded.get()), encoded.size())) return false; if (nLen != nSize) memcpy(pBuf_, p + nLen, nSize - nLen); pCurrent_ = pBuf_ + (nSize - nLen); nSize = 0; } else { size_t nRest = pCurrent_ - pBuf_; size_t nLen = QSMAX(static_cast<size_t>(pBufEnd_ - pCurrent_), nSize); memcpy(pCurrent_, p, nLen); WCHAR* pCurrentOld = pCurrent_; if (!flushBuffer()) return false; if (pCurrent_ != pBuf_ && static_cast<size_t>(pCurrentOld - pCurrent_) >= nRest) { p += pCurrentOld - pCurrent_ - nRest; nSize -= pCurrentOld - pCurrent_ - nRest; pCurrent_ = pBuf_; } else { p += nLen; nSize -= nLen; } } } return true; } bool qs::OutputStreamWriterImpl::writeToStream(const unsigned char* p, size_t nLen) { const unsigned char* pszNewLine = reinterpret_cast<const unsigned char*>("\r\n"); const unsigned char* pBegin = p; const unsigned char* pEnd = p + nLen; while (true) { if (p == pEnd || *p == '\r' || *p == '\n') { if (p != pBegin) { if (pOutputStream_->write(pBegin, p - pBegin) == -1) return false; } if (p == pEnd) { break; } else if (*p == '\n') { if (pOutputStream_->write(pszNewLine, 2) == -1) return false; } pBegin = p + 1; } ++p; } return true; } /**************************************************************************** * * OutputStreamWriter * */ qs::OutputStreamWriter::OutputStreamWriter(OutputStream* pOutputStream, bool bDelete, const WCHAR* pwszEncoding) : pImpl_(0) { assert(pOutputStream); malloc_ptr<WCHAR> pBuf(static_cast<WCHAR*>( malloc(OutputStreamWriterImpl::BUFFER_SIZE*sizeof(WCHAR)))); if (!pBuf.get()) return; if (!pwszEncoding) pwszEncoding = getSystemEncoding(); std::auto_ptr<Converter> pConverter(ConverterFactory::getInstance(pwszEncoding)); if (!pConverter.get()) return; pImpl_ = new OutputStreamWriterImpl(); pImpl_->pOutputStream_ = pOutputStream; pImpl_->bDelete_ = bDelete; pImpl_->pConverter_ = pConverter; pImpl_->pBuf_ = pBuf.release(); pImpl_->pBufEnd_ = pImpl_->pBuf_ + OutputStreamWriterImpl::BUFFER_SIZE; pImpl_->pCurrent_ = pImpl_->pBuf_; } qs::OutputStreamWriter::~OutputStreamWriter() { if (pImpl_) { if (pImpl_->bDelete_) delete pImpl_->pOutputStream_; free(pImpl_->pBuf_); delete pImpl_; pImpl_ = 0; } } bool qs::OutputStreamWriter::operator!() const { return pImpl_ == 0; } bool qs::OutputStreamWriter::close() { if (!pImpl_->flushBuffer()) return false; return pImpl_->pOutputStream_->close(); } size_t qs::OutputStreamWriter::write(const WCHAR* p, size_t nWrite) { assert(p); if (static_cast<size_t>(pImpl_->pBufEnd_ - pImpl_->pCurrent_) >= nWrite) { memcpy(pImpl_->pCurrent_, p, nWrite*sizeof(WCHAR)); pImpl_->pCurrent_ += nWrite; } else { if (!pImpl_->flushBuffer()) return -1; if (nWrite > static_cast<size_t>(pImpl_->pBufEnd_ - pImpl_->pCurrent_)) { if (!pImpl_->write(p, nWrite)) return -1; } else { memcpy(pImpl_->pCurrent_, p, nWrite*sizeof(WCHAR)); pImpl_->pCurrent_ += nWrite; } } return nWrite; } /**************************************************************************** * * StringWriterImpl * */ struct qs::StringWriterImpl { enum { BUFFER_SIZE = 256 }; bool allocBuffer(size_t nSize); wxstring_ptr wstr_; WCHAR* pEnd_; WCHAR* pCurrent_; }; bool qs::StringWriterImpl::allocBuffer(size_t nSize) { size_t nNewSize = 0; if (!wstr_.get()) { nNewSize = QSMAX(static_cast<size_t>(BUFFER_SIZE), nSize); } else { nNewSize = pEnd_ - wstr_.get(); nNewSize += QSMAX(nNewSize, nSize); } size_t nLen = pCurrent_ - wstr_.get(); if (!wstr_.get()) wstr_ = allocWXString(nNewSize); else wstr_ = reallocWXString(wstr_, nNewSize); if (!wstr_.get()) return false; pEnd_ = wstr_.get() + nNewSize; pCurrent_ = wstr_.get() + nLen; return true; } /**************************************************************************** * * StringWriter * */ qs::StringWriter::StringWriter() : pImpl_(0) { pImpl_ = new StringWriterImpl(); pImpl_->pEnd_ = 0; pImpl_->pCurrent_ = 0; } qs::StringWriter::~StringWriter() { delete pImpl_; pImpl_ = 0; } bool qs::StringWriter::close() { return true; } size_t qs::StringWriter::write(const WCHAR* p, size_t nWrite) { if (static_cast<size_t>(pImpl_->pEnd_ - pImpl_->pCurrent_) < nWrite) { if (!pImpl_->allocBuffer(nWrite)) return -1; } memcpy(pImpl_->pCurrent_, p, nWrite*sizeof(WCHAR)); pImpl_->pCurrent_ += nWrite; return nWrite; } /**************************************************************************** * * BufferedWriterImpl * */ struct qs::BufferedWriterImpl { enum { BUFFER_SIZE = 4096 }; bool flushBuffer(); Writer* pWriter_; bool bDelete_; auto_ptr_array<WCHAR> pBuf_; WCHAR* pBufEnd_; WCHAR* pCurrent_; }; bool qs::BufferedWriterImpl::flushBuffer() { if (pCurrent_ != pBuf_.get()) { if (pWriter_->write(pBuf_.get(), pCurrent_ - pBuf_.get()) == -1) return false; pCurrent_ = pBuf_.get(); } return true; } /**************************************************************************** * * BufferedWriter * */ qs::BufferedWriter::BufferedWriter(Writer* pWriter, bool bDelete) : pImpl_(0) { auto_ptr_array<WCHAR> pBuf(new WCHAR[BufferedWriterImpl::BUFFER_SIZE]); pImpl_ = new BufferedWriterImpl(); pImpl_->pWriter_ = pWriter; pImpl_->bDelete_ = bDelete; pImpl_->pBuf_ = pBuf; pImpl_->pBufEnd_ = pImpl_->pBuf_.get() + BufferedWriterImpl::BUFFER_SIZE; pImpl_->pCurrent_ = pImpl_->pBuf_.get(); } qs::BufferedWriter::~BufferedWriter() { if (pImpl_) { if (pImpl_->bDelete_) delete pImpl_->pWriter_; delete pImpl_; pImpl_ = 0; } } bool qs::BufferedWriter::newLine() { return write(L"\r\n", 2) == 2; } bool qs::BufferedWriter::close() { if (!pImpl_->flushBuffer()) return false; return pImpl_->pWriter_->close(); } size_t qs::BufferedWriter::write(const WCHAR* p, size_t nWrite) { assert(p); if (static_cast<size_t>(pImpl_->pBufEnd_ - pImpl_->pCurrent_) >= nWrite) { memcpy(pImpl_->pCurrent_, p, nWrite*sizeof(WCHAR)); pImpl_->pCurrent_ += nWrite; } else { if (!pImpl_->flushBuffer()) return -1; if (nWrite > BufferedWriterImpl::BUFFER_SIZE/2) { if (pImpl_->pWriter_->write(p, nWrite) == -1) return -1; } else { memcpy(pImpl_->pCurrent_, p, nWrite*sizeof(WCHAR)); pImpl_->pCurrent_ += nWrite; } } return nWrite; } <|endoftext|>
<commit_before>#include "Genetic.hpp" #include "Util.hpp" #include <iostream> #define GAME_SPEED 0 #define MUT_PROB 0.01 ai::Genetic::Genetic(logic::Game *game, ui::UI *uiPtr) { gameInstance = game; ui = uiPtr; for (int i = 0; i < POPULATION_SIZE; i++) { generateRandomCrom(population[i].chromosome, CHROM_LENGTH); population[i].fitness = gameInstance->run(population[i].chromosome, GAME_SPEED); } } void ai::Genetic::run() { int iterations = 0; double avg = 0; while (iterations < 20000 && avg < 0.99) { ai::Individual &parent1 = selection(); ai::Individual &parent2 = selection(); std::vector<ai::Individual> children; crossover(parent1, parent2, children); mutation(children[0], MUT_PROB); mutation(children[1], MUT_PROB); children[0].fitness = gameInstance->run(children[0].chromosome, GAME_SPEED); children[1].fitness = gameInstance->run(children[1].chromosome, GAME_SPEED); replacement(children[0]); replacement(children[1]); iterations++; avg = ui->showGeneticStats(); } ui->showGeneticStats(); } ai::Individual& ai::Genetic::selection() { /* Rank-selection (steps): // 1. Two chromosomes are chosen randomly. // 2. Each chromosome is given a probability (proportionally to their fitness) to be chosen. // 3. A random number R [0, 1] is generated. // 4. A chromosome is chosen. */ int first = 0; int second = 0; while (first == second) { first = getRandomInteger(0, POPULATION_SIZE - 1); second = getRandomInteger(0, POPULATION_SIZE - 1); } Individual &crom1 = population[first]; Individual &crom2 = population[second]; double fitSum = crom1.fitness + crom2.fitness; double prob1 = crom1.fitness / fitSum; double r = getRandomReal(0, 1); if (r < prob1) { return crom1; } return crom2; } void ai::Genetic::crossover(ai::Individual &parent1, ai::Individual &parent2, std::vector<ai::Individual> &children) { /* Uniform crossover is performed. // a random binary mask is generated of the same size of the cromosome // for each gen i, if the ith value of the mask is 1, the first child will // copy its ith gene from his first parent, and the second child from his second // parent. Otherwise if the ith value of the mask is 0. */ std::vector<bool> mask; generateRandomCrom(mask, CHROM_LENGTH); ai::Individual child1; ai::Individual child2; children.push_back(child1); children.push_back(child2); for (std::size_t i = 0; i < CHROM_LENGTH; i++) { if (mask[i] == 1) { children[0].chromosome.push_back(parent1.chromosome[i]); children[1].chromosome.push_back(parent2.chromosome[i]); } else { children[0].chromosome.push_back(parent2.chromosome[i]); children[1].chromosome.push_back(parent1.chromosome[i]); } } } void ai::Genetic::mutation(ai::Individual &ind, double mutationProbability) { for (std::size_t i = 0; i < ind.chromosome.size(); i++) { double z = getRandomReal(0, 1); if (z <= mutationProbability) { // Value is fliiped. ind.chromosome[i] = !ind.chromosome[i]; } } } void ai::Genetic::replacement(ai::Individual &ind) { int randIndex = getRandomInteger(0, POPULATION_SIZE - 1); if (population[randIndex].fitness < ind.fitness) { population[randIndex].chromosome = ind.chromosome; population[randIndex].fitness = ind.fitness; } } const ai::Individual* ai::Genetic::getPopulation() { return population; }<commit_msg>The number of iterations done are now displayed.<commit_after>#include "Genetic.hpp" #include "Util.hpp" #include <iostream> #define GAME_SPEED 0 #define MUT_PROB 0.01 ai::Genetic::Genetic(logic::Game *game, ui::UI *uiPtr) { gameInstance = game; ui = uiPtr; for (int i = 0; i < POPULATION_SIZE; i++) { generateRandomCrom(population[i].chromosome, CHROM_LENGTH); population[i].fitness = gameInstance->run(population[i].chromosome, GAME_SPEED); } } void ai::Genetic::run() { int iterations = 0; double avg = 0; while (iterations < 20000 && avg < 0.99) { ai::Individual &parent1 = selection(); ai::Individual &parent2 = selection(); std::vector<ai::Individual> children; crossover(parent1, parent2, children); mutation(children[0], MUT_PROB); mutation(children[1], MUT_PROB); children[0].fitness = gameInstance->run(children[0].chromosome, GAME_SPEED); children[1].fitness = gameInstance->run(children[1].chromosome, GAME_SPEED); replacement(children[0]); replacement(children[1]); iterations++; avg = ui->showGeneticStats(); } ui->showGeneticStats(); std::cout << "Number of iterations: " << iterations + 1 << std::endl; } ai::Individual& ai::Genetic::selection() { /* Rank-selection (steps): // 1. Two chromosomes are chosen randomly. // 2. Each chromosome is given a probability (proportionally to their fitness) to be chosen. // 3. A random number R [0, 1] is generated. // 4. A chromosome is chosen. */ int first = 0; int second = 0; while (first == second) { first = getRandomInteger(0, POPULATION_SIZE - 1); second = getRandomInteger(0, POPULATION_SIZE - 1); } Individual &crom1 = population[first]; Individual &crom2 = population[second]; double fitSum = crom1.fitness + crom2.fitness; double prob1 = crom1.fitness / fitSum; double r = getRandomReal(0, 1); if (r < prob1) { return crom1; } return crom2; } void ai::Genetic::crossover(ai::Individual &parent1, ai::Individual &parent2, std::vector<ai::Individual> &children) { /* Uniform crossover is performed. // a random binary mask is generated of the same size of the cromosome // for each gen i, if the ith value of the mask is 1, the first child will // copy its ith gene from his first parent, and the second child from his second // parent. Otherwise if the ith value of the mask is 0. */ std::vector<bool> mask; generateRandomCrom(mask, CHROM_LENGTH); ai::Individual child1; ai::Individual child2; children.push_back(child1); children.push_back(child2); for (std::size_t i = 0; i < CHROM_LENGTH; i++) { if (mask[i] == 1) { children[0].chromosome.push_back(parent1.chromosome[i]); children[1].chromosome.push_back(parent2.chromosome[i]); } else { children[0].chromosome.push_back(parent2.chromosome[i]); children[1].chromosome.push_back(parent1.chromosome[i]); } } } void ai::Genetic::mutation(ai::Individual &ind, double mutationProbability) { for (std::size_t i = 0; i < ind.chromosome.size(); i++) { double z = getRandomReal(0, 1); if (z <= mutationProbability) { // Value is fliiped. ind.chromosome[i] = !ind.chromosome[i]; } } } void ai::Genetic::replacement(ai::Individual &ind) { int randIndex = getRandomInteger(0, POPULATION_SIZE - 1); if (population[randIndex].fitness < ind.fitness) { population[randIndex].chromosome = ind.chromosome; population[randIndex].fitness = ind.fitness; } } const ai::Individual* ai::Genetic::getPopulation() { return population; }<|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2007 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 * *****************************************************************************/ // $Id$ #include "ogr_datasource.hpp" #include "ogr_featureset.hpp" #include <mapnik/ptree_helpers.hpp> using std::clog; using std::endl; using mapnik::datasource; using mapnik::parameters; DATASOURCE_PLUGIN(ogr_datasource) using mapnik::Envelope; using mapnik::coord2d; using mapnik::query; using mapnik::featureset_ptr; using mapnik::layer_descriptor; using mapnik::attribute_descriptor; using mapnik::datasource_exception; ogr_datasource::ogr_datasource(parameters const& params) : datasource(params), extent_(), type_(datasource::Vector), desc_(*params.get<std::string>("type"),"utf-8") { OGRRegisterAll(); boost::optional<std::string> file = params.get<std::string>("file"); if (!file) throw datasource_exception("missing <file> paramater"); boost::optional<std::string> layer = params.get<std::string>("layer"); if (!layer) throw datasource_exception("missing <layer> paramater"); layerName_ = *layer; multiple_geometries_ = *params_.get<mapnik::boolean>("multiple_geometries",false); dataset_ = OGRSFDriverRegistrar::Open ((*file).c_str(), FALSE); if (!dataset_) throw datasource_exception(CPLGetLastErrorMsg()); layer_ = dataset_->GetLayerByName (layerName_.c_str()); if (! layer_) throw datasource_exception("cannot find <layer> in dataset"); OGREnvelope envelope; layer_->GetExtent (&envelope); extent_.init (envelope.MinX, envelope.MinY, envelope.MaxX, envelope.MaxY); OGRFeatureDefn* def = layer_->GetLayerDefn (); if (def != 0) { int fld_count = def->GetFieldCount (); for (int i = 0; i < fld_count; i++) { OGRFieldDefn* fld = def->GetFieldDefn (i); std_string fld_name = fld->GetNameRef (); OGRFieldType type_oid = fld->GetType (); switch (type_oid) { case OFTInteger: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer)); break; case OFTReal: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double)); break; case OFTString: case OFTWideString: // deprecated desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String)); break; case OFTBinary: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Object)); break; case OFTIntegerList: case OFTRealList: case OFTStringList: case OFTWideStringList: // deprecated ! #ifdef MAPNIK_DEBUG clog << "unhandled type_oid=" << type_oid << endl; #endif break; case OFTDate: case OFTTime: case OFTDateTime: // unhandled ! #ifdef MAPNIK_DEBUG clog << "unhandled type_oid=" << type_oid << endl; #endif desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Object)); break; default: // unknown #ifdef MAPNIK_DEBUG clog << "unknown type_oid=" << type_oid << endl; #endif break; } } } } ogr_datasource::~ogr_datasource() { OGRDataSource::DestroyDataSource (dataset_); } std::string const ogr_datasource::name_="ogr"; std::string ogr_datasource::name() { return name_; } int ogr_datasource::type() const { return type_; } Envelope<double> ogr_datasource::envelope() const { return extent_; } layer_descriptor ogr_datasource::get_descriptor() const { return desc_; } featureset_ptr ogr_datasource::features(query const& q) const { if (dataset_ && layer_) { mapnik::Envelope<double> const& query_extent = q.get_bbox(); layer_->SetSpatialFilterRect (query_extent.minx(), query_extent.miny(), query_extent.maxx(), query_extent.maxy()); #if 0 std::ostringstream s; s << "select "; std::set<std::string> const& props=q.property_names(); std::set<std::string>::const_iterator pos=props.begin(); std::set<std::string>::const_iterator end=props.end(); while (pos != end) { s <<",\""<<*pos<<"\""; ++pos; } s << " from " << layerName_ ; // execute existing SQL OGRLayer* layer = dataset_->ExecuteSQL (s.str(), poly); // layer must be freed dataset_->ReleaseResultSet (layer); #endif return featureset_ptr(new ogr_featureset(*dataset_, *layer_, desc_.get_encoding(), multiple_geometries_)); } return featureset_ptr(); } featureset_ptr ogr_datasource::features_at_point(coord2d const& pt) const { if (dataset_ && layer_) { OGRPoint point; point.setX (pt.x); point.setY (pt.y); layer_->SetSpatialFilter (&point); return featureset_ptr(new ogr_featureset(*dataset_, *layer_, desc_.get_encoding(), multiple_geometries_)); } return featureset_ptr(); } <commit_msg>+ apply ogr_6th_revision.patch to allow unicode support<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2007 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 * *****************************************************************************/ // $Id$ #include "ogr_datasource.hpp" #include "ogr_featureset.hpp" #include <mapnik/ptree_helpers.hpp> using std::clog; using std::endl; using mapnik::datasource; using mapnik::parameters; DATASOURCE_PLUGIN(ogr_datasource) using mapnik::Envelope; using mapnik::coord2d; using mapnik::query; using mapnik::featureset_ptr; using mapnik::layer_descriptor; using mapnik::attribute_descriptor; using mapnik::datasource_exception; ogr_datasource::ogr_datasource(parameters const& params) : datasource(params), extent_(), type_(datasource::Vector), desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8")) { OGRRegisterAll(); boost::optional<std::string> file = params.get<std::string>("file"); if (!file) throw datasource_exception("missing <file> paramater"); boost::optional<std::string> layer = params.get<std::string>("layer"); if (!layer) throw datasource_exception("missing <layer> paramater"); layerName_ = *layer; multiple_geometries_ = *params_.get<mapnik::boolean>("multiple_geometries",false); dataset_ = OGRSFDriverRegistrar::Open ((*file).c_str(), FALSE); if (!dataset_) throw datasource_exception(CPLGetLastErrorMsg()); layer_ = dataset_->GetLayerByName (layerName_.c_str()); if (! layer_) throw datasource_exception("cannot find <layer> in dataset"); OGREnvelope envelope; layer_->GetExtent (&envelope); extent_.init (envelope.MinX, envelope.MinY, envelope.MaxX, envelope.MaxY); OGRFeatureDefn* def = layer_->GetLayerDefn (); if (def != 0) { int fld_count = def->GetFieldCount (); for (int i = 0; i < fld_count; i++) { OGRFieldDefn* fld = def->GetFieldDefn (i); std_string fld_name = fld->GetNameRef (); OGRFieldType type_oid = fld->GetType (); switch (type_oid) { case OFTInteger: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer)); break; case OFTReal: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double)); break; case OFTString: case OFTWideString: // deprecated desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String)); break; case OFTBinary: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Object)); break; case OFTIntegerList: case OFTRealList: case OFTStringList: case OFTWideStringList: // deprecated ! #ifdef MAPNIK_DEBUG clog << "unhandled type_oid=" << type_oid << endl; #endif break; case OFTDate: case OFTTime: case OFTDateTime: // unhandled ! #ifdef MAPNIK_DEBUG clog << "unhandled type_oid=" << type_oid << endl; #endif desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Object)); break; default: // unknown #ifdef MAPNIK_DEBUG clog << "unknown type_oid=" << type_oid << endl; #endif break; } } } } ogr_datasource::~ogr_datasource() { OGRDataSource::DestroyDataSource (dataset_); } std::string const ogr_datasource::name_="ogr"; std::string ogr_datasource::name() { return name_; } int ogr_datasource::type() const { return type_; } Envelope<double> ogr_datasource::envelope() const { return extent_; } layer_descriptor ogr_datasource::get_descriptor() const { return desc_; } featureset_ptr ogr_datasource::features(query const& q) const { if (dataset_ && layer_) { mapnik::Envelope<double> const& query_extent = q.get_bbox(); layer_->SetSpatialFilterRect (query_extent.minx(), query_extent.miny(), query_extent.maxx(), query_extent.maxy()); #if 0 std::ostringstream s; s << "select "; std::set<std::string> const& props=q.property_names(); std::set<std::string>::const_iterator pos=props.begin(); std::set<std::string>::const_iterator end=props.end(); while (pos != end) { s <<",\""<<*pos<<"\""; ++pos; } s << " from " << layerName_ ; // execute existing SQL OGRLayer* layer = dataset_->ExecuteSQL (s.str(), poly); // layer must be freed dataset_->ReleaseResultSet (layer); #endif return featureset_ptr(new ogr_featureset(*dataset_, *layer_, desc_.get_encoding(), multiple_geometries_)); } return featureset_ptr(); } featureset_ptr ogr_datasource::features_at_point(coord2d const& pt) const { if (dataset_ && layer_) { OGRPoint point; point.setX (pt.x); point.setY (pt.y); layer_->SetSpatialFilter (&point); return featureset_ptr(new ogr_featureset(*dataset_, *layer_, desc_.get_encoding(), multiple_geometries_)); } return featureset_ptr(); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ //$Id: connection.hpp 17 2005-03-08 23:58:43Z pavlenko $ #ifndef CONNECTION_HPP #define CONNECTION_HPP #include <mapnik/datasource.hpp> extern "C" { #include "libpq-fe.h" } #include "resultset.hpp" class ResultSet; class Connection { private: PGconn *conn_; int cursorId; bool closed_; public: Connection(std::string const& connection_str) :cursorId(0), closed_(false) { conn_=PQconnectdb(connection_str.c_str()); if (PQstatus(conn_) != CONNECTION_OK) { std::string s("Postgis Plugin: PSQL error"); if (conn_ ) { std::string msg = PQerrorMessage( conn_ ); if ( ! msg.empty() ) { s << ":" << std::endl << msg.substr( 0, msg.size() - 1 ); } } throw mapnik::datasource_exception( s ); } } bool execute(const std::string& sql) const { PGresult *result=PQexec(conn_,sql.c_str()); bool ok=(result && PQresultStatus(result)==PGRES_COMMAND_OK); PQclear(result); return ok; } boost::shared_ptr<ResultSet> executeQuery(const std::string& sql,int type=0) const { PGresult *result=0; if (type==1) { result=PQexecParams(conn_,sql.c_str(),0,0,0,0,0,1); } else { result=PQexec(conn_,sql.c_str()); } if(!result || PQresultStatus(result) != PGRES_TUPLES_OK) { std::string s("Postgis Plugin: PSQL error"); if (conn_ ) { std::string msg = PQerrorMessage( conn_ ); if ( ! msg.empty() ) { s << ":" << std::endl << msg.substr( 0, msg.size() - 1 ); } s << std::endl << "Full sql was: '" + sql + "'" << std::endl; } throw mapnik::datasource_exception( s ); } return boost::shared_ptr<ResultSet>(new ResultSet(result)); } std::string client_encoding() const { return PQparameterStatus(conn_,"client_encoding"); } bool isOK() const { return (PQstatus(conn_)!=CONNECTION_BAD); } void close() { if (!closed_) { PQfinish(conn_); #ifdef MAPNIK_DEBUG std::clog << "PostGIS: datasource closed, also closing connection - " << conn_ << std::endl; #endif closed_ = true; } } std::string new_cursor_name() { std::ostringstream s; s << "mapnik_" << (cursorId++); return s.str(); } ~Connection() { if (!closed_) { PQfinish(conn_); #ifdef MAPNIK_DEBUG std::clog << "PostGIS: postgresql connection closed - " << conn_ << std::endl; #endif closed_ = true; } } }; #endif //CONNECTION_HPP <commit_msg>avoid compiler errors on os x<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ //$Id: connection.hpp 17 2005-03-08 23:58:43Z pavlenko $ #ifndef CONNECTION_HPP #define CONNECTION_HPP #include <mapnik/datasource.hpp> extern "C" { #include "libpq-fe.h" } #include "resultset.hpp" class ResultSet; class Connection { private: PGconn *conn_; int cursorId; bool closed_; public: Connection(std::string const& connection_str) :cursorId(0), closed_(false) { conn_=PQconnectdb(connection_str.c_str()); if (PQstatus(conn_) != CONNECTION_OK) { std::ostringstream s("Postgis Plugin: PSQL error"); if (conn_ ) { std::string msg = PQerrorMessage( conn_ ); if ( ! msg.empty() ) { s << ":\n" << msg.substr( 0, msg.size() - 1 ); } } throw mapnik::datasource_exception( s.str() ); } } bool execute(const std::string& sql) const { PGresult *result=PQexec(conn_,sql.c_str()); bool ok=(result && PQresultStatus(result)==PGRES_COMMAND_OK); PQclear(result); return ok; } boost::shared_ptr<ResultSet> executeQuery(const std::string& sql,int type=0) const { PGresult *result=0; if (type==1) { result=PQexecParams(conn_,sql.c_str(),0,0,0,0,0,1); } else { result=PQexec(conn_,sql.c_str()); } if(!result || PQresultStatus(result) != PGRES_TUPLES_OK) { std::ostringstream s("Postgis Plugin: PSQL error"); if (conn_ ) { std::string msg = PQerrorMessage( conn_ ); if ( ! msg.empty() ) { s << ":" << std::endl << msg.substr( 0, msg.size() - 1 ); } s << std::endl << "Full sql was: '" + sql + "'" << std::endl; } throw mapnik::datasource_exception( s.str() ); } return boost::shared_ptr<ResultSet>(new ResultSet(result)); } std::string client_encoding() const { return PQparameterStatus(conn_,"client_encoding"); } bool isOK() const { return (PQstatus(conn_)!=CONNECTION_BAD); } void close() { if (!closed_) { PQfinish(conn_); #ifdef MAPNIK_DEBUG std::clog << "PostGIS: datasource closed, also closing connection - " << conn_ << std::endl; #endif closed_ = true; } } std::string new_cursor_name() { std::ostringstream s; s << "mapnik_" << (cursorId++); return s.str(); } ~Connection() { if (!closed_) { PQfinish(conn_); #ifdef MAPNIK_DEBUG std::clog << "PostGIS: postgresql connection closed - " << conn_ << std::endl; #endif closed_ = true; } } }; #endif //CONNECTION_HPP <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ //$Id: connection.hpp 17 2005-03-08 23:58:43Z pavlenko $ #ifndef CONNECTION_HPP #define CONNECTION_HPP #include <mapnik/datasource.hpp> extern "C" { #include "libpq-fe.h" } #include "resultset.hpp" class ResultSet; class Connection { private: PGconn *conn_; int cursorId; public: Connection(std::string const& connection_str) :cursorId(0) { conn_=PQconnectdb(connection_str.c_str()); if (PQstatus(conn_) != CONNECTION_OK) { std::string s("PSQL error"); if (conn_ ) { std::string msg = PQerrorMessage( conn_ ); if ( ! msg.empty() ) { s += ":\n" + msg.substr( 0, msg.size() - 1 ); } } throw mapnik::datasource_exception( s ); } } bool execute(const std::string& sql) const { PGresult *result=PQexec(conn_,sql.c_str()); bool ok=(result && PQresultStatus(result)==PGRES_COMMAND_OK); PQclear(result); return ok; } boost::shared_ptr<ResultSet> executeQuery(const std::string& sql,int type=0) const { PGresult *result=0; if (type==1) { result=PQexecParams(conn_,sql.c_str(),0,0,0,0,0,1); } else { result=PQexec(conn_,sql.c_str()); } if(!result || PQresultStatus(result) != PGRES_TUPLES_OK) { std::string s("PSQL error"); if (conn_ ) { std::string msg = PQerrorMessage( conn_ ); if ( ! msg.empty() ) { s += ":\n" + msg.substr( 0, msg.size() - 1 ); } } throw mapnik::datasource_exception( s ); } return boost::shared_ptr<ResultSet>(new ResultSet(result)); } std::string client_encoding() const { return PQparameterStatus(conn_,"client_encoding"); } bool isOK() const { return (PQstatus(conn_)!=CONNECTION_BAD); } void close() { PQfinish(conn_); } std::string new_cursor_name() { std::ostringstream s; s << "mapnik_" << (cursorId++); return s.str(); } ~Connection() { PQfinish(conn_); #ifdef MAPNIK_DEBUG std::clog << "close connection " << conn_ << "\n"; #endif } }; #endif //CONNECTION_HPP <commit_msg>when a SQL query sent to postgres fails, output the whole thing so users know what mapnik tried to send (as the PSQL error hint truncates the sql)<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ //$Id: connection.hpp 17 2005-03-08 23:58:43Z pavlenko $ #ifndef CONNECTION_HPP #define CONNECTION_HPP #include <mapnik/datasource.hpp> extern "C" { #include "libpq-fe.h" } #include "resultset.hpp" class ResultSet; class Connection { private: PGconn *conn_; int cursorId; public: Connection(std::string const& connection_str) :cursorId(0) { conn_=PQconnectdb(connection_str.c_str()); if (PQstatus(conn_) != CONNECTION_OK) { std::string s("PSQL error"); if (conn_ ) { std::string msg = PQerrorMessage( conn_ ); if ( ! msg.empty() ) { s += ":\n" + msg.substr( 0, msg.size() - 1 ); } } throw mapnik::datasource_exception( s ); } } bool execute(const std::string& sql) const { PGresult *result=PQexec(conn_,sql.c_str()); bool ok=(result && PQresultStatus(result)==PGRES_COMMAND_OK); PQclear(result); return ok; } boost::shared_ptr<ResultSet> executeQuery(const std::string& sql,int type=0) const { PGresult *result=0; if (type==1) { result=PQexecParams(conn_,sql.c_str(),0,0,0,0,0,1); } else { result=PQexec(conn_,sql.c_str()); } if(!result || PQresultStatus(result) != PGRES_TUPLES_OK) { std::string s("PSQL error"); if (conn_ ) { std::string msg = PQerrorMessage( conn_ ); if ( ! msg.empty() ) { s += ":\n" + msg.substr( 0, msg.size() - 1 ); } s += "\nFull sql was: '" + sql + "'\n"; } throw mapnik::datasource_exception( s ); } return boost::shared_ptr<ResultSet>(new ResultSet(result)); } std::string client_encoding() const { return PQparameterStatus(conn_,"client_encoding"); } bool isOK() const { return (PQstatus(conn_)!=CONNECTION_BAD); } void close() { PQfinish(conn_); } std::string new_cursor_name() { std::ostringstream s; s << "mapnik_" << (cursorId++); return s.str(); } ~Connection() { PQfinish(conn_); #ifdef MAPNIK_DEBUG std::clog << "close connection " << conn_ << "\n"; #endif } }; #endif //CONNECTION_HPP <|endoftext|>
<commit_before>#ifndef __ETERNAL_TCP_HEADERS__ #define __ETERNAL_TCP_HEADERS__ #include <errno.h> #include <pthread.h> /* POSIX Threads */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <algorithm> #include <array> #include <exception> #include <fstream> #include <iostream> #include <memory> #include <mutex> #include <sstream> #include <sstream> #include <streambuf> #include <string> #include <thread> #include <unordered_map> #include <unordered_set> #include <vector> #include <boost/circular_buffer.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include <google/protobuf/message.h> #include "ET.pb.h" using namespace std; namespace et { void equalOrFatal(ssize_t expected, ssize_t actual); } #define FATAL_FAIL(X) \ if ((X == -1)) LOG(FATAL) << "Error: (" << errno << "): " << strerror(errno); #endif <commit_msg>Add missing header<commit_after>#ifndef __ETERNAL_TCP_HEADERS__ #define __ETERNAL_TCP_HEADERS__ #include <errno.h> #include <pthread.h> /* POSIX Threads */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <arpa/inet.h> #include <algorithm> #include <array> #include <exception> #include <fstream> #include <iostream> #include <memory> #include <mutex> #include <sstream> #include <sstream> #include <streambuf> #include <string> #include <thread> #include <unordered_map> #include <unordered_set> #include <vector> #include <boost/circular_buffer.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include <google/protobuf/message.h> #include "ET.pb.h" using namespace std; namespace et { void equalOrFatal(ssize_t expected, ssize_t actual); } #define FATAL_FAIL(X) \ if ((X == -1)) LOG(FATAL) << "Error: (" << errno << "): " << strerror(errno); #endif <|endoftext|>
<commit_before>// header file for storing integration schemes #include "IBSolver.h" #include "Geometry.h" #include "ProjectionSolver.h" #include "ConjugateGradientSolver.h" #include "CholeskySolver.h" #include "BoundaryVector.h" #include "Grid.h" #include "State.h" #include "VectorOperations.h" #include <string> using namespace std; namespace ibpm { IBSolver::IBSolver( const Grid& grid, NavierStokesModel& model, double dt, Scheme::SchemeType scheme ) : _grid( grid ), _scheme( scheme ), _name( _scheme.name( ) ), _dt( dt ), _model( model ), _Nprev( grid ), _Ntemp( grid ), _oldSaved( false ), _solver( _scheme.nsteps() ), _tol( 1e-7) { createAllSolvers(); } IBSolver::IBSolver( const Grid& grid, NavierStokesModel& model, double dt, Scheme::SchemeType scheme, double tol ) : _grid( grid ), _scheme( scheme ), _name( _scheme.name( ) ), _dt( dt ), _model( model ), _Nprev( grid ), _Ntemp( grid ), _oldSaved( false ), _solver( _scheme.nsteps() ), _tol( tol ) { createAllSolvers(); } IBSolver::~IBSolver() { deleteAllSolvers(); } string IBSolver::getName() { return _name; } string IBSolver::getTimestep() { return _dt; } void IBSolver::init() { for ( int i = 0; i < _scheme.nsteps(); i++ ) { _solver[i] -> init(); } } void IBSolver::reset() { _oldSaved = false; } bool IBSolver::load(const string& basename) { bool successInit = false; bool successTemp = true; for ( int i = 0; i < _scheme.nsteps(); i++ ) { char num[256]; sprintf( num, "%02d", i+1 ); string filename = basename + "_" + num; successTemp = _solver[i] -> load( filename ) && successTemp; if ( i == 0 ) { successInit = true; } } return successInit && successTemp; } bool IBSolver::save(const string& basename) { bool successInit = false; bool successTemp = true; for ( int i = 0; i < _scheme.nsteps(); i++ ) { char num[256]; sprintf( num, "%02d", i+1 ); string filename = basename + "_" + num; successTemp = _solver[i] -> save( filename ) && successTemp; if ( i == 0 ) { successInit = true; } } return successInit && successTemp; } void IBSolver::createAllSolvers() { for ( int i = 0; i < _scheme.nsteps(); i++ ) { _solver[i] = createSolver( ( _scheme.an(i) + _scheme.bn(i) )*_dt ); } } void IBSolver::deleteAllSolvers() { for (unsigned int i = 0; i < _solver.size(); i++) { delete _solver[i]; } } ProjectionSolver* IBSolver::createSolver(double beta) { // Check whether all bodies are stationary // If so, return a CholeskySolver // If not, return a ConjugateGradientSolver if ( _model.isTimeDependent() ) { cerr << "Using ConjugateGradient solver for projection step" << endl << " tolerance = " << _tol << endl; return new ConjugateGradientSolver( _grid, _model, beta, _tol ); } else { cerr << "Using Cholesky solver for projection step" << endl; return new CholeskySolver( _grid, _model, beta ); } } void IBSolver::setTol( double tol ) { _tol = tol; createAllSolvers(); } void IBSolver::advance( State& x ) { for ( int i = 0; i < _scheme.nsteps(); i++ ) { Scalar nonlinear = N(x); advanceSubstep( x, nonlinear, i ); } x.time += _dt; ++x.timestep; } void IBSolver::advance( State& x, const Scalar& Bu ) { for ( int i = 0; i < _scheme.nsteps(); i++ ) { Scalar nonlinear = N(x) + Bu; advanceSubstep( x, nonlinear, i ); } x.time += _dt; ++x.timestep; } void IBSolver::advanceSubstep( State& x, const Scalar& nonlinear, int i ) { // If the body is moving, update the positions of the bodies if ( _model.isTimeDependent() ) { _model.updateOperators( x.time + _scheme.cn(i) * _dt ); } // Evaluate Right-Hand-Side (a) for first equation of ProjectionSolver Scalar a = Laplacian( x.omega ); a *= 0.5 * _model.getAlpha() * ( _scheme.an(i) + _scheme.bn(i) ); a += _scheme.an(i)*nonlinear; if ( _scheme.bn(i) != 0 ) { // for ab2 if ( _oldSaved == false ) { _Nprev = nonlinear; } a += _scheme.bn(i) * _Nprev; } a *= _dt; a += x.omega; // Evaluate Right-Hand-Side (b) for second equation of ProjectionSolver BoundaryVector b = _model.getConstraints(); // Call the ProjectionSolver to determine the vorticity and forces _solver[i]->solve( a, b, x.omega, x.f ); // Update the state, for instance to compute the corresponding flux _model.refreshState( x ); _Nprev = nonlinear; if( _oldSaved == false ) { _oldSaved = true; } } // ===================== // // Derived class methods // // ===================== // Scalar NonlinearIBSolver::N(const State& x) const { Flux v = CrossProduct( x.q, x.omega ); Scalar g = Curl( v ); return g; } Scalar LinearizedIBSolver::N(const State& x) const { Flux v = CrossProduct( _x0.q, x.omega ); v += CrossProduct( x.q, _x0.omega ); Scalar g = Curl( v ); return g; } Scalar AdjointIBSolver::N(const State& x) const { Scalar g = Laplacian( CrossProduct( _x0.q, x.q )); g -= Curl(CrossProduct( x.q, _x0.omega )); return g; } Scalar LinearizedPeriodicIBSolver::N(const State& x) const { int k = x.timestep % _period; cout << "At time step " << x.timestep << ", phase k = " << k << endl; Flux v = CrossProduct( _x0periodic[k].q, x.omega ); v += CrossProduct( x.q, _x0periodic[k].omega ); Scalar g = Curl( v ); return g; } // =========== // // SFD methods // // =========== // Scalar SFDSolver::N(const State& x) const { Flux v = CrossProduct( x.q, x.omega ); Scalar g = Curl( v ); Scalar temp( x.omega ); // because x is const here...hmmm g -= _chi * ( temp - _xhat.omega ); return g; } void SFDSolver::advanceSubstep( State& x, const Scalar& nonlinear, int i ) { assert( x.time == _xhat.time ); // Initialize _xhat if necessary, save current vorticity field if ( _xhatSaved == false ) { _xhat = x; _xhatSaved = true; } _omegaTemp = x.omega; // Advance state x IBSolver::advanceSubstep( x, nonlinear, i ); // Advance state _xhat Scalar rhs = ( _omegaTemp - _xhat.omega ) / _Delta; Scalar a = _scheme.an(i)*rhs; if ( _scheme.bn(i) != 0 ) { if ( _rhsSaved == false ) { _rhsPrev = rhs; } a += _scheme.bn(i) * _rhsPrev; } a *= _dt; _xhat.omega += a; if ( i == _scheme.nsteps()-1 ) { _xhat.time += _dt; _xhat.timestep++; } _rhsPrev = rhs; if( _rhsSaved == false ) { _rhsSaved = true; } } void SFDSolver::saveFilteredState( string outdir, string name, string numDigitInFileName ) { string formatString = outdir+name+numDigitInFileName+".bin"+"_xhat"; char filename[256]; sprintf( filename, formatString.c_str(), _xhat.timestep ); _xhat.save( filename ); } void SFDSolver::loadFilteredState( string icFile ) { string xhatFile = icFile+"_xhat"; _xhat.omega = 0.; _xhat.f = 0.; _xhat.q = 0.; if (xhatFile != "_xhat") { cout << "Loading initial condition from file: " << xhatFile << endl; if ( ! _xhat.load(xhatFile) ) { cout << " (failed: setting xhat = x)" << endl; } } else { cout << "Setting xhat = x" << endl; } _xhatSaved = true; } } // ibpm <commit_msg>Fixed minor bug in new IBSolver method getTimestep(). Code now compiles.<commit_after>// header file for storing integration schemes #include "IBSolver.h" #include "Geometry.h" #include "ProjectionSolver.h" #include "ConjugateGradientSolver.h" #include "CholeskySolver.h" #include "BoundaryVector.h" #include "Grid.h" #include "State.h" #include "VectorOperations.h" #include <string> using namespace std; namespace ibpm { IBSolver::IBSolver( const Grid& grid, NavierStokesModel& model, double dt, Scheme::SchemeType scheme ) : _grid( grid ), _scheme( scheme ), _name( _scheme.name( ) ), _dt( dt ), _model( model ), _Nprev( grid ), _Ntemp( grid ), _oldSaved( false ), _solver( _scheme.nsteps() ), _tol( 1e-7) { createAllSolvers(); } IBSolver::IBSolver( const Grid& grid, NavierStokesModel& model, double dt, Scheme::SchemeType scheme, double tol ) : _grid( grid ), _scheme( scheme ), _name( _scheme.name( ) ), _dt( dt ), _model( model ), _Nprev( grid ), _Ntemp( grid ), _oldSaved( false ), _solver( _scheme.nsteps() ), _tol( tol ) { createAllSolvers(); } IBSolver::~IBSolver() { deleteAllSolvers(); } string IBSolver::getName() { return _name; } double IBSolver::getTimestep() { return _dt; } void IBSolver::init() { for ( int i = 0; i < _scheme.nsteps(); i++ ) { _solver[i] -> init(); } } void IBSolver::reset() { _oldSaved = false; } bool IBSolver::load(const string& basename) { bool successInit = false; bool successTemp = true; for ( int i = 0; i < _scheme.nsteps(); i++ ) { char num[256]; sprintf( num, "%02d", i+1 ); string filename = basename + "_" + num; successTemp = _solver[i] -> load( filename ) && successTemp; if ( i == 0 ) { successInit = true; } } return successInit && successTemp; } bool IBSolver::save(const string& basename) { bool successInit = false; bool successTemp = true; for ( int i = 0; i < _scheme.nsteps(); i++ ) { char num[256]; sprintf( num, "%02d", i+1 ); string filename = basename + "_" + num; successTemp = _solver[i] -> save( filename ) && successTemp; if ( i == 0 ) { successInit = true; } } return successInit && successTemp; } void IBSolver::createAllSolvers() { for ( int i = 0; i < _scheme.nsteps(); i++ ) { _solver[i] = createSolver( ( _scheme.an(i) + _scheme.bn(i) )*_dt ); } } void IBSolver::deleteAllSolvers() { for (unsigned int i = 0; i < _solver.size(); i++) { delete _solver[i]; } } ProjectionSolver* IBSolver::createSolver(double beta) { // Check whether all bodies are stationary // If so, return a CholeskySolver // If not, return a ConjugateGradientSolver if ( _model.isTimeDependent() ) { cerr << "Using ConjugateGradient solver for projection step" << endl << " tolerance = " << _tol << endl; return new ConjugateGradientSolver( _grid, _model, beta, _tol ); } else { cerr << "Using Cholesky solver for projection step" << endl; return new CholeskySolver( _grid, _model, beta ); } } void IBSolver::setTol( double tol ) { _tol = tol; createAllSolvers(); } void IBSolver::advance( State& x ) { for ( int i = 0; i < _scheme.nsteps(); i++ ) { Scalar nonlinear = N(x); advanceSubstep( x, nonlinear, i ); } x.time += _dt; ++x.timestep; } void IBSolver::advance( State& x, const Scalar& Bu ) { for ( int i = 0; i < _scheme.nsteps(); i++ ) { Scalar nonlinear = N(x) + Bu; advanceSubstep( x, nonlinear, i ); } x.time += _dt; ++x.timestep; } void IBSolver::advanceSubstep( State& x, const Scalar& nonlinear, int i ) { // If the body is moving, update the positions of the bodies if ( _model.isTimeDependent() ) { _model.updateOperators( x.time + _scheme.cn(i) * _dt ); } // Evaluate Right-Hand-Side (a) for first equation of ProjectionSolver Scalar a = Laplacian( x.omega ); a *= 0.5 * _model.getAlpha() * ( _scheme.an(i) + _scheme.bn(i) ); a += _scheme.an(i)*nonlinear; if ( _scheme.bn(i) != 0 ) { // for ab2 if ( _oldSaved == false ) { _Nprev = nonlinear; } a += _scheme.bn(i) * _Nprev; } a *= _dt; a += x.omega; // Evaluate Right-Hand-Side (b) for second equation of ProjectionSolver BoundaryVector b = _model.getConstraints(); // Call the ProjectionSolver to determine the vorticity and forces _solver[i]->solve( a, b, x.omega, x.f ); // Update the state, for instance to compute the corresponding flux _model.refreshState( x ); _Nprev = nonlinear; if( _oldSaved == false ) { _oldSaved = true; } } // ===================== // // Derived class methods // // ===================== // Scalar NonlinearIBSolver::N(const State& x) const { Flux v = CrossProduct( x.q, x.omega ); Scalar g = Curl( v ); return g; } Scalar LinearizedIBSolver::N(const State& x) const { Flux v = CrossProduct( _x0.q, x.omega ); v += CrossProduct( x.q, _x0.omega ); Scalar g = Curl( v ); return g; } Scalar AdjointIBSolver::N(const State& x) const { Scalar g = Laplacian( CrossProduct( _x0.q, x.q )); g -= Curl(CrossProduct( x.q, _x0.omega )); return g; } Scalar LinearizedPeriodicIBSolver::N(const State& x) const { int k = x.timestep % _period; cout << "At time step " << x.timestep << ", phase k = " << k << endl; Flux v = CrossProduct( _x0periodic[k].q, x.omega ); v += CrossProduct( x.q, _x0periodic[k].omega ); Scalar g = Curl( v ); return g; } // =========== // // SFD methods // // =========== // Scalar SFDSolver::N(const State& x) const { Flux v = CrossProduct( x.q, x.omega ); Scalar g = Curl( v ); Scalar temp( x.omega ); // because x is const here...hmmm g -= _chi * ( temp - _xhat.omega ); return g; } void SFDSolver::advanceSubstep( State& x, const Scalar& nonlinear, int i ) { assert( x.time == _xhat.time ); // Initialize _xhat if necessary, save current vorticity field if ( _xhatSaved == false ) { _xhat = x; _xhatSaved = true; } _omegaTemp = x.omega; // Advance state x IBSolver::advanceSubstep( x, nonlinear, i ); // Advance state _xhat Scalar rhs = ( _omegaTemp - _xhat.omega ) / _Delta; Scalar a = _scheme.an(i)*rhs; if ( _scheme.bn(i) != 0 ) { if ( _rhsSaved == false ) { _rhsPrev = rhs; } a += _scheme.bn(i) * _rhsPrev; } a *= _dt; _xhat.omega += a; if ( i == _scheme.nsteps()-1 ) { _xhat.time += _dt; _xhat.timestep++; } _rhsPrev = rhs; if( _rhsSaved == false ) { _rhsSaved = true; } } void SFDSolver::saveFilteredState( string outdir, string name, string numDigitInFileName ) { string formatString = outdir+name+numDigitInFileName+".bin"+"_xhat"; char filename[256]; sprintf( filename, formatString.c_str(), _xhat.timestep ); _xhat.save( filename ); } void SFDSolver::loadFilteredState( string icFile ) { string xhatFile = icFile+"_xhat"; _xhat.omega = 0.; _xhat.f = 0.; _xhat.q = 0.; if (xhatFile != "_xhat") { cout << "Loading initial condition from file: " << xhatFile << endl; if ( ! _xhat.load(xhatFile) ) { cout << " (failed: setting xhat = x)" << endl; } } else { cout << "Setting xhat = x" << endl; } _xhatSaved = true; } } // ibpm <|endoftext|>
<commit_before>/* Rapicorn * Copyright (C) 2008 Tim Janik * * 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. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #ifndef __RAPICORN_MODELS_HH__ #define __RAPICORN_MODELS_HH__ #include <rapicorn-core/types.hh> #include <rapicorn-core/values.hh> namespace Rapicorn { /* --- Data Models --- */ class Model0 : public virtual ReferenceCountImpl { // 1*Type + 1*Value class Model0Value : public BaseValue { virtual void changed (); public: explicit Model0Value (StorageType s) : BaseValue (s) {} }; Type m_type; Model0Value m_value; protected: virtual ~Model0 (void); virtual void changed (void); public: explicit Model0 (Type t); Type type (void) { return m_type; } /* notification */ Signal<Model0, void ()> sig_changed; /* accessors */ template<typename T> void set (T tvalue) { m_value.set (tvalue); } template<typename T> void operator= (T tvalue) { m_value.set (tvalue); } template<typename T> T get () { return m_value.convert ((T*) 0); } template<typename T> /*T*/ operator T () { return m_value.convert ((T*) 0); } }; typedef class Model0 Variable; class Store1; class Model1 : public virtual ReferenceCountImpl { // 1*Type + n*Value Type m_type; protected: void changed (uint64 first, uint64 count); void inserted (uint64 first, uint64 count); void deleted (uint64 first, uint64 count); virtual ~Model1 (void); virtual void handle_changed (uint64, uint64); virtual void handle_inserted (uint64, uint64); virtual void handle_deleted (uint64, uint64); virtual Store1* pget_store (void) = 0; virtual uint64 pcount_rows (void) = 0; virtual Array pget_row (uint64 row) = 0; public: explicit Model1 (Type row_type); Store1* store (void) { return pget_store(); } Type type (void) const { return m_type; } int64 count (void) { return pcount_rows(); } Array get (uint64 nth) { return pget_row (nth); } /* notification */ typedef Signal<Model1, void (uint64,uint64)> RangeSignal; RangeSignal sig_changed; RangeSignal sig_inserted; RangeSignal sig_deleted; }; class Store1 : public virtual ReferenceCountImpl { // 1*Type + n*Value protected: virtual ~Store1 (void); virtual Model1& pget_model (void) = 0; virtual void pchange_rows (uint64 first, uint64 count, const Array *array) = 0; virtual void pinsert_rows (int64 first, uint64 count, const Array *arrays) = 0; virtual void premove_rows (uint64 first, uint64 count) = 0; public: explicit Store1 (void); Model1& model (void) { return pget_model(); } Type type (void) { return model().type(); } int64 count (void) { return model().count(); } Array get (uint64 nth) { return model().get (nth); } void set (uint64 nth, const Array &array) { pchange_rows (nth, 1, &array); } void insert (int64 nth, const Array &array) { pinsert_rows (nth, 1, &array); } void remove (uint64 nth) { premove_rows (nth, 1); } void update (uint64 nth, const Array &array) { pchange_rows (nth, 1, &array); } /* premade stores */ static Store1* create_memory_store (Type row_type); }; } // Rapicorn #endif /* __RAPICORN_MODELS_HH__ */ <commit_msg>Added clear() method to models.<commit_after>/* Rapicorn * Copyright (C) 2008 Tim Janik * * 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. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #ifndef __RAPICORN_MODELS_HH__ #define __RAPICORN_MODELS_HH__ #include <rapicorn-core/types.hh> #include <rapicorn-core/values.hh> namespace Rapicorn { /* --- Data Models --- */ class Model0 : public virtual ReferenceCountImpl { // 1*Type + 1*Value class Model0Value : public BaseValue { virtual void changed (); public: explicit Model0Value (StorageType s) : BaseValue (s) {} }; Type m_type; Model0Value m_value; protected: virtual ~Model0 (void); virtual void changed (void); public: explicit Model0 (Type t); Type type (void) { return m_type; } /* notification */ Signal<Model0, void ()> sig_changed; /* accessors */ template<typename T> void set (T tvalue) { m_value.set (tvalue); } template<typename T> void operator= (T tvalue) { m_value.set (tvalue); } template<typename T> T get () { return m_value.convert ((T*) 0); } template<typename T> /*T*/ operator T () { return m_value.convert ((T*) 0); } }; typedef class Model0 Variable; class Store1; class Model1 : public virtual ReferenceCountImpl { // 1*Type + n*Value Type m_type; protected: void changed (uint64 first, uint64 count); void inserted (uint64 first, uint64 count); void deleted (uint64 first, uint64 count); virtual ~Model1 (void); virtual void handle_changed (uint64, uint64); virtual void handle_inserted (uint64, uint64); virtual void handle_deleted (uint64, uint64); virtual Store1* pget_store (void) = 0; virtual uint64 pcount_rows (void) = 0; virtual Array pget_row (uint64 row) = 0; public: explicit Model1 (Type row_type); Store1* store (void) { return pget_store(); } Type type (void) const { return m_type; } int64 count (void) { return pcount_rows(); } Array get (uint64 nth) { return pget_row (nth); } /* notification */ typedef Signal<Model1, void (uint64,uint64)> RangeSignal; RangeSignal sig_changed; RangeSignal sig_inserted; RangeSignal sig_deleted; }; class Store1 : public virtual ReferenceCountImpl { // 1*Type + n*Value protected: virtual ~Store1 (void); virtual Model1& pget_model (void) = 0; virtual void pchange_rows (uint64 first, uint64 count, const Array *array) = 0; virtual void pinsert_rows (int64 first, uint64 count, const Array *arrays) = 0; virtual void premove_rows (uint64 first, uint64 count) = 0; public: explicit Store1 (void); Model1& model (void) { return pget_model(); } Type type (void) { return model().type(); } int64 count (void) { return model().count(); } Array get (uint64 nth) { return model().get (nth); } void set (uint64 nth, const Array &array) { pchange_rows (nth, 1, &array); } void insert (int64 nth, const Array &array) { pinsert_rows (nth, 1, &array); } void remove (uint64 nth) { premove_rows (nth, 1); } void update (uint64 nth, const Array &array) { pchange_rows (nth, 1, &array); } void clear () { premove_rows (0, count()); } /* premade stores */ static Store1* create_memory_store (Type row_type); }; } // Rapicorn #endif /* __RAPICORN_MODELS_HH__ */ <|endoftext|>
<commit_before>#include "Operations.hpp" #include "Wallet.hpp" #include <graphene/utilities/key_conversion.hpp> #include <fc/smart_ref_impl.hpp> TransferOperation* OperationBuilder::transfer(ObjectId sender, ObjectId receiver, qint64 amount, ObjectId amountType, QString memo, ObjectId feeType) { try { TransferOperation* op = new TransferOperation; op->setSender(sender); op->setReceiver(receiver); op->setAmount(amount); op->setAmountType(amountType); op->setMemo(memo); op->setFeeType(feeType); auto feeParameters = model.global_properties().parameters.current_fees->get<graphene::chain::transfer_operation>(); op->setFee(op->operation().calculate_fee(feeParameters).value); return op; } catch (const fc::exception& e) { qDebug() << e.to_detail_string().c_str(); return nullptr; } } QString TransferOperation::memo() const { if (!m_op.memo) return QString::null; if (memoIsEncrypted()) return tr("Encrypted Memo"); QString memo = QString::fromStdString(m_op.memo->get_message({}, {})); while (memo.endsWith('\0')) memo.chop(1); return memo; } bool TransferOperation::memoIsEncrypted() const { if (!m_op.memo) return false; if (m_op.memo->message.empty()) return false; if (m_op.memo->from == public_key_type() && m_op.memo->to == public_key_type()) return false; return true; } bool TransferOperation::canEncryptMemo(Wallet* wallet, ChainDataModel* model) const { if (!m_op.memo) return false; auto pub = model->getAccount(sender())->memoKey(); if (!wallet->hasPrivateKey(pub)) return false; return graphene::utilities::wif_to_key(wallet->getPrivateKey(pub).toStdString()).valid(); } bool TransferOperation::canDecryptMemo(Wallet* wallet, ChainDataModel* model) const { if (!m_op.memo) return false; auto pub = model->getAccount(receiver())->memoKey(); if (!wallet->hasPrivateKey(pub)) return false; return graphene::utilities::wif_to_key(wallet->getPrivateKey(pub).toStdString()).valid(); } QString TransferOperation::decryptedMemo(Wallet* wallet, ChainDataModel* model) const { fc::ecc::private_key privateKey; fc::ecc::public_key publicKey; if (canEncryptMemo(wallet, model)) { privateKey = *graphene::utilities::wif_to_key(wallet->getPrivateKey(model->getAccount(sender())->memoKey()).toStdString()); publicKey = m_op.memo->to; } else if (canDecryptMemo(wallet, model)) { privateKey = *graphene::utilities::wif_to_key(wallet->getPrivateKey(model->getAccount(receiver())->memoKey()).toStdString()); publicKey = m_op.memo->from; } else return QString::null; return QString::fromStdString(m_op.memo->get_message(privateKey, publicKey)); } void TransferOperation::setMemo(QString memo) { if (memo == this->memo()) return; if (!m_op.memo) m_op.memo = graphene::chain::memo_data(); while (memo.size() % 32) memo.append('\0'); m_op.memo->set_message({}, {}, memo.toStdString()); Q_EMIT memoChanged(); } void TransferOperation::encryptMemo(Wallet* wallet, ChainDataModel* model) { if (!canEncryptMemo(wallet, model)) return; auto privateKey = graphene::utilities::wif_to_key(wallet->getPrivateKey(model->getAccount(sender())->memoKey()).toStdString()); if (!privateKey) return; m_op.memo->set_message(*privateKey, public_key_type(model->getAccount(receiver())->memoKey().toStdString()), memo().toStdString()); Q_EMIT memoChanged(); } <commit_msg>[GUI] Fix build on Linux<commit_after>#include "Operations.hpp" #include "Wallet.hpp" #include <graphene/utilities/key_conversion.hpp> #include <fc/smart_ref_impl.hpp> TransferOperation* OperationBuilder::transfer(ObjectId sender, ObjectId receiver, qint64 amount, ObjectId amountType, QString memo, ObjectId feeType) { try { TransferOperation* op = new TransferOperation; op->setSender(sender); op->setReceiver(receiver); op->setAmount(amount); op->setAmountType(amountType); op->setMemo(memo); op->setFeeType(feeType); auto feeParameters = model.global_properties().parameters.current_fees->get<graphene::chain::transfer_operation>(); op->setFee(op->operation().calculate_fee(feeParameters).value); return op; } catch (const fc::exception& e) { qDebug() << e.to_detail_string().c_str(); return nullptr; } } QString TransferOperation::memo() const { if (!m_op.memo) return QString::null; if (memoIsEncrypted()) return tr("Encrypted Memo"); QString memo = QString::fromStdString(m_op.memo->get_message({}, {})); while (memo.endsWith(QChar('\0'))) memo.chop(1); return memo; } bool TransferOperation::memoIsEncrypted() const { if (!m_op.memo) return false; if (m_op.memo->message.empty()) return false; if (m_op.memo->from == public_key_type() && m_op.memo->to == public_key_type()) return false; return true; } bool TransferOperation::canEncryptMemo(Wallet* wallet, ChainDataModel* model) const { if (!m_op.memo) return false; auto pub = model->getAccount(sender())->memoKey(); if (!wallet->hasPrivateKey(pub)) return false; return graphene::utilities::wif_to_key(wallet->getPrivateKey(pub).toStdString()).valid(); } bool TransferOperation::canDecryptMemo(Wallet* wallet, ChainDataModel* model) const { if (!m_op.memo) return false; auto pub = model->getAccount(receiver())->memoKey(); if (!wallet->hasPrivateKey(pub)) return false; return graphene::utilities::wif_to_key(wallet->getPrivateKey(pub).toStdString()).valid(); } QString TransferOperation::decryptedMemo(Wallet* wallet, ChainDataModel* model) const { fc::ecc::private_key privateKey; fc::ecc::public_key publicKey; if (canEncryptMemo(wallet, model)) { privateKey = *graphene::utilities::wif_to_key(wallet->getPrivateKey(model->getAccount(sender())->memoKey()).toStdString()); publicKey = m_op.memo->to; } else if (canDecryptMemo(wallet, model)) { privateKey = *graphene::utilities::wif_to_key(wallet->getPrivateKey(model->getAccount(receiver())->memoKey()).toStdString()); publicKey = m_op.memo->from; } else return QString::null; return QString::fromStdString(m_op.memo->get_message(privateKey, publicKey)); } void TransferOperation::setMemo(QString memo) { if (memo == this->memo()) return; if (!m_op.memo) m_op.memo = graphene::chain::memo_data(); while (memo.size() % 32) memo.append('\0'); m_op.memo->set_message({}, {}, memo.toStdString()); Q_EMIT memoChanged(); } void TransferOperation::encryptMemo(Wallet* wallet, ChainDataModel* model) { if (!canEncryptMemo(wallet, model)) return; auto privateKey = graphene::utilities::wif_to_key(wallet->getPrivateKey(model->getAccount(sender())->memoKey()).toStdString()); if (!privateKey) return; m_op.memo->set_message(*privateKey, public_key_type(model->getAccount(receiver())->memoKey().toStdString()), memo().toStdString()); Q_EMIT memoChanged(); } <|endoftext|>
<commit_before>/********************************************************************************** Infomap software package for multi-level network clustering Copyright (c) 2013 Daniel Edler, Martin Rosvall For more information, see <http://www.mapequation.org> This file is part of Infomap software package. Infomap software package 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. Infomap software package 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 Infomap software package. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include <iostream> #include <sstream> #include <fstream> #include <stdexcept> #include "utils/Logger.h" #include "io/Config.h" #include "infomap/InfomapContext.h" #include "utils/Stopwatch.h" #include "io/ProgramInterface.h" #include "io/convert.h" #include "utils/FileURI.h" #include "utils/Date.h" #include <iomanip> #include "io/version.h" void runInfomap(Config const& config) { InfomapContext context(config); context.getInfomap()->run(); } Config getConfig(int argc, char *argv[]) { Config conf; ProgramInterface api("Infomap", "Implementation of the Infomap clustering algorithm based on the Map Equation (see www.mapequation.org)", INFOMAP_VERSION); // --------------------- Input options --------------------- api.addNonOptionArgument(conf.networkFile, "network_file", "The file containing the network data. Accepted formats: Pajek (implied by .net) and link list (.txt)"); api.addOptionArgument(conf.inputFormat, 'i', "input-format", "Specify input format ('pajek' or 'link-list') to override format possibly implied by file extension.", "s"); api.addOptionArgument(conf.parseWithoutIOStreams, "without-iostream", "Parse the input network data without the iostream library. Can be a bit faster, but not as robust."); api.addOptionArgument(conf.zeroBasedNodeNumbers, 'z', "zero-based-numbering", "Assume node numbers start from zero in the input file instead of one."); api.addOptionArgument(conf.includeSelfLinks, 'k', "include-self-links", "Include links with the same source and target node. (Ignored by default.)"); api.addOptionArgument(conf.nodeLimit, 'O', "node-limit", "Limit the number of nodes to read from the network. Ignore links connected to ignored nodes.", "n"); api.addOptionArgument(conf.clusterDataFile, 'c', "cluster-data", "Provide an initial two-level solution (.clu format).", "p"); // --------------------- Output options --------------------- api.addOptionArgument(conf.printTree, "tree", "Print the hierarchy in .tree format. (default true if no other output with cluster data)"); api.addOptionArgument(conf.printMap, "map", "Print the top two-level modular network in the .map format."); api.addOptionArgument(conf.printClu, "clu", "Print the top cluster indices for each node."); api.addOptionArgument(conf.printNodeRanks, "node-ranks", "Print the calculated flow for each node to a file."); api.addOptionArgument(conf.printPajekNetwork, "pajek", "Print the parsed network in Pajek format."); api.addOptionArgument(conf.printBinaryTree, "btree", "Print the tree in a streamable binary format."); api.addOptionArgument(conf.printBinaryFlowTree, "bftree", "Print the tree including horizontal flow links in a streamable binary format."); api.addOptionArgument(conf.printFlowNetwork, "flow-network", "Print the network with calculated flow values."); api.addOptionArgument(conf.noFileOutput, '0', "no-file-output", "Don't print any output to file."); // --------------------- Core algorithm options --------------------- api.addOptionArgument(conf.twoLevel, '2', "two-level", "Optimize a two-level partition of the network."); bool dummyUndirected; api.addOptionArgument(dummyUndirected, 'u', "undirected", "Assume undirected links. (default)"); api.addOptionArgument(conf.directed, 'd', "directed", "Assume directed links."); api.addOptionArgument(conf.undirdir, 't', "undirdir", "Two-mode dynamics: Assume undirected links for calculating flow, but directed when minimizing codelength."); api.addOptionArgument(conf.outdirdir, "outdirdir", "Two-mode dynamics: Count only ingoing links when calculating the flow, but all when minimizing codelength."); api.addOptionArgument(conf.rawdir, 'w', "rawdir", "Two-mode dynamics: Assume directed links and let the raw link weights be the flow."); api.addOptionArgument(conf.recordedTeleportation, 'e', "recorded-teleportation", "If teleportation is used to calculate the flow, also record it when minimizing codelength."); api.addOptionArgument(conf.teleportToNodes, 'o', "to-nodes", "Teleport to nodes (like the PageRank algorithm) instead of to links."); api.addOptionArgument(conf.teleportationProbability, 'p', "teleportation-probability", "The probability of teleporting to a random node or link.", "f"); api.addOptionArgument(conf.selfTeleportationProbability, 'y', "self-link-teleportation-probability", "The probability of teleporting to itself. Effectively increasing the code rate, generating more and smaller modules.", "f"); api.addOptionArgument(conf.seedToRandomNumberGenerator, 's', "seed", "A seed (integer) to the random number generator.", "n"); // --------------------- Performance and accuracy options --------------------- api.addOptionArgument(conf.numTrials, 'N', "num-trials", "The number of outer-most loops to run before picking the best solution.", "n"); api.addOptionArgument(conf.minimumCodelengthImprovement, 'm', "min-improvement", "Minimum codelength threshold for accepting a new solution.", "f"); api.addOptionArgument(conf.randomizeCoreLoopLimit, 'a', "random-loop-limit", "Randomize the core loop limit from 1 to 'core-loop-limit'"); api.addOptionArgument(conf.coreLoopLimit, 'M', "core-loop-limit", "Limit the number of loops that tries to move each node into the best possible module", "n"); api.addOptionArgument(conf.levelAggregationLimit, 'L', "core-level-limit", "Limit the number of times the core loops are reapplied on existing modular network to search bigger structures.", "n"); api.addOptionArgument(conf.tuneIterationLimit, 'T', "tune-iteration-limit", "Limit the number of main iterations in the two-level partition algorithm. 0 means no limit.", "n"); api.addOptionArgument(conf.minimumRelativeTuneIterationImprovement, 'U', "tune-iteration-threshold", "Set a codelength improvement threshold of each new tune iteration to 'f' times the initial two-level codelength.", "f"); api.addOptionArgument(conf.fastCoarseTunePartition, 'C', "fast-coarse-tune", "Try to find the quickest partition of each module when creating sub-modules for the coarse-tune part."); api.addOptionArgument(conf.alternateCoarseTuneLevel, 'A', "alternate-coarse-tune-level", "Try to find different levels of sub-modules to move in the coarse-tune part."); api.addOptionArgument(conf.coarseTuneLevel, 'S', "coarse-tune-level", "Set the recursion limit when searching for sub-modules. A level of 1 will find sub-sub-modules.", "n"); api.addIncrementalOptionArgument(conf.fastHierarchicalSolution, 'F', "fast-hierarchical-solution", "Find top modules fast. Use -FF to keep all fast levels. Use -FFF to skip recursive part."); // --------------------- Output options --------------------- api.addNonOptionArgument(conf.outDirectory, "out_directory", "The directory to write the results to"); api.addIncrementalOptionArgument(conf.verbosity, 'v', "verbose", "Verbose output on the console. Add additional 'v' flags to increase verbosity up to -vvv."); api.parseArgs(argc, argv); // Some checks if (*--conf.outDirectory.end() != '/') conf.outDirectory.append("/"); if (!conf.haveModularResultOutput()) conf.printTree = true; return conf; } void initBenchmark(const Config& conf, int argc, char * const argv[]) { std::string networkName = FileURI(conf.networkFile).getName(); std::string logFilename = io::Str() << conf.outDirectory << networkName << ".tsv"; Logger::setBenchmarkFilename(logFilename); std::ostringstream logInfo; logInfo << "#benchmark for"; for (int i = 0; i < argc; ++i) logInfo << " " << argv[i]; Logger::benchmark(logInfo.str(), 0, 0, 0, 0, true); Logger::benchmark("elapsedSeconds\ttag\tcodelength\tnumTopModules\tnumNonTrivialTopModules\ttreeDepth", 0, 0, 0, 0, true); // (todo: fix problem with initializing same static file from different functions to simplify above) std::cout << "(Writing benchmark log to '" << logFilename << "'...)\n"; } int run(int argc, char* argv[]) { Date startDate; Config conf; try { conf = getConfig(argc, argv); if (conf.benchmark) initBenchmark(conf, argc, argv); if (conf.verbosity == 0) conf.verboseNumberPrecision = 4; std::cout << std::setprecision(conf.verboseNumberPrecision); } catch (std::exception& e) { std::cerr << e.what() << std::endl; return 1; } std::cout << "===========================================\n"; std::cout << " Infomap v" << INFOMAP_VERSION << " starts at " << Date() << "\n"; std::cout << "===========================================\n"; runInfomap(conf); ASSERT(NodeBase::nodeCount() == 0); //TODO: Not working with OpenMP // if (NodeBase::nodeCount() != 0) // std::cout << "Warning: " << NodeBase::nodeCount() << " nodes not deleted!\n"; std::cout << "===========================================\n"; std::cout << " Infomap ends at " << Date() << "\n"; std::cout << " (Elapsed time: " << (Date() - startDate) << ")\n"; std::cout << "===========================================\n"; // ElapsedTime t1 = (Date() - startDate); // std::cout << "Elapsed time: " << t1 << " (" << // Stopwatch::getElapsedTimeSinceProgramStartInSec() << "s serial)." << std::endl; return 0; } int main(int argc, char* argv[]) { return run(argc, argv); } <commit_msg>Added option --no-infomap to keep initial external cluster data.<commit_after>/********************************************************************************** Infomap software package for multi-level network clustering Copyright (c) 2013 Daniel Edler, Martin Rosvall For more information, see <http://www.mapequation.org> This file is part of Infomap software package. Infomap software package 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. Infomap software package 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 Infomap software package. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include <iostream> #include <sstream> #include <fstream> #include <stdexcept> #include "utils/Logger.h" #include "io/Config.h" #include "infomap/InfomapContext.h" #include "utils/Stopwatch.h" #include "io/ProgramInterface.h" #include "io/convert.h" #include "utils/FileURI.h" #include "utils/Date.h" #include <iomanip> #include "io/version.h" void runInfomap(Config const& config) { InfomapContext context(config); context.getInfomap()->run(); } Config getConfig(int argc, char *argv[]) { Config conf; ProgramInterface api("Infomap", "Implementation of the Infomap clustering algorithm based on the Map Equation (see www.mapequation.org)", INFOMAP_VERSION); // --------------------- Input options --------------------- api.addNonOptionArgument(conf.networkFile, "network_file", "The file containing the network data. Accepted formats: Pajek (implied by .net) and link list (.txt)"); api.addOptionArgument(conf.inputFormat, 'i', "input-format", "Specify input format ('pajek' or 'link-list') to override format possibly implied by file extension.", "s"); api.addOptionArgument(conf.parseWithoutIOStreams, "without-iostream", "Parse the input network data without the iostream library. Can be a bit faster, but not as robust."); api.addOptionArgument(conf.zeroBasedNodeNumbers, 'z', "zero-based-numbering", "Assume node numbers start from zero in the input file instead of one."); api.addOptionArgument(conf.includeSelfLinks, 'k', "include-self-links", "Include links with the same source and target node. (Ignored by default.)"); api.addOptionArgument(conf.nodeLimit, 'O', "node-limit", "Limit the number of nodes to read from the network. Ignore links connected to ignored nodes.", "n"); api.addOptionArgument(conf.clusterDataFile, 'c', "cluster-data", "Provide an initial two-level solution (.clu format).", "p"); api.addOptionArgument(conf.noInfomap, "no-infomap", "Don't run Infomap. Useful if initial cluster data should be preserved or non-modular data printed."); // --------------------- Output options --------------------- api.addOptionArgument(conf.printTree, "tree", "Print the hierarchy in .tree format. (default true if no other output with cluster data)"); api.addOptionArgument(conf.printMap, "map", "Print the top two-level modular network in the .map format."); api.addOptionArgument(conf.printClu, "clu", "Print the top cluster indices for each node."); api.addOptionArgument(conf.printNodeRanks, "node-ranks", "Print the calculated flow for each node to a file."); api.addOptionArgument(conf.printPajekNetwork, "pajek", "Print the parsed network in Pajek format."); api.addOptionArgument(conf.printBinaryTree, "btree", "Print the tree in a streamable binary format."); api.addOptionArgument(conf.printBinaryFlowTree, "bftree", "Print the tree including horizontal flow links in a streamable binary format."); api.addOptionArgument(conf.printFlowNetwork, "flow-network", "Print the network with calculated flow values."); api.addOptionArgument(conf.noFileOutput, '0', "no-file-output", "Don't print any output to file."); // --------------------- Core algorithm options --------------------- api.addOptionArgument(conf.twoLevel, '2', "two-level", "Optimize a two-level partition of the network."); bool dummyUndirected; api.addOptionArgument(dummyUndirected, 'u', "undirected", "Assume undirected links. (default)"); api.addOptionArgument(conf.directed, 'd', "directed", "Assume directed links."); api.addOptionArgument(conf.undirdir, 't', "undirdir", "Two-mode dynamics: Assume undirected links for calculating flow, but directed when minimizing codelength."); api.addOptionArgument(conf.outdirdir, "outdirdir", "Two-mode dynamics: Count only ingoing links when calculating the flow, but all when minimizing codelength."); api.addOptionArgument(conf.rawdir, 'w', "rawdir", "Two-mode dynamics: Assume directed links and let the raw link weights be the flow."); api.addOptionArgument(conf.recordedTeleportation, 'e', "recorded-teleportation", "If teleportation is used to calculate the flow, also record it when minimizing codelength."); api.addOptionArgument(conf.teleportToNodes, 'o', "to-nodes", "Teleport to nodes (like the PageRank algorithm) instead of to links."); api.addOptionArgument(conf.teleportationProbability, 'p', "teleportation-probability", "The probability of teleporting to a random node or link.", "f"); api.addOptionArgument(conf.selfTeleportationProbability, 'y', "self-link-teleportation-probability", "The probability of teleporting to itself. Effectively increasing the code rate, generating more and smaller modules.", "f"); api.addOptionArgument(conf.seedToRandomNumberGenerator, 's', "seed", "A seed (integer) to the random number generator.", "n"); // --------------------- Performance and accuracy options --------------------- api.addOptionArgument(conf.numTrials, 'N', "num-trials", "The number of outer-most loops to run before picking the best solution.", "n"); api.addOptionArgument(conf.minimumCodelengthImprovement, 'm', "min-improvement", "Minimum codelength threshold for accepting a new solution.", "f"); api.addOptionArgument(conf.randomizeCoreLoopLimit, 'a', "random-loop-limit", "Randomize the core loop limit from 1 to 'core-loop-limit'"); api.addOptionArgument(conf.coreLoopLimit, 'M', "core-loop-limit", "Limit the number of loops that tries to move each node into the best possible module", "n"); api.addOptionArgument(conf.levelAggregationLimit, 'L', "core-level-limit", "Limit the number of times the core loops are reapplied on existing modular network to search bigger structures.", "n"); api.addOptionArgument(conf.tuneIterationLimit, 'T', "tune-iteration-limit", "Limit the number of main iterations in the two-level partition algorithm. 0 means no limit.", "n"); api.addOptionArgument(conf.minimumRelativeTuneIterationImprovement, 'U', "tune-iteration-threshold", "Set a codelength improvement threshold of each new tune iteration to 'f' times the initial two-level codelength.", "f"); api.addOptionArgument(conf.fastCoarseTunePartition, 'C', "fast-coarse-tune", "Try to find the quickest partition of each module when creating sub-modules for the coarse-tune part."); api.addOptionArgument(conf.alternateCoarseTuneLevel, 'A', "alternate-coarse-tune-level", "Try to find different levels of sub-modules to move in the coarse-tune part."); api.addOptionArgument(conf.coarseTuneLevel, 'S', "coarse-tune-level", "Set the recursion limit when searching for sub-modules. A level of 1 will find sub-sub-modules.", "n"); api.addIncrementalOptionArgument(conf.fastHierarchicalSolution, 'F', "fast-hierarchical-solution", "Find top modules fast. Use -FF to keep all fast levels. Use -FFF to skip recursive part."); // --------------------- Output options --------------------- api.addNonOptionArgument(conf.outDirectory, "out_directory", "The directory to write the results to"); api.addIncrementalOptionArgument(conf.verbosity, 'v', "verbose", "Verbose output on the console. Add additional 'v' flags to increase verbosity up to -vvv."); api.parseArgs(argc, argv); // Some checks if (*--conf.outDirectory.end() != '/') conf.outDirectory.append("/"); if (!conf.haveModularResultOutput()) conf.printTree = true; return conf; } void initBenchmark(const Config& conf, int argc, char * const argv[]) { std::string networkName = FileURI(conf.networkFile).getName(); std::string logFilename = io::Str() << conf.outDirectory << networkName << ".tsv"; Logger::setBenchmarkFilename(logFilename); std::ostringstream logInfo; logInfo << "#benchmark for"; for (int i = 0; i < argc; ++i) logInfo << " " << argv[i]; Logger::benchmark(logInfo.str(), 0, 0, 0, 0, true); Logger::benchmark("elapsedSeconds\ttag\tcodelength\tnumTopModules\tnumNonTrivialTopModules\ttreeDepth", 0, 0, 0, 0, true); // (todo: fix problem with initializing same static file from different functions to simplify above) std::cout << "(Writing benchmark log to '" << logFilename << "'...)\n"; } int run(int argc, char* argv[]) { Date startDate; Config conf; try { conf = getConfig(argc, argv); if (conf.benchmark) initBenchmark(conf, argc, argv); if (conf.verbosity == 0) conf.verboseNumberPrecision = 4; std::cout << std::setprecision(conf.verboseNumberPrecision); } catch (std::exception& e) { std::cerr << e.what() << std::endl; return 1; } std::cout << "===========================================\n"; std::cout << " Infomap v" << INFOMAP_VERSION << " starts at " << Date() << "\n"; std::cout << "===========================================\n"; runInfomap(conf); ASSERT(NodeBase::nodeCount() == 0); //TODO: Not working with OpenMP // if (NodeBase::nodeCount() != 0) // std::cout << "Warning: " << NodeBase::nodeCount() << " nodes not deleted!\n"; std::cout << "===========================================\n"; std::cout << " Infomap ends at " << Date() << "\n"; std::cout << " (Elapsed time: " << (Date() - startDate) << ")\n"; std::cout << "===========================================\n"; // ElapsedTime t1 = (Date() - startDate); // std::cout << "Elapsed time: " << t1 << " (" << // Stopwatch::getElapsedTimeSinceProgramStartInSec() << "s serial)." << std::endl; return 0; } int main(int argc, char* argv[]) { return run(argc, argv); } <|endoftext|>
<commit_before>#include "LRUCache.h" #include <sys/time.h> #include <math.h> #ifndef __APPLE__ #include <unordered_map> #endif using namespace v8; unsigned long getCurrentTime() { timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec; } std::string getStringValue(Handle<Value> value) { String::Utf8Value keyUtf8Value(value); return std::string(*keyUtf8Value); } void LRUCache::init(Handle<Object> exports) { Local<String> className = String::NewSymbol("LRUCache"); Local<FunctionTemplate> constructor = FunctionTemplate::New(New); constructor->SetClassName(className); Handle<ObjectTemplate> instance = constructor->InstanceTemplate(); instance->SetInternalFieldCount(6); Handle<ObjectTemplate> prototype = constructor->PrototypeTemplate(); prototype->Set("get", FunctionTemplate::New(Get)->GetFunction()); prototype->Set("set", FunctionTemplate::New(Set)->GetFunction()); prototype->Set("remove", FunctionTemplate::New(Remove)->GetFunction()); prototype->Set("clear", FunctionTemplate::New(Clear)->GetFunction()); prototype->Set("size", FunctionTemplate::New(Size)->GetFunction()); prototype->Set("stats", FunctionTemplate::New(Stats)->GetFunction()); exports->Set(className, Persistent<Function>::New(constructor->GetFunction())); } Handle<Value> LRUCache::New(const Arguments& args) { LRUCache* cache = new LRUCache(); if (args.Length() > 0 && args[0]->IsObject()) { Local<Object> config = args[0]->ToObject(); Local<Value> maxElements = config->Get(String::NewSymbol("maxElements")); if (maxElements->IsUint32()) cache->maxElements = maxElements->Uint32Value(); Local<Value> maxAge = config->Get(String::NewSymbol("maxAge")); if (maxAge->IsUint32()) cache->maxAge = maxAge->Uint32Value(); Local<Value> maxLoadFactor = config->Get(String::NewSymbol("maxLoadFactor")); if (maxLoadFactor->IsNumber()) cache->data.max_load_factor(maxLoadFactor->NumberValue()); Local<Value> size = config->Get(String::NewSymbol("size")); if (size->IsUint32()) cache->data.rehash(ceil(size->Uint32Value() / cache->data.max_load_factor())); } cache->Wrap(args.This()); return args.This(); } LRUCache::LRUCache() { this->maxElements = 0; this->maxAge = 0; } LRUCache::~LRUCache() { this->disposeAll(); } void LRUCache::disposeAll() { for (HashMap::iterator itr = this->data.begin(); itr != this->data.end(); itr++) { HashEntry* entry = itr->second; entry->value.Dispose(); delete entry; } } void LRUCache::evict() { const HashMap::iterator itr = this->data.find(this->lru.front()); if (itr == this->data.end()) return; HashEntry* entry = itr->second; // Dispose the V8 handle contained in the entry. entry->value.Dispose(); // Remove the entry from the hash and from the LRU list. this->data.erase(itr); this->lru.pop_front(); // Free the entry itself. delete entry; } void LRUCache::remove(const HashMap::const_iterator itr) { HashEntry* entry = itr->second; // Dispose the V8 handle contained in the entry. entry->value.Dispose(); // Remove the entry from the hash and from the LRU list. this->data.erase(itr); this->lru.erase(entry->pointer); // Free the entry itself. delete entry; } Handle<Value> LRUCache::Get(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); if (args.Length() != 1) return ThrowException(Exception::RangeError(String::New("Incorrect number of arguments for get(), expected 1"))); std::string key = getStringValue(args[0]); const HashMap::const_iterator itr = cache->data.find(key); // If the specified entry doesn't exist, return undefined. if (itr == cache->data.end()) return scope.Close(Handle<Value>()); HashEntry* entry = itr->second; if (cache->maxAge > 0 && getCurrentTime() - entry->timestamp > cache->maxAge) { // The entry has passed the maximum age, so we need to remove it. cache->remove(itr); // Return undefined. return scope.Close(Handle<Value>()); } else { // Move the value to the end of the LRU list. cache->lru.splice(cache->lru.end(), cache->lru, entry->pointer); // Return the value. return scope.Close(entry->value); } } Handle<Value> LRUCache::Set(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); unsigned long now = cache->maxAge == 0 ? 0 : getCurrentTime(); if (args.Length() != 2) return ThrowException(Exception::RangeError(String::New("Incorrect number of arguments for set(), expected 2"))); std::string key = getStringValue(args[0]); Local<Value> value = args[1]; const HashMap::iterator itr = cache->data.find(key); if (itr == cache->data.end()) { // We're adding a new item. First ensure we have space. if (cache->maxElements > 0 && cache->data.size() == cache->maxElements) cache->evict(); // Add the value to the end of the LRU list. KeyList::iterator pointer = cache->lru.insert(cache->lru.end(), key); // Add the entry to the key-value map. HashEntry* entry = new HashEntry(Persistent<Value>::New(value), pointer, now); cache->data.insert(std::make_pair(key, entry)); } else { HashEntry* entry = itr->second; // We're replacing an existing value, so dispose the old V8 handle to ensure it gets GC'd. entry->value.Dispose(); // Replace the value in the key-value map with the new one, and update the timestamp. entry->value = Persistent<Value>::New(value); entry->timestamp = now; // Move the value to the end of the LRU list. cache->lru.splice(cache->lru.end(), cache->lru, entry->pointer); } // Return undefined. return scope.Close(Handle<Value>()); } Handle<Value> LRUCache::Remove(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); if (args.Length() != 1) return ThrowException(Exception::RangeError(String::New("Incorrect number of arguments for remove(), expected 1"))); std::string key = getStringValue(args[0]); const HashMap::iterator itr = cache->data.find(key); if (itr != cache->data.end()) cache->remove(itr); return scope.Close(Handle<Value>()); } Handle<Value> LRUCache::Clear(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); cache->disposeAll(); cache->data.clear(); cache->lru.clear(); return scope.Close(Handle<Value>()); } Handle<Value> LRUCache::Size(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); return scope.Close(Integer::New(cache->data.size())); } Handle<Value> LRUCache::Stats(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); Local<Object> stats = Object::New(); stats->Set(String::NewSymbol("size"), Integer::New(cache->data.size())); stats->Set(String::NewSymbol("buckets"), Integer::New(cache->data.bucket_count())); stats->Set(String::NewSymbol("loadFactor"), Number::New(cache->data.load_factor())); stats->Set(String::NewSymbol("maxLoadFactor"), Number::New(cache->data.max_load_factor())); return scope.Close(stats); } <commit_msg>Hey guys, microseconds aren't milliseconds<commit_after>#include "LRUCache.h" #include <sys/time.h> #include <math.h> #ifndef __APPLE__ #include <unordered_map> #endif using namespace v8; unsigned long getCurrentTime() { timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; } std::string getStringValue(Handle<Value> value) { String::Utf8Value keyUtf8Value(value); return std::string(*keyUtf8Value); } void LRUCache::init(Handle<Object> exports) { Local<String> className = String::NewSymbol("LRUCache"); Local<FunctionTemplate> constructor = FunctionTemplate::New(New); constructor->SetClassName(className); Handle<ObjectTemplate> instance = constructor->InstanceTemplate(); instance->SetInternalFieldCount(6); Handle<ObjectTemplate> prototype = constructor->PrototypeTemplate(); prototype->Set("get", FunctionTemplate::New(Get)->GetFunction()); prototype->Set("set", FunctionTemplate::New(Set)->GetFunction()); prototype->Set("remove", FunctionTemplate::New(Remove)->GetFunction()); prototype->Set("clear", FunctionTemplate::New(Clear)->GetFunction()); prototype->Set("size", FunctionTemplate::New(Size)->GetFunction()); prototype->Set("stats", FunctionTemplate::New(Stats)->GetFunction()); exports->Set(className, Persistent<Function>::New(constructor->GetFunction())); } Handle<Value> LRUCache::New(const Arguments& args) { LRUCache* cache = new LRUCache(); if (args.Length() > 0 && args[0]->IsObject()) { Local<Object> config = args[0]->ToObject(); Local<Value> maxElements = config->Get(String::NewSymbol("maxElements")); if (maxElements->IsUint32()) cache->maxElements = maxElements->Uint32Value(); Local<Value> maxAge = config->Get(String::NewSymbol("maxAge")); if (maxAge->IsUint32()) cache->maxAge = maxAge->Uint32Value(); Local<Value> maxLoadFactor = config->Get(String::NewSymbol("maxLoadFactor")); if (maxLoadFactor->IsNumber()) cache->data.max_load_factor(maxLoadFactor->NumberValue()); Local<Value> size = config->Get(String::NewSymbol("size")); if (size->IsUint32()) cache->data.rehash(ceil(size->Uint32Value() / cache->data.max_load_factor())); } cache->Wrap(args.This()); return args.This(); } LRUCache::LRUCache() { this->maxElements = 0; this->maxAge = 0; } LRUCache::~LRUCache() { this->disposeAll(); } void LRUCache::disposeAll() { for (HashMap::iterator itr = this->data.begin(); itr != this->data.end(); itr++) { HashEntry* entry = itr->second; entry->value.Dispose(); delete entry; } } void LRUCache::evict() { const HashMap::iterator itr = this->data.find(this->lru.front()); if (itr == this->data.end()) return; HashEntry* entry = itr->second; // Dispose the V8 handle contained in the entry. entry->value.Dispose(); // Remove the entry from the hash and from the LRU list. this->data.erase(itr); this->lru.pop_front(); // Free the entry itself. delete entry; } void LRUCache::remove(const HashMap::const_iterator itr) { HashEntry* entry = itr->second; // Dispose the V8 handle contained in the entry. entry->value.Dispose(); // Remove the entry from the hash and from the LRU list. this->data.erase(itr); this->lru.erase(entry->pointer); // Free the entry itself. delete entry; } Handle<Value> LRUCache::Get(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); if (args.Length() != 1) return ThrowException(Exception::RangeError(String::New("Incorrect number of arguments for get(), expected 1"))); std::string key = getStringValue(args[0]); const HashMap::const_iterator itr = cache->data.find(key); // If the specified entry doesn't exist, return undefined. if (itr == cache->data.end()) return scope.Close(Handle<Value>()); HashEntry* entry = itr->second; if (cache->maxAge > 0 && getCurrentTime() - entry->timestamp > cache->maxAge) { // The entry has passed the maximum age, so we need to remove it. cache->remove(itr); // Return undefined. return scope.Close(Handle<Value>()); } else { // Move the value to the end of the LRU list. cache->lru.splice(cache->lru.end(), cache->lru, entry->pointer); // Return the value. return scope.Close(entry->value); } } Handle<Value> LRUCache::Set(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); unsigned long now = cache->maxAge == 0 ? 0 : getCurrentTime(); if (args.Length() != 2) return ThrowException(Exception::RangeError(String::New("Incorrect number of arguments for set(), expected 2"))); std::string key = getStringValue(args[0]); Local<Value> value = args[1]; const HashMap::iterator itr = cache->data.find(key); if (itr == cache->data.end()) { // We're adding a new item. First ensure we have space. if (cache->maxElements > 0 && cache->data.size() == cache->maxElements) cache->evict(); // Add the value to the end of the LRU list. KeyList::iterator pointer = cache->lru.insert(cache->lru.end(), key); // Add the entry to the key-value map. HashEntry* entry = new HashEntry(Persistent<Value>::New(value), pointer, now); cache->data.insert(std::make_pair(key, entry)); } else { HashEntry* entry = itr->second; // We're replacing an existing value, so dispose the old V8 handle to ensure it gets GC'd. entry->value.Dispose(); // Replace the value in the key-value map with the new one, and update the timestamp. entry->value = Persistent<Value>::New(value); entry->timestamp = now; // Move the value to the end of the LRU list. cache->lru.splice(cache->lru.end(), cache->lru, entry->pointer); } // Return undefined. return scope.Close(Handle<Value>()); } Handle<Value> LRUCache::Remove(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); if (args.Length() != 1) return ThrowException(Exception::RangeError(String::New("Incorrect number of arguments for remove(), expected 1"))); std::string key = getStringValue(args[0]); const HashMap::iterator itr = cache->data.find(key); if (itr != cache->data.end()) cache->remove(itr); return scope.Close(Handle<Value>()); } Handle<Value> LRUCache::Clear(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); cache->disposeAll(); cache->data.clear(); cache->lru.clear(); return scope.Close(Handle<Value>()); } Handle<Value> LRUCache::Size(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); return scope.Close(Integer::New(cache->data.size())); } Handle<Value> LRUCache::Stats(const Arguments& args) { HandleScope scope; LRUCache* cache = ObjectWrap::Unwrap<LRUCache>(args.This()); Local<Object> stats = Object::New(); stats->Set(String::NewSymbol("size"), Integer::New(cache->data.size())); stats->Set(String::NewSymbol("buckets"), Integer::New(cache->data.bucket_count())); stats->Set(String::NewSymbol("loadFactor"), Number::New(cache->data.load_factor())); stats->Set(String::NewSymbol("maxLoadFactor"), Number::New(cache->data.max_load_factor())); return scope.Close(stats); } <|endoftext|>
<commit_before><commit_msg>ord: change write_lef multi-file to info<commit_after><|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 // // 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 "google/cloud/pubsub/internal/subscription_lease_management.h" #include <chrono> namespace google { namespace cloud { namespace pubsub_internal { inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS { std::chrono::seconds constexpr SubscriptionLeaseManagement::kMinimumAckDeadline; std::chrono::seconds constexpr SubscriptionLeaseManagement::kAckDeadlineSlack; void SubscriptionLeaseManagement::Start(BatchCallback cb) { auto weak = std::weak_ptr<SubscriptionLeaseManagement>(shared_from_this()); child_->Start( [weak, cb](StatusOr<google::pubsub::v1::StreamingPullResponse> r) { if (auto self = weak.lock()) self->OnRead(r); cb(std::move(r)); }); } void SubscriptionLeaseManagement::Shutdown() { std::unique_lock<std::mutex> lk(mu_); // Cancel any existing timers. if (refresh_timer_.valid()) refresh_timer_.cancel(); // Schedule a nack for each pending message, using the existing executor. NackAll(std::move(lk)); child_->Shutdown(); } void SubscriptionLeaseManagement::AckMessage(std::string const& ack_id) { std::unique_lock<std::mutex> lk(mu_); leases_.erase(ack_id); lk.unlock(); child_->AckMessage(ack_id); } void SubscriptionLeaseManagement::NackMessage(std::string const& ack_id) { std::unique_lock<std::mutex> lk(mu_); leases_.erase(ack_id); lk.unlock(); child_->NackMessage(ack_id); } void SubscriptionLeaseManagement::BulkNack(std::vector<std::string> ack_ids) { std::unique_lock<std::mutex> lk(mu_); for (auto const& id : ack_ids) leases_.erase(id); lk.unlock(); child_->BulkNack(std::move(ack_ids)); } // Users of this class should have no need to call ExtendLeases(); they create // it to automate lease management after all. We could create a hierarchy of // classes for "BatchSourceWithoutExtendLeases", but that seems like overkill. void SubscriptionLeaseManagement::ExtendLeases(std::vector<std::string>, std::chrono::seconds) {} void SubscriptionLeaseManagement::OnRead( StatusOr<google::pubsub::v1::StreamingPullResponse> const& response) { if (!response) { shutdown_manager_->MarkAsShutdown(__func__, response.status()); std::unique_lock<std::mutex> lk(mu_); // Cancel any existing timers. if (refresh_timer_.valid()) refresh_timer_.cancel(); return; } std::unique_lock<std::mutex> lk(mu_); auto const now = std::chrono::system_clock::now(); auto const estimated_server_deadline = now + std::chrono::seconds(10); auto const handling_deadline = now + max_deadline_time_; for (auto const& rm : response->received_messages()) { leases_.emplace(rm.ack_id(), LeaseStatus{estimated_server_deadline, handling_deadline}); } // Setup a timer to refresh the message leases. We do not want to immediately // refresh them because there is a good chance they will be handled before // the minimum lease time, and it seems wasteful to refresh the lease just to // quickly turnaround and ack or nack the message. StartRefreshTimer(std::move(lk), std::chrono::system_clock::now() + kMinimumAckDeadline); } void SubscriptionLeaseManagement::RefreshMessageLeases( std::unique_lock<std::mutex> lk) { using seconds = std::chrono::seconds; if (leases_.empty() || refreshing_leases_) return; std::vector<std::string> ack_ids; ack_ids.reserve(leases_.size()); auto extension = max_deadline_extension_; auto const now = std::chrono::system_clock::now(); for (auto const& kv : leases_) { // This message lease cannot be extended any further, and we do not want to // send an extension of 0 seconds because that is a nack. if (kv.second.handling_deadline < now + seconds(1)) continue; auto const message_extension = std::chrono::duration_cast<seconds>(kv.second.handling_deadline - now); extension = (std::min)(extension, message_extension); ack_ids.push_back(kv.first); } auto const new_deadline = now + extension; if (ack_ids.empty()) { StartRefreshTimer(std::move(lk), new_deadline); return; } lk.unlock(); child_->ExtendLeases(ack_ids, extension); lk.lock(); for (auto const& ack : ack_ids) { auto i = leases_.find(ack); if (i == leases_.end()) continue; i->second.estimated_server_deadline = new_deadline; } StartRefreshTimer(std::move(lk), new_deadline); } void SubscriptionLeaseManagement::StartRefreshTimer( std::unique_lock<std::mutex>, std::chrono::system_clock::time_point new_server_deadline) { std::weak_ptr<SubscriptionLeaseManagement> weak = shared_from_this(); auto deadline = new_server_deadline - kAckDeadlineSlack; shutdown_manager_->StartOperation(__func__, "OnRefreshTimer", [&] { if (refresh_timer_.valid()) refresh_timer_.cancel(); using TimerFuture = future<StatusOr<std::chrono::system_clock::time_point>>; cq_.MakeDeadlineTimer(deadline).then([weak](TimerFuture tp) { if (auto self = weak.lock()) self->OnRefreshTimer(!tp.get()); }); }); } void SubscriptionLeaseManagement::OnRefreshTimer(bool cancelled) { if (shutdown_manager_->FinishedOperation(__func__)) return; if (cancelled) return; RefreshMessageLeases(std::unique_lock<std::mutex>(mu_)); } void SubscriptionLeaseManagement::NackAll(std::unique_lock<std::mutex> lk) { if (leases_.empty()) return; std::vector<std::string> ack_ids; ack_ids.reserve(leases_.size()); for (auto const& kv : leases_) { ack_ids.push_back(kv.first); } lk.unlock(); BulkNack(std::move(ack_ids)); } } // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS } // namespace pubsub_internal } // namespace cloud } // namespace google <commit_msg>fix(pubsub): save refresh timer for cancellation (#6662)<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 // // 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 "google/cloud/pubsub/internal/subscription_lease_management.h" #include <chrono> namespace google { namespace cloud { namespace pubsub_internal { inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS { std::chrono::seconds constexpr SubscriptionLeaseManagement::kMinimumAckDeadline; std::chrono::seconds constexpr SubscriptionLeaseManagement::kAckDeadlineSlack; void SubscriptionLeaseManagement::Start(BatchCallback cb) { auto weak = std::weak_ptr<SubscriptionLeaseManagement>(shared_from_this()); child_->Start( [weak, cb](StatusOr<google::pubsub::v1::StreamingPullResponse> r) { if (auto self = weak.lock()) self->OnRead(r); cb(std::move(r)); }); } void SubscriptionLeaseManagement::Shutdown() { std::unique_lock<std::mutex> lk(mu_); // Cancel any existing timers. if (refresh_timer_.valid()) refresh_timer_.cancel(); // Schedule a nack for each pending message, using the existing executor. NackAll(std::move(lk)); child_->Shutdown(); } void SubscriptionLeaseManagement::AckMessage(std::string const& ack_id) { std::unique_lock<std::mutex> lk(mu_); leases_.erase(ack_id); lk.unlock(); child_->AckMessage(ack_id); } void SubscriptionLeaseManagement::NackMessage(std::string const& ack_id) { std::unique_lock<std::mutex> lk(mu_); leases_.erase(ack_id); lk.unlock(); child_->NackMessage(ack_id); } void SubscriptionLeaseManagement::BulkNack(std::vector<std::string> ack_ids) { std::unique_lock<std::mutex> lk(mu_); for (auto const& id : ack_ids) leases_.erase(id); lk.unlock(); child_->BulkNack(std::move(ack_ids)); } // Users of this class should have no need to call ExtendLeases(); they create // it to automate lease management after all. We could create a hierarchy of // classes for "BatchSourceWithoutExtendLeases", but that seems like overkill. void SubscriptionLeaseManagement::ExtendLeases(std::vector<std::string>, std::chrono::seconds) {} void SubscriptionLeaseManagement::OnRead( StatusOr<google::pubsub::v1::StreamingPullResponse> const& response) { if (!response) { shutdown_manager_->MarkAsShutdown(__func__, response.status()); std::unique_lock<std::mutex> lk(mu_); // Cancel any existing timers. if (refresh_timer_.valid()) refresh_timer_.cancel(); return; } std::unique_lock<std::mutex> lk(mu_); auto const now = std::chrono::system_clock::now(); auto const estimated_server_deadline = now + std::chrono::seconds(10); auto const handling_deadline = now + max_deadline_time_; for (auto const& rm : response->received_messages()) { leases_.emplace(rm.ack_id(), LeaseStatus{estimated_server_deadline, handling_deadline}); } // Setup a timer to refresh the message leases. We do not want to immediately // refresh them because there is a good chance they will be handled before // the minimum lease time, and it seems wasteful to refresh the lease just to // quickly turnaround and ack or nack the message. StartRefreshTimer(std::move(lk), std::chrono::system_clock::now() + kMinimumAckDeadline); } void SubscriptionLeaseManagement::RefreshMessageLeases( std::unique_lock<std::mutex> lk) { using seconds = std::chrono::seconds; if (leases_.empty() || refreshing_leases_) return; std::vector<std::string> ack_ids; ack_ids.reserve(leases_.size()); auto extension = max_deadline_extension_; auto const now = std::chrono::system_clock::now(); for (auto const& kv : leases_) { // This message lease cannot be extended any further, and we do not want to // send an extension of 0 seconds because that is a nack. if (kv.second.handling_deadline < now + seconds(1)) continue; auto const message_extension = std::chrono::duration_cast<seconds>(kv.second.handling_deadline - now); extension = (std::min)(extension, message_extension); ack_ids.push_back(kv.first); } auto const new_deadline = now + extension; if (ack_ids.empty()) { StartRefreshTimer(std::move(lk), new_deadline); return; } lk.unlock(); child_->ExtendLeases(ack_ids, extension); lk.lock(); for (auto const& ack : ack_ids) { auto i = leases_.find(ack); if (i == leases_.end()) continue; i->second.estimated_server_deadline = new_deadline; } StartRefreshTimer(std::move(lk), new_deadline); } void SubscriptionLeaseManagement::StartRefreshTimer( std::unique_lock<std::mutex>, std::chrono::system_clock::time_point new_server_deadline) { std::weak_ptr<SubscriptionLeaseManagement> weak = shared_from_this(); auto deadline = new_server_deadline - kAckDeadlineSlack; shutdown_manager_->StartOperation(__func__, "OnRefreshTimer", [&] { using TimerFuture = future<StatusOr<std::chrono::system_clock::time_point>>; if (refresh_timer_.valid()) refresh_timer_.cancel(); refresh_timer_ = cq_.MakeDeadlineTimer(deadline).then([weak](TimerFuture tp) { if (auto self = weak.lock()) self->OnRefreshTimer(!tp.get()); }); }); } void SubscriptionLeaseManagement::OnRefreshTimer(bool cancelled) { if (shutdown_manager_->FinishedOperation(__func__)) return; if (cancelled) return; RefreshMessageLeases(std::unique_lock<std::mutex>(mu_)); } void SubscriptionLeaseManagement::NackAll(std::unique_lock<std::mutex> lk) { if (leases_.empty()) return; std::vector<std::string> ack_ids; ack_ids.reserve(leases_.size()); for (auto const& kv : leases_) { ack_ids.push_back(kv.first); } lk.unlock(); BulkNack(std::move(ack_ids)); } } // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS } // namespace pubsub_internal } // namespace cloud } // namespace google <|endoftext|>
<commit_before>// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef CLOTHO_BATCH_CROSSOVER_MTWE_GENERATOR_HPP_ #define CLOTHO_BATCH_CROSSOVER_MTWE_GENERATOR_HPP_ #include "clotho/data_spaces/crossover/batch_crossover_tasks.hpp" #include "clotho/recombination/sequence_bias_parameter.hpp" #include "clotho/recombination/recombination_rate_parameter.hpp" #include "clotho/data_spaces/task/thread_pool.hpp" #include "clotho/data_spaces/generators/position_distribution_helper.hpp" #include "clotho/data_spaces/generators/crossover_event_distribution_helper.hpp" #include <boost/random/bernoulli_distribution.hpp> namespace clotho { namespace genetics { template < class RNG, class SequenceSpaceType, class AlleleSpaceType > class BatchCrossoverMTWE { public: typedef SequenceSpaceType sequence_space_type; typedef AlleleSpaceType allele_space_type; typedef typename position_distribution_helper< typename allele_space_type::position_type >::type position_distribution_type; typedef typename crossover_event_distribution_helper< double >::type event_distribution_type; BatchCrossoverMTWE( RNG * rng, boost::property_tree::ptree & config ) : m_rng( rng ) , m_seq_bias(config) , m_recomb_rate(config) { } template < class SelectionType, class PoolType > void operator()( const SelectionType & parents, sequence_space_type * parental, sequence_space_type * offspring, allele_space_type * alleles, PoolType & pool ) { batch_generate( parents, parental, offspring, alleles, pool ); } virtual ~BatchCrossoverMTWE() {} protected: template < class SelectionType, class PoolType > void batch_generate( const SelectionType & parents, sequence_space_type * parental, sequence_space_type * offspring, allele_space_type * alleles, PoolType & pool ) { #ifdef DEBUGGING BOOST_LOG_TRIVIAL(debug) << "Launching crossover batch jobs"; #endif // DEBUGGING typedef typename SelectionType::mate_pair_vector mate_pair_type; typedef batch_crossover_taskwe< mate_pair_type, SequenceSpaceType, AlleleSpaceType > crossover_task_type; typedef typename crossover_task_type::event_pool_type event_pool_type; typedef typename crossover_task_type::event_lookup_type event_lookup_type; typedef typename crossover_task_type::bias_pool_type bias_pool_type; event_pool_type ep = crossover_task_type::make_event_pool(); event_lookup_type el; fill_event_pool( ep, el, 2 * parents.size() ); bias_pool_type bp; fill_bias_pool( bp, 2 * parents.size() ); const size_t TC = pool.pool_size() + 1; // + 1 for master thread const size_t BATCH_SIZE = (parents.size() / TC) + ((parents.size() % TC > 0)? 1 : 0); unsigned int off_idx = 0; while( off_idx + BATCH_SIZE < parents.size() ) { unsigned int off_end = off_idx + BATCH_SIZE; #ifdef DEBUGGING BOOST_LOG_TRIVIAL(info) << "Batch Crossover: [" << off_idx << ", " << off_end << ");"; #endif // DEBUGGING crossover_task_type x( parental, offspring, alleles, ep, off_idx, parents.begin() + off_idx, parents.begin() + off_end, el.begin() + 2 * off_idx, el.begin() + 2 * off_end, bp.begin() + 2 * off_idx, bp.begin() + 2 * off_end ); pool.post( x ); off_idx = off_end; } if( off_idx < parents.size() ){ #ifdef DEBUGGING BOOST_LOG_TRIVIAL(info) << "Batch Crossover: [" << off_idx << ", " << parents.size() << ");"; #endif // DEBUGGING crossover_task_type t( parental, offspring, alleles, ep, off_idx, parents.begin() + off_idx, parents.end(), el.begin() + 2 * off_idx, el.end(), bp.begin() + 2 * off_idx, bp.end()); t(); } pool.sync(); #ifdef DEBUGGING BOOST_LOG_TRIVIAL(debug) << "Thread pool synced"; #endif // DEBUGGING } template < class EventPool, class EventLookup > void fill_event_pool( EventPool & events, EventLookup & lookup, unsigned int offspring_pop_size ) { event_distribution_type event_dist( m_recomb_rate.m_rho ); position_distribution_type pos_dist; while( offspring_pop_size-- ) { lookup.push_back( events->size() ); unsigned int N = event_dist( *m_rng ); while( N-- ) { events->push_back( pos_dist( *m_rng ) ); } } lookup.push_back( events->size() ); BOOST_LOG_TRIVIAL( info ) << "Events Count: " << events->size() << "; Lookup size: " << lookup.size(); } template < class BiasPool > void fill_bias_pool( BiasPool & bp, unsigned int offspring_pop_size ) { boost::random::bernoulli_distribution< double > bias_dist( m_seq_bias.m_bias ); while( offspring_pop_size-- ) { bp.push_back( bias_dist( *m_rng ) ); } } RNG * m_rng; sequence_bias_parameter< double > m_seq_bias; recombination_rate_parameter< double > m_recomb_rate; }; } // namespace genetics } // namespace clotho #endif // CLOTHO_BATCH_CROSSOVER_MTWE_GENERATOR_HPP_ <commit_msg>Adding comments<commit_after>// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef CLOTHO_BATCH_CROSSOVER_MTWE_GENERATOR_HPP_ #define CLOTHO_BATCH_CROSSOVER_MTWE_GENERATOR_HPP_ #include "clotho/data_spaces/crossover/batch_crossover_tasks.hpp" #include "clotho/recombination/sequence_bias_parameter.hpp" #include "clotho/recombination/recombination_rate_parameter.hpp" #include "clotho/data_spaces/task/thread_pool.hpp" #include "clotho/data_spaces/generators/position_distribution_helper.hpp" #include "clotho/data_spaces/generators/crossover_event_distribution_helper.hpp" #include <boost/random/bernoulli_distribution.hpp> namespace clotho { namespace genetics { /** * * Single pool of crossover events (WE => with events) * Common event pool intended to make simulations more reproduceable * */ template < class RNG, class SequenceSpaceType, class AlleleSpaceType > class BatchCrossoverMTWE { public: typedef SequenceSpaceType sequence_space_type; typedef AlleleSpaceType allele_space_type; typedef typename position_distribution_helper< typename allele_space_type::position_type >::type position_distribution_type; typedef typename crossover_event_distribution_helper< double >::type event_distribution_type; BatchCrossoverMTWE( RNG * rng, boost::property_tree::ptree & config ) : m_rng( rng ) , m_seq_bias(config) , m_recomb_rate(config) { } template < class SelectionType, class PoolType > void operator()( const SelectionType & parents, sequence_space_type * parental, sequence_space_type * offspring, allele_space_type * alleles, PoolType & pool ) { batch_generate( parents, parental, offspring, alleles, pool ); } virtual ~BatchCrossoverMTWE() {} protected: template < class SelectionType, class PoolType > void batch_generate( const SelectionType & parents, sequence_space_type * parental, sequence_space_type * offspring, allele_space_type * alleles, PoolType & pool ) { #ifdef DEBUGGING BOOST_LOG_TRIVIAL(debug) << "Launching crossover batch jobs"; #endif // DEBUGGING typedef typename SelectionType::mate_pair_vector mate_pair_type; typedef batch_crossover_taskwe< mate_pair_type, SequenceSpaceType, AlleleSpaceType > crossover_task_type; typedef typename crossover_task_type::event_pool_type event_pool_type; typedef typename crossover_task_type::event_lookup_type event_lookup_type; typedef typename crossover_task_type::bias_pool_type bias_pool_type; // generate a new event pool for every generation event_pool_type ep = crossover_task_type::make_event_pool(); event_lookup_type el; fill_event_pool( ep, el, 2 * parents.size() ); bias_pool_type bp; fill_bias_pool( bp, 2 * parents.size() ); const size_t TC = pool.pool_size() + 1; // + 1 for master thread const size_t BATCH_SIZE = (parents.size() / TC) + ((parents.size() % TC > 0)? 1 : 0); unsigned int off_idx = 0; while( off_idx + BATCH_SIZE < parents.size() ) { unsigned int off_end = off_idx + BATCH_SIZE; #ifdef DEBUGGING BOOST_LOG_TRIVIAL(info) << "Batch Crossover: [" << off_idx << ", " << off_end << ");"; #endif // DEBUGGING crossover_task_type x( parental, offspring, alleles, ep, off_idx, parents.begin() + off_idx, parents.begin() + off_end, el.begin() + 2 * off_idx, el.begin() + 2 * off_end, bp.begin() + 2 * off_idx, bp.begin() + 2 * off_end ); pool.post( x ); off_idx = off_end; } if( off_idx < parents.size() ){ #ifdef DEBUGGING BOOST_LOG_TRIVIAL(info) << "Batch Crossover: [" << off_idx << ", " << parents.size() << ");"; #endif // DEBUGGING crossover_task_type t( parental, offspring, alleles, ep, off_idx, parents.begin() + off_idx, parents.end(), el.begin() + 2 * off_idx, el.end(), bp.begin() + 2 * off_idx, bp.end()); t(); } pool.sync(); #ifdef DEBUGGING BOOST_LOG_TRIVIAL(debug) << "Thread pool synced"; #endif // DEBUGGING } template < class EventPool, class EventLookup > void fill_event_pool( EventPool & events, EventLookup & lookup, unsigned int offspring_pop_size ) { event_distribution_type event_dist( m_recomb_rate.m_rho ); position_distribution_type pos_dist; lookup.reserve( offspring_pop_size + 1); events->reserve( offspring_pop_size ); while( offspring_pop_size-- ) { lookup.push_back( events->size() ); unsigned int N = event_dist( *m_rng ); while( N-- ) { events->push_back( pos_dist( *m_rng ) ); } } lookup.push_back( events->size() ); BOOST_LOG_TRIVIAL( info ) << "Events Count: " << events->size() << "; Lookup size: " << lookup.size(); } template < class BiasPool > void fill_bias_pool( BiasPool & bp, unsigned int offspring_pop_size ) { boost::random::bernoulli_distribution< double > bias_dist( m_seq_bias.m_bias ); bp.reserve( offspring_pop_size ); while( offspring_pop_size-- ) { bp.push_back( bias_dist( *m_rng ) ); } } RNG * m_rng; sequence_bias_parameter< double > m_seq_bias; recombination_rate_parameter< double > m_recomb_rate; }; } // namespace genetics } // namespace clotho #endif // CLOTHO_BATCH_CROSSOVER_MTWE_GENERATOR_HPP_ <|endoftext|>
<commit_before>#include "stdafx.h" #include "AutoPacket.h" #include "Autowired.h" #include "AutoPacketFactory.h" #include "AutoPacketProfiler.h" #include "ContextEnumerator.h" #include "SatCounter.h" #include <list> AutoPacket::AutoPacket(AutoPacketFactory& factory) { // Traverse all contexts, adding their packet subscriber vectors one at a time: for(const auto& curContext : ContextEnumerator(factory.GetContext())) { AutowiredFast<AutoPacketFactory> curFactory(curContext); if(curFactory) // Only insert if this context actually has a packet factory curFactory->AppendAutoFiltersTo(m_satCounters); } // Prime the satisfaction graph for each element: for(auto& satCounter : m_satCounters) { for( auto pCur = satCounter.GetAutoFilterInput(); *pCur; pCur++ ) { DecorationDisposition& entry = m_decorations[*pCur->ti]; // Decide what to do with this entry: switch(pCur->subscriberType) { case inTypeInvalid: // Should never happen--trivially ignore this entry break; case inTypeRequired: entry.m_subscribers.push_back(std::make_pair(&satCounter, true)); break; case inTypeOptional: entry.m_subscribers.push_back(std::make_pair(&satCounter, false)); break; case outTypeRef: case outTypeRefAutoReady: // We don't do anything with these types. // Optionally, we might want to register them as outputs, or do some kind // of runtime detection that a multi-satisfaction case exists--but for now, // we just trivially ignore them. break; } } } // Invoke any output-only AutoFilter routines Initialize(); } AutoPacket::~AutoPacket() { // Last chance for AutoFilter call ResolveOptions(); } ObjectPool<AutoPacket> AutoPacket::CreateObjectPool(AutoPacketFactory& factory) { return ObjectPool<AutoPacket>( ~0, ~0, [&factory] { return new AutoPacket(factory); }, [] (AutoPacket& packet) { // Last chance for AutoFilter optional calls packet.ResolveOptions(); // Reinitialize the whole packet: packet.Initialize(); } ); } void AutoPacket::ResolveOptions(void) { // Queue calls to ensure that calls to Decorate inside of AutoFilter methods // will NOT effect the resolution of optional arguments. std::list<SatCounter*> callQueue; { boost::lock_guard<boost::mutex> lk(m_lock); for(auto& decoration : m_decorations) for(auto& satCounter : decoration.second.m_subscribers) if(!satCounter.second) if(satCounter.first->Resolve()) callQueue.push_back(satCounter.first); } for (SatCounter* call : callQueue) call->CallAutoFilter(*this); } void AutoPacket::MarkUnsatisfiable(const std::type_info& info) { DecorationDisposition* decoration; { boost::lock_guard<boost::mutex> lk(m_lock); auto dFind = m_decorations.find(info); if(dFind == m_decorations.end()) // Trivial return, there's no subscriber to this decoration and so we have nothing to do return; decoration = &dFind->second; } // Update everything for(auto& satCounter : decoration->m_subscribers) { if(satCounter.second) // Entry is mandatory, leave it unsatisfaible continue; // Entry is optional, we will call if we're satisfied after decrementing this optional field if(satCounter.first->Decrement(false)) satCounter.first->CallAutoFilter(*this); } } void AutoPacket::UpdateSatisfaction(const std::type_info& info) { DecorationDisposition* decoration; { boost::lock_guard<boost::mutex> lk(m_lock); auto dFind = m_decorations.find(info); if(dFind == m_decorations.end()) // Trivial return, there's no subscriber to this decoration and so we have nothing to do return; decoration = &dFind->second; } // Update everything for(auto& satCounter : decoration->m_subscribers) if(satCounter.first->Decrement(satCounter.second)) satCounter.first->CallAutoFilter(*this); } void AutoPacket::PulseSatisfaction(DecorationDisposition* pTypeSubs[], size_t nInfos) { // First pass, decrement what we can: for(size_t i = nInfos; i--;) { for(std::pair<SatCounter*, bool>& subscriber : pTypeSubs[i]->m_subscribers) { SatCounter* cur = subscriber.first; if( // We only care about mandatory inputs subscriber.second && // We only care about sat counters that aren't deferred--skip everyone else // Deferred calls will be too late. !cur->IsDeferred() && // Now do the decrementation, and only proceed if the decremented value is zero !--cur->remaining ) // Finally, a call is safe to make on this type cur->CallAutoFilter(*this); } } // Reset all counters // since data in this call will not be available subsequently for(size_t i = nInfos; i--;) { for(auto& satCounter : pTypeSubs[i]->m_subscribers) { auto& cur = satCounter.first; if (satCounter.second) { ++cur->remaining; } } } } void AutoPacket::Initialize(void) { // Initialize all counters: { boost::lock_guard<boost::mutex> lk(m_lock); for(auto& satCounter : m_satCounters) satCounter.Reset(); for(auto& decoration : m_decorations) decoration.second.Reset(); } // Call all subscribers with no required or optional arguments: for (auto& satCounter : m_satCounters) if (satCounter) satCounter.CallAutoFilter(*this); // Initial satisfaction of the AutoPacket: UpdateSatisfaction(typeid(AutoPacket)); } bool AutoPacket::HasSubscribers(const std::type_info& ti) const { return m_decorations.count(ti) != 0; } <commit_msg>Adding duplicate elimination after saturation counter generation<commit_after>#include "stdafx.h" #include "AutoPacket.h" #include "Autowired.h" #include "AutoPacketFactory.h" #include "AutoPacketProfiler.h" #include "ContextEnumerator.h" #include "SatCounter.h" #include <list> AutoPacket::AutoPacket(AutoPacketFactory& factory) { // Traverse all contexts, adding their packet subscriber vectors one at a time: for(const auto& curContext : ContextEnumerator(factory.GetContext())) { AutowiredFast<AutoPacketFactory> curFactory(curContext); if(curFactory) // Only insert if this context actually has a packet factory curFactory->AppendAutoFiltersTo(m_satCounters); } // Sort, eliminate duplicates std::sort(m_satCounters.begin(), m_satCounters.end()); m_satCounters.erase(std::unique(m_satCounters.begin(), m_satCounters.end()), m_satCounters.end()); // Prime the satisfaction graph for each element: for(auto& satCounter : m_satCounters) { for( auto pCur = satCounter.GetAutoFilterInput(); *pCur; pCur++ ) { DecorationDisposition& entry = m_decorations[*pCur->ti]; // Decide what to do with this entry: switch(pCur->subscriberType) { case inTypeInvalid: // Should never happen--trivially ignore this entry break; case inTypeRequired: entry.m_subscribers.push_back(std::make_pair(&satCounter, true)); break; case inTypeOptional: entry.m_subscribers.push_back(std::make_pair(&satCounter, false)); break; case outTypeRef: case outTypeRefAutoReady: // We don't do anything with these types. // Optionally, we might want to register them as outputs, or do some kind // of runtime detection that a multi-satisfaction case exists--but for now, // we just trivially ignore them. break; } } } // Invoke any output-only AutoFilter routines Initialize(); } AutoPacket::~AutoPacket() { // Last chance for AutoFilter call ResolveOptions(); } ObjectPool<AutoPacket> AutoPacket::CreateObjectPool(AutoPacketFactory& factory) { return ObjectPool<AutoPacket>( ~0, ~0, [&factory] { return new AutoPacket(factory); }, [] (AutoPacket& packet) { // Last chance for AutoFilter optional calls packet.ResolveOptions(); // Reinitialize the whole packet: packet.Initialize(); } ); } void AutoPacket::ResolveOptions(void) { // Queue calls to ensure that calls to Decorate inside of AutoFilter methods // will NOT effect the resolution of optional arguments. std::list<SatCounter*> callQueue; { boost::lock_guard<boost::mutex> lk(m_lock); for(auto& decoration : m_decorations) for(auto& satCounter : decoration.second.m_subscribers) if(!satCounter.second) if(satCounter.first->Resolve()) callQueue.push_back(satCounter.first); } for (SatCounter* call : callQueue) call->CallAutoFilter(*this); } void AutoPacket::MarkUnsatisfiable(const std::type_info& info) { DecorationDisposition* decoration; { boost::lock_guard<boost::mutex> lk(m_lock); auto dFind = m_decorations.find(info); if(dFind == m_decorations.end()) // Trivial return, there's no subscriber to this decoration and so we have nothing to do return; decoration = &dFind->second; } // Update everything for(auto& satCounter : decoration->m_subscribers) { if(satCounter.second) // Entry is mandatory, leave it unsatisfaible continue; // Entry is optional, we will call if we're satisfied after decrementing this optional field if(satCounter.first->Decrement(false)) satCounter.first->CallAutoFilter(*this); } } void AutoPacket::UpdateSatisfaction(const std::type_info& info) { DecorationDisposition* decoration; { boost::lock_guard<boost::mutex> lk(m_lock); auto dFind = m_decorations.find(info); if(dFind == m_decorations.end()) // Trivial return, there's no subscriber to this decoration and so we have nothing to do return; decoration = &dFind->second; } // Update everything for(auto& satCounter : decoration->m_subscribers) if(satCounter.first->Decrement(satCounter.second)) satCounter.first->CallAutoFilter(*this); } void AutoPacket::PulseSatisfaction(DecorationDisposition* pTypeSubs[], size_t nInfos) { // First pass, decrement what we can: for(size_t i = nInfos; i--;) { for(std::pair<SatCounter*, bool>& subscriber : pTypeSubs[i]->m_subscribers) { SatCounter* cur = subscriber.first; if( // We only care about mandatory inputs subscriber.second && // We only care about sat counters that aren't deferred--skip everyone else // Deferred calls will be too late. !cur->IsDeferred() && // Now do the decrementation, and only proceed if the decremented value is zero !--cur->remaining ) // Finally, a call is safe to make on this type cur->CallAutoFilter(*this); } } // Reset all counters // since data in this call will not be available subsequently for(size_t i = nInfos; i--;) { for(auto& satCounter : pTypeSubs[i]->m_subscribers) { auto& cur = satCounter.first; if (satCounter.second) { ++cur->remaining; } } } } void AutoPacket::Initialize(void) { // Initialize all counters: { boost::lock_guard<boost::mutex> lk(m_lock); for(auto& satCounter : m_satCounters) satCounter.Reset(); for(auto& decoration : m_decorations) decoration.second.Reset(); } // Call all subscribers with no required or optional arguments: for (auto& satCounter : m_satCounters) if (satCounter) satCounter.CallAutoFilter(*this); // Initial satisfaction of the AutoPacket: UpdateSatisfaction(typeid(AutoPacket)); } bool AutoPacket::HasSubscribers(const std::type_info& ti) const { return m_decorations.count(ti) != 0; } <|endoftext|>
<commit_before>#include "render_test.h" #include <QApplication> #include <qdir.h> #include "core/FS/file_system.h" #include "core/FS/ifile.h" #include "core/log.h" #include "core/profiler.h" #include "core/resource_manager.h" #include "core/resource_manager_base.h" #include "editor/world_editor.h" #include "editor/gizmo.h" #include "engine/engine.h" #include "engine/plugin_manager.h" #include "graphics/gl_ext.h" #include "graphics/irender_device.h" #include "graphics/pipeline.h" #include "graphics/renderer.h" #include "graphics/texture.h" #include "physics/physics_scene.h" #include "physics/physics_system.h" class WGLRenderDevice : public Lumix::IRenderDevice { public: WGLRenderDevice(Lumix::Engine& engine, const char* pipeline_path) { Lumix::Pipeline* pipeline_object = static_cast<Lumix::Pipeline*>(engine.getResourceManager().get(Lumix::ResourceManager::PIPELINE)->load(Lumix::Path(pipeline_path))); ASSERT(pipeline_object); if (pipeline_object) { m_pipeline = Lumix::PipelineInstance::create(*pipeline_object, engine.getAllocator()); m_pipeline->setRenderer(engine.getRenderer()); } } ~WGLRenderDevice() { if (m_pipeline) { Lumix::PipelineInstance::destroy(m_pipeline); } } virtual void beginFrame() override { PROFILE_FUNCTION(); wglMakeCurrent(m_hdc, m_opengl_context); } virtual void endFrame() override { PROFILE_FUNCTION(); wglSwapLayerBuffers(m_hdc, WGL_SWAP_MAIN_PLANE); } virtual Lumix::PipelineInstance& getPipeline() { return *m_pipeline; } virtual int getWidth() const override { return m_pipeline->getWidth(); } virtual int getHeight() const override { return m_pipeline->getHeight(); } Lumix::PipelineInstance* m_pipeline; HDC m_hdc; HGLRC m_opengl_context; }; class App { public: App() { m_qt_app = NULL; m_main_window = NULL; m_current_test = -1; m_is_test_universe_loaded = false; } ~App() { delete m_main_window; delete m_qt_app; } HGLRC createGLContext(HWND hwnd[], int count) { ASSERT(count > 0); QWidget* widget = new QWidget(); HWND gl_hwnd = (HWND)widget->winId(); HDC hdc; hdc = GetDC(gl_hwnd); ASSERT(hdc != NULL); if (hdc == NULL) { Lumix::g_log_error.log("renderer") << "Could not get the device context"; return NULL; } BOOL success; PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd 1, // version number PFD_DRAW_TO_WINDOW | // support window PFD_SUPPORT_OPENGL | // support OpenGL PFD_DOUBLEBUFFER, // double buffered PFD_TYPE_RGBA, // RGBA type 24, // 24-bit color depth 0, 0, 0, 0, 0, 0, // color bits ignored 0, // no alpha buffer 0, // shift bit ignored 0, // no accumulation buffer 0, 0, 0, 0, // accum bits ignored 32, // 32-bit z-buffer 0, // no stencil buffer 0, // no auxiliary buffer PFD_MAIN_PLANE, // main layer 0, // reserved 0, 0, 0 // layer masks ignored }; int pixelformat = ChoosePixelFormat(hdc, &pfd); if (pixelformat == 0) { delete widget; ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not choose a pixel format"; return NULL; } success = SetPixelFormat(hdc, pixelformat, &pfd); if (success == FALSE) { delete widget; ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not set a pixel format"; return NULL; } HGLRC hglrc = wglCreateContext(hdc); if (hglrc == NULL) { delete widget; ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not create an opengl context"; return NULL; } success = wglMakeCurrent(hdc, hglrc); if (success == FALSE) { delete widget; ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not make the opengl context current rendering context"; return NULL; } { UINT numFormats; int atrribs[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, WGL_SAMPLES_ARB, 4, 0 }; PFNWGLCHOOSEPIXELFORMATARBPROC foo; foo = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); if (!foo) { delete widget; ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not get function wglChoosePixelFormatARB"; return NULL; } success = foo(hdc, atrribs, NULL, 1, &pixelformat, &numFormats); } wglDeleteContext(hglrc); hglrc = NULL; delete widget; for (int i = 0; i < count; ++i) { if (hwnd[i]) { hdc = GetDC(hwnd[i]); ChoosePixelFormat(hdc, &pfd); if (hdc == NULL) { ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not get the device context"; return NULL; } SetPixelFormat(hdc, pixelformat, &pfd); if (!hglrc) { hglrc = wglCreateContext(hdc); if (hglrc == NULL) { ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not create an opengl context"; return NULL; } success = wglMakeCurrent(hdc, hglrc); if (success == FALSE) { ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not make the opengl context current rendering context"; return NULL; } } } } return hglrc; } void universeFileLoaded(Lumix::FS::IFile* file, bool success, Lumix::FS::FileSystem& fs) { ASSERT(success); if (success) { ASSERT(file->getBuffer()); Lumix::InputBlob blob(file->getBuffer(), file->size()); uint32_t hash = 0; blob.read(hash); uint32_t engine_hash = 0; blob.read(engine_hash); if (crc32((const uint8_t*)blob.getData() + sizeof(hash), blob.getSize() - sizeof(hash)) != hash) { ASSERT(false); return; } bool deserialize_succeeded = m_engine->deserialize(blob); m_is_test_universe_loaded = true; ASSERT(deserialize_succeeded); } fs.close(file); } void init(int argc, char* argv[]) { m_qt_app = new QApplication(argc, argv); QFile file("editor/stylesheet.qss"); file.open(QFile::ReadOnly); m_qt_app->setStyleSheet(QLatin1String(file.readAll())); m_main_window = new RenderTest(); m_main_window->show(); HWND hwnd = (HWND)m_main_window->centralWidget()->winId(); HWND hwnds[] = { hwnd }; HGLRC hglrc = createGLContext(hwnds, sizeof(hwnds) / sizeof(hwnds[0])); m_engine = Lumix::Engine::create("", NULL, NULL, m_allocator); m_render_device = new WGLRenderDevice(*m_engine, "pipelines/main.json"); m_render_device->m_hdc = GetDC(hwnd); m_render_device->m_opengl_context = hglrc; m_engine->createUniverse(); m_render_device->getPipeline().setScene((Lumix::RenderScene*)m_engine->getScene(crc32("renderer"))); m_engine->getRenderer().setRenderDevice(*m_render_device); m_render_device->getPipeline().resize(600, 400); } void shutdown() { } void handleEvents() { PROFILE_FUNCTION(); { PROFILE_BLOCK("qt::processEvents"); m_qt_app->processEvents(); } } bool nextTest() { static const char* tests[] = { "render_tests/1" }; Lumix::FS::FileSystem& fs = m_engine->getFileSystem(); bool can_do_next_test = m_current_test == -1 || (!m_engine->getResourceManager().isLoading() && m_is_test_universe_loaded); if (can_do_next_test) { char path[LUMIX_MAX_PATH]; if (m_current_test >= 0) { Lumix::copyString(path, sizeof(path), tests[m_current_test]); Lumix::catCString(path, sizeof(path), "_res.tga"); m_engine->getRenderer().makeScreenshot(Lumix::Path(path), 500, 500); char path_preimage[LUMIX_MAX_PATH]; Lumix::copyString(path_preimage, sizeof(path), tests[m_current_test]); Lumix::catCString(path_preimage, sizeof(path), ".tga"); auto file1 = fs.open(fs.getDefaultDevice(), path, Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ); auto file2 = fs.open(fs.getDefaultDevice(), path_preimage, Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ); unsigned int diference = Lumix::Texture::compareTGA(m_allocator, file1, file2, 10); fs.close(file1); fs.close(file2); ASSERT(diference < 100); } ++m_current_test; if (m_current_test < sizeof(tests) / sizeof(tests[0])) { Lumix::copyString(path, sizeof(path), tests[m_current_test]); Lumix::catCString(path, sizeof(path), ".unv"); Lumix::FS::ReadCallback file_read_cb; file_read_cb.bind<App, &App::universeFileLoaded>(this); fs.openAsync(fs.getDefaultDevice(), path, Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ, file_read_cb); m_is_test_universe_loaded = false; return true; } return false; } return true; } void run() { while (m_main_window->isVisible()) { { PROFILE_BLOCK("tick"); m_engine->getRenderer().renderGame(); m_engine->update(false, 0); if (!m_engine->getResourceManager().isLoading()) { if (!nextTest()) return; } m_engine->getFileSystem().updateAsyncTransactions(); handleEvents(); } Lumix::g_profiler.frame(); } } private: Lumix::DefaultAllocator m_allocator; Lumix::Engine* m_engine; RenderTest* m_main_window; QApplication* m_qt_app; WGLRenderDevice* m_render_device; QWidget* m_view; int m_current_test; bool m_is_test_universe_loaded; }; int main(int argc, char* argv[]) { App app; app.init(argc, argv); app.run(); app.shutdown(); return 0; } <commit_msg>enumerate all tests in render_test directory<commit_after>#include "render_test.h" #include <QApplication> #include <qdir.h> #include "core/FS/file_system.h" #include "core/FS/ifile.h" #include "core/log.h" #include "core/profiler.h" #include "core/resource_manager.h" #include "core/resource_manager_base.h" #include "editor/world_editor.h" #include "editor/gizmo.h" #include "engine/engine.h" #include "engine/plugin_manager.h" #include "graphics/gl_ext.h" #include "graphics/irender_device.h" #include "graphics/pipeline.h" #include "graphics/renderer.h" #include "graphics/texture.h" #include "physics/physics_scene.h" #include "physics/physics_system.h" class WGLRenderDevice : public Lumix::IRenderDevice { public: WGLRenderDevice(Lumix::Engine& engine, const char* pipeline_path) { Lumix::Pipeline* pipeline_object = static_cast<Lumix::Pipeline*>(engine.getResourceManager().get(Lumix::ResourceManager::PIPELINE)->load(Lumix::Path(pipeline_path))); ASSERT(pipeline_object); if (pipeline_object) { m_pipeline = Lumix::PipelineInstance::create(*pipeline_object, engine.getAllocator()); m_pipeline->setRenderer(engine.getRenderer()); } } ~WGLRenderDevice() { if (m_pipeline) { Lumix::PipelineInstance::destroy(m_pipeline); } } virtual void beginFrame() override { PROFILE_FUNCTION(); wglMakeCurrent(m_hdc, m_opengl_context); } virtual void endFrame() override { PROFILE_FUNCTION(); wglSwapLayerBuffers(m_hdc, WGL_SWAP_MAIN_PLANE); } virtual Lumix::PipelineInstance& getPipeline() { return *m_pipeline; } virtual int getWidth() const override { return m_pipeline->getWidth(); } virtual int getHeight() const override { return m_pipeline->getHeight(); } Lumix::PipelineInstance* m_pipeline; HDC m_hdc; HGLRC m_opengl_context; }; class App { public: App() { m_qt_app = NULL; m_main_window = NULL; m_current_test = -1; m_is_test_universe_loaded = false; } ~App() { delete m_main_window; delete m_qt_app; } HGLRC createGLContext(HWND hwnd[], int count) { ASSERT(count > 0); QWidget* widget = new QWidget(); HWND gl_hwnd = (HWND)widget->winId(); HDC hdc; hdc = GetDC(gl_hwnd); ASSERT(hdc != NULL); if (hdc == NULL) { Lumix::g_log_error.log("renderer") << "Could not get the device context"; return NULL; } BOOL success; PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd 1, // version number PFD_DRAW_TO_WINDOW | // support window PFD_SUPPORT_OPENGL | // support OpenGL PFD_DOUBLEBUFFER, // double buffered PFD_TYPE_RGBA, // RGBA type 24, // 24-bit color depth 0, 0, 0, 0, 0, 0, // color bits ignored 0, // no alpha buffer 0, // shift bit ignored 0, // no accumulation buffer 0, 0, 0, 0, // accum bits ignored 32, // 32-bit z-buffer 0, // no stencil buffer 0, // no auxiliary buffer PFD_MAIN_PLANE, // main layer 0, // reserved 0, 0, 0 // layer masks ignored }; int pixelformat = ChoosePixelFormat(hdc, &pfd); if (pixelformat == 0) { delete widget; ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not choose a pixel format"; return NULL; } success = SetPixelFormat(hdc, pixelformat, &pfd); if (success == FALSE) { delete widget; ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not set a pixel format"; return NULL; } HGLRC hglrc = wglCreateContext(hdc); if (hglrc == NULL) { delete widget; ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not create an opengl context"; return NULL; } success = wglMakeCurrent(hdc, hglrc); if (success == FALSE) { delete widget; ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not make the opengl context current rendering context"; return NULL; } { UINT numFormats; int atrribs[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, WGL_SAMPLES_ARB, 4, 0 }; PFNWGLCHOOSEPIXELFORMATARBPROC foo; foo = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); if (!foo) { delete widget; ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not get function wglChoosePixelFormatARB"; return NULL; } success = foo(hdc, atrribs, NULL, 1, &pixelformat, &numFormats); } wglDeleteContext(hglrc); hglrc = NULL; delete widget; for (int i = 0; i < count; ++i) { if (hwnd[i]) { hdc = GetDC(hwnd[i]); ChoosePixelFormat(hdc, &pfd); if (hdc == NULL) { ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not get the device context"; return NULL; } SetPixelFormat(hdc, pixelformat, &pfd); if (!hglrc) { hglrc = wglCreateContext(hdc); if (hglrc == NULL) { ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not create an opengl context"; return NULL; } success = wglMakeCurrent(hdc, hglrc); if (success == FALSE) { ASSERT(false); Lumix::g_log_error.log("renderer") << "Could not make the opengl context current rendering context"; return NULL; } } } } return hglrc; } void universeFileLoaded(Lumix::FS::IFile* file, bool success, Lumix::FS::FileSystem& fs) { ASSERT(success); if (success) { ASSERT(file->getBuffer()); Lumix::InputBlob blob(file->getBuffer(), file->size()); uint32_t hash = 0; blob.read(hash); uint32_t engine_hash = 0; blob.read(engine_hash); if (crc32((const uint8_t*)blob.getData() + sizeof(hash), blob.getSize() - sizeof(hash)) != hash) { ASSERT(false); return; } bool deserialize_succeeded = m_engine->deserialize(blob); m_is_test_universe_loaded = true; ASSERT(deserialize_succeeded); } fs.close(file); } void init(int argc, char* argv[]) { m_qt_app = new QApplication(argc, argv); QFile file("editor/stylesheet.qss"); file.open(QFile::ReadOnly); m_qt_app->setStyleSheet(QLatin1String(file.readAll())); m_main_window = new RenderTest(); m_main_window->show(); HWND hwnd = (HWND)m_main_window->centralWidget()->winId(); HWND hwnds[] = { hwnd }; HGLRC hglrc = createGLContext(hwnds, sizeof(hwnds) / sizeof(hwnds[0])); m_engine = Lumix::Engine::create("", NULL, NULL, m_allocator); m_render_device = new WGLRenderDevice(*m_engine, "pipelines/main.json"); m_render_device->m_hdc = GetDC(hwnd); m_render_device->m_opengl_context = hglrc; m_engine->createUniverse(); m_render_device->getPipeline().setScene((Lumix::RenderScene*)m_engine->getScene(crc32("renderer"))); m_engine->getRenderer().setRenderDevice(*m_render_device); m_render_device->getPipeline().resize(600, 400); enumerateTests(); } void shutdown() { } void handleEvents() { PROFILE_FUNCTION(); { PROFILE_BLOCK("qt::processEvents"); m_qt_app->processEvents(); } } void enumerateTests() { QDir dir("render_tests"); QStringList files = dir.entryList(QStringList() << "*.unv"); for (int i = 0; i < files.size(); ++i) { m_tests.push_back(QString("render_tests/") + files[i].left(files[i].size() - 4)); } } bool nextTest() { Lumix::FS::FileSystem& fs = m_engine->getFileSystem(); bool can_do_next_test = m_current_test == -1 || (!m_engine->getResourceManager().isLoading() && m_is_test_universe_loaded); if (can_do_next_test) { char path[LUMIX_MAX_PATH]; if (m_current_test >= 0) { Lumix::copyString(path, sizeof(path), m_tests[m_current_test].toLatin1().data()); Lumix::catCString(path, sizeof(path), "_res.tga"); m_engine->getRenderer().makeScreenshot(Lumix::Path(path), 500, 500); char path_preimage[LUMIX_MAX_PATH]; Lumix::copyString(path_preimage, sizeof(path), m_tests[m_current_test].toLatin1().data()); Lumix::catCString(path_preimage, sizeof(path), ".tga"); auto file1 = fs.open(fs.getDefaultDevice(), path, Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ); auto file2 = fs.open(fs.getDefaultDevice(), path_preimage, Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ); unsigned int diference = Lumix::Texture::compareTGA(m_allocator, file1, file2, 10); fs.close(file1); fs.close(file2); ASSERT(diference < 100); } ++m_current_test; if (m_current_test < m_tests.size()) { Lumix::copyString(path, sizeof(path), m_tests[m_current_test].toLatin1().data()); Lumix::catCString(path, sizeof(path), ".unv"); Lumix::FS::ReadCallback file_read_cb; file_read_cb.bind<App, &App::universeFileLoaded>(this); fs.openAsync(fs.getDefaultDevice(), path, Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ, file_read_cb); m_is_test_universe_loaded = false; return true; } return false; } return true; } void run() { while (m_main_window->isVisible()) { { PROFILE_BLOCK("tick"); m_engine->getRenderer().renderGame(); m_engine->update(false, 0); if (!m_engine->getResourceManager().isLoading()) { if (!nextTest()) return; } m_engine->getFileSystem().updateAsyncTransactions(); handleEvents(); } Lumix::g_profiler.frame(); } } private: Lumix::DefaultAllocator m_allocator; Lumix::Engine* m_engine; RenderTest* m_main_window; QApplication* m_qt_app; WGLRenderDevice* m_render_device; QWidget* m_view; QStringList m_tests; int m_current_test; bool m_is_test_universe_loaded; }; int main(int argc, char* argv[]) { App app; app.init(argc, argv); app.run(); app.shutdown(); return 0; } <|endoftext|>
<commit_before>/**********************************************************************/ /* Copyright 2014 RCF */ /* */ /* 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. */ /**********************************************************************/ /** * @file Simplex.cpp * @brief Main interface for use of the Network Simplex Algorithm */ // Default libraries #include <cstdio> #include <iostream> using namespace std; // Libraries #include "Options.hpp" #include "graph/graph.tcc" #include "graph/flow/flow.tcc" /** * @fn Main * @param argc Number of arguments in the command line * @param argv Array of string with the arguments * @return 0 if success; non-zero otherwise */ int main(int argc, char **argv) { // Process options Options::parse_args(argc, argv); if(argc-optind != 1) { cerr << "Usage: Simplex [-h] [-d] input.dat ..." << endl; cerr << "Type --help for more information" << endl; return EXIT_FAILURE; } typedef graph::flow::Vertex<>::type vertex; typedef graph::flow::Arc<>::type arc; vertex v1 { 0 }, v2 { 1 }; arc a1 { v1, v2 }, a2 { v2, v1 }; cout << a1.beg << endl; cout << a1.end << endl; cout << a1 << endl; cout << a2.beg << endl; cout << a2.end << endl; cout << a2 << endl; cout << "Vertex list" << endl; cout << "=======================" << endl; typedef std::vector<vertex> vertex_list; vertex_list vl { v1, v2 }; for(const vertex& v : vl) cout << v << endl; cout << "Arc list" << endl; cout << "=======================" << endl; typedef std::vector<arc> arc_list; arc_list al { a1, a2 }; for(const arc& a : al) cout << a << endl; cout << "Adjacency list" << endl; cout << "=======================" << endl; typedef graph::Adjacency_list<graph::directed,vertex,arc> digraph; digraph adj ( vl, al ); cout << "Digraph" << endl; cout << "=======================" << endl; vertex_list tr1_v; vertex::id_type id {}; for(size_t i = 0; i < 5; i++) tr1_v.emplace_back(id++); arc_list tr1_a { arc{ tr1_v[0], tr1_v[1], {9 } }, arc{ tr1_v[0], tr1_v[3], {10} }, arc{ tr1_v[1], tr1_v[2], {7 } }, arc{ tr1_v[1], tr1_v[3], {4 } }, arc{ tr1_v[1], tr1_v[4], {5 } }, arc{ tr1_v[2], tr1_v[4], {9 } }, arc{ tr1_v[3], tr1_v[1], {4 } }, arc{ tr1_v[3], tr1_v[4], {9 } } }; digraph T { tr1_v, tr1_a }; auto it = T.out_arcs(tr1_v[0]).first; auto end = T.out_arcs(tr1_v[0]).second; for(; it != end; it++) cout << **it << endl; return EXIT_SUCCESS; } <commit_msg>Cleaning example and updating<commit_after>/**********************************************************************/ /* Copyright 2014 RCF */ /* */ /* 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. */ /**********************************************************************/ /** * @file Simplex.cpp * @brief Main interface for use of the Network Simplex Algorithm */ // Default libraries #include <cstdio> #include <iostream> using namespace std; // Libraries #include "Options.hpp" #include "graph/graph.tcc" #include "graph/flow/flow.tcc" /** * @fn Main * @param argc Number of arguments in the command line * @param argv Array of string with the arguments * @return 0 if success; non-zero otherwise */ int main(int argc, char **argv) { // Process options Options::parse_args(argc, argv); if(argc-optind != 1) { cerr << "Usage: Simplex [-h] [-d] input.dat ..." << endl; cerr << "Type --help for more information" << endl; return EXIT_FAILURE; } typedef graph::flow::Vertex<>::type vertex; typedef graph::flow::Arc<>::type arc; vertex v1 { 0 }, v2 { 1 }; arc a1 { v1, v2 }, a2 { v2, v1 }; cout << endl << "Vertex list" << endl; cout << "=======================" << endl; typedef std::vector<vertex> vertex_list; vertex_list vl { v1, v2 }; for(const vertex& v : vl) cout << v << endl; cout << endl << "Arc list" << endl; cout << "=======================" << endl; typedef std::vector<arc> arc_list; arc_list al { a1, a2 }; for(const arc& a : al) cout << a << endl; cout << endl << "Digraph" << endl; cout << "=======================" << endl; typedef graph::Adjacency_list<graph::directed,vertex,arc> digraph; vertex_list tr1_v; vertex::id_type id {}; for(size_t i = 0; i < 5; i++) tr1_v.emplace_back(id++); arc_list tr1_a { arc{ tr1_v[0], tr1_v[1], {9 } }, arc{ tr1_v[0], tr1_v[3], {10} }, arc{ tr1_v[1], tr1_v[2], {7 } }, arc{ tr1_v[1], tr1_v[3], {4 } }, arc{ tr1_v[1], tr1_v[4], {5 } }, arc{ tr1_v[2], tr1_v[4], {9 } }, arc{ tr1_v[3], tr1_v[1], {4 } }, arc{ tr1_v[3], tr1_v[4], {9 } } }; digraph T { tr1_v, tr1_a }; auto it = T.out_arcs(tr1_v[0]).first; auto end = T.out_arcs(tr1_v[0]).second; for(; it != end; it++) cout << **it << endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Semaphore.h" using namespace decaf; using namespace decaf::lang; using namespace decaf::lang::exceptions; using namespace decaf::util; using namespace decaf::util::concurrent; //////////////////////////////////////////////////////////////////////////////// namespace decaf { namespace util { namespace concurrent { class SemaphoreHandle { public: int permits; bool fair; public: SemaphoreHandle( int permits ) : permits( permits ), fair( false ) { } SemaphoreHandle( int permits, bool fair ) : permits( permits ), fair( fair ) { } ~SemaphoreHandle() { } }; }}} //////////////////////////////////////////////////////////////////////////////// Semaphore::Semaphore( int permits ) { this->handle.reset( new SemaphoreHandle( permits ) ); } //////////////////////////////////////////////////////////////////////////////// Semaphore::Semaphore( int permits, bool fair ) { this->handle.reset( new SemaphoreHandle( permits, fair ) ); } //////////////////////////////////////////////////////////////////////////////// Semaphore::~Semaphore() { } //////////////////////////////////////////////////////////////////////////////// void Semaphore::acquire() throw( decaf::lang::exceptions::InterruptedException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// void Semaphore::acquireUninterruptibly() throw ( decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// bool Semaphore::tryAcquire() throw ( decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// bool Semaphore::tryAcquire( long long timeout, const TimeUnit& unit ) throw( decaf::lang::exceptions::InterruptedException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// void Semaphore::release() throw ( decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// void Semaphore::acquire( int permits ) throw( decaf::lang::exceptions::InterruptedException, decaf::lang::exceptions::IllegalArgumentException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// void Semaphore::acquireUninterruptibly( int permits ) throw( decaf::lang::exceptions::IllegalArgumentException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// bool Semaphore::tryAcquire( int permits ) throw( decaf::lang::exceptions::IllegalArgumentException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// bool Semaphore::tryAcquire( int permits, long long timeout, const TimeUnit& unit ) throw( decaf::lang::exceptions::IllegalArgumentException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// void Semaphore::release( int permits ) throw( decaf::lang::exceptions::IllegalArgumentException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// int Semaphore::availablePermits() const { } //////////////////////////////////////////////////////////////////////////////// int Semaphore::drainPermits() throw( decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// bool Semaphore::isFair() const { } //////////////////////////////////////////////////////////////////////////////// std::string Semaphore::toString() const { } <commit_msg>Commit some fixes found while building on Solaris.<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Semaphore.h" using namespace decaf; using namespace decaf::lang; using namespace decaf::lang::exceptions; using namespace decaf::util; using namespace decaf::util::concurrent; //////////////////////////////////////////////////////////////////////////////// namespace decaf { namespace util { namespace concurrent { class SemaphoreHandle { public: int permits; bool fair; public: SemaphoreHandle( int permits ) : permits( permits ), fair( false ) { } SemaphoreHandle( int permits, bool fair ) : permits( permits ), fair( fair ) { } ~SemaphoreHandle() { } }; }}} //////////////////////////////////////////////////////////////////////////////// Semaphore::Semaphore( int permits ) { this->handle.reset( new SemaphoreHandle( permits ) ); } //////////////////////////////////////////////////////////////////////////////// Semaphore::Semaphore( int permits, bool fair ) { this->handle.reset( new SemaphoreHandle( permits, fair ) ); } //////////////////////////////////////////////////////////////////////////////// Semaphore::~Semaphore() { } //////////////////////////////////////////////////////////////////////////////// void Semaphore::acquire() throw( decaf::lang::exceptions::InterruptedException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// void Semaphore::acquireUninterruptibly() throw ( decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// bool Semaphore::tryAcquire() throw ( decaf::lang::exceptions::RuntimeException ) { return false; } //////////////////////////////////////////////////////////////////////////////// bool Semaphore::tryAcquire( long long timeout, const TimeUnit& unit ) throw( decaf::lang::exceptions::InterruptedException, decaf::lang::exceptions::RuntimeException ) { return false; } //////////////////////////////////////////////////////////////////////////////// void Semaphore::release() throw ( decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// void Semaphore::acquire( int permits ) throw( decaf::lang::exceptions::InterruptedException, decaf::lang::exceptions::IllegalArgumentException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// void Semaphore::acquireUninterruptibly( int permits ) throw( decaf::lang::exceptions::IllegalArgumentException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// bool Semaphore::tryAcquire( int permits ) throw( decaf::lang::exceptions::IllegalArgumentException, decaf::lang::exceptions::RuntimeException ) { return false; } //////////////////////////////////////////////////////////////////////////////// bool Semaphore::tryAcquire( int permits, long long timeout, const TimeUnit& unit ) throw( decaf::lang::exceptions::IllegalArgumentException, decaf::lang::exceptions::RuntimeException ) { return false; } //////////////////////////////////////////////////////////////////////////////// void Semaphore::release( int permits ) throw( decaf::lang::exceptions::IllegalArgumentException, decaf::lang::exceptions::RuntimeException ) { } //////////////////////////////////////////////////////////////////////////////// int Semaphore::availablePermits() const { return 0; } //////////////////////////////////////////////////////////////////////////////// int Semaphore::drainPermits() throw( decaf::lang::exceptions::RuntimeException ) { return 0; } //////////////////////////////////////////////////////////////////////////////// bool Semaphore::isFair() const { return false; } //////////////////////////////////////////////////////////////////////////////// std::string Semaphore::toString() const { return ""; } <|endoftext|>
<commit_before><commit_msg>Fix error of not calculating dose second time<commit_after><|endoftext|>
<commit_before>// // Copyright (C) 2003 Grzegorz Jaskiewicz <gj at pointblue.com.pl> // // gadupubdir.cpp // Gadu-Gadu Public directory contains people data, using it you can search friends // different criteria // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301, USA. // #include "gadupubdir.h" #include "gadueditcontact.h" #include "gaducontactlist.h" #include "gaduaccount.h" #include "gaduprotocol.h" #include <q3widgetstack.h> #include <q3listview.h> #include <q3ptrlist.h> #include <qradiobutton.h> #include <qspinbox.h> #include <qcheckbox.h> //Added by qt3to4: #include <QPixmap> #include <kcombobox.h> #include <krestrictedline.h> #include <klineedit.h> #include <k3listview.h> #include <klocale.h> GaduPublicDir::GaduPublicDir( GaduAccount* account, QWidget* parent ) : KDialog( parent ) { setButtons( KDialog::User1 | KDialog::User2 | KDialog::User3 | KDialog::Cancel ); setDefaultButton( KDialog::User2 ); mAccount = account; createWidget(); initConnections(); show(); } GaduPublicDir::GaduPublicDir( GaduAccount* account, int searchFor, QWidget* parent ) : KDialog( parent ) { setButtons( KDialog::User1 | KDialog::User2 | KDialog::User3 | KDialog::Cancel ); setDefaultButton( KDialog::User2 ); ResLine rs; mAccount = account; createWidget(); initConnections(); kDebug( 14100 ) << "search for Uin: " << searchFor << endl; mMainWidget->listFound->clear(); show(); if ( searchFor == 0 ) { return; } mMainWidget->pubsearch->raiseWidget( 1 ); mMainWidget->radioByUin->setChecked( true ); setButtonGuiItem( KDialog::User2, KGuiItem( i18n( "Search &More..." ) ) ); showButton( KDialog::User3, true ); showButton( KDialog::User1, true ); enableButton( KDialog::User3, false ); enableButton( KDialog::User2, false ); // now it is time to switch to Right Page(tm) rs.uin = searchFor; fName = fSurname = fNick = fCity = QString::null; fUin = searchFor; fGender = fAgeFrom = fAgeTo = 0; fOnlyOnline = false; mAccount->pubDirSearch( rs, fAgeFrom, fAgeTo, fOnlyOnline ); } GaduPublicDir::~GaduPublicDir() { delete mMainWidget; } void GaduPublicDir::createWidget() { setCaption( i18n( "Gadu-Gadu Public Directory" ) ); QWidget* w = new QWidget( this ); mMainWidget = new Ui::GaduPublicDirectory; mMainWidget->setupUi( this ); setMainWidget( w ); mMainWidget->UIN->setValidChars( "1234567890" ); setButtonGuiItem( KDialog::User1, KGuiItem( i18n( "&New Search" ) ) ); setButtonGuiItem( KDialog::User2, KGuiItem( i18n( "S&earch" ) ) ); setButtonGuiItem( KDialog::User3, KGuiItem( i18n( "&Add User..." ) ) ); setButtonGuiItem( KDialog::Cancel, KGuiItem( i18n( "&Close" ) ) ); showButton( KDialog::User1, false ); showButton( KDialog::User3, false ); enableButton( KDialog::User2, false ); mMainWidget->radioByData->setChecked( true ); mAccount->pubDirSearchClose(); } void GaduPublicDir::slotAddContact() { GaduContactsList::ContactLine* cl = new GaduContactsList::ContactLine; Q3ListViewItem* item = mMainWidget->listFound->currentItem(); cl->ignored = false; cl->firstname = item->text( 1 ); cl->uin = item->text( 5 ); cl->nickname = item->text( 2 ); cl->surname = fSurname; // GaduEditContact *ed = new GaduEditContact( mAccount, cl, this ); } void GaduPublicDir::slotListSelected( ) { Q3ListViewItem* item = mMainWidget->listFound->currentItem(); if ( item ) { enableButton( KDialog::User3, true ); } else { enableButton( KDialog::User3, false ); } } void GaduPublicDir::initConnections() { connect( this, SIGNAL( user2Clicked() ), SLOT( slotSearch() ) ); connect( this, SIGNAL( user1Clicked() ), SLOT( slotNewSearch() ) ); connect( this, SIGNAL( user3Clicked() ), SLOT( slotAddContact() ) ); connect( mAccount, SIGNAL( pubDirSearchResult( const SearchResult&, unsigned int ) ), SLOT( slotSearchResult( const SearchResult&, unsigned int ) ) ); connect( mMainWidget->nameS, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->surname, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->nick, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->UIN, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->cityS, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->gender, SIGNAL( activated( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->ageFrom, SIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->ageTo, SIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->radioByData, SIGNAL( toggled( bool ) ), SLOT( inputChanged( bool ) ) ); connect( mMainWidget->listFound, SIGNAL( selectionChanged () ), SLOT( slotListSelected() ) ); } void GaduPublicDir::inputChanged( bool ) { inputChanged( QString::null ); } void GaduPublicDir::inputChanged( const QString& ) { if ( validateData() == false ) { enableButton( User2, false ); } else { enableButton( User2, true ); } } void GaduPublicDir::getData() { fName = mMainWidget->nameS->text(); fSurname = mMainWidget->surname->text(); fNick = mMainWidget->nick->text(); fUin = mMainWidget->UIN->text().toInt(); fGender = mMainWidget->gender->currentItem(); fOnlyOnline = mMainWidget->onlyOnline->isChecked(); fAgeFrom = mMainWidget->ageFrom->value(); fAgeTo = mMainWidget->ageTo->value(); fCity = mMainWidget->cityS->text(); } // return true if not empty #define CHECK_STRING(A) { if ( !A.isEmpty() ) { return true; } } #define CHECK_INT(A) { if ( A ) { return true; } } bool GaduPublicDir::validateData() { getData(); if ( mMainWidget->radioByData->isChecked() ) { CHECK_STRING( fCity ); CHECK_STRING( fName ); CHECK_STRING( fSurname ); CHECK_STRING( fNick ); CHECK_INT( fGender ); CHECK_INT( fAgeFrom ); CHECK_INT( fAgeTo ); } else { fSurname = QString::null; CHECK_INT( fUin ); } return false; } // Move to GaduProtocol someday QPixmap GaduPublicDir::iconForStatus( uint status ) { QPixmap n; if ( GaduProtocol::protocol() ) { return GaduProtocol::protocol()->convertStatus( status ).protocolIcon(); } return n; } void GaduPublicDir::slotSearchResult( const SearchResult& result, unsigned int ) { Q3ListView* list = mMainWidget->listFound; kDebug(14100) << "searchResults(" << result.count() <<")" << endl; Q3ListViewItem* sl; SearchResult::const_iterator r; for ( r = result.begin(); r != result.end() ; ++r ){ kDebug(14100) << "adding" << (*r).uin << endl; sl= new Q3ListViewItem( list, QString::fromAscii(""), (*r).firstname, (*r).nickname, (*r).age, (*r).city, QString::number( (*r).uin ).toAscii() ); sl->setPixmap( 0, iconForStatus( (*r).status ) ); } // if not found anything, obviously we don't want to search for more // if we are looking just for one UIN, don't allow search more - it is pointless if ( result.count() && fUin==0 ) { enableButton( KDialog:: User2, true ); } enableButton( KDialog::User1, true ); enableButton( KDialog::User3, false ); mMainWidget->pubsearch->setDisabled( false ); } void GaduPublicDir::slotNewSearch() { mMainWidget->pubsearch->raiseWidget( 0 ); setButtonGuiItem( KDialog::User2, KGuiItem( i18n( "S&earch" ) ) ); showButton( KDialog::User1, false ); showButton( KDialog::User3, false ); enableButton( KDialog::User2, false ); inputChanged( QString() ); mAccount->pubDirSearchClose(); } void GaduPublicDir::slotSearch() { mMainWidget->listFound->clear(); QString empty; // search more, or search ? if ( mMainWidget->pubsearch->id( mMainWidget->pubsearch->visibleWidget() ) == 0 ) { kDebug(14100) << "start search... " << endl; getData(); // validate data if ( validateData() == false ) { return; } // go on mMainWidget->pubsearch->raiseWidget( 1 ); } else{ kDebug(14100) << "search more... " << endl; // Search for more } mMainWidget->pubsearch->setDisabled( true ); setButtonGuiItem( KDialog::User2, KGuiItem( i18n( "Search &More..." ) ) ); showButton( KDialog::User3, true ); showButton( KDialog::User1, true ); enableButton( KDialog::User3, false ); enableButton( KDialog::User2, false ); ResLine rs; rs.firstname = fName; rs.surname = fSurname; rs.nickname = fNick; rs.uin = fUin; rs.city = fCity; if ( fGender == 1 ) { rs.gender = GG_PUBDIR50_GENDER_MALE; } if ( fGender == 2 ) { rs.gender = GG_PUBDIR50_GENDER_FEMALE; } if ( mMainWidget->radioByData->isChecked() ) { mAccount->pubDirSearch( rs, fAgeFrom, fAgeTo, fOnlyOnline ); } else { mAccount->pubDirSearch( rs, 0, 0, fOnlyOnline ); } } #include "gadupubdir.moc" <commit_msg>replaced assignment to QString::null with QString() (should compile/work without problems, if not please e-mail me)<commit_after>// // Copyright (C) 2003 Grzegorz Jaskiewicz <gj at pointblue.com.pl> // // gadupubdir.cpp // Gadu-Gadu Public directory contains people data, using it you can search friends // different criteria // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301, USA. // #include "gadupubdir.h" #include "gadueditcontact.h" #include "gaducontactlist.h" #include "gaduaccount.h" #include "gaduprotocol.h" #include <q3widgetstack.h> #include <q3listview.h> #include <q3ptrlist.h> #include <qradiobutton.h> #include <qspinbox.h> #include <qcheckbox.h> //Added by qt3to4: #include <QPixmap> #include <kcombobox.h> #include <krestrictedline.h> #include <klineedit.h> #include <k3listview.h> #include <klocale.h> GaduPublicDir::GaduPublicDir( GaduAccount* account, QWidget* parent ) : KDialog( parent ) { setButtons( KDialog::User1 | KDialog::User2 | KDialog::User3 | KDialog::Cancel ); setDefaultButton( KDialog::User2 ); mAccount = account; createWidget(); initConnections(); show(); } GaduPublicDir::GaduPublicDir( GaduAccount* account, int searchFor, QWidget* parent ) : KDialog( parent ) { setButtons( KDialog::User1 | KDialog::User2 | KDialog::User3 | KDialog::Cancel ); setDefaultButton( KDialog::User2 ); ResLine rs; mAccount = account; createWidget(); initConnections(); kDebug( 14100 ) << "search for Uin: " << searchFor << endl; mMainWidget->listFound->clear(); show(); if ( searchFor == 0 ) { return; } mMainWidget->pubsearch->raiseWidget( 1 ); mMainWidget->radioByUin->setChecked( true ); setButtonGuiItem( KDialog::User2, KGuiItem( i18n( "Search &More..." ) ) ); showButton( KDialog::User3, true ); showButton( KDialog::User1, true ); enableButton( KDialog::User3, false ); enableButton( KDialog::User2, false ); // now it is time to switch to Right Page(tm) rs.uin = searchFor; fName = fSurname = fNick = fCity = QString(); fUin = searchFor; fGender = fAgeFrom = fAgeTo = 0; fOnlyOnline = false; mAccount->pubDirSearch( rs, fAgeFrom, fAgeTo, fOnlyOnline ); } GaduPublicDir::~GaduPublicDir() { delete mMainWidget; } void GaduPublicDir::createWidget() { setCaption( i18n( "Gadu-Gadu Public Directory" ) ); QWidget* w = new QWidget( this ); mMainWidget = new Ui::GaduPublicDirectory; mMainWidget->setupUi( this ); setMainWidget( w ); mMainWidget->UIN->setValidChars( "1234567890" ); setButtonGuiItem( KDialog::User1, KGuiItem( i18n( "&New Search" ) ) ); setButtonGuiItem( KDialog::User2, KGuiItem( i18n( "S&earch" ) ) ); setButtonGuiItem( KDialog::User3, KGuiItem( i18n( "&Add User..." ) ) ); setButtonGuiItem( KDialog::Cancel, KGuiItem( i18n( "&Close" ) ) ); showButton( KDialog::User1, false ); showButton( KDialog::User3, false ); enableButton( KDialog::User2, false ); mMainWidget->radioByData->setChecked( true ); mAccount->pubDirSearchClose(); } void GaduPublicDir::slotAddContact() { GaduContactsList::ContactLine* cl = new GaduContactsList::ContactLine; Q3ListViewItem* item = mMainWidget->listFound->currentItem(); cl->ignored = false; cl->firstname = item->text( 1 ); cl->uin = item->text( 5 ); cl->nickname = item->text( 2 ); cl->surname = fSurname; // GaduEditContact *ed = new GaduEditContact( mAccount, cl, this ); } void GaduPublicDir::slotListSelected( ) { Q3ListViewItem* item = mMainWidget->listFound->currentItem(); if ( item ) { enableButton( KDialog::User3, true ); } else { enableButton( KDialog::User3, false ); } } void GaduPublicDir::initConnections() { connect( this, SIGNAL( user2Clicked() ), SLOT( slotSearch() ) ); connect( this, SIGNAL( user1Clicked() ), SLOT( slotNewSearch() ) ); connect( this, SIGNAL( user3Clicked() ), SLOT( slotAddContact() ) ); connect( mAccount, SIGNAL( pubDirSearchResult( const SearchResult&, unsigned int ) ), SLOT( slotSearchResult( const SearchResult&, unsigned int ) ) ); connect( mMainWidget->nameS, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->surname, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->nick, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->UIN, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->cityS, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->gender, SIGNAL( activated( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->ageFrom, SIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->ageTo, SIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) ); connect( mMainWidget->radioByData, SIGNAL( toggled( bool ) ), SLOT( inputChanged( bool ) ) ); connect( mMainWidget->listFound, SIGNAL( selectionChanged () ), SLOT( slotListSelected() ) ); } void GaduPublicDir::inputChanged( bool ) { inputChanged( QString::null ); } void GaduPublicDir::inputChanged( const QString& ) { if ( validateData() == false ) { enableButton( User2, false ); } else { enableButton( User2, true ); } } void GaduPublicDir::getData() { fName = mMainWidget->nameS->text(); fSurname = mMainWidget->surname->text(); fNick = mMainWidget->nick->text(); fUin = mMainWidget->UIN->text().toInt(); fGender = mMainWidget->gender->currentItem(); fOnlyOnline = mMainWidget->onlyOnline->isChecked(); fAgeFrom = mMainWidget->ageFrom->value(); fAgeTo = mMainWidget->ageTo->value(); fCity = mMainWidget->cityS->text(); } // return true if not empty #define CHECK_STRING(A) { if ( !A.isEmpty() ) { return true; } } #define CHECK_INT(A) { if ( A ) { return true; } } bool GaduPublicDir::validateData() { getData(); if ( mMainWidget->radioByData->isChecked() ) { CHECK_STRING( fCity ); CHECK_STRING( fName ); CHECK_STRING( fSurname ); CHECK_STRING( fNick ); CHECK_INT( fGender ); CHECK_INT( fAgeFrom ); CHECK_INT( fAgeTo ); } else { fSurname = QString::null; CHECK_INT( fUin ); } return false; } // Move to GaduProtocol someday QPixmap GaduPublicDir::iconForStatus( uint status ) { QPixmap n; if ( GaduProtocol::protocol() ) { return GaduProtocol::protocol()->convertStatus( status ).protocolIcon(); } return n; } void GaduPublicDir::slotSearchResult( const SearchResult& result, unsigned int ) { Q3ListView* list = mMainWidget->listFound; kDebug(14100) << "searchResults(" << result.count() <<")" << endl; Q3ListViewItem* sl; SearchResult::const_iterator r; for ( r = result.begin(); r != result.end() ; ++r ){ kDebug(14100) << "adding" << (*r).uin << endl; sl= new Q3ListViewItem( list, QString::fromAscii(""), (*r).firstname, (*r).nickname, (*r).age, (*r).city, QString::number( (*r).uin ).toAscii() ); sl->setPixmap( 0, iconForStatus( (*r).status ) ); } // if not found anything, obviously we don't want to search for more // if we are looking just for one UIN, don't allow search more - it is pointless if ( result.count() && fUin==0 ) { enableButton( KDialog:: User2, true ); } enableButton( KDialog::User1, true ); enableButton( KDialog::User3, false ); mMainWidget->pubsearch->setDisabled( false ); } void GaduPublicDir::slotNewSearch() { mMainWidget->pubsearch->raiseWidget( 0 ); setButtonGuiItem( KDialog::User2, KGuiItem( i18n( "S&earch" ) ) ); showButton( KDialog::User1, false ); showButton( KDialog::User3, false ); enableButton( KDialog::User2, false ); inputChanged( QString() ); mAccount->pubDirSearchClose(); } void GaduPublicDir::slotSearch() { mMainWidget->listFound->clear(); QString empty; // search more, or search ? if ( mMainWidget->pubsearch->id( mMainWidget->pubsearch->visibleWidget() ) == 0 ) { kDebug(14100) << "start search... " << endl; getData(); // validate data if ( validateData() == false ) { return; } // go on mMainWidget->pubsearch->raiseWidget( 1 ); } else{ kDebug(14100) << "search more... " << endl; // Search for more } mMainWidget->pubsearch->setDisabled( true ); setButtonGuiItem( KDialog::User2, KGuiItem( i18n( "Search &More..." ) ) ); showButton( KDialog::User3, true ); showButton( KDialog::User1, true ); enableButton( KDialog::User3, false ); enableButton( KDialog::User2, false ); ResLine rs; rs.firstname = fName; rs.surname = fSurname; rs.nickname = fNick; rs.uin = fUin; rs.city = fCity; if ( fGender == 1 ) { rs.gender = GG_PUBDIR50_GENDER_MALE; } if ( fGender == 2 ) { rs.gender = GG_PUBDIR50_GENDER_FEMALE; } if ( mMainWidget->radioByData->isChecked() ) { mAccount->pubDirSearch( rs, fAgeFrom, fAgeTo, fOnlyOnline ); } else { mAccount->pubDirSearch( rs, 0, 0, fOnlyOnline ); } } #include "gadupubdir.moc" <|endoftext|>
<commit_before>//===-- Serialization.cpp - Binary serialization of index data ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Serialization.h" #include "Index.h" #include "RIFF.h" #include "llvm/Support/Compression.h" #include "llvm/Support/Endian.h" #include "llvm/Support/Error.h" using namespace llvm; namespace clang { namespace clangd { namespace { Error makeError(const Twine &Msg) { return make_error<StringError>(Msg, inconvertibleErrorCode()); } // IO PRIMITIVES // We use little-endian 32 bit ints, sometimes with variable-length encoding. // // Variable-length int encoding (varint) uses the bottom 7 bits of each byte // to encode the number, and the top bit to indicate whether more bytes follow. // e.g. 9a 2f means [0x1a and keep reading, 0x2f and stop]. // This represents 0x1a | 0x2f<<7 = 6042. // A 32-bit integer takes 1-5 bytes to encode; small numbers are more compact. // Reads binary data from a StringRef, and keeps track of position. class Reader { const char *Begin, *End; bool Err; public: Reader(StringRef Data) : Begin(Data.begin()), End(Data.end()) {} // The "error" bit is set by reading past EOF or reading invalid data. // When in an error state, reads may return zero values: callers should check. bool err() const { return Err; } // Did we read all the data, or encounter an error? bool eof() const { return Begin == End || Err; } // All the data we didn't read yet. StringRef rest() const { return StringRef(Begin, End - Begin); } uint8_t consume8() { if (LLVM_UNLIKELY(Begin == End)) { Err = true; return 0; } return *Begin++; } uint32_t consume32() { if (LLVM_UNLIKELY(Begin + 4 > End)) { Err = true; return 0; } auto Ret = support::endian::read32le(Begin); Begin += 4; return Ret; } StringRef consume(int N) { if (LLVM_UNLIKELY(Begin + N > End)) { Err = true; return StringRef(); } StringRef Ret(Begin, N); Begin += N; return Ret; } uint32_t consumeVar() { constexpr static uint8_t More = 1 << 7; uint8_t B = consume8(); if (LLVM_LIKELY(!(B & More))) return B; uint32_t Val = B & ~More; for (int Shift = 7; B & More && Shift < 32; Shift += 7) { B = consume8(); Val |= (B & ~More) << Shift; } return Val; } StringRef consumeString(ArrayRef<StringRef> Strings) { auto StringIndex = consumeVar(); if (LLVM_UNLIKELY(StringIndex >= Strings.size())) { Err = true; return StringRef(); } return Strings[StringIndex]; } SymbolID consumeID() { StringRef Raw = consume(SymbolID::RawSize); // short if truncated. return LLVM_UNLIKELY(err()) ? SymbolID() : SymbolID::fromRaw(Raw); } }; void write32(uint32_t I, raw_ostream &OS) { char buf[4]; support::endian::write32le(buf, I); OS.write(buf, sizeof(buf)); } void writeVar(uint32_t I, raw_ostream &OS) { constexpr static uint8_t More = 1 << 7; if (LLVM_LIKELY(I < 1 << 7)) { OS.write(I); return; } for (;;) { OS.write(I | More); I >>= 7; if (I < 1 << 7) { OS.write(I); return; } } } // STRING TABLE ENCODING // Index data has many string fields, and many strings are identical. // We store each string once, and refer to them by index. // // The string table's format is: // - UncompressedSize : uint32 (or 0 for no compression) // - CompressedData : byte[CompressedSize] // // CompressedData is a zlib-compressed byte[UncompressedSize]. // It contains a sequence of null-terminated strings, e.g. "foo\0bar\0". // These are sorted to improve compression. // Maps each string to a canonical representation. // Strings remain owned externally (e.g. by SymbolSlab). class StringTableOut { DenseSet<StringRef> Unique; std::vector<StringRef> Sorted; // Since strings are interned, look up can be by pointer. DenseMap<std::pair<const char *, size_t>, unsigned> Index; public: StringTableOut() { // Ensure there's at least one string in the table. // Table size zero is reserved to indicate no compression. Unique.insert(""); } // Add a string to the table. Overwrites S if an identical string exists. void intern(StringRef &S) { S = *Unique.insert(S).first; }; // Finalize the table and write it to OS. No more strings may be added. void finalize(raw_ostream &OS) { Sorted = {Unique.begin(), Unique.end()}; std::sort(Sorted.begin(), Sorted.end()); for (unsigned I = 0; I < Sorted.size(); ++I) Index.try_emplace({Sorted[I].data(), Sorted[I].size()}, I); std::string RawTable; for (StringRef S : Sorted) { RawTable.append(S); RawTable.push_back(0); } if (zlib::isAvailable()) { SmallString<1> Compressed; cantFail(zlib::compress(RawTable, Compressed)); write32(RawTable.size(), OS); OS << Compressed; } else { write32(0, OS); // No compression. OS << RawTable; } } // Get the ID of an string, which must be interned. Table must be finalized. unsigned index(StringRef S) const { assert(!Sorted.empty() && "table not finalized"); assert(Index.count({S.data(), S.size()}) && "string not interned"); return Index.find({S.data(), S.size()})->second; } }; struct StringTableIn { BumpPtrAllocator Arena; std::vector<StringRef> Strings; }; Expected<StringTableIn> readStringTable(StringRef Data) { Reader R(Data); size_t UncompressedSize = R.consume32(); if (R.err()) return makeError("Truncated string table"); StringRef Uncompressed; SmallString<1> UncompressedStorage; if (UncompressedSize == 0) // No compression Uncompressed = R.rest(); else { if (Error E = llvm::zlib::uncompress(R.rest(), UncompressedStorage, UncompressedSize)) return std::move(E); Uncompressed = UncompressedStorage; } StringTableIn Table; StringSaver Saver(Table.Arena); R = Reader(Uncompressed); for (Reader R(Uncompressed); !R.eof();) { auto Len = R.rest().find(0); if (Len == StringRef::npos) return makeError("Bad string table: not null terminated"); Table.Strings.push_back(Saver.save(R.consume(Len))); R.consume8(); } if (R.err()) return makeError("Truncated string table"); return std::move(Table); } // SYMBOL ENCODING // Each field of clangd::Symbol is encoded in turn (see implementation). // - StringRef fields encode as varint (index into the string table) // - enums encode as the underlying type // - most numbers encode as varint void writeLocation(const SymbolLocation &Loc, const StringTableOut &Strings, raw_ostream &OS) { writeVar(Strings.index(Loc.FileURI), OS); for (const auto &Endpoint : {Loc.Start, Loc.End}) { writeVar(Endpoint.Line, OS); writeVar(Endpoint.Column, OS); } } SymbolLocation readLocation(Reader &Data, ArrayRef<StringRef> Strings) { SymbolLocation Loc; Loc.FileURI = Data.consumeString(Strings); for (auto *Endpoint : {&Loc.Start, &Loc.End}) { Endpoint->Line = Data.consumeVar(); Endpoint->Column = Data.consumeVar(); } return Loc; } void writeSymbol(const Symbol &Sym, const StringTableOut &Strings, raw_ostream &OS) { OS << Sym.ID.raw(); // TODO: once we start writing xrefs and posting lists, // symbol IDs should probably be in a string table. OS.write(static_cast<uint8_t>(Sym.SymInfo.Kind)); OS.write(static_cast<uint8_t>(Sym.SymInfo.Lang)); writeVar(Strings.index(Sym.Name), OS); writeVar(Strings.index(Sym.Scope), OS); writeLocation(Sym.Definition, Strings, OS); writeLocation(Sym.CanonicalDeclaration, Strings, OS); writeVar(Sym.References, OS); OS.write(static_cast<uint8_t>(Sym.Flags)); OS.write(static_cast<uint8_t>(Sym.Origin)); writeVar(Strings.index(Sym.Signature), OS); writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS); writeVar(Strings.index(Sym.Documentation), OS); writeVar(Strings.index(Sym.ReturnType), OS); auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences &Include) { writeVar(Strings.index(Include.IncludeHeader), OS); writeVar(Include.References, OS); }; writeVar(Sym.IncludeHeaders.size(), OS); for (const auto &Include : Sym.IncludeHeaders) WriteInclude(Include); } Symbol readSymbol(Reader &Data, ArrayRef<StringRef> Strings) { Symbol Sym; Sym.ID = Data.consumeID(); Sym.SymInfo.Kind = static_cast<index::SymbolKind>(Data.consume8()); Sym.SymInfo.Lang = static_cast<index::SymbolLanguage>(Data.consume8()); Sym.Name = Data.consumeString(Strings); Sym.Scope = Data.consumeString(Strings); Sym.Definition = readLocation(Data, Strings); Sym.CanonicalDeclaration = readLocation(Data, Strings); Sym.References = Data.consumeVar(); Sym.Flags = static_cast<Symbol::SymbolFlag>(Data.consumeVar()); Sym.Origin = static_cast<SymbolOrigin>(Data.consumeVar()); Sym.Signature = Data.consumeString(Strings); Sym.CompletionSnippetSuffix = Data.consumeString(Strings); Sym.Documentation = Data.consumeString(Strings); Sym.ReturnType = Data.consumeString(Strings); Sym.IncludeHeaders.resize(Data.consumeVar()); for (auto &I : Sym.IncludeHeaders) { I.IncludeHeader = Data.consumeString(Strings); I.References = Data.consumeVar(); } return Sym; } } // namespace // FILE ENCODING // A file is a RIFF chunk with type 'CdIx'. // It contains the sections: // - meta: version number // - stri: string table // - symb: symbols // The current versioning scheme is simple - non-current versions are rejected. // If you make a breaking change, bump this version number to invalidate stored // data. Later we may want to support some backward compatibility. constexpr static uint32_t Version = 4; Expected<IndexFileIn> readIndexFile(StringRef Data) { auto RIFF = riff::readFile(Data); if (!RIFF) return RIFF.takeError(); if (RIFF->Type != riff::fourCC("CdIx")) return makeError("wrong RIFF type"); StringMap<StringRef> Chunks; for (const auto &Chunk : RIFF->Chunks) Chunks.try_emplace(StringRef(Chunk.ID.data(), Chunk.ID.size()), Chunk.Data); for (StringRef RequiredChunk : {"meta", "stri"}) if (!Chunks.count(RequiredChunk)) return makeError("missing required chunk " + RequiredChunk); Reader Meta(Chunks.lookup("meta")); if (Meta.consume32() != Version) return makeError("wrong version"); auto Strings = readStringTable(Chunks.lookup("stri")); if (!Strings) return Strings.takeError(); IndexFileIn Result; if (Chunks.count("symb")) { Reader SymbolReader(Chunks.lookup("symb")); SymbolSlab::Builder Symbols; while (!SymbolReader.eof()) Symbols.insert(readSymbol(SymbolReader, Strings->Strings)); if (SymbolReader.err()) return makeError("malformed or truncated symbol"); Result.Symbols = std::move(Symbols).build(); } return std::move(Result); } raw_ostream &operator<<(raw_ostream &OS, const IndexFileOut &Data) { assert(Data.Symbols && "An index file without symbols makes no sense!"); riff::File RIFF; RIFF.Type = riff::fourCC("CdIx"); SmallString<4> Meta; { raw_svector_ostream MetaOS(Meta); write32(Version, MetaOS); } RIFF.Chunks.push_back({riff::fourCC("meta"), Meta}); StringTableOut Strings; std::vector<Symbol> Symbols; for (const auto &Sym : *Data.Symbols) { Symbols.emplace_back(Sym); visitStrings(Symbols.back(), [&](StringRef &S) { Strings.intern(S); }); } std::string StringSection; { raw_string_ostream StringOS(StringSection); Strings.finalize(StringOS); } RIFF.Chunks.push_back({riff::fourCC("stri"), StringSection}); std::string SymbolSection; { raw_string_ostream SymbolOS(SymbolSection); for (const auto &Sym : Symbols) writeSymbol(Sym, Strings, SymbolOS); } RIFF.Chunks.push_back({riff::fourCC("symb"), SymbolSection}); return OS << RIFF; } } // namespace clangd } // namespace clang <commit_msg>[clangd] Fix uninit bool in r342888<commit_after>//===-- Serialization.cpp - Binary serialization of index data ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Serialization.h" #include "Index.h" #include "RIFF.h" #include "llvm/Support/Compression.h" #include "llvm/Support/Endian.h" #include "llvm/Support/Error.h" using namespace llvm; namespace clang { namespace clangd { namespace { Error makeError(const Twine &Msg) { return make_error<StringError>(Msg, inconvertibleErrorCode()); } // IO PRIMITIVES // We use little-endian 32 bit ints, sometimes with variable-length encoding. // // Variable-length int encoding (varint) uses the bottom 7 bits of each byte // to encode the number, and the top bit to indicate whether more bytes follow. // e.g. 9a 2f means [0x1a and keep reading, 0x2f and stop]. // This represents 0x1a | 0x2f<<7 = 6042. // A 32-bit integer takes 1-5 bytes to encode; small numbers are more compact. // Reads binary data from a StringRef, and keeps track of position. class Reader { const char *Begin, *End; bool Err = false; public: Reader(StringRef Data) : Begin(Data.begin()), End(Data.end()) {} // The "error" bit is set by reading past EOF or reading invalid data. // When in an error state, reads may return zero values: callers should check. bool err() const { return Err; } // Did we read all the data, or encounter an error? bool eof() const { return Begin == End || Err; } // All the data we didn't read yet. StringRef rest() const { return StringRef(Begin, End - Begin); } uint8_t consume8() { if (LLVM_UNLIKELY(Begin == End)) { Err = true; return 0; } return *Begin++; } uint32_t consume32() { if (LLVM_UNLIKELY(Begin + 4 > End)) { Err = true; return 0; } auto Ret = support::endian::read32le(Begin); Begin += 4; return Ret; } StringRef consume(int N) { if (LLVM_UNLIKELY(Begin + N > End)) { Err = true; return StringRef(); } StringRef Ret(Begin, N); Begin += N; return Ret; } uint32_t consumeVar() { constexpr static uint8_t More = 1 << 7; uint8_t B = consume8(); if (LLVM_LIKELY(!(B & More))) return B; uint32_t Val = B & ~More; for (int Shift = 7; B & More && Shift < 32; Shift += 7) { B = consume8(); Val |= (B & ~More) << Shift; } return Val; } StringRef consumeString(ArrayRef<StringRef> Strings) { auto StringIndex = consumeVar(); if (LLVM_UNLIKELY(StringIndex >= Strings.size())) { Err = true; return StringRef(); } return Strings[StringIndex]; } SymbolID consumeID() { StringRef Raw = consume(SymbolID::RawSize); // short if truncated. return LLVM_UNLIKELY(err()) ? SymbolID() : SymbolID::fromRaw(Raw); } }; void write32(uint32_t I, raw_ostream &OS) { char buf[4]; support::endian::write32le(buf, I); OS.write(buf, sizeof(buf)); } void writeVar(uint32_t I, raw_ostream &OS) { constexpr static uint8_t More = 1 << 7; if (LLVM_LIKELY(I < 1 << 7)) { OS.write(I); return; } for (;;) { OS.write(I | More); I >>= 7; if (I < 1 << 7) { OS.write(I); return; } } } // STRING TABLE ENCODING // Index data has many string fields, and many strings are identical. // We store each string once, and refer to them by index. // // The string table's format is: // - UncompressedSize : uint32 (or 0 for no compression) // - CompressedData : byte[CompressedSize] // // CompressedData is a zlib-compressed byte[UncompressedSize]. // It contains a sequence of null-terminated strings, e.g. "foo\0bar\0". // These are sorted to improve compression. // Maps each string to a canonical representation. // Strings remain owned externally (e.g. by SymbolSlab). class StringTableOut { DenseSet<StringRef> Unique; std::vector<StringRef> Sorted; // Since strings are interned, look up can be by pointer. DenseMap<std::pair<const char *, size_t>, unsigned> Index; public: StringTableOut() { // Ensure there's at least one string in the table. // Table size zero is reserved to indicate no compression. Unique.insert(""); } // Add a string to the table. Overwrites S if an identical string exists. void intern(StringRef &S) { S = *Unique.insert(S).first; }; // Finalize the table and write it to OS. No more strings may be added. void finalize(raw_ostream &OS) { Sorted = {Unique.begin(), Unique.end()}; std::sort(Sorted.begin(), Sorted.end()); for (unsigned I = 0; I < Sorted.size(); ++I) Index.try_emplace({Sorted[I].data(), Sorted[I].size()}, I); std::string RawTable; for (StringRef S : Sorted) { RawTable.append(S); RawTable.push_back(0); } if (zlib::isAvailable()) { SmallString<1> Compressed; cantFail(zlib::compress(RawTable, Compressed)); write32(RawTable.size(), OS); OS << Compressed; } else { write32(0, OS); // No compression. OS << RawTable; } } // Get the ID of an string, which must be interned. Table must be finalized. unsigned index(StringRef S) const { assert(!Sorted.empty() && "table not finalized"); assert(Index.count({S.data(), S.size()}) && "string not interned"); return Index.find({S.data(), S.size()})->second; } }; struct StringTableIn { BumpPtrAllocator Arena; std::vector<StringRef> Strings; }; Expected<StringTableIn> readStringTable(StringRef Data) { Reader R(Data); size_t UncompressedSize = R.consume32(); if (R.err()) return makeError("Truncated string table"); StringRef Uncompressed; SmallString<1> UncompressedStorage; if (UncompressedSize == 0) // No compression Uncompressed = R.rest(); else { if (Error E = llvm::zlib::uncompress(R.rest(), UncompressedStorage, UncompressedSize)) return std::move(E); Uncompressed = UncompressedStorage; } StringTableIn Table; StringSaver Saver(Table.Arena); R = Reader(Uncompressed); for (Reader R(Uncompressed); !R.eof();) { auto Len = R.rest().find(0); if (Len == StringRef::npos) return makeError("Bad string table: not null terminated"); Table.Strings.push_back(Saver.save(R.consume(Len))); R.consume8(); } if (R.err()) return makeError("Truncated string table"); return std::move(Table); } // SYMBOL ENCODING // Each field of clangd::Symbol is encoded in turn (see implementation). // - StringRef fields encode as varint (index into the string table) // - enums encode as the underlying type // - most numbers encode as varint void writeLocation(const SymbolLocation &Loc, const StringTableOut &Strings, raw_ostream &OS) { writeVar(Strings.index(Loc.FileURI), OS); for (const auto &Endpoint : {Loc.Start, Loc.End}) { writeVar(Endpoint.Line, OS); writeVar(Endpoint.Column, OS); } } SymbolLocation readLocation(Reader &Data, ArrayRef<StringRef> Strings) { SymbolLocation Loc; Loc.FileURI = Data.consumeString(Strings); for (auto *Endpoint : {&Loc.Start, &Loc.End}) { Endpoint->Line = Data.consumeVar(); Endpoint->Column = Data.consumeVar(); } return Loc; } void writeSymbol(const Symbol &Sym, const StringTableOut &Strings, raw_ostream &OS) { OS << Sym.ID.raw(); // TODO: once we start writing xrefs and posting lists, // symbol IDs should probably be in a string table. OS.write(static_cast<uint8_t>(Sym.SymInfo.Kind)); OS.write(static_cast<uint8_t>(Sym.SymInfo.Lang)); writeVar(Strings.index(Sym.Name), OS); writeVar(Strings.index(Sym.Scope), OS); writeLocation(Sym.Definition, Strings, OS); writeLocation(Sym.CanonicalDeclaration, Strings, OS); writeVar(Sym.References, OS); OS.write(static_cast<uint8_t>(Sym.Flags)); OS.write(static_cast<uint8_t>(Sym.Origin)); writeVar(Strings.index(Sym.Signature), OS); writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS); writeVar(Strings.index(Sym.Documentation), OS); writeVar(Strings.index(Sym.ReturnType), OS); auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences &Include) { writeVar(Strings.index(Include.IncludeHeader), OS); writeVar(Include.References, OS); }; writeVar(Sym.IncludeHeaders.size(), OS); for (const auto &Include : Sym.IncludeHeaders) WriteInclude(Include); } Symbol readSymbol(Reader &Data, ArrayRef<StringRef> Strings) { Symbol Sym; Sym.ID = Data.consumeID(); Sym.SymInfo.Kind = static_cast<index::SymbolKind>(Data.consume8()); Sym.SymInfo.Lang = static_cast<index::SymbolLanguage>(Data.consume8()); Sym.Name = Data.consumeString(Strings); Sym.Scope = Data.consumeString(Strings); Sym.Definition = readLocation(Data, Strings); Sym.CanonicalDeclaration = readLocation(Data, Strings); Sym.References = Data.consumeVar(); Sym.Flags = static_cast<Symbol::SymbolFlag>(Data.consumeVar()); Sym.Origin = static_cast<SymbolOrigin>(Data.consumeVar()); Sym.Signature = Data.consumeString(Strings); Sym.CompletionSnippetSuffix = Data.consumeString(Strings); Sym.Documentation = Data.consumeString(Strings); Sym.ReturnType = Data.consumeString(Strings); Sym.IncludeHeaders.resize(Data.consumeVar()); for (auto &I : Sym.IncludeHeaders) { I.IncludeHeader = Data.consumeString(Strings); I.References = Data.consumeVar(); } return Sym; } } // namespace // FILE ENCODING // A file is a RIFF chunk with type 'CdIx'. // It contains the sections: // - meta: version number // - stri: string table // - symb: symbols // The current versioning scheme is simple - non-current versions are rejected. // If you make a breaking change, bump this version number to invalidate stored // data. Later we may want to support some backward compatibility. constexpr static uint32_t Version = 4; Expected<IndexFileIn> readIndexFile(StringRef Data) { auto RIFF = riff::readFile(Data); if (!RIFF) return RIFF.takeError(); if (RIFF->Type != riff::fourCC("CdIx")) return makeError("wrong RIFF type"); StringMap<StringRef> Chunks; for (const auto &Chunk : RIFF->Chunks) Chunks.try_emplace(StringRef(Chunk.ID.data(), Chunk.ID.size()), Chunk.Data); for (StringRef RequiredChunk : {"meta", "stri"}) if (!Chunks.count(RequiredChunk)) return makeError("missing required chunk " + RequiredChunk); Reader Meta(Chunks.lookup("meta")); if (Meta.consume32() != Version) return makeError("wrong version"); auto Strings = readStringTable(Chunks.lookup("stri")); if (!Strings) return Strings.takeError(); IndexFileIn Result; if (Chunks.count("symb")) { Reader SymbolReader(Chunks.lookup("symb")); SymbolSlab::Builder Symbols; while (!SymbolReader.eof()) Symbols.insert(readSymbol(SymbolReader, Strings->Strings)); if (SymbolReader.err()) return makeError("malformed or truncated symbol"); Result.Symbols = std::move(Symbols).build(); } return std::move(Result); } raw_ostream &operator<<(raw_ostream &OS, const IndexFileOut &Data) { assert(Data.Symbols && "An index file without symbols makes no sense!"); riff::File RIFF; RIFF.Type = riff::fourCC("CdIx"); SmallString<4> Meta; { raw_svector_ostream MetaOS(Meta); write32(Version, MetaOS); } RIFF.Chunks.push_back({riff::fourCC("meta"), Meta}); StringTableOut Strings; std::vector<Symbol> Symbols; for (const auto &Sym : *Data.Symbols) { Symbols.emplace_back(Sym); visitStrings(Symbols.back(), [&](StringRef &S) { Strings.intern(S); }); } std::string StringSection; { raw_string_ostream StringOS(StringSection); Strings.finalize(StringOS); } RIFF.Chunks.push_back({riff::fourCC("stri"), StringSection}); std::string SymbolSection; { raw_string_ostream SymbolOS(SymbolSection); for (const auto &Sym : Symbols) writeSymbol(Sym, Strings, SymbolOS); } RIFF.Chunks.push_back({riff::fourCC("symb"), SymbolSection}); return OS << RIFF; } } // namespace clangd } // namespace clang <|endoftext|>
<commit_before>//============================================================================= //File Name: GyroBase.hpp //Description: Wrapper for a gyro-accelerometer Kalman filter (GyroFilter) //Author: FRC Team 3512, Spartatroniks //============================================================================= /* Usage: * * This class is a wrapper for a gyro-accelerometer Kalman Filter. Since this * class can't possibly know how to interface with every gyro and accelerometer * that exists, you'll instead handle your gyro/accelerometer in your own * derived class and pass in the required data from them via the pure virtual * functions. * * * To use this interface, derive from this class and override all pure * virtual member functions privately. * * Function clarifications: * * readGyroX() should return the value of the X-axis of the gyro * * readAccelY() should return the value of the Y-axis of the accelerometer * * getGyroZzero() should return the constant representing the zero point of * the Z-axis of the gyro * * getGyroLSBsPerUnit() should return the number of least significant bits * representing a change in the gyro's value of 1 degree/second. This can * be found in the data sheet for the specific gyro you're using. * * Misc. Help: * * If your accelerometer or gyro doesn't have one or more of the three * axes, don't inherit the functions related to them. Avoid calling * functions returning data for that respective axis, since it will be * garbage. */ #ifndef GYRO_BASE_HPP #define GYRO_BASE_HPP #include <Notifier.h> #include <Synchronized.h> #include "GyroFilter.hpp" class GyroBase { public: GyroBase(); virtual ~GyroBase(); // Return the internally stored values for gyro angles double getXangle(); double getYangle(); double getZangle(); // Used to reset starting angle for the respective axis void resetXangle( double newAngle ); void resetYangle( double newAngle ); void resetZangle( double newAngle ); // Return the unbiased rate of the respective axis double getXrate(); double getYrate(); double getZrate(); protected: // Return angle calculated with accelerometer data (returns degrees) double getAccelXangle(); double getAccelYangle(); double getAccelZangle(); // Return rate calculated with gyro data double getGyroXrate(); double getGyroYrate(); double getGyroZrate(); private: GyroFilter xFilter; GyroFilter yFilter; GyroFilter zFilter; // Read angle change (usually raw data) from gyro virtual int readGyroX(); virtual int readGyroY(); virtual int readGyroZ(); // Read acceleration (usually raw data) from accelerometer virtual int readAccelX(); virtual int readAccelY(); virtual int readAccelZ(); // Return zero points for gyro virtual double getGyroXzero(); virtual double getGyroYzero(); virtual double getGyroZzero(); // Return zero points for accelerometer virtual double getAccelXzero(); virtual double getAccelYzero(); virtual double getAccelZzero(); // Return sensitivity of gyro in least significant bits per degree/second virtual double getGyroLSBsPerUnit() = 0; }; #endif // GYRO_BASE_HPP <commit_msg>Added more to explanation of GyroBase::getGyroLSBsPerUnit() ; added note about GyroBase class only supporting digital gyros at this time<commit_after>//============================================================================= //File Name: GyroBase.hpp //Description: Wrapper for a gyro-accelerometer Kalman filter (GyroFilter) //Author: FRC Team 3512, Spartatroniks //============================================================================= /* Usage: * * This class is a wrapper for a gyro-accelerometer Kalman Filter. Since this * class can't possibly know how to interface with every gyro and accelerometer * that exists, you'll instead handle your gyro/accelerometer in your own * derived class and pass in the required data from them via the virtual * functions. This class is designed for use with a digital (not analog) gyro. * TODO: Support analog gyros * * * To use this interface, derive from this class and override all pure * virtual member functions privately. * * Function clarifications: * * readGyroX() should return the value of the X-axis of the gyro * * readAccelY() should return the value of the Y-axis of the accelerometer * * getGyroZzero() should return the constant representing the zero point of * the Z-axis of the gyro * * getGyroLSBsPerUnit() should return the number of least significant bits * which represent a change in the gyro's value of 1 degree/second. This * can be found in the data sheet for the specific gyro you're using. Some * data sheets may tell you that one LSB is A degrees/second, or A units * per LSB, in which case 1/A, or 1/A LSBs per unit, would be the value to * return from this function. * * Misc. Help: * * If your accelerometer or gyro doesn't have one or more of the three * axes, don't inherit the functions related to them. Avoid calling * functions returning data for that respective axis, since it will be * garbage. */ #ifndef GYRO_BASE_HPP #define GYRO_BASE_HPP #include <Notifier.h> #include <Synchronized.h> #include "GyroFilter.hpp" class GyroBase { public: GyroBase(); virtual ~GyroBase(); // Return the internally stored values for gyro angles double getXangle(); double getYangle(); double getZangle(); // Used to reset starting angle for the respective axis void resetXangle( double newAngle ); void resetYangle( double newAngle ); void resetZangle( double newAngle ); // Return the unbiased rate of the respective axis double getXrate(); double getYrate(); double getZrate(); protected: // Return angle calculated with accelerometer data (returns degrees) double getAccelXangle(); double getAccelYangle(); double getAccelZangle(); // Return rate calculated with gyro data double getGyroXrate(); double getGyroYrate(); double getGyroZrate(); private: GyroFilter xFilter; GyroFilter yFilter; GyroFilter zFilter; // Read angle change (usually raw data) from gyro virtual int readGyroX(); virtual int readGyroY(); virtual int readGyroZ(); // Read acceleration (usually raw data) from accelerometer virtual int readAccelX(); virtual int readAccelY(); virtual int readAccelZ(); // Return zero points for gyro virtual double getGyroXzero(); virtual double getGyroYzero(); virtual double getGyroZzero(); // Return zero points for accelerometer virtual double getAccelXzero(); virtual double getAccelYzero(); virtual double getAccelZzero(); // Return sensitivity of gyro in least significant bits per degree/second virtual double getGyroLSBsPerUnit() = 0; }; #endif // GYRO_BASE_HPP <|endoftext|>
<commit_before>/* RapicornSignal * Copyright (C) 2005-2006 Tim Janik * * 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. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #include "rapicornsignal.hh" namespace Rapicorn { namespace Signals { /* --- TrampolineLink --- */ TrampolineLink::~TrampolineLink() { if (next || prev) { next->prev = prev; prev->next = next; prev = next = NULL; } } /* --- SignalBase --- */ bool SignalBase::EmbeddedLink::operator== (const TrampolineLink &other) const { return false; } void SignalBase::EmbeddedLink::delete_this () { /* not deleting, because this structure is always embedded as SignalBase::start */ } } // Signals } // Rapicorn <commit_msg>RCORE: fixed disconnected TrampolineLink destruction<commit_after>/* RapicornSignal * Copyright (C) 2005-2006 Tim Janik * * 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. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #include "rapicornsignal.hh" namespace Rapicorn { namespace Signals { /* --- TrampolineLink --- */ TrampolineLink::~TrampolineLink() { if (next || prev) { // disconnect_equal_link() might have left next and prev != NULL prev = next = NULL; } } /* --- SignalBase --- */ bool SignalBase::EmbeddedLink::operator== (const TrampolineLink &other) const { return false; } void SignalBase::EmbeddedLink::delete_this () { /* not deleting, because this structure is always embedded as SignalBase::start */ } } // Signals } // Rapicorn <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "bvh_builder_twolevel.h" #include "bvh_statistics.h" #include "../builders/bvh_builder_sah.h" #include "../common/scene_line_segments.h" #include "../common/scene_triangle_mesh.h" #include "../common/scene_quad_mesh.h" #define PROFILE 0 #define MAX_OPEN_SIZE 10000 #define PROFILE_ITERATIONS 200 namespace embree { namespace isa { template<int N, typename Mesh> BVHNBuilderTwoLevel<N,Mesh>::BVHNBuilderTwoLevel (BVH* bvh, Scene* scene, const createMeshAccelTy createMeshAccel) : bvh(bvh), objects(bvh->objects), scene(scene), createMeshAccel(createMeshAccel), refs(scene->device), prims(scene->device) {} template<int N, typename Mesh> BVHNBuilderTwoLevel<N,Mesh>::~BVHNBuilderTwoLevel () { for (size_t i=0; i<builders.size(); i++) delete builders[i]; } template<int N, typename Mesh> void BVHNBuilderTwoLevel<N,Mesh>::build(size_t threadIndex, size_t threadCount) { /* delete some objects */ size_t num = scene->size(); if (num < objects.size()) { parallel_for(num, objects.size(), [&] (const range<size_t>& r) { for (size_t i=r.begin(); i<r.end(); i++) { delete builders[i]; builders[i] = nullptr; delete objects[i]; objects[i] = nullptr; } }); } /* reset memory allocator */ bvh->alloc.reset(); /* skip build for empty scene */ const size_t numPrimitives = scene->getNumPrimitives<Mesh,false>(); if (numPrimitives == 0) { prims.resize(0); bvh->set(BVH::emptyNode,empty,0); return; } double t0 = bvh->preBuild(TOSTRING(isa) "::BVH" + toString(N) + "BuilderTwoLevel"); #if PROFILE profile(2,PROFILE_ITERATIONS,numPrimitives,[&] (ProfileTimer& timer) { #endif /* resize object array if scene got larger */ if (objects.size() < num) objects.resize(num); if (builders.size() < num) builders.resize(num); if (refs.size() < num) refs.resize(num); nextRef.store(0); /* create of acceleration structures */ parallel_for(size_t(0), num, [&] (const range<size_t>& r) { for (size_t objectID=r.begin(); objectID<r.end(); objectID++) { Mesh* mesh = scene->getSafe<Mesh>(objectID); /* verify meshes got deleted properly */ if (mesh == nullptr || mesh->numTimeSteps != 1) { assert(objectID < objects.size () && objects[objectID] == nullptr); assert(objectID < builders.size() && builders[objectID] == nullptr); continue; } /* create BVH and builder for new meshes */ if (objects[objectID] == nullptr) createMeshAccel(mesh,(AccelData*&)objects[objectID],builders[objectID]); } }); /* parallel build of acceleration structures */ parallel_for(size_t(0), num, [&] (const range<size_t>& r) { for (size_t objectID=r.begin(); objectID<r.end(); objectID++) { /* ignore if no triangle mesh or not enabled */ Mesh* mesh = scene->getSafe<Mesh>(objectID); if (mesh == nullptr || !mesh->isEnabled() || mesh->numTimeSteps != 1) continue; BVH* object = objects [objectID]; assert(object); Builder* builder = builders[objectID]; assert(builder); /* build object if it got modified */ #if !PROFILE if (mesh->isModified()) #endif builder->build(0,0); /* create build primitive */ if (!object->getBounds().empty()) refs[nextRef++] = BVHNBuilderTwoLevel::BuildRef(object->getBounds(),object->root); } }); /* fast path for single geometry scenes */ if (nextRef == 1) { bvh->set(refs[0].node,LBBox3fa(refs[0].bounds()),numPrimitives); return; } /* open all large nodes */ refs.resize(nextRef); open_sequential(numPrimitives); /* fast path for small geometries */ if (refs.size() == 1) { bvh->set(refs[0].node,LBBox3fa(refs[0].bounds()),numPrimitives); return; } /* compute PrimRefs */ prims.resize(refs.size()); const PrimInfo pinfo = parallel_reduce(size_t(0), refs.size(), PrimInfo(empty), [&] (const range<size_t>& r) -> PrimInfo { PrimInfo pinfo(empty); for (size_t i=r.begin(); i<r.end(); i++) { pinfo.add(refs[i].bounds()); prims[i] = PrimRef(refs[i].bounds(),(size_t)refs[i].node); } return pinfo; }, [] (const PrimInfo& a, const PrimInfo& b) { return PrimInfo::merge(a,b); }); /* skip if all objects where empty */ if (pinfo.size() == 0) bvh->set(BVH::emptyNode,empty,0); /* otherwise build toplevel hierarchy */ else { NodeRef root; BVHBuilderBinnedSAH::build<NodeRef> (root, [&] { return bvh->alloc.threadLocal2(); }, [&] (const isa::BVHBuilderBinnedSAH::BuildRecord& current, BVHBuilderBinnedSAH::BuildRecord* children, const size_t n, FastAllocator::ThreadLocal2* alloc) -> int { AlignedNode* node = (AlignedNode*) alloc->alloc0->malloc(sizeof(AlignedNode)); node->clear(); for (size_t i=0; i<n; i++) { node->set(i,children[i].pinfo.geomBounds); children[i].parent = (size_t*)&node->child(i); } *current.parent = bvh->encodeNode(node); return 0; }, [&] (const BVHBuilderBinnedSAH::BuildRecord& current, FastAllocator::ThreadLocal2* alloc) -> int { assert(current.prims.size() == 1); *current.parent = (NodeRef) prims[current.prims.begin()].ID(); return 1; }, [&] (size_t dn) { bvh->scene->progressMonitor(0); }, prims.data(),pinfo,N,BVH::maxBuildDepthLeaf,N,1,1,1.0f,1.0f); bvh->set(root,LBBox3fa(pinfo.geomBounds),numPrimitives); } #if PROFILE }); #endif bvh->alloc.cleanup(); bvh->postBuild(t0); } template<int N, typename Mesh> void BVHNBuilderTwoLevel<N,Mesh>::deleteGeometry(size_t geomID) { if (geomID >= objects.size()) return; delete builders[geomID]; builders[geomID] = nullptr; delete objects [geomID]; objects [geomID] = nullptr; } template<int N, typename Mesh> void BVHNBuilderTwoLevel<N,Mesh>::clear() { for (size_t i=0; i<objects.size(); i++) if (objects[i]) objects[i]->clear(); for (size_t i=0; i<builders.size(); i++) if (builders[i]) builders[i]->clear(); refs.clear(); } template<int N, typename Mesh> void BVHNBuilderTwoLevel<N,Mesh>::open_sequential(size_t numPrimitives) { if (refs.size() == 0) return; size_t num = min(numPrimitives/400,size_t(MAX_OPEN_SIZE)); refs.reserve(num); #if 1 for (size_t i=0;i<refs.size();i++) { NodeRef ref = refs.back().node; if (ref.isAlignedNode()) ref.prefetch(); } #endif std::make_heap(refs.begin(),refs.end()); while (refs.size()+3 <= num) { std::pop_heap (refs.begin(),refs.end()); NodeRef ref = refs.back().node; if (ref.isLeaf()) break; refs.pop_back(); AlignedNode* node = ref.alignedNode(); for (size_t i=0; i<N; i++) { if (node->child(i) == BVH::emptyNode) continue; refs.push_back(BuildRef(node->bounds(i),node->child(i))); #if 1 NodeRef ref_pre = node->child(i); if (ref_pre.isAlignedNode()) ref_pre.prefetch(); #endif std::push_heap (refs.begin(),refs.end()); } } } #if defined(EMBREE_GEOMETRY_LINES) Builder* BVH4BuilderTwoLevelLineSegmentsSAH (void* bvh, Scene* scene, const createLineSegmentsAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<4,LineSegments>((BVH4*)bvh,scene,createMeshAccel); } #endif #if defined(EMBREE_GEOMETRY_TRIANGLES) Builder* BVH4BuilderTwoLevelTriangleMeshSAH (void* bvh, Scene* scene, const createTriangleMeshAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<4,TriangleMesh>((BVH4*)bvh,scene,createMeshAccel); } #endif #if defined(EMBREE_GEOMETRY_QUADS) Builder* BVH4BuilderTwoLevelQuadMeshSAH (void* bvh, Scene* scene, const createQuadMeshAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<4,QuadMesh>((BVH4*)bvh,scene,createMeshAccel); } #endif #if defined(EMBREE_GEOMETRY_USER) Builder* BVH4BuilderTwoLevelVirtualSAH (void* bvh, Scene* scene, const createAccelSetAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<4,AccelSet>((BVH4*)bvh,scene,createMeshAccel); } #endif #if defined(__AVX__) #if defined(EMBREE_GEOMETRY_TRIANGLES) Builder* BVH8BuilderTwoLevelTriangleMeshSAH (void* bvh, Scene* scene, const createTriangleMeshAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<8,TriangleMesh>((BVH8*)bvh,scene,createMeshAccel); } #endif #if defined(EMBREE_GEOMETRY_QUADS) Builder* BVH8BuilderTwoLevelQuadMeshSAH (void* bvh, Scene* scene, const createQuadMeshAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<8,QuadMesh>((BVH8*)bvh,scene,createMeshAccel); } #endif #if defined(EMBREE_GEOMETRY_USER) Builder* BVH8BuilderTwoLevelVirtualSAH (void* bvh, Scene* scene, const createAccelSetAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<8,AccelSet>((BVH8*)bvh,scene,createMeshAccel); } #endif #endif } } <commit_msg>small fix in twolevel builder<commit_after>// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "bvh_builder_twolevel.h" #include "bvh_statistics.h" #include "../builders/bvh_builder_sah.h" #include "../common/scene_line_segments.h" #include "../common/scene_triangle_mesh.h" #include "../common/scene_quad_mesh.h" #define PROFILE 0 #define MAX_OPEN_SIZE 10000 #define PROFILE_ITERATIONS 200 namespace embree { namespace isa { template<int N, typename Mesh> BVHNBuilderTwoLevel<N,Mesh>::BVHNBuilderTwoLevel (BVH* bvh, Scene* scene, const createMeshAccelTy createMeshAccel) : bvh(bvh), objects(bvh->objects), scene(scene), createMeshAccel(createMeshAccel), refs(scene->device), prims(scene->device) {} template<int N, typename Mesh> BVHNBuilderTwoLevel<N,Mesh>::~BVHNBuilderTwoLevel () { for (size_t i=0; i<builders.size(); i++) delete builders[i]; } template<int N, typename Mesh> void BVHNBuilderTwoLevel<N,Mesh>::build(size_t threadIndex, size_t threadCount) { /* delete some objects */ size_t num = scene->size(); if (num < objects.size()) { parallel_for(num, objects.size(), [&] (const range<size_t>& r) { for (size_t i=r.begin(); i<r.end(); i++) { delete builders[i]; builders[i] = nullptr; delete objects[i]; objects[i] = nullptr; } }); } /* reset memory allocator */ bvh->alloc.reset(); /* skip build for empty scene */ const size_t numPrimitives = scene->getNumPrimitives<Mesh,false>(); if (numPrimitives == 0) { prims.resize(0); bvh->set(BVH::emptyNode,empty,0); return; } double t0 = bvh->preBuild(TOSTRING(isa) "::BVH" + toString(N) + "BuilderTwoLevel"); #if PROFILE profile(2,PROFILE_ITERATIONS,numPrimitives,[&] (ProfileTimer& timer) { #endif /* resize object array if scene got larger */ if (objects.size() < num) objects.resize(num); if (builders.size() < num) builders.resize(num); if (refs.size() < num) refs.resize(num); nextRef.store(0); /* create of acceleration structures */ parallel_for(size_t(0), num, [&] (const range<size_t>& r) { for (size_t objectID=r.begin(); objectID<r.end(); objectID++) { Mesh* mesh = scene->getSafe<Mesh>(objectID); /* verify meshes got deleted properly */ if (mesh == nullptr || mesh->numTimeSteps != 1) { assert(objectID < objects.size () && objects[objectID] == nullptr); assert(objectID < builders.size() && builders[objectID] == nullptr); continue; } /* create BVH and builder for new meshes */ if (objects[objectID] == nullptr) createMeshAccel(mesh,(AccelData*&)objects[objectID],builders[objectID]); } }); /* parallel build of acceleration structures */ parallel_for(size_t(0), num, [&] (const range<size_t>& r) { for (size_t objectID=r.begin(); objectID<r.end(); objectID++) { /* ignore if no triangle mesh or not enabled */ Mesh* mesh = scene->getSafe<Mesh>(objectID); if (mesh == nullptr || !mesh->isEnabled() || mesh->numTimeSteps != 1) continue; BVH* object = objects [objectID]; assert(object); Builder* builder = builders[objectID]; assert(builder); /* build object if it got modified */ #if !PROFILE if (mesh->isModified()) #endif builder->build(0,0); /* create build primitive */ if (!object->getBounds().empty()) refs[nextRef++] = BVHNBuilderTwoLevel::BuildRef(object->getBounds(),object->root); } }); /* fast path for single geometry scenes */ if (nextRef == 1) { bvh->set(refs[0].node,LBBox3fa(refs[0].bounds()),numPrimitives); } else { /* open all large nodes */ refs.resize(nextRef); open_sequential(numPrimitives); /* compute PrimRefs */ prims.resize(refs.size()); const PrimInfo pinfo = parallel_reduce(size_t(0), refs.size(), PrimInfo(empty), [&] (const range<size_t>& r) -> PrimInfo { PrimInfo pinfo(empty); for (size_t i=r.begin(); i<r.end(); i++) { pinfo.add(refs[i].bounds()); prims[i] = PrimRef(refs[i].bounds(),(size_t)refs[i].node); } return pinfo; }, [] (const PrimInfo& a, const PrimInfo& b) { return PrimInfo::merge(a,b); }); /* skip if all objects where empty */ if (pinfo.size() == 0) bvh->set(BVH::emptyNode,empty,0); /* otherwise build toplevel hierarchy */ else { NodeRef root; BVHBuilderBinnedSAH::build<NodeRef> (root, [&] { return bvh->alloc.threadLocal2(); }, [&] (const isa::BVHBuilderBinnedSAH::BuildRecord& current, BVHBuilderBinnedSAH::BuildRecord* children, const size_t n, FastAllocator::ThreadLocal2* alloc) -> int { AlignedNode* node = (AlignedNode*) alloc->alloc0->malloc(sizeof(AlignedNode)); node->clear(); for (size_t i=0; i<n; i++) { node->set(i,children[i].pinfo.geomBounds); children[i].parent = (size_t*)&node->child(i); } *current.parent = bvh->encodeNode(node); return 0; }, [&] (const BVHBuilderBinnedSAH::BuildRecord& current, FastAllocator::ThreadLocal2* alloc) -> int { assert(current.prims.size() == 1); *current.parent = (NodeRef) prims[current.prims.begin()].ID(); return 1; }, [&] (size_t dn) { bvh->scene->progressMonitor(0); }, prims.data(),pinfo,N,BVH::maxBuildDepthLeaf,N,1,1,1.0f,1.0f); bvh->set(root,LBBox3fa(pinfo.geomBounds),numPrimitives); } } #if PROFILE }); #endif bvh->alloc.cleanup(); bvh->postBuild(t0); } template<int N, typename Mesh> void BVHNBuilderTwoLevel<N,Mesh>::deleteGeometry(size_t geomID) { if (geomID >= objects.size()) return; delete builders[geomID]; builders[geomID] = nullptr; delete objects [geomID]; objects [geomID] = nullptr; } template<int N, typename Mesh> void BVHNBuilderTwoLevel<N,Mesh>::clear() { for (size_t i=0; i<objects.size(); i++) if (objects[i]) objects[i]->clear(); for (size_t i=0; i<builders.size(); i++) if (builders[i]) builders[i]->clear(); refs.clear(); } template<int N, typename Mesh> void BVHNBuilderTwoLevel<N,Mesh>::open_sequential(size_t numPrimitives) { if (refs.size() == 0) return; size_t num = min(numPrimitives/400,size_t(MAX_OPEN_SIZE)); refs.reserve(num); #if 1 for (size_t i=0;i<refs.size();i++) { NodeRef ref = refs.back().node; if (ref.isAlignedNode()) ref.prefetch(); } #endif std::make_heap(refs.begin(),refs.end()); while (refs.size()+3 <= num) { std::pop_heap (refs.begin(),refs.end()); NodeRef ref = refs.back().node; if (ref.isLeaf()) break; refs.pop_back(); AlignedNode* node = ref.alignedNode(); for (size_t i=0; i<N; i++) { if (node->child(i) == BVH::emptyNode) continue; refs.push_back(BuildRef(node->bounds(i),node->child(i))); #if 1 NodeRef ref_pre = node->child(i); if (ref_pre.isAlignedNode()) ref_pre.prefetch(); #endif std::push_heap (refs.begin(),refs.end()); } } } #if defined(EMBREE_GEOMETRY_LINES) Builder* BVH4BuilderTwoLevelLineSegmentsSAH (void* bvh, Scene* scene, const createLineSegmentsAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<4,LineSegments>((BVH4*)bvh,scene,createMeshAccel); } #endif #if defined(EMBREE_GEOMETRY_TRIANGLES) Builder* BVH4BuilderTwoLevelTriangleMeshSAH (void* bvh, Scene* scene, const createTriangleMeshAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<4,TriangleMesh>((BVH4*)bvh,scene,createMeshAccel); } #endif #if defined(EMBREE_GEOMETRY_QUADS) Builder* BVH4BuilderTwoLevelQuadMeshSAH (void* bvh, Scene* scene, const createQuadMeshAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<4,QuadMesh>((BVH4*)bvh,scene,createMeshAccel); } #endif #if defined(EMBREE_GEOMETRY_USER) Builder* BVH4BuilderTwoLevelVirtualSAH (void* bvh, Scene* scene, const createAccelSetAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<4,AccelSet>((BVH4*)bvh,scene,createMeshAccel); } #endif #if defined(__AVX__) #if defined(EMBREE_GEOMETRY_TRIANGLES) Builder* BVH8BuilderTwoLevelTriangleMeshSAH (void* bvh, Scene* scene, const createTriangleMeshAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<8,TriangleMesh>((BVH8*)bvh,scene,createMeshAccel); } #endif #if defined(EMBREE_GEOMETRY_QUADS) Builder* BVH8BuilderTwoLevelQuadMeshSAH (void* bvh, Scene* scene, const createQuadMeshAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<8,QuadMesh>((BVH8*)bvh,scene,createMeshAccel); } #endif #if defined(EMBREE_GEOMETRY_USER) Builder* BVH8BuilderTwoLevelVirtualSAH (void* bvh, Scene* scene, const createAccelSetAccelTy createMeshAccel) { return new BVHNBuilderTwoLevel<8,AccelSet>((BVH8*)bvh,scene,createMeshAccel); } #endif #endif } } <|endoftext|>
<commit_before>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (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 Affero 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, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "Backup.h" #include "server_settings.h" #include "../Interface/Server.h" #include "database.h" #include "../urbackupcommon/os_functions.h" #include "server_log.h" #include "../stringtools.h" #include "ClientMain.h" #include "../urlplugin/IUrlFactory.h" #include "server_status.h" #include "server_cleanup.h" extern IUrlFactory *url_fak; namespace { class DelayedWakeup : public IThread { public: DelayedWakeup(ClientMain* client_main) : client_main(client_main) { } void operator()() { Server->wait(1000); client_main->getInternalCommandPipe()->Write("WAKEUP"); delete this; } private: ClientMain* client_main; }; } Backup::Backup(ClientMain* client_main, int clientid, std::string clientname, std::string clientsubname, LogAction log_action, bool is_file_backup, bool is_incremental, std::string server_token, std::string details, bool scheduled) : client_main(client_main), clientid(clientid), clientname(clientname), clientsubname(clientsubname), log_action(log_action), is_file_backup(is_file_backup), r_incremental(is_incremental), r_resumed(false), backup_result(false), log_backup(true), has_early_error(false), should_backoff(true), db(NULL), status_id(0), has_timeout_error(false), server_token(server_token), details(details), num_issues(0), stop_backup_running(true), scheduled(scheduled) { } void Backup::operator()() { logid = ServerLogger::getLogId(clientid); db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER); server_settings.reset(new ServerSettings(db, clientid)); ScopedFreeObjRef<ServerBackupDao*> backup_dao_free(backup_dao); backup_dao = new ServerBackupDao(db); ScopedActiveThread sat; active_thread=sat.get(); if(is_file_backup) { if(r_incremental) { if(r_resumed) { status_id = ServerStatus::startProcess(clientname, sa_resume_incr_file, details, logid, true); } else { status_id = ServerStatus::startProcess(clientname, sa_incr_file, details, logid, true); } } else { if(r_resumed) { status_id = ServerStatus::startProcess(clientname, sa_resume_full_file, details, logid, true); } else { status_id = ServerStatus::startProcess(clientname, sa_full_file, details, logid, true); } } } else { if(r_incremental) { status_id = ServerStatus::startProcess(clientname, sa_incr_image, details, logid, true); } else { status_id = ServerStatus::startProcess(clientname, sa_full_image, details, logid, true); } ServerStatus::setProcessPcDone(clientname, status_id, 0); } createDirectoryForClient(); int64 backup_starttime=Server->getTimeMS(); bool do_log = false; backup_result = doBackup(); if (stop_backup_running) { client_main->stopBackupRunning(is_file_backup); } if(!has_early_error && log_action!=LogAction_NoLogging) { ServerLogger::Log(logid, "Time taken for backing up client "+clientname+": "+PrettyPrintTime(Server->getTimeMS()-backup_starttime), LL_INFO); if(!backup_result) { ServerLogger::Log(logid, "Backup failed", LL_ERROR); } else if(num_issues==0) { ServerLogger::Log(logid, "Backup succeeded", LL_INFO); } else { ServerLogger::Log(logid, "Backup completed with issues", LL_INFO); } } if (!has_early_error) { ServerCleanupThread::updateStats(false); } if( (log_backup || log_action == LogAction_AlwaysLog) && log_action!=LogAction_NoLogging) { saveClientLogdata(is_file_backup?0:1, r_incremental?1:0, backup_result && !has_early_error, r_resumed); } ServerLogger::reset(logid); ServerStatus::stopProcess(clientname, status_id); server_settings.reset(); db=NULL; Server->getThreadPool()->execute(new DelayedWakeup(client_main)); } void Backup::setErrors(Backup& other) { should_backoff = other->shouldBackoff(); has_timeout_error = other->hasTimeoutError(); } bool Backup::createDirectoryForClient(void) { std::string backupfolder=server_settings->getSettings()->backupfolder; if(!os_create_dir(os_file_prefix(backupfolder+os_file_sep()+clientname)) && !os_directory_exists(os_file_prefix(backupfolder+os_file_sep()+clientname)) ) { Server->Log("Could not create or read directory for client \""+clientname+"\"", LL_ERROR); return false; } return true; } void Backup::saveClientLogdata(int image, int incremental, bool r_success, bool resumed) { int errors=0; int warnings=0; int infos=0; std::string logdata=ServerLogger::getLogdata(logid, errors, warnings, infos); backup_dao->saveBackupLog(clientid, errors, warnings, infos, is_file_backup?0:1, r_incremental?1:0, r_resumed?1:0, 0); backup_dao->saveBackupLogData(db->getLastInsertID(), logdata); sendLogdataMail(r_success, image, incremental, resumed, errors, warnings, infos, logdata); } void Backup::sendLogdataMail(bool r_success, int image, int incremental, bool resumed, int errors, int warnings, int infos, std::string &data) { MailServer mail_server=ClientMain::getMailServerSettings(); if(mail_server.servername.empty()) return; if(url_fak==NULL) return; std::vector<int> mailable_user_ids = backup_dao->getMailableUserIds(); for(size_t i=0;i<mailable_user_ids.size();++i) { std::string logr=getUserRights(mailable_user_ids[i], "logs"); bool has_r=false; if(logr!="all") { std::vector<std::string> toks; Tokenize(logr, toks, ","); for(size_t j=0;j<toks.size();++j) { if(watoi(toks[j])==clientid) { has_r=true; } } } else { has_r=true; } if(has_r) { ServerBackupDao::SReportSettings report_settings = backup_dao->getUserReportSettings(mailable_user_ids[i]); if(report_settings.exists) { std::string report_mail=report_settings.report_mail; int report_loglevel=report_settings.report_loglevel; int report_sendonly=report_settings.report_sendonly; if( ( ( report_loglevel==0 && infos>0 ) || ( report_loglevel<=1 && warnings>0 ) || ( report_loglevel<=2 && errors>0 ) ) && (report_sendonly==0 || ( report_sendonly==1 && !r_success ) || ( report_sendonly==2 && r_success) || ( report_sendonly==3 && !r_success && !has_timeout_error) ) ) { std::vector<std::string> to_addrs; Tokenize(report_mail, to_addrs, ",;"); std::string subj="UrBackup: "; std::string msg="UrBackup just did "; if(incremental>0) { if(resumed) { msg+="a resumed incremental "; subj+="Resumed incremental "; } else { msg+="an incremental "; subj+="Incremental "; } } else { if(resumed) { msg+="a resumed full "; subj+="Resumed full "; } else { msg+="a full "; subj+="Full "; } } if(image>0) { msg+="image "; subj+="image "; } else { msg+="file "; subj+="file "; } subj+="backup of \""+clientname+"\"\n"; msg+="backup of \""+clientname+"\".\n"; msg+="\nReport:\n"; msg+="( "+convert(infos); if(infos!=1) msg+=" infos, "; else msg+=" info, "; msg+=convert(warnings); if(warnings!=1) msg+=" warnings, "; else msg+=" warning, "; msg+=convert(errors); if(errors!=1) msg+=" errors"; else msg+=" error"; msg+=" )\n\n"; std::vector<std::string> msgs; TokenizeMail(data, msgs, "\n"); for(size_t j=0;j<msgs.size();++j) { std::string ll; if(!msgs[j].empty()) ll=msgs[j][0]; int li=watoi(ll); msgs[j].erase(0, 2); std::string tt=getuntil("-", msgs[j]); std::string m=getafter("-", msgs[j]); tt=backup_dao->formatUnixtime(watoi64(tt)).value; std::string lls="info"; if(li==1) lls="warning"; else if(li==2) lls="error"; msg+=(tt)+"("+lls+"): "+(m)+"\n"; } if(!r_success) subj+=" - failed"; else subj+=" - success"; std::string errmsg; bool b=url_fak->sendMail(mail_server, to_addrs, subj, msg, &errmsg); if(!b) { Server->Log("Sending mail failed. "+errmsg, LL_WARNING); } } } } } } std::string Backup::getUserRights(int userid, std::string domain) { if(domain!="all") { if(getUserRights(userid, "all")=="all") return "all"; } ServerBackupDao::CondString t_right = backup_dao->getUserRight(userid, domain); if(t_right.exists) { return t_right.value; } else { return "none"; } } <commit_msg>Set shouldBackoff and hasTimeoutError after SYSVOL/ESP backup fails<commit_after>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (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 Affero 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, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "Backup.h" #include "server_settings.h" #include "../Interface/Server.h" #include "database.h" #include "../urbackupcommon/os_functions.h" #include "server_log.h" #include "../stringtools.h" #include "ClientMain.h" #include "../urlplugin/IUrlFactory.h" #include "server_status.h" #include "server_cleanup.h" extern IUrlFactory *url_fak; namespace { class DelayedWakeup : public IThread { public: DelayedWakeup(ClientMain* client_main) : client_main(client_main) { } void operator()() { Server->wait(1000); client_main->getInternalCommandPipe()->Write("WAKEUP"); delete this; } private: ClientMain* client_main; }; } Backup::Backup(ClientMain* client_main, int clientid, std::string clientname, std::string clientsubname, LogAction log_action, bool is_file_backup, bool is_incremental, std::string server_token, std::string details, bool scheduled) : client_main(client_main), clientid(clientid), clientname(clientname), clientsubname(clientsubname), log_action(log_action), is_file_backup(is_file_backup), r_incremental(is_incremental), r_resumed(false), backup_result(false), log_backup(true), has_early_error(false), should_backoff(true), db(NULL), status_id(0), has_timeout_error(false), server_token(server_token), details(details), num_issues(0), stop_backup_running(true), scheduled(scheduled) { } void Backup::operator()() { logid = ServerLogger::getLogId(clientid); db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER); server_settings.reset(new ServerSettings(db, clientid)); ScopedFreeObjRef<ServerBackupDao*> backup_dao_free(backup_dao); backup_dao = new ServerBackupDao(db); ScopedActiveThread sat; active_thread=sat.get(); if(is_file_backup) { if(r_incremental) { if(r_resumed) { status_id = ServerStatus::startProcess(clientname, sa_resume_incr_file, details, logid, true); } else { status_id = ServerStatus::startProcess(clientname, sa_incr_file, details, logid, true); } } else { if(r_resumed) { status_id = ServerStatus::startProcess(clientname, sa_resume_full_file, details, logid, true); } else { status_id = ServerStatus::startProcess(clientname, sa_full_file, details, logid, true); } } } else { if(r_incremental) { status_id = ServerStatus::startProcess(clientname, sa_incr_image, details, logid, true); } else { status_id = ServerStatus::startProcess(clientname, sa_full_image, details, logid, true); } ServerStatus::setProcessPcDone(clientname, status_id, 0); } createDirectoryForClient(); int64 backup_starttime=Server->getTimeMS(); bool do_log = false; backup_result = doBackup(); if (stop_backup_running) { client_main->stopBackupRunning(is_file_backup); } if(!has_early_error && log_action!=LogAction_NoLogging) { ServerLogger::Log(logid, "Time taken for backing up client "+clientname+": "+PrettyPrintTime(Server->getTimeMS()-backup_starttime), LL_INFO); if(!backup_result) { ServerLogger::Log(logid, "Backup failed", LL_ERROR); } else if(num_issues==0) { ServerLogger::Log(logid, "Backup succeeded", LL_INFO); } else { ServerLogger::Log(logid, "Backup completed with issues", LL_INFO); } } if (!has_early_error) { ServerCleanupThread::updateStats(false); } if( (log_backup || log_action == LogAction_AlwaysLog) && log_action!=LogAction_NoLogging) { saveClientLogdata(is_file_backup?0:1, r_incremental?1:0, backup_result && !has_early_error, r_resumed); } ServerLogger::reset(logid); ServerStatus::stopProcess(clientname, status_id); server_settings.reset(); db=NULL; Server->getThreadPool()->execute(new DelayedWakeup(client_main)); } void Backup::setErrors(Backup& other) { should_backoff = other.shouldBackoff(); has_timeout_error = other.hasTimeoutError(); } bool Backup::createDirectoryForClient(void) { std::string backupfolder=server_settings->getSettings()->backupfolder; if(!os_create_dir(os_file_prefix(backupfolder+os_file_sep()+clientname)) && !os_directory_exists(os_file_prefix(backupfolder+os_file_sep()+clientname)) ) { Server->Log("Could not create or read directory for client \""+clientname+"\"", LL_ERROR); return false; } return true; } void Backup::saveClientLogdata(int image, int incremental, bool r_success, bool resumed) { int errors=0; int warnings=0; int infos=0; std::string logdata=ServerLogger::getLogdata(logid, errors, warnings, infos); backup_dao->saveBackupLog(clientid, errors, warnings, infos, is_file_backup?0:1, r_incremental?1:0, r_resumed?1:0, 0); backup_dao->saveBackupLogData(db->getLastInsertID(), logdata); sendLogdataMail(r_success, image, incremental, resumed, errors, warnings, infos, logdata); } void Backup::sendLogdataMail(bool r_success, int image, int incremental, bool resumed, int errors, int warnings, int infos, std::string &data) { MailServer mail_server=ClientMain::getMailServerSettings(); if(mail_server.servername.empty()) return; if(url_fak==NULL) return; std::vector<int> mailable_user_ids = backup_dao->getMailableUserIds(); for(size_t i=0;i<mailable_user_ids.size();++i) { std::string logr=getUserRights(mailable_user_ids[i], "logs"); bool has_r=false; if(logr!="all") { std::vector<std::string> toks; Tokenize(logr, toks, ","); for(size_t j=0;j<toks.size();++j) { if(watoi(toks[j])==clientid) { has_r=true; } } } else { has_r=true; } if(has_r) { ServerBackupDao::SReportSettings report_settings = backup_dao->getUserReportSettings(mailable_user_ids[i]); if(report_settings.exists) { std::string report_mail=report_settings.report_mail; int report_loglevel=report_settings.report_loglevel; int report_sendonly=report_settings.report_sendonly; if( ( ( report_loglevel==0 && infos>0 ) || ( report_loglevel<=1 && warnings>0 ) || ( report_loglevel<=2 && errors>0 ) ) && (report_sendonly==0 || ( report_sendonly==1 && !r_success ) || ( report_sendonly==2 && r_success) || ( report_sendonly==3 && !r_success && !has_timeout_error) ) ) { std::vector<std::string> to_addrs; Tokenize(report_mail, to_addrs, ",;"); std::string subj="UrBackup: "; std::string msg="UrBackup just did "; if(incremental>0) { if(resumed) { msg+="a resumed incremental "; subj+="Resumed incremental "; } else { msg+="an incremental "; subj+="Incremental "; } } else { if(resumed) { msg+="a resumed full "; subj+="Resumed full "; } else { msg+="a full "; subj+="Full "; } } if(image>0) { msg+="image "; subj+="image "; } else { msg+="file "; subj+="file "; } subj+="backup of \""+clientname+"\"\n"; msg+="backup of \""+clientname+"\".\n"; msg+="\nReport:\n"; msg+="( "+convert(infos); if(infos!=1) msg+=" infos, "; else msg+=" info, "; msg+=convert(warnings); if(warnings!=1) msg+=" warnings, "; else msg+=" warning, "; msg+=convert(errors); if(errors!=1) msg+=" errors"; else msg+=" error"; msg+=" )\n\n"; std::vector<std::string> msgs; TokenizeMail(data, msgs, "\n"); for(size_t j=0;j<msgs.size();++j) { std::string ll; if(!msgs[j].empty()) ll=msgs[j][0]; int li=watoi(ll); msgs[j].erase(0, 2); std::string tt=getuntil("-", msgs[j]); std::string m=getafter("-", msgs[j]); tt=backup_dao->formatUnixtime(watoi64(tt)).value; std::string lls="info"; if(li==1) lls="warning"; else if(li==2) lls="error"; msg+=(tt)+"("+lls+"): "+(m)+"\n"; } if(!r_success) subj+=" - failed"; else subj+=" - success"; std::string errmsg; bool b=url_fak->sendMail(mail_server, to_addrs, subj, msg, &errmsg); if(!b) { Server->Log("Sending mail failed. "+errmsg, LL_WARNING); } } } } } } std::string Backup::getUserRights(int userid, std::string domain) { if(domain!="all") { if(getUserRights(userid, "all")=="all") return "all"; } ServerBackupDao::CondString t_right = backup_dao->getUserRight(userid, domain); if(t_right.exists) { return t_right.value; } else { return "none"; } } <|endoftext|>
<commit_before>//_________________________________________________________________________ // Utility Class for transverse energy studies // Base class for ESD & MC analysis // - cuts for reconstruction and MonteCarlo // implementation file // //*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL) //_________________________________________________________________________ #include "AliAnalysisEtCuts.h" #include <iostream> #include "TNamed.h" using namespace std; ClassImp(AliAnalysisEtCuts); AliAnalysisEtCuts::AliAnalysisEtCuts() : TNamed() // ,fCommonEtaCut(0.5) ,fCommonClusterEnergyCut(0.15) ,fCommonTrackPtCut(0.0) ,fCommonSingleCell(1) ,fEmcalTrackDistanceCut(15.0) ,fEmcalTrackDxCut(5.0) ,fEmcalTrackDzCut(5.0) ,fPhosTrackDistanceCut(10.0) ,fPhosTrackDxCut(8.0) ,fPhosTrackDzCut(3.0) ,fPhosTrackRCut(5.0) ,fPhosBadDistanceCut(3.0) ,fGeometryPhosEtaAccCut(0.12) ,fGeometryPhosPhiAccMinCut(260.0) ,fGeometryPhosPhiAccMaxCut(320.0) ,fGeometryPhosDetectorRadius(460.0) // ,fGeometryEmcalEtaAccCut(0.7) ,fGeometryEmcalPhiAccMinCut(80.0) // rad 1.4 ,fGeometryEmcalPhiAccMaxCut(120.0) // rad 2.1 ,fGeometryEmcalDetectorRadius(440.0) // ,fReconstructedVertexXCut(0.5) ,fReconstructedVertexYCut(0.5) ,fReconstructedVertexZCut(12.0) ,fReconstructedIPxyCut(1.5) ,fReconstructedIPzCut(1.5) ,fReconstructedNTpcClustersCut(30) ,fReconstructedNItsClustersCut(3) ,fReconstructedPidCut(0.0) // ,fReconstructedPhosClusterType(-1) ,fReconstructedPhosClusterEnergyCut(0.25) ,fReconstructedPhosSingleCellEnergyCut(0.5) ,fReconstructedPhosTrackDistanceTightCut(3.0) ,fReconstructedPhosTrackDistanceMediumCut(5.0) ,fReconstructedPhosTrackDistanceLooseCut(15.0) // ,fReconstructedEmcalClusterType(1) ,fReconstructedEmcalClusterEnergyCut(0.3) // GeV ,fReconstructedEmcalSingleCellEnergyCut(0.5) ,fReconstructedEmcalTrackDistanceTightCut(5.0) ,fReconstructedEmcalTrackDistanceMediumCut(10.0) ,fReconstructedEmcalTrackDistanceLooseCut(15.0) ,fMonteCarloSingleChargedParticle(3) ,fMonteCarloNeutralParticle(0) ,fHistMakeTree(kTRUE) ,fHistMakeTreeDeposit(kFALSE) ,fHistNbinsMult(2000) ,fHistMinMult(-0.5) ,fHistMaxMult(1999.5) ,fHistNbinsTotEt(10000) ,fHistMinTotEt(0.000) ,fHistMaxTotEt(1000) ,fHistNbinsParticleEt(5000) ,fHistMinParticleEt(0) ,fHistMaxParticleEt(500) ,fHistNbinsParticlePt(200) ,fHistMinParticlePt(0) ,fHistMaxParticlePt(20) ,fPrimaryVertexCutXY(4.0) ,fPrimaryVertexCutZ(20.0) { // ctor } AliAnalysisEtCuts::~AliAnalysisEtCuts() { // dtor } void AliAnalysisEtCuts::SetPbPbDefaults() { // just increase seom histogram max values for now // enough to multiply conservative p+p defaults by a factor 100? fHistMaxMult = 20000; fHistMaxTotEt = 10000; } <commit_msg>Changing eta cut for the EMCal since we arent getting clusters on the edges anyways<commit_after>//_________________________________________________________________________ // Utility Class for transverse energy studies // Base class for ESD & MC analysis // - cuts for reconstruction and MonteCarlo // implementation file // //*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL) //_________________________________________________________________________ #include "AliAnalysisEtCuts.h" #include <iostream> #include "TNamed.h" using namespace std; ClassImp(AliAnalysisEtCuts); AliAnalysisEtCuts::AliAnalysisEtCuts() : TNamed() // ,fCommonEtaCut(0.5) ,fCommonClusterEnergyCut(0.15) ,fCommonTrackPtCut(0.0) ,fCommonSingleCell(1) ,fEmcalTrackDistanceCut(15.0) ,fEmcalTrackDxCut(5.0) ,fEmcalTrackDzCut(5.0) ,fPhosTrackDistanceCut(10.0) ,fPhosTrackDxCut(8.0) ,fPhosTrackDzCut(3.0) ,fPhosTrackRCut(5.0) ,fPhosBadDistanceCut(3.0) ,fGeometryPhosEtaAccCut(0.12) ,fGeometryPhosPhiAccMinCut(260.0) ,fGeometryPhosPhiAccMaxCut(320.0) ,fGeometryPhosDetectorRadius(460.0) // ,fGeometryEmcalEtaAccCut(0.6) ,fGeometryEmcalPhiAccMinCut(80.0) // rad 1.4 ,fGeometryEmcalPhiAccMaxCut(120.0) // rad 2.1 ,fGeometryEmcalDetectorRadius(440.0) // ,fReconstructedVertexXCut(0.5) ,fReconstructedVertexYCut(0.5) ,fReconstructedVertexZCut(12.0) ,fReconstructedIPxyCut(1.5) ,fReconstructedIPzCut(1.5) ,fReconstructedNTpcClustersCut(30) ,fReconstructedNItsClustersCut(3) ,fReconstructedPidCut(0.0) // ,fReconstructedPhosClusterType(-1) ,fReconstructedPhosClusterEnergyCut(0.25) ,fReconstructedPhosSingleCellEnergyCut(0.5) ,fReconstructedPhosTrackDistanceTightCut(3.0) ,fReconstructedPhosTrackDistanceMediumCut(5.0) ,fReconstructedPhosTrackDistanceLooseCut(15.0) // ,fReconstructedEmcalClusterType(1) ,fReconstructedEmcalClusterEnergyCut(0.3) // GeV ,fReconstructedEmcalSingleCellEnergyCut(0.5) ,fReconstructedEmcalTrackDistanceTightCut(5.0) ,fReconstructedEmcalTrackDistanceMediumCut(10.0) ,fReconstructedEmcalTrackDistanceLooseCut(15.0) ,fMonteCarloSingleChargedParticle(3) ,fMonteCarloNeutralParticle(0) ,fHistMakeTree(kTRUE) ,fHistMakeTreeDeposit(kFALSE) ,fHistNbinsMult(2000) ,fHistMinMult(-0.5) ,fHistMaxMult(1999.5) ,fHistNbinsTotEt(10000) ,fHistMinTotEt(0.000) ,fHistMaxTotEt(1000) ,fHistNbinsParticleEt(5000) ,fHistMinParticleEt(0) ,fHistMaxParticleEt(500) ,fHistNbinsParticlePt(200) ,fHistMinParticlePt(0) ,fHistMaxParticlePt(20) ,fPrimaryVertexCutXY(4.0) ,fPrimaryVertexCutZ(20.0) { // ctor } AliAnalysisEtCuts::~AliAnalysisEtCuts() { // dtor } void AliAnalysisEtCuts::SetPbPbDefaults() { // just increase seom histogram max values for now // enough to multiply conservative p+p defaults by a factor 100? fHistMaxMult = 20000; fHistMaxTotEt = 10000; } <|endoftext|>
<commit_before>/* mbed Microcontroller Library - stackheap * Copyright (C) 2009-2011 ARM Limited. All rights reserved. * * Setup a fixed single stack/heap memory model, * between the top of the RW/ZI region and the stackpointer */ #ifdef __cplusplus extern "C" { #endif #include <sys/types.h> #include <errno.h> extern void exit(int return_code); int _kill(int pid, int sig) { errno = EINVAL; return -1; } void _exit(int status) { exit(status); } int _getpid(void) { return 1; } #ifdef __cplusplus } #endif <commit_msg>Fix KL43Z GCC_ARM build<commit_after><|endoftext|>
<commit_before>//===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The LiveRangeEdit class represents changes done to a virtual register when it // is spilled or split. //===----------------------------------------------------------------------===// #define DEBUG_TYPE "regalloc" #include "llvm/CodeGen/LiveRangeEdit.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/CalcSpillWeights.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/VirtRegMap.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetInstrInfo.h" using namespace llvm; STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE"); STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE"); STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE"); void LiveRangeEdit::Delegate::anchor() { } LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg) { unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg)); if (VRM) { VRM->grow(); VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg)); } LiveInterval &LI = LIS.getOrCreateInterval(VReg); NewRegs.push_back(&LI); return LI; } bool LiveRangeEdit::checkRematerializable(VNInfo *VNI, const MachineInstr *DefMI, AliasAnalysis *aa) { assert(DefMI && "Missing instruction"); ScannedRemattable = true; if (!TII.isTriviallyReMaterializable(DefMI, aa)) return false; Remattable.insert(VNI); return true; } void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) { for (LiveInterval::vni_iterator I = getParent().vni_begin(), E = getParent().vni_end(); I != E; ++I) { VNInfo *VNI = *I; if (VNI->isUnused()) continue; MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def); if (!DefMI) continue; checkRematerializable(VNI, DefMI, aa); } ScannedRemattable = true; } bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) { if (!ScannedRemattable) scanRemattable(aa); return !Remattable.empty(); } /// allUsesAvailableAt - Return true if all registers used by OrigMI at /// OrigIdx are also available with the same value at UseIdx. bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI, SlotIndex OrigIdx, SlotIndex UseIdx) const { OrigIdx = OrigIdx.getRegSlot(true); UseIdx = UseIdx.getRegSlot(true); for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = OrigMI->getOperand(i); if (!MO.isReg() || !MO.getReg() || !MO.readsReg()) continue; // We can't remat physreg uses, unless it is a constant. if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) { if (MRI.isConstantPhysReg(MO.getReg(), *OrigMI->getParent()->getParent())) continue; return false; } LiveInterval &li = LIS.getInterval(MO.getReg()); const VNInfo *OVNI = li.getVNInfoAt(OrigIdx); if (!OVNI) continue; // Don't allow rematerialization immediately after the original def. // It would be incorrect if OrigMI redefines the register. // See PR14098. if (SlotIndex::isSameInstr(OrigIdx, UseIdx)) return false; if (OVNI != li.getVNInfoAt(UseIdx)) return false; } return true; } bool LiveRangeEdit::canRematerializeAt(Remat &RM, SlotIndex UseIdx, bool cheapAsAMove) { assert(ScannedRemattable && "Call anyRematerializable first"); // Use scanRemattable info. if (!Remattable.count(RM.ParentVNI)) return false; // No defining instruction provided. SlotIndex DefIdx; if (RM.OrigMI) DefIdx = LIS.getInstructionIndex(RM.OrigMI); else { DefIdx = RM.ParentVNI->def; RM.OrigMI = LIS.getInstructionFromIndex(DefIdx); assert(RM.OrigMI && "No defining instruction for remattable value"); } // If only cheap remats were requested, bail out early. if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove()) return false; // Verify that all used registers are available with the same values. if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx)) return false; return true; } SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg, const Remat &RM, const TargetRegisterInfo &tri, bool Late) { assert(RM.OrigMI && "Invalid remat"); TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri); Rematted.insert(RM.ParentVNI); return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late) .getRegSlot(); } void LiveRangeEdit::eraseVirtReg(unsigned Reg) { if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg)) LIS.removeInterval(Reg); } bool LiveRangeEdit::foldAsLoad(LiveInterval *LI, SmallVectorImpl<MachineInstr*> &Dead) { MachineInstr *DefMI = 0, *UseMI = 0; // Check that there is a single def and a single use. for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg), E = MRI.reg_nodbg_end(); I != E; ++I) { MachineOperand &MO = I.getOperand(); MachineInstr *MI = MO.getParent(); if (MO.isDef()) { if (DefMI && DefMI != MI) return false; if (!MI->canFoldAsLoad()) return false; DefMI = MI; } else if (!MO.isUndef()) { if (UseMI && UseMI != MI) return false; // FIXME: Targets don't know how to fold subreg uses. if (MO.getSubReg()) return false; UseMI = MI; } } if (!DefMI || !UseMI) return false; // Since we're moving the DefMI load, make sure we're not extending any live // ranges. if (!allUsesAvailableAt(DefMI, LIS.getInstructionIndex(DefMI), LIS.getInstructionIndex(UseMI))) return false; // We also need to make sure it is safe to move the load. // Assume there are stores between DefMI and UseMI. bool SawStore = true; if (!DefMI->isSafeToMove(&TII, 0, SawStore)) return false; DEBUG(dbgs() << "Try to fold single def: " << *DefMI << " into single use: " << *UseMI); SmallVector<unsigned, 8> Ops; if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second) return false; MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI); if (!FoldMI) return false; DEBUG(dbgs() << " folded: " << *FoldMI); LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI); UseMI->eraseFromParent(); DefMI->addRegisterDead(LI->reg, 0); Dead.push_back(DefMI); ++NumDCEFoldedLoads; return true; } /// Find all live intervals that need to shrink, then remove the instruction. void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) { assert(MI->allDefsAreDead() && "Def isn't really dead"); SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot(); // Never delete inline asm. if (MI->isInlineAsm()) { DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI); return; } // Use the same criteria as DeadMachineInstructionElim. bool SawStore = false; if (!MI->isSafeToMove(&TII, 0, SawStore)) { DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI); return; } DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI); // Collect virtual registers to be erased after MI is gone. SmallVector<unsigned, 8> RegsToErase; bool ReadsPhysRegs = false; // Check for live intervals that may shrink for (MachineInstr::mop_iterator MOI = MI->operands_begin(), MOE = MI->operands_end(); MOI != MOE; ++MOI) { if (!MOI->isReg()) continue; unsigned Reg = MOI->getReg(); if (!TargetRegisterInfo::isVirtualRegister(Reg)) { // Check if MI reads any unreserved physregs. if (Reg && MOI->readsReg() && !MRI.isReserved(Reg)) ReadsPhysRegs = true; else if (MOI->isDef()) { for (MCRegUnitIterator Units(Reg, MRI.getTargetRegisterInfo()); Units.isValid(); ++Units) { if (LiveInterval *LI = LIS.getCachedRegUnit(*Units)) { if (VNInfo *VNI = LI->getVNInfoAt(Idx)) LI->removeValNo(VNI); } } } continue; } LiveInterval &LI = LIS.getInterval(Reg); // Shrink read registers, unless it is likely to be expensive and // unlikely to change anything. We typically don't want to shrink the // PIC base register that has lots of uses everywhere. // Always shrink COPY uses that probably come from live range splitting. if (MI->readsVirtualRegister(Reg) && (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) || LI.killedAt(Idx))) ToShrink.insert(&LI); // Remove defined value. if (MOI->isDef()) { if (VNInfo *VNI = LI.getVNInfoAt(Idx)) { if (TheDelegate) TheDelegate->LRE_WillShrinkVirtReg(LI.reg); LI.removeValNo(VNI); if (LI.empty()) RegsToErase.push_back(Reg); } } } // Currently, we don't support DCE of physreg live ranges. If MI reads // any unreserved physregs, don't erase the instruction, but turn it into // a KILL instead. This way, the physreg live ranges don't end up // dangling. // FIXME: It would be better to have something like shrinkToUses() for // physregs. That could potentially enable more DCE and it would free up // the physreg. It would not happen often, though. if (ReadsPhysRegs) { MI->setDesc(TII.get(TargetOpcode::KILL)); // Remove all operands that aren't physregs. for (unsigned i = MI->getNumOperands(); i; --i) { const MachineOperand &MO = MI->getOperand(i-1); if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg())) continue; MI->RemoveOperand(i-1); } DEBUG(dbgs() << "Converted physregs to:\t" << *MI); } else { if (TheDelegate) TheDelegate->LRE_WillEraseInstruction(MI); LIS.RemoveMachineInstrFromMaps(MI); MI->eraseFromParent(); ++NumDCEDeleted; } // Erase any virtregs that are now empty and unused. There may be <undef> // uses around. Keep the empty live range in that case. for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) { unsigned Reg = RegsToErase[i]; if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) { ToShrink.remove(&LIS.getInterval(Reg)); eraseVirtReg(Reg); } } } void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead, ArrayRef<unsigned> RegsBeingSpilled) { ToShrinkSet ToShrink; for (;;) { // Erase all dead defs. while (!Dead.empty()) eliminateDeadDef(Dead.pop_back_val(), ToShrink); if (ToShrink.empty()) break; // Shrink just one live interval. Then delete new dead defs. LiveInterval *LI = ToShrink.back(); ToShrink.pop_back(); if (foldAsLoad(LI, Dead)) continue; if (TheDelegate) TheDelegate->LRE_WillShrinkVirtReg(LI->reg); if (!LIS.shrinkToUses(LI, &Dead)) continue; // Don't create new intervals for a register being spilled. // The new intervals would have to be spilled anyway so its not worth it. // Also they currently aren't spilled so creating them and not spilling // them results in incorrect code. bool BeingSpilled = false; for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) { if (LI->reg == RegsBeingSpilled[i]) { BeingSpilled = true; break; } } if (BeingSpilled) continue; // LI may have been separated, create new intervals. LI->RenumberValues(LIS); ConnectedVNInfoEqClasses ConEQ(LIS); unsigned NumComp = ConEQ.Classify(LI); if (NumComp <= 1) continue; ++NumFracRanges; bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg; DEBUG(dbgs() << NumComp << " components: " << *LI << '\n'); SmallVector<LiveInterval*, 8> Dups(1, LI); for (unsigned i = 1; i != NumComp; ++i) { Dups.push_back(&createFrom(LI->reg)); // If LI is an original interval that hasn't been split yet, make the new // intervals their own originals instead of referring to LI. The original // interval must contain all the split products, and LI doesn't. if (IsOriginal) VRM->setIsSplitFromReg(Dups.back()->reg, 0); if (TheDelegate) TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg); } ConEQ.Distribute(&Dups[0], MRI); DEBUG({ for (unsigned i = 0; i != NumComp; ++i) dbgs() << '\t' << *Dups[i] << '\n'; }); } } void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF, const MachineLoopInfo &Loops, const MachineBlockFrequencyInfo &MBFI) { VirtRegAuxInfo VRAI(MF, LIS, Loops, MBFI); for (iterator I = begin(), E = end(); I != E; ++I) { LiveInterval &LI = **I; if (MRI.recomputeRegClass(LI.reg, MF.getTarget())) DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to " << MRI.getRegClass(LI.reg)->getName() << '\n'); VRAI.CalculateWeightAndHint(LI); } } <commit_msg>Prevent LiveRangeEdit from deleting bundled instructions.<commit_after>//===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The LiveRangeEdit class represents changes done to a virtual register when it // is spilled or split. //===----------------------------------------------------------------------===// #define DEBUG_TYPE "regalloc" #include "llvm/CodeGen/LiveRangeEdit.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/CalcSpillWeights.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/VirtRegMap.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetInstrInfo.h" using namespace llvm; STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE"); STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE"); STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE"); void LiveRangeEdit::Delegate::anchor() { } LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg) { unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg)); if (VRM) { VRM->grow(); VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg)); } LiveInterval &LI = LIS.getOrCreateInterval(VReg); NewRegs.push_back(&LI); return LI; } bool LiveRangeEdit::checkRematerializable(VNInfo *VNI, const MachineInstr *DefMI, AliasAnalysis *aa) { assert(DefMI && "Missing instruction"); ScannedRemattable = true; if (!TII.isTriviallyReMaterializable(DefMI, aa)) return false; Remattable.insert(VNI); return true; } void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) { for (LiveInterval::vni_iterator I = getParent().vni_begin(), E = getParent().vni_end(); I != E; ++I) { VNInfo *VNI = *I; if (VNI->isUnused()) continue; MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def); if (!DefMI) continue; checkRematerializable(VNI, DefMI, aa); } ScannedRemattable = true; } bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) { if (!ScannedRemattable) scanRemattable(aa); return !Remattable.empty(); } /// allUsesAvailableAt - Return true if all registers used by OrigMI at /// OrigIdx are also available with the same value at UseIdx. bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI, SlotIndex OrigIdx, SlotIndex UseIdx) const { OrigIdx = OrigIdx.getRegSlot(true); UseIdx = UseIdx.getRegSlot(true); for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = OrigMI->getOperand(i); if (!MO.isReg() || !MO.getReg() || !MO.readsReg()) continue; // We can't remat physreg uses, unless it is a constant. if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) { if (MRI.isConstantPhysReg(MO.getReg(), *OrigMI->getParent()->getParent())) continue; return false; } LiveInterval &li = LIS.getInterval(MO.getReg()); const VNInfo *OVNI = li.getVNInfoAt(OrigIdx); if (!OVNI) continue; // Don't allow rematerialization immediately after the original def. // It would be incorrect if OrigMI redefines the register. // See PR14098. if (SlotIndex::isSameInstr(OrigIdx, UseIdx)) return false; if (OVNI != li.getVNInfoAt(UseIdx)) return false; } return true; } bool LiveRangeEdit::canRematerializeAt(Remat &RM, SlotIndex UseIdx, bool cheapAsAMove) { assert(ScannedRemattable && "Call anyRematerializable first"); // Use scanRemattable info. if (!Remattable.count(RM.ParentVNI)) return false; // No defining instruction provided. SlotIndex DefIdx; if (RM.OrigMI) DefIdx = LIS.getInstructionIndex(RM.OrigMI); else { DefIdx = RM.ParentVNI->def; RM.OrigMI = LIS.getInstructionFromIndex(DefIdx); assert(RM.OrigMI && "No defining instruction for remattable value"); } // If only cheap remats were requested, bail out early. if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove()) return false; // Verify that all used registers are available with the same values. if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx)) return false; return true; } SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg, const Remat &RM, const TargetRegisterInfo &tri, bool Late) { assert(RM.OrigMI && "Invalid remat"); TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri); Rematted.insert(RM.ParentVNI); return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late) .getRegSlot(); } void LiveRangeEdit::eraseVirtReg(unsigned Reg) { if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg)) LIS.removeInterval(Reg); } bool LiveRangeEdit::foldAsLoad(LiveInterval *LI, SmallVectorImpl<MachineInstr*> &Dead) { MachineInstr *DefMI = 0, *UseMI = 0; // Check that there is a single def and a single use. for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg), E = MRI.reg_nodbg_end(); I != E; ++I) { MachineOperand &MO = I.getOperand(); MachineInstr *MI = MO.getParent(); if (MO.isDef()) { if (DefMI && DefMI != MI) return false; if (!MI->canFoldAsLoad()) return false; DefMI = MI; } else if (!MO.isUndef()) { if (UseMI && UseMI != MI) return false; // FIXME: Targets don't know how to fold subreg uses. if (MO.getSubReg()) return false; UseMI = MI; } } if (!DefMI || !UseMI) return false; // Since we're moving the DefMI load, make sure we're not extending any live // ranges. if (!allUsesAvailableAt(DefMI, LIS.getInstructionIndex(DefMI), LIS.getInstructionIndex(UseMI))) return false; // We also need to make sure it is safe to move the load. // Assume there are stores between DefMI and UseMI. bool SawStore = true; if (!DefMI->isSafeToMove(&TII, 0, SawStore)) return false; DEBUG(dbgs() << "Try to fold single def: " << *DefMI << " into single use: " << *UseMI); SmallVector<unsigned, 8> Ops; if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second) return false; MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI); if (!FoldMI) return false; DEBUG(dbgs() << " folded: " << *FoldMI); LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI); UseMI->eraseFromParent(); DefMI->addRegisterDead(LI->reg, 0); Dead.push_back(DefMI); ++NumDCEFoldedLoads; return true; } /// Find all live intervals that need to shrink, then remove the instruction. void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) { assert(MI->allDefsAreDead() && "Def isn't really dead"); SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot(); // Never delete a bundled instruction. if (MI->isBundled()) { return; } // Never delete inline asm. if (MI->isInlineAsm()) { DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI); return; } // Use the same criteria as DeadMachineInstructionElim. bool SawStore = false; if (!MI->isSafeToMove(&TII, 0, SawStore)) { DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI); return; } DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI); // Collect virtual registers to be erased after MI is gone. SmallVector<unsigned, 8> RegsToErase; bool ReadsPhysRegs = false; // Check for live intervals that may shrink for (MachineInstr::mop_iterator MOI = MI->operands_begin(), MOE = MI->operands_end(); MOI != MOE; ++MOI) { if (!MOI->isReg()) continue; unsigned Reg = MOI->getReg(); if (!TargetRegisterInfo::isVirtualRegister(Reg)) { // Check if MI reads any unreserved physregs. if (Reg && MOI->readsReg() && !MRI.isReserved(Reg)) ReadsPhysRegs = true; else if (MOI->isDef()) { for (MCRegUnitIterator Units(Reg, MRI.getTargetRegisterInfo()); Units.isValid(); ++Units) { if (LiveInterval *LI = LIS.getCachedRegUnit(*Units)) { if (VNInfo *VNI = LI->getVNInfoAt(Idx)) LI->removeValNo(VNI); } } } continue; } LiveInterval &LI = LIS.getInterval(Reg); // Shrink read registers, unless it is likely to be expensive and // unlikely to change anything. We typically don't want to shrink the // PIC base register that has lots of uses everywhere. // Always shrink COPY uses that probably come from live range splitting. if (MI->readsVirtualRegister(Reg) && (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) || LI.killedAt(Idx))) ToShrink.insert(&LI); // Remove defined value. if (MOI->isDef()) { if (VNInfo *VNI = LI.getVNInfoAt(Idx)) { if (TheDelegate) TheDelegate->LRE_WillShrinkVirtReg(LI.reg); LI.removeValNo(VNI); if (LI.empty()) RegsToErase.push_back(Reg); } } } // Currently, we don't support DCE of physreg live ranges. If MI reads // any unreserved physregs, don't erase the instruction, but turn it into // a KILL instead. This way, the physreg live ranges don't end up // dangling. // FIXME: It would be better to have something like shrinkToUses() for // physregs. That could potentially enable more DCE and it would free up // the physreg. It would not happen often, though. if (ReadsPhysRegs) { MI->setDesc(TII.get(TargetOpcode::KILL)); // Remove all operands that aren't physregs. for (unsigned i = MI->getNumOperands(); i; --i) { const MachineOperand &MO = MI->getOperand(i-1); if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg())) continue; MI->RemoveOperand(i-1); } DEBUG(dbgs() << "Converted physregs to:\t" << *MI); } else { if (TheDelegate) TheDelegate->LRE_WillEraseInstruction(MI); LIS.RemoveMachineInstrFromMaps(MI); MI->eraseFromParent(); ++NumDCEDeleted; } // Erase any virtregs that are now empty and unused. There may be <undef> // uses around. Keep the empty live range in that case. for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) { unsigned Reg = RegsToErase[i]; if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) { ToShrink.remove(&LIS.getInterval(Reg)); eraseVirtReg(Reg); } } } void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead, ArrayRef<unsigned> RegsBeingSpilled) { ToShrinkSet ToShrink; for (;;) { // Erase all dead defs. while (!Dead.empty()) eliminateDeadDef(Dead.pop_back_val(), ToShrink); if (ToShrink.empty()) break; // Shrink just one live interval. Then delete new dead defs. LiveInterval *LI = ToShrink.back(); ToShrink.pop_back(); if (foldAsLoad(LI, Dead)) continue; if (TheDelegate) TheDelegate->LRE_WillShrinkVirtReg(LI->reg); if (!LIS.shrinkToUses(LI, &Dead)) continue; // Don't create new intervals for a register being spilled. // The new intervals would have to be spilled anyway so its not worth it. // Also they currently aren't spilled so creating them and not spilling // them results in incorrect code. bool BeingSpilled = false; for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) { if (LI->reg == RegsBeingSpilled[i]) { BeingSpilled = true; break; } } if (BeingSpilled) continue; // LI may have been separated, create new intervals. LI->RenumberValues(LIS); ConnectedVNInfoEqClasses ConEQ(LIS); unsigned NumComp = ConEQ.Classify(LI); if (NumComp <= 1) continue; ++NumFracRanges; bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg; DEBUG(dbgs() << NumComp << " components: " << *LI << '\n'); SmallVector<LiveInterval*, 8> Dups(1, LI); for (unsigned i = 1; i != NumComp; ++i) { Dups.push_back(&createFrom(LI->reg)); // If LI is an original interval that hasn't been split yet, make the new // intervals their own originals instead of referring to LI. The original // interval must contain all the split products, and LI doesn't. if (IsOriginal) VRM->setIsSplitFromReg(Dups.back()->reg, 0); if (TheDelegate) TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg); } ConEQ.Distribute(&Dups[0], MRI); DEBUG({ for (unsigned i = 0; i != NumComp; ++i) dbgs() << '\t' << *Dups[i] << '\n'; }); } } void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF, const MachineLoopInfo &Loops, const MachineBlockFrequencyInfo &MBFI) { VirtRegAuxInfo VRAI(MF, LIS, Loops, MBFI); for (iterator I = begin(), E = end(); I != E; ++I) { LiveInterval &LI = **I; if (MRI.recomputeRegClass(LI.reg, MF.getTarget())) DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to " << MRI.getRegClass(LI.reg)->getName() << '\n'); VRAI.CalculateWeightAndHint(LI); } } <|endoftext|>
<commit_before>// Copyright (c) 2014, 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. // // This file implements the "bridge" between Java and C++ and enables // calling c++ rocksdb::Iterator methods from Java side. #include <stdio.h> #include <stdlib.h> #include <jni.h> #include "include/org_rocksdb_TransactionLogIterator.h" #include "rocksdb/transaction_log.h" #include "rocksjni/portal.h" /* * Class: org_rocksdb_TransactionLogIterator * Method: disposeInternal * Signature: (J)V */ void Java_org_rocksdb_TransactionLogIterator_disposeInternal( JNIEnv* env, jobject jobj, jlong handle) { auto* it = reinterpret_cast<rocksdb::TransactionLogIterator*>(handle); delete it; } /* * Class: org_rocksdb_TransactionLogIterator * Method: isValid * Signature: (J)Z */ jboolean Java_org_rocksdb_TransactionLogIterator_isValid( JNIEnv* env, jobject jobj, jlong handle) { return reinterpret_cast<rocksdb::TransactionLogIterator*>(handle)->Valid(); } /* * Class: org_rocksdb_TransactionLogIterator * Method: next * Signature: (J)V */ void Java_org_rocksdb_TransactionLogIterator_next( JNIEnv* env, jobject jobj, jlong handle) { reinterpret_cast<rocksdb::TransactionLogIterator*>(handle)->Next(); } /* * Class: org_rocksdb_TransactionLogIterator * Method: status * Signature: (J)V */ void Java_org_rocksdb_TransactionLogIterator_status( JNIEnv* env, jobject jobj, jlong handle) { rocksdb::Status s = reinterpret_cast< rocksdb::TransactionLogIterator*>(handle)->status(); if (!s.ok()) { rocksdb::RocksDBExceptionJni::ThrowNew(env, s); } } /* * Class: org_rocksdb_TransactionLogIterator * Method: getBatch * Signature: (J)Lorg/rocksdb/TransactionLogIterator$BatchResult */ jobject Java_org_rocksdb_TransactionLogIterator_getBatch( JNIEnv* env, jobject jobj, jlong handle) { rocksdb::BatchResult batch_result = reinterpret_cast<rocksdb::TransactionLogIterator*>(handle)->GetBatch(); jclass jclazz = env->FindClass( "org/rocksdb/TransactionLogIterator$BatchResult"); assert(jclazz != nullptr); jmethodID mid = env->GetMethodID( jclazz, "<init>", "(Lorg/rocksdb/TransactionLogIterator;JJ)V"); assert(mid != nullptr); return env->NewObject(jclazz, mid, jobj, batch_result.sequence, batch_result.writeBatchPtr.release()); } <commit_msg>[RocksJava] GetUpdatesSince support<commit_after>// Copyright (c) 2014, 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. // // This file implements the "bridge" between Java and C++ and enables // calling c++ rocksdb::Iterator methods from Java side. #include <jni.h> #include <stdio.h> #include <stdlib.h> #include "include/org_rocksdb_TransactionLogIterator.h" #include "rocksdb/transaction_log.h" #include "rocksjni/portal.h" /* * Class: org_rocksdb_TransactionLogIterator * Method: disposeInternal * Signature: (J)V */ void Java_org_rocksdb_TransactionLogIterator_disposeInternal( JNIEnv* env, jobject jobj, jlong handle) { auto* it = reinterpret_cast<rocksdb::TransactionLogIterator*>(handle); delete it; } /* * Class: org_rocksdb_TransactionLogIterator * Method: isValid * Signature: (J)Z */ jboolean Java_org_rocksdb_TransactionLogIterator_isValid( JNIEnv* env, jobject jobj, jlong handle) { return reinterpret_cast<rocksdb::TransactionLogIterator*>(handle)->Valid(); } /* * Class: org_rocksdb_TransactionLogIterator * Method: next * Signature: (J)V */ void Java_org_rocksdb_TransactionLogIterator_next( JNIEnv* env, jobject jobj, jlong handle) { reinterpret_cast<rocksdb::TransactionLogIterator*>(handle)->Next(); } /* * Class: org_rocksdb_TransactionLogIterator * Method: status * Signature: (J)V */ void Java_org_rocksdb_TransactionLogIterator_status( JNIEnv* env, jobject jobj, jlong handle) { rocksdb::Status s = reinterpret_cast< rocksdb::TransactionLogIterator*>(handle)->status(); if (!s.ok()) { rocksdb::RocksDBExceptionJni::ThrowNew(env, s); } } /* * Class: org_rocksdb_TransactionLogIterator * Method: getBatch * Signature: (J)Lorg/rocksdb/TransactionLogIterator$BatchResult */ jobject Java_org_rocksdb_TransactionLogIterator_getBatch( JNIEnv* env, jobject jobj, jlong handle) { rocksdb::BatchResult batch_result = reinterpret_cast<rocksdb::TransactionLogIterator*>(handle)->GetBatch(); jclass jclazz = env->FindClass( "org/rocksdb/TransactionLogIterator$BatchResult"); assert(jclazz != nullptr); jmethodID mid = env->GetMethodID( jclazz, "<init>", "(Lorg/rocksdb/TransactionLogIterator;JJ)V"); assert(mid != nullptr); return env->NewObject(jclazz, mid, jobj, batch_result.sequence, batch_result.writeBatchPtr.release()); } <|endoftext|>
<commit_before><commit_msg>vtk_dump solution<commit_after><|endoftext|>
<commit_before><commit_msg>Backport r851236 by tmcguire from trunk to the 4.1 branch:<commit_after><|endoftext|>
<commit_before>#include "coreplugin.h" #include "applicationextension.h" #include "engineextension.h" #include "componentextension.h" #include "contextextension.h" #include <QApplication> #include <QQmlEngine> #include <QQmlComponent> #include <QQmlContext> Q_DECLARE_METATYPE(const QMetaObject*) namespace RubyQml { CorePlugin::CorePlugin(QObject *parent) : QObject(parent) { qRegisterMetaType<ApplicationExtension *>(); qRegisterMetaType<EngineExtension *>(); qRegisterMetaType<ComponentExtension *>(); qRegisterMetaType<ContextExtension *>(); qRegisterMetaType<QApplication *>(); qRegisterMetaType<QCoreApplication *>(); qRegisterMetaType<QQmlEngine *>(); qRegisterMetaType<QQmlComponent *>(); qRegisterMetaType<QQmlContext *>(); const QMetaObject *metaObjects[] = { &staticQtMetaObject, &QApplication::staticMetaObject, &QQmlEngine::staticMetaObject, &QQmlComponent::staticMetaObject, &QQmlContext::staticMetaObject}; for (auto metaobj : metaObjects) { mMetaObjects[metaobj->className()] = QVariant::fromValue(metaobj); } } QApplication *CorePlugin::applicationInstance() { return qApp; } QApplication *CorePlugin::createApplication(const QVariantList &args) { static bool created = false; static QList<QByteArray> staticArgs; static int argc; static char **argv; if (created) { throw std::logic_error("Application already created"); } argc = args.size(); argv = new char*[argc]; std::transform(args.begin(), args.end(), std::back_inserter(staticArgs), [](const QVariant &arg) { return arg.toString().toUtf8(); }); std::transform(staticArgs.begin(), staticArgs.end(), argv, [](QByteArray &ba) { return ba.data(); }); auto app = new QApplication(argc, argv); created = true; return app; } QQmlEngine *CorePlugin::createEngine() { return new QQmlEngine(); } QQmlComponent *CorePlugin::createComponent(QQmlEngine *e) { return new QQmlComponent(e); } QQmlContext *CorePlugin::createContext(QQmlEngine *engine) { return new QQmlContext(engine); } ApplicationExtension *CorePlugin::createApplicationExtension(QApplication *app) { return new ApplicationExtension(app); } EngineExtension *CorePlugin::createEngineExtension(QQmlEngine *engine) { return new EngineExtension(engine); } ComponentExtension *CorePlugin::createComponentExtension(QQmlComponent *component) { return new ComponentExtension(component); } ContextExtension *CorePlugin::createContextExtension(QQmlContext *context) { return new ContextExtension(context); } QQmlContext *CorePlugin::contextForObject(QObject *object) { return QQmlEngine::contextForObject(object); } } // namespace RubyQml <commit_msg>Add #include <stdexcept> to coreplugin.cpp<commit_after>#include "coreplugin.h" #include "applicationextension.h" #include "engineextension.h" #include "componentextension.h" #include "contextextension.h" #include <QApplication> #include <QQmlEngine> #include <QQmlComponent> #include <QQmlContext> #include <stdexcept> Q_DECLARE_METATYPE(const QMetaObject*) namespace RubyQml { CorePlugin::CorePlugin(QObject *parent) : QObject(parent) { qRegisterMetaType<ApplicationExtension *>(); qRegisterMetaType<EngineExtension *>(); qRegisterMetaType<ComponentExtension *>(); qRegisterMetaType<ContextExtension *>(); qRegisterMetaType<QApplication *>(); qRegisterMetaType<QCoreApplication *>(); qRegisterMetaType<QQmlEngine *>(); qRegisterMetaType<QQmlComponent *>(); qRegisterMetaType<QQmlContext *>(); const QMetaObject *metaObjects[] = { &staticQtMetaObject, &QApplication::staticMetaObject, &QQmlEngine::staticMetaObject, &QQmlComponent::staticMetaObject, &QQmlContext::staticMetaObject}; for (auto metaobj : metaObjects) { mMetaObjects[metaobj->className()] = QVariant::fromValue(metaobj); } } QApplication *CorePlugin::applicationInstance() { return qApp; } QApplication *CorePlugin::createApplication(const QVariantList &args) { static bool created = false; static QList<QByteArray> staticArgs; static int argc; static char **argv; if (created) { throw std::logic_error("Application already created"); } argc = args.size(); argv = new char*[argc]; std::transform(args.begin(), args.end(), std::back_inserter(staticArgs), [](const QVariant &arg) { return arg.toString().toUtf8(); }); std::transform(staticArgs.begin(), staticArgs.end(), argv, [](QByteArray &ba) { return ba.data(); }); auto app = new QApplication(argc, argv); created = true; return app; } QQmlEngine *CorePlugin::createEngine() { return new QQmlEngine(); } QQmlComponent *CorePlugin::createComponent(QQmlEngine *e) { return new QQmlComponent(e); } QQmlContext *CorePlugin::createContext(QQmlEngine *engine) { return new QQmlContext(engine); } ApplicationExtension *CorePlugin::createApplicationExtension(QApplication *app) { return new ApplicationExtension(app); } EngineExtension *CorePlugin::createEngineExtension(QQmlEngine *engine) { return new EngineExtension(engine); } ComponentExtension *CorePlugin::createComponentExtension(QQmlComponent *component) { return new ComponentExtension(component); } ContextExtension *CorePlugin::createContextExtension(QQmlContext *context) { return new ContextExtension(context); } QQmlContext *CorePlugin::contextForObject(QObject *object) { return QQmlEngine::contextForObject(object); } } // namespace RubyQml <|endoftext|>
<commit_before>// Scott Wiedemann // 05/13/2013 // evenfib.cpp // Largest prime factor #include <stdio.h> #include <stdlib.h> #include <math.h> using namespace std; int main(int argc, char **argv) { if (argc!=2) { printf("Usage: %s [long to factor]\n", argv[0]); return 1; } long toFactor = atol(argv[1]); long k = 2; while(k < toFactor) { if(toFactor % k == 0) { toFactor = toFactor / k--; } k++; } printf("Largest prime: %ld\n", toFactor); return 0; } <commit_msg>typo.<commit_after>// Scott Wiedemann // 05/13/2013 // largeprimefactor.cpp // Largest prime factor #include <stdio.h> #include <stdlib.h> #include <math.h> using namespace std; int main(int argc, char **argv) { if (argc!=2) { printf("Usage: %s [long to factor]\n", argv[0]); return 1; } long toFactor = atol(argv[1]); long k = 2; while(k < toFactor) { if(toFactor % k == 0) { toFactor = toFactor / k--; } k++; } printf("Largest prime: %ld\n", toFactor); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: Triangle.cc Language: C++ Date: $Date$ Version: $Revision$ Description: --------------------------------------------------------------------------- This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "Triangle.hh" #include "Polygon.hh" #include "Plane.hh" #include "vlMath.hh" #include "CellArr.hh" #include "Line.hh" int vlTriangle::EvaluatePosition(float x[3], int& subId, float pcoords[3], float& dist2, float weights[MAX_CELL_SIZE]) { int i, j; vlPolygon poly; float *pt1, *pt2, *pt3, n[3], xProj[3]; float rhs[2], c1[2], c2[2]; float closestPoint[3], det; vlPlane plane; vlMath math; float maxComponent; int idx, indices[2]; subId = 0; pcoords[0] = pcoords[1] = pcoords[2] = 0.0; // // Get normal for triangle // pt1 = this->Points.GetPoint(1); pt2 = this->Points.GetPoint(2); pt3 = this->Points.GetPoint(0); poly.ComputeNormal (pt1, pt2, pt3, n); // // Project point to plane // plane.ProjectPoint(x,pt1,n,xProj); // // Construct matrices. Since we have over determined system, need to find // which 2 out of 3 equations to use to develop equations. (Any 2 should // work since we've projected point to plane.) // for (maxComponent=0.0, i=0; i<3; i++) { if (n[i] > maxComponent) { maxComponent = n[i]; idx = i; } } for (j=0, i=0; i<3; i++) { if ( i != idx ) indices[j++] = i; } for (i=0; i<2; i++) { rhs[i] = x[indices[i]] - pt3[indices[i]]; c1[i] = pt1[indices[i]] - pt3[indices[i]]; c2[i] = pt2[indices[i]] - pt3[indices[i]]; } if ( (det = math.Determinate2x2(c1,c2)) == 0.0 ) return 0; pcoords[0] = math.Determinate2x2 (rhs,c2) / det; pcoords[1] = math.Determinate2x2 (c1,rhs) / det; pcoords[2] = 1.0 - pcoords[0] - pcoords[1]; // // Okay, now find closest point to element // if ( pcoords[0] >= 0.0 && pcoords[1] <= 1.0 && pcoords[1] >= 0.0 && pcoords[1] <= 1.0 && pcoords[2] >= 0.0 && pcoords[2] <= 1.0 ) { dist2 = math.Distance2BetweenPoints(xProj,x); //projection distance weights[0] = pcoords[2]; weights[1] = pcoords[0]; weights[2] = pcoords[1]; return 1; } else { for (i=0; i<2; i++) { if (pcoords[i] < 0.0) pcoords[i] = 0.0; if (pcoords[i] > 1.0) pcoords[i] = 1.0; } this->EvaluateLocation(subId, pcoords, closestPoint, weights); dist2 = math.Distance2BetweenPoints(closestPoint,x); return 0; } } void vlTriangle::EvaluateLocation(int& subId, float pcoords[3], float x[3], float weights[MAX_CELL_SIZE]) { float u3; float *pt1, *pt2, *pt3; int i; pt1 = this->Points.GetPoint(1); pt2 = this->Points.GetPoint(2); pt3 = this->Points.GetPoint(0); u3 = 1.0 - pcoords[0] - pcoords[1]; for (i=0; i<3; i++) { x[i] = pt1[i]*pcoords[0] + pt2[i]*pcoords[1] + pt3[i]*u3; } weights[0] = u3; weights[1] = pcoords[0]; weights[2] = pcoords[1]; } // // Marching triangles // typedef int EDGE_LIST; typedef struct { EDGE_LIST edges[3]; } LINE_CASES; static LINE_CASES lineCases[] = { {-1, -1, -1}, {0, 2, -1}, {1, 0, -1}, {1, 2, -1}, {2, 1, -1}, {0, 1, -1}, {2, 0, -1}, {-1, -1, -1} }; void vlTriangle::Contour(float value, vlFloatScalars *cellScalars, vlFloatPoints *points, vlCellArray *verts, vlCellArray *lines, vlCellArray *polys, vlFloatScalars *scalars) { static int CASE_MASK[3] = {1,2,4}; LINE_CASES *lineCase; EDGE_LIST *edge; int i, j, index, *vert; static int edges[3][2] = { {0,1}, {1,2}, {2,0} }; int pts[2]; float t, *x1, *x2, x[3]; // Build the case table for ( i=0, index = 0; i < 3; i++) if (cellScalars->GetScalar(i) >= value) index |= CASE_MASK[i]; lineCase = lineCases + index; edge = lineCase->edges; for ( ; edge[0] > -1; edge += 2 ) { for (i=0; i<2; i++) // insert line { vert = edges[edge[i]]; t = (value - cellScalars->GetScalar(vert[0])) / (cellScalars->GetScalar(vert[1]) - cellScalars->GetScalar(vert[0])); x1 = this->Points.GetPoint(vert[0]); x2 = this->Points.GetPoint(vert[1]); for (j=0; j<3; j++) x[j] = x1[j] + t * (x2[j] - x1[j]); pts[i] = points->InsertNextPoint(x); scalars->InsertNextScalar(value); } lines->InsertNextCell(2,pts); } } vlCell *vlTriangle::GetEdge(int edgeId) { static vlLine line; // load point id's line.PointIds.SetId(0,this->PointIds.GetId(edgeId)); line.PointIds.SetId(1,this->PointIds.GetId((edgeId+1) % 3)); // load coordinates line.Points.SetPoint(0,this->Points.GetPoint(edgeId)); line.Points.SetPoint(1,this->Points.GetPoint((edgeId+1) % 3)); return &line; } <commit_msg>ERR:Fixed bug in pcoords.<commit_after>/*========================================================================= Program: Visualization Library Module: Triangle.cc Language: C++ Date: $Date$ Version: $Revision$ Description: --------------------------------------------------------------------------- This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "Triangle.hh" #include "Polygon.hh" #include "Plane.hh" #include "vlMath.hh" #include "CellArr.hh" #include "Line.hh" int vlTriangle::EvaluatePosition(float x[3], int& subId, float pcoords[3], float& dist2, float weights[MAX_CELL_SIZE]) { int i, j; vlPolygon poly; float *pt1, *pt2, *pt3, n[3], xProj[3]; float rhs[2], c1[2], c2[2]; float closestPoint[3], det; vlPlane plane; vlMath math; float maxComponent; int idx, indices[2]; subId = 0; pcoords[0] = pcoords[1] = pcoords[2] = 0.0; // // Get normal for triangle // pt1 = this->Points.GetPoint(1); pt2 = this->Points.GetPoint(2); pt3 = this->Points.GetPoint(0); poly.ComputeNormal (pt1, pt2, pt3, n); // // Project point to plane // plane.ProjectPoint(x,pt1,n,xProj); // // Construct matrices. Since we have over determined system, need to find // which 2 out of 3 equations to use to develop equations. (Any 2 should // work since we've projected point to plane.) // for (maxComponent=0.0, i=0; i<3; i++) { if (n[i] > maxComponent) { maxComponent = n[i]; idx = i; } } for (j=0, i=0; i<3; i++) { if ( i != idx ) indices[j++] = i; } for (i=0; i<2; i++) { rhs[i] = x[indices[i]] - pt3[indices[i]]; c1[i] = pt1[indices[i]] - pt3[indices[i]]; c2[i] = pt2[indices[i]] - pt3[indices[i]]; } if ( (det = math.Determinate2x2(c1,c2)) == 0.0 ) return 0; pcoords[0] = math.Determinate2x2 (rhs,c2) / det; pcoords[1] = math.Determinate2x2 (c1,rhs) / det; pcoords[2] = 1.0 - pcoords[0] - pcoords[1]; // // Okay, now find closest point to element // if ( pcoords[0] >= 0.0 && pcoords[1] <= 1.0 && pcoords[1] >= 0.0 && pcoords[1] <= 1.0 && pcoords[2] >= 0.0 && pcoords[2] <= 1.0 ) { dist2 = math.Distance2BetweenPoints(xProj,x); //projection distance weights[0] = pcoords[2]; weights[1] = pcoords[0]; weights[2] = pcoords[1]; return 1; } else { for (i=0; i<2; i++) { if (pcoords[i] < 0.0) pcoords[i] = 0.0; if (pcoords[i] > 1.0) pcoords[i] = 1.0; } if ( (1.0 - pcoords[0] - pcoords[1]) < 0.0 ) { float ratio = pcoords[0]/pcoords[1]; pcoords[1] = 1.0 / (1.0 + ratio); pcoords[0] = ratio * pcoords[1]; } this->EvaluateLocation(subId, pcoords, closestPoint, weights); dist2 = math.Distance2BetweenPoints(closestPoint,x); return 0; } } void vlTriangle::EvaluateLocation(int& subId, float pcoords[3], float x[3], float weights[MAX_CELL_SIZE]) { float u3; float *pt1, *pt2, *pt3; int i; pt1 = this->Points.GetPoint(1); pt2 = this->Points.GetPoint(2); pt3 = this->Points.GetPoint(0); u3 = 1.0 - pcoords[0] - pcoords[1]; for (i=0; i<3; i++) { x[i] = pt1[i]*pcoords[0] + pt2[i]*pcoords[1] + pt3[i]*u3; } weights[0] = u3; weights[1] = pcoords[0]; weights[2] = pcoords[1]; } // // Marching triangles // typedef int EDGE_LIST; typedef struct { EDGE_LIST edges[3]; } LINE_CASES; static LINE_CASES lineCases[] = { {-1, -1, -1}, {0, 2, -1}, {1, 0, -1}, {1, 2, -1}, {2, 1, -1}, {0, 1, -1}, {2, 0, -1}, {-1, -1, -1} }; void vlTriangle::Contour(float value, vlFloatScalars *cellScalars, vlFloatPoints *points, vlCellArray *verts, vlCellArray *lines, vlCellArray *polys, vlFloatScalars *scalars) { static int CASE_MASK[3] = {1,2,4}; LINE_CASES *lineCase; EDGE_LIST *edge; int i, j, index, *vert; static int edges[3][2] = { {0,1}, {1,2}, {2,0} }; int pts[2]; float t, *x1, *x2, x[3]; // Build the case table for ( i=0, index = 0; i < 3; i++) if (cellScalars->GetScalar(i) >= value) index |= CASE_MASK[i]; lineCase = lineCases + index; edge = lineCase->edges; for ( ; edge[0] > -1; edge += 2 ) { for (i=0; i<2; i++) // insert line { vert = edges[edge[i]]; t = (value - cellScalars->GetScalar(vert[0])) / (cellScalars->GetScalar(vert[1]) - cellScalars->GetScalar(vert[0])); x1 = this->Points.GetPoint(vert[0]); x2 = this->Points.GetPoint(vert[1]); for (j=0; j<3; j++) x[j] = x1[j] + t * (x2[j] - x1[j]); pts[i] = points->InsertNextPoint(x); scalars->InsertNextScalar(value); } lines->InsertNextCell(2,pts); } } vlCell *vlTriangle::GetEdge(int edgeId) { static vlLine line; // load point id's line.PointIds.SetId(0,this->PointIds.GetId(edgeId)); line.PointIds.SetId(1,this->PointIds.GetId((edgeId+1) % 3)); // load coordinates line.Points.SetPoint(0,this->Points.GetPoint(edgeId)); line.Points.SetPoint(1,this->Points.GetPoint((edgeId+1) % 3)); return &line; } <|endoftext|>
<commit_before>#include <vector> #include <boost/filesystem.hpp> #include <bitcoin/bitcoin.hpp> #include <obelisk/zmq_message.hpp> #include "config.hpp" #define HEARTBEAT_LIVENESS 3 // 3-5 is reasonable #define HEARTBEAT_INTERVAL 1000 // msecs #define LOG_BALANCER "balancer" using namespace bc; using namespace obelisk; typedef data_chunk worker_uuid; static void s_version_assert(int want_major, int want_minor) { int major, minor, patch; zmq_version (&major, &minor, &patch); if (major < want_major || (major == want_major && minor < want_minor)) { std::cout << "Current 0MQ version is " << major << "." << minor << std::endl; std::cout << "Application needs at least " << want_major << "." << want_minor << " - cannot continue" << std::endl; exit (EXIT_FAILURE); } } // Return current system clock as milliseconds static int64_t s_clock(void) { #if (defined (__WINDOWS__)) SYSTEMTIME st; GetSystemTime (&st); return (int64_t) st.wSecond * 1000 + st.wMilliseconds; #else struct timeval tv; gettimeofday (&tv, NULL); return (int64_t) (tv.tv_sec * 1000 + tv.tv_usec / 1000); #endif } // This defines one active worker in our worker queue typedef struct { worker_uuid identity; // Address of worker int64_t expiry; // Expires at this time } worker_t; // Insert worker at end of queue, reset expiry // Worker must not already be in queue void s_worker_append(std::vector<worker_t>& queue, const worker_uuid& identity) { bool found = false; for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { std::cout << "E: duplicate worker identity " << identity << std::endl; found = true; break; } } if (!found) { worker_t worker; worker.identity = identity; worker.expiry = s_clock() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS; queue.push_back(worker); } } // Remove worker from queue, if present void s_worker_delete(std::vector<worker_t>& queue, const worker_uuid& identity) { for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { it = queue.erase(it); break; } } } // Reset worker expiry, worker must be present void s_worker_refresh(std::vector<worker_t>& queue, const worker_uuid& identity) { bool found = false; for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { it->expiry = s_clock() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS; found = true; break; } } if (!found) { std::cout << "E: worker " << identity << " not ready" << std::endl; } } // Pop next available worker off queue, return identity const worker_uuid s_worker_dequeue(std::vector<worker_t>& queue) { assert(queue.size()); const worker_uuid identity = queue[0].identity; queue.erase(queue.begin()); return identity; } // Look for & kill expired workers void s_queue_purge(std::vector<worker_t>& queue) { int64_t clock = s_clock(); for (auto it = queue.begin(); it < queue.end(); ++it) { if (clock > it->expiry) { it = queue.erase(it) - 1; } } } typedef std::vector<worker_t> worker_queue; void forward_request(zmq::socket_t& frontend, zmq::socket_t& backend, worker_queue& queue) { // Get client request. zmq_message msg_in; msg_in.recv(frontend); const data_stack& in_parts = msg_in.parts(); if (in_parts.size() != 6) { log_warning(LOG_BALANCER) << "Wrong sized message"; return; } // First item is client's identity. if (in_parts[0].size() != 17) { log_warning(LOG_BALANCER) << "Client UUID malformed"; return; } // Second item is worker identity or nothing. if (in_parts[1].size() > 255) { log_warning(LOG_BALANCER) << "Worker UUID malformed"; return; } // We now deconstruct the request message to the backend // which looks like: // [CLIENT UUID] // [WORKER UUID] // ... // And create a new message that looks like: // [WORKER UUID] // [CLIENT UUID] // ... // Before sending it to the worker. // This is so the client can specify a worker to send their // request specifically to. zmq_message msg_out; // If second frame is nothing, then we select a random worker. if (in_parts[1].empty()) { // Route to next worker worker_uuid worker_identity = s_worker_dequeue(queue); msg_out.append(worker_identity); } else { // Route to client's preferred worker. msg_out.append(in_parts[1]); } msg_out.append(in_parts[0]); // Copy the remaining data. for (auto it = in_parts.begin() + 2; it != in_parts.end(); ++it) msg_out.append(*it); msg_out.send(backend); } void handle_control_message(const data_stack& in_parts, worker_queue& queue, const worker_uuid& identity) { std::string command(in_parts[1].begin(), in_parts[1].end()); log_info(LOG_BALANCER) << "command: " << command; if (command == "READY") { s_worker_delete(queue, identity); s_worker_append(queue, identity); } else if (command == "HEARTBEAT") { s_worker_refresh(queue, identity); } else log_error(LOG_BALANCER) << "Invalid command from " << identity; } void passback_response(zmq::socket_t& backend, zmq::socket_t& frontend, worker_queue& queue) { zmq_message msg_in; msg_in.recv(backend); const data_stack& in_parts = msg_in.parts(); BITCOIN_ASSERT(in_parts.size() == 2 || in_parts.size() == 6); worker_uuid identity = in_parts[0]; // Return reply to client if it's not a control message if (in_parts.size() == 2) return handle_control_message(in_parts, queue, identity); // We now deconstruct the request message to the frontend // which looks like: // [WORKER UUID] // [CLIENT UUID] // ... // And create a new message that looks like: // [CLIENT UUID] // [WORKER UUID] // ... // Before sending it to the backend. // This is so the client will know which worker // responded to their request. BITCOIN_ASSERT(in_parts.size() == 6); zmq_message msg_out; BITCOIN_ASSERT(in_parts[1].size() == 17); msg_out.append(in_parts[1]); BITCOIN_ASSERT(in_parts[0].size() > 0 && in_parts[0].size() < 256); msg_out.append(in_parts[0]); for (auto it = in_parts.begin() + 2; it != in_parts.end(); ++it) msg_out.append(*it); BITCOIN_ASSERT(in_parts.size() == msg_out.parts().size()); msg_out.send(frontend); // Add worker back to available pool of workers. s_worker_append(queue, identity); } int main(int argc, char** argv) { s_version_assert(2, 1); config_map_type config; if (argc == 2) { std::cout << "Using config file: " << argv[1] << std::endl; load_config(config, argv[1]); } else { using boost::filesystem::path; path conf_filename = path(SYSCONFDIR) / "obelisk" / "balancer.cfg"; load_config(config, conf_filename.native()); } // Prepare our context and sockets zmq::context_t context(1); zmq::socket_t frontend(context, ZMQ_ROUTER); zmq::socket_t backend(context, ZMQ_ROUTER); // For clients frontend.bind(config["frontend"].c_str()); // For workers backend.bind(config["backend"].c_str()); // Queue of available workers worker_queue queue; // Send out heartbeats at regular intervals int64_t heartbeat_at = s_clock() + HEARTBEAT_INTERVAL; while (1) { zmq::pollitem_t items[] = { { backend, 0, ZMQ_POLLIN, 0 }, { frontend, 0, ZMQ_POLLIN, 0 } }; // Poll frontend only if we have available workers if (queue.size()) zmq::poll(items, 2, HEARTBEAT_INTERVAL * 1000); else zmq::poll(items, 1, HEARTBEAT_INTERVAL * 1000); // Handle worker activity on backend if (items [0].revents & ZMQ_POLLIN) passback_response(backend, frontend, queue); if (items [1].revents & ZMQ_POLLIN) forward_request(frontend, backend, queue); // Send heartbeats to idle workers if it's time if (s_clock() > heartbeat_at) { for (auto it = queue.begin(); it < queue.end(); ++it) { zmq_message msg; msg.append(it->identity); std::string command = "HEARTBEAT"; msg.append(data_chunk(command.begin(), command.end())); msg.send(backend); } heartbeat_at = s_clock() + HEARTBEAT_INTERVAL; } s_queue_purge(queue); } // We never exit the main loop // But pretend to do the right shutdown anyhow queue.clear(); return 0; } <commit_msg>recent ZMQ versions change the UUID size from 17 to 5 bytes.<commit_after>#include <vector> #include <boost/filesystem.hpp> #include <bitcoin/bitcoin.hpp> #include <obelisk/zmq_message.hpp> #include "config.hpp" #define HEARTBEAT_LIVENESS 3 // 3-5 is reasonable #define HEARTBEAT_INTERVAL 1000 // msecs #define LOG_BALANCER "balancer" #if ZMQ_VERSION_MAJOR == 4 constexpr size_t zmq_uuid_size = 5; #else constexpr size_t zmq_uuid_size = 17; #endif using namespace bc; using namespace obelisk; typedef data_chunk worker_uuid; static void s_version_assert(int want_major, int want_minor) { int major, minor, patch; zmq_version (&major, &minor, &patch); if (major < want_major || (major == want_major && minor < want_minor)) { std::cout << "Current 0MQ version is " << major << "." << minor << std::endl; std::cout << "Application needs at least " << want_major << "." << want_minor << " - cannot continue" << std::endl; exit (EXIT_FAILURE); } } // Return current system clock as milliseconds static int64_t s_clock(void) { #if (defined (__WINDOWS__)) SYSTEMTIME st; GetSystemTime (&st); return (int64_t) st.wSecond * 1000 + st.wMilliseconds; #else struct timeval tv; gettimeofday (&tv, NULL); return (int64_t) (tv.tv_sec * 1000 + tv.tv_usec / 1000); #endif } // This defines one active worker in our worker queue typedef struct { worker_uuid identity; // Address of worker int64_t expiry; // Expires at this time } worker_t; // Insert worker at end of queue, reset expiry // Worker must not already be in queue void s_worker_append(std::vector<worker_t>& queue, const worker_uuid& identity) { bool found = false; for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { std::cout << "E: duplicate worker identity " << identity << std::endl; found = true; break; } } if (!found) { worker_t worker; worker.identity = identity; worker.expiry = s_clock() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS; queue.push_back(worker); } } // Remove worker from queue, if present void s_worker_delete(std::vector<worker_t>& queue, const worker_uuid& identity) { for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { it = queue.erase(it); break; } } } // Reset worker expiry, worker must be present void s_worker_refresh(std::vector<worker_t>& queue, const worker_uuid& identity) { bool found = false; for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { it->expiry = s_clock() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS; found = true; break; } } if (!found) { std::cout << "E: worker " << identity << " not ready" << std::endl; } } // Pop next available worker off queue, return identity const worker_uuid s_worker_dequeue(std::vector<worker_t>& queue) { assert(queue.size()); const worker_uuid identity = queue[0].identity; queue.erase(queue.begin()); return identity; } // Look for & kill expired workers void s_queue_purge(std::vector<worker_t>& queue) { int64_t clock = s_clock(); for (auto it = queue.begin(); it < queue.end(); ++it) { if (clock > it->expiry) { it = queue.erase(it) - 1; } } } typedef std::vector<worker_t> worker_queue; void forward_request(zmq::socket_t& frontend, zmq::socket_t& backend, worker_queue& queue) { // Get client request. zmq_message msg_in; msg_in.recv(frontend); const data_stack& in_parts = msg_in.parts(); if (in_parts.size() != 6) { log_warning(LOG_BALANCER) << "Wrong sized message"; return; } // First item is client's identity. if (in_parts[0].size() != zmq_uuid_size) { log_warning(LOG_BALANCER) << "Client UUID malformed " << in_parts[0]; return; } // Second item is worker identity or nothing. if (in_parts[1].size() > 255) { log_warning(LOG_BALANCER) << "Worker UUID malformed"; return; } // We now deconstruct the request message to the backend // which looks like: // [CLIENT UUID] // [WORKER UUID] // ... // And create a new message that looks like: // [WORKER UUID] // [CLIENT UUID] // ... // Before sending it to the worker. // This is so the client can specify a worker to send their // request specifically to. zmq_message msg_out; // If second frame is nothing, then we select a random worker. if (in_parts[1].empty()) { // Route to next worker worker_uuid worker_identity = s_worker_dequeue(queue); msg_out.append(worker_identity); } else { // Route to client's preferred worker. msg_out.append(in_parts[1]); } msg_out.append(in_parts[0]); // Copy the remaining data. for (auto it = in_parts.begin() + 2; it != in_parts.end(); ++it) msg_out.append(*it); msg_out.send(backend); } void handle_control_message(const data_stack& in_parts, worker_queue& queue, const worker_uuid& identity) { std::string command(in_parts[1].begin(), in_parts[1].end()); log_info(LOG_BALANCER) << "command: " << command; if (command == "READY") { s_worker_delete(queue, identity); s_worker_append(queue, identity); } else if (command == "HEARTBEAT") { s_worker_refresh(queue, identity); } else log_error(LOG_BALANCER) << "Invalid command from " << identity; } void passback_response(zmq::socket_t& backend, zmq::socket_t& frontend, worker_queue& queue) { zmq_message msg_in; msg_in.recv(backend); const data_stack& in_parts = msg_in.parts(); BITCOIN_ASSERT(in_parts.size() == 2 || in_parts.size() == 6); worker_uuid identity = in_parts[0]; // Return reply to client if it's not a control message if (in_parts.size() == 2) return handle_control_message(in_parts, queue, identity); // We now deconstruct the request message to the frontend // which looks like: // [WORKER UUID] // [CLIENT UUID] // ... // And create a new message that looks like: // [CLIENT UUID] // [WORKER UUID] // ... // Before sending it to the backend. // This is so the client will know which worker // responded to their request. BITCOIN_ASSERT(in_parts.size() == 6); zmq_message msg_out; BITCOIN_ASSERT(in_parts[1].size() == zmq_uuid_size); msg_out.append(in_parts[1]); BITCOIN_ASSERT(in_parts[0].size() > 0 && in_parts[0].size() < 256); msg_out.append(in_parts[0]); for (auto it = in_parts.begin() + 2; it != in_parts.end(); ++it) msg_out.append(*it); BITCOIN_ASSERT(in_parts.size() == msg_out.parts().size()); msg_out.send(frontend); // Add worker back to available pool of workers. s_worker_append(queue, identity); } int main(int argc, char** argv) { s_version_assert(2, 1); config_map_type config; if (argc == 2) { std::cout << "Using config file: " << argv[1] << std::endl; load_config(config, argv[1]); } else { using boost::filesystem::path; path conf_filename = path(SYSCONFDIR) / "obelisk" / "balancer.cfg"; load_config(config, conf_filename.native()); } // Prepare our context and sockets zmq::context_t context(1); zmq::socket_t frontend(context, ZMQ_ROUTER); zmq::socket_t backend(context, ZMQ_ROUTER); // For clients frontend.bind(config["frontend"].c_str()); // For workers backend.bind(config["backend"].c_str()); // Queue of available workers worker_queue queue; // Send out heartbeats at regular intervals int64_t heartbeat_at = s_clock() + HEARTBEAT_INTERVAL; while (1) { zmq::pollitem_t items[] = { { backend, 0, ZMQ_POLLIN, 0 }, { frontend, 0, ZMQ_POLLIN, 0 } }; // Poll frontend only if we have available workers if (queue.size()) zmq::poll(items, 2, HEARTBEAT_INTERVAL * 1000); else zmq::poll(items, 1, HEARTBEAT_INTERVAL * 1000); // Handle worker activity on backend if (items [0].revents & ZMQ_POLLIN) passback_response(backend, frontend, queue); if (items [1].revents & ZMQ_POLLIN) forward_request(frontend, backend, queue); // Send heartbeats to idle workers if it's time if (s_clock() > heartbeat_at) { for (auto it = queue.begin(); it < queue.end(); ++it) { zmq_message msg; msg.append(it->identity); std::string command = "HEARTBEAT"; msg.append(data_chunk(command.begin(), command.end())); msg.send(backend); } heartbeat_at = s_clock() + HEARTBEAT_INTERVAL; } s_queue_purge(queue); } // We never exit the main loop // But pretend to do the right shutdown anyhow queue.clear(); return 0; } <|endoftext|>
<commit_before>#include "CWTableView.h" using namespace cocos2d; using namespace cocos2d::ui; namespace cw { TableView::TableView() : _vordering(VerticalFillOrder::BOTTOM_UP) , _isUsedCellsDirty(false) , _delegate(nullptr) { } TableView::~TableView() { } TableView *TableView::create() { TableView *table = new (std::nothrow) TableView(); if (table != nullptr && table->init()) { table->autorelease(); return table; } CC_SAFE_DELETE(table); return NULL; } bool TableView::init() { if (!ScrollView::init()) { return false; } _cellsPositions.clear(); _cellsUsed.clear(); _cellsFreed.clear(); _indices.clear(); _vordering = VerticalFillOrder::BOTTOM_UP; this->setDirection(Direction::VERTICAL); return true; } void TableView::onSizeChanged() { Size orginSize = _innerContainer->getContentSize(); Vec2 orginPos = _innerContainer->getPosition(); ScrollView::onSizeChanged(); if (orginSize.equals(_innerContainer->getContentSize())) { _innerContainer->setPosition(orginPos); } } void TableView::setVerticalFillOrder(VerticalFillOrder fillOrder) { if (_vordering != fillOrder) { _vordering = fillOrder; if (!_cellsUsed.empty()) { this->reloadData(); } } } TableView::VerticalFillOrder TableView::getVerticalFillOrder() { return _vordering; } void TableView::setDirection(Direction dir) { switch (_direction) { case Direction::NONE: case Direction::HORIZONTAL: case Direction::VERTICAL: _direction = dir; break; case Direction::BOTH: CCAssert(0, "TableView doesn't support both diretion!"); break; default: CCAssert(0, "Unknown diretion!"); break; } } void TableView::reloadData() { for (const auto &cell : _cellsUsed) { _delegate->tableCellWillRecycle(this, cell); _cellsFreed.pushBack(cell); cell->reset(); if (cell->getParent() == _innerContainer) { _innerContainer->removeChild(cell, true); } } _indices.clear(); _cellsUsed.clear(); ssize_t cellsCount = _delegate->numberOfCellsInTableView(this); this->_updateCellPositions(cellsCount); this->_updateContentSize(cellsCount); if (cellsCount > 0) { _scrollViewDidScroll(cellsCount); this->processScrollingEvent(); } } void TableView::reloadDataInplacement() { Vec2 pos = getInnerContainerPosition(); const Vec2 offset1 = minContainerOffset(); for (const auto &cell : _cellsUsed) { _delegate->tableCellWillRecycle(this, cell); _cellsFreed.pushBack(cell); cell->reset(); if (cell->getParent() == _innerContainer) { _innerContainer->removeChild(cell, true); } } _indices.clear(); _cellsUsed.clear(); ssize_t cellsCount = _delegate->numberOfCellsInTableView(this); this->_updateCellPositions(cellsCount); this->_updateContentSize(cellsCount); const Vec2 offset2 = minContainerOffset(); if (_direction == Direction::HORIZONTAL) { pos.x = std::max(pos.x, offset2.x); setInnerContainerPosition(pos); } else { if (_vordering == VerticalFillOrder::BOTTOM_UP) { pos.y = std::max(pos.y, offset2.y); setInnerContainerPosition(pos); } else { float temp = offset1.y - pos.y; pos.y = offset2.y - temp; pos.y = std::min(pos.y, 0.0f); setInnerContainerPosition(pos); } } if (cellsCount > 0) { _scrollViewDidScroll(cellsCount); this->processScrollingEvent(); } } TableViewCell *TableView::cellAtIndex(ssize_t idx) { if (_indices.find(idx) != _indices.end()) { for (const auto &cell : _cellsUsed) { if (cell->getIdx() == idx) { return cell; } } } return nullptr; } void TableView::updateCellAtIndex(ssize_t idx) { if (idx == CC_INVALID_INDEX) { return; } ssize_t countOfItems = _delegate->numberOfCellsInTableView(this); if (0 == countOfItems || idx > countOfItems-1) { return; } TableViewCell *cell = this->cellAtIndex(idx); if (cell != nullptr) { this->_moveCellOutOfSight(cell); } cell = _delegate->tableCellAtIndex(this, idx); this->_setIndexForCell(idx, cell); this->_addCellIfNecessary(cell); } void TableView::insertCellAtIndex(ssize_t idx) { if (idx == CC_INVALID_INDEX) { return; } ssize_t countOfItems = _delegate->numberOfCellsInTableView(this); if (0 == countOfItems || idx > countOfItems-1) { return; } long newIdx = 0; auto cell = cellAtIndex(idx); if (cell != nullptr) { newIdx = _cellsUsed.getIndex(cell); // Move all cells behind the inserted position for (ssize_t i = newIdx; i < _cellsUsed.size(); ++i) { cell = _cellsUsed.at(i); this->_setIndexForCell(cell->getIdx()+1, cell); } } //insert a new cell cell = _delegate->tableCellAtIndex(this, idx); this->_setIndexForCell(idx, cell); this->_addCellIfNecessary(cell); this->_updateCellPositions(countOfItems); this->_updateContentSize(countOfItems); if (countOfItems > 0) { _scrollViewDidScroll(countOfItems); this->processScrollingEvent(); } } void TableView::removeCellAtIndex(ssize_t idx) { if (idx == CC_INVALID_INDEX) { return; } ssize_t countOfItems = _delegate->numberOfCellsInTableView(this); if (0 == countOfItems || idx + 1 > countOfItems) { return; } TableViewCell* cell = this->cellAtIndex(idx); if (cell == nullptr) { return; } ssize_t newIdx = _cellsUsed.getIndex(cell); //remove first this->_moveCellOutOfSight(cell); _indices.erase(idx); this->_updateCellPositions(countOfItems); this->_updateContentSize(countOfItems); for (ssize_t i = _cellsUsed.size() - 1; i > newIdx; --i) { cell = _cellsUsed.at(i); this->_setIndexForCell(cell->getIdx() - 1, cell); } if (countOfItems > 0) { _scrollViewDidScroll(countOfItems); this->processScrollingEvent(); } } TableViewCell *TableView::dequeueCell() { TableViewCell *cell; if (_cellsFreed.empty()) { cell = nullptr; } else { cell = _cellsFreed.back(); cell->retain(); _cellsFreed.popBack(); cell->autorelease(); } return cell; } void TableView::_addCellIfNecessary(TableViewCell *cell) { if (cell->getParent() != _innerContainer) { _innerContainer->addChild(cell); } _cellsUsed.pushBack(cell); _indices.insert(cell->getIdx()); _isUsedCellsDirty = true; } void TableView::_updateContentSize(ssize_t cellsCount) { Size size = Size::ZERO; if (cellsCount > 0) { float maxPosition = _cellsPositions[cellsCount]; size = _contentSize; (_direction == Direction::HORIZONTAL ? size.width : size.height) = maxPosition; } this->setInnerContainerSize(size); } Vec2 TableView::_offsetFromIndex(ssize_t index) { Vec2 offset = this->__offsetFromIndex(index); Size cellSize = _delegate->tableCellSizeForIndex(this, index); if (_vordering == VerticalFillOrder::TOP_DOWN) { offset.y = _innerContainer->getContentSize().height - offset.y - cellSize.height; } return offset; } Vec2 TableView::__offsetFromIndex(ssize_t index) { Vec2 offset; (_direction == Direction::HORIZONTAL ? offset.x : offset.y) = _cellsPositions[index]; return offset; } long TableView::_indexFromOffset(Vec2 offset, ssize_t cellsCount) { long index = 0; const long maxIdx = cellsCount - 1; if (_vordering == VerticalFillOrder::TOP_DOWN) { offset.y = _innerContainer->getContentSize().height - offset.y; } index = this->__indexFromOffset(offset, cellsCount); if (index != -1) { index = MAX(0, index); if (index > maxIdx) { index = CC_INVALID_INDEX; } } return index; } long TableView::__indexFromOffset(const Vec2 &offset, ssize_t cellsCount) { long low = 0; long high = cellsCount - 1; const float search = (_direction == Direction::HORIZONTAL ? offset.x : offset.y); // binary search while (high >= low) { long index = low + (high - low) / 2; const float cellStart = _cellsPositions[index]; const float cellEnd = _cellsPositions[index + 1]; if (search >= cellStart && search <= cellEnd) { return index; } else if (search < cellStart) { high = index - 1; } else { low = index + 1; } } return (low <= 0) ? 0 : -1; } void TableView::_moveCellOutOfSight(TableViewCell *cell) { _delegate->tableCellWillRecycle(this, cell); _cellsFreed.pushBack(cell); _cellsUsed.eraseObject(cell); _isUsedCellsDirty = true; _indices.erase(cell->getIdx()); cell->reset(); if (cell->getParent() == _innerContainer) { _innerContainer->removeChild(cell, true); } } void TableView::_setIndexForCell(ssize_t index, TableViewCell *cell) { cell->setAnchorPoint(Vec2(0.0f, 0.0f)); cell->setPosition(this->_offsetFromIndex(index)); cell->setIdx(index); } void TableView::_updateCellPositions(ssize_t cellsCount) { _cellsPositions.resize(cellsCount + 1, 0.0f); if (cellsCount > 0) { float currentPos = 0; Size cellSize; for (ssize_t i = 0; i < cellsCount; ++i) { _cellsPositions[i] = currentPos; cellSize = _delegate->tableCellSizeForIndex(this, i); currentPos += (_direction == Direction::HORIZONTAL ? cellSize.width : cellSize.height); } _cellsPositions[cellsCount] = currentPos;//1 extra value allows us to get right/bottom of the last cell } } Vec2 TableView::maxContainerOffset() { return Vec2(0, 0); } Vec2 TableView::minContainerOffset() { const Size &contentSize = _innerContainer->getContentSize(); const Size &viewSize = _contentSize; return Vec2(viewSize.width - contentSize.width * _innerContainer->getScaleX(), viewSize.height - contentSize.height * _innerContainer->getScaleY()); } void TableView::_scrollViewDidScroll(ssize_t cellsCount) { if (0 == cellsCount) { return; } if (_isUsedCellsDirty) { _isUsedCellsDirty = false; std::sort(_cellsUsed.begin(), _cellsUsed.end(), [](TableViewCell *a, TableViewCell *b) -> bool{ return a->getIdx() < b->getIdx(); }); } ssize_t startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0; Vec2 offset = _innerContainer->getPosition(); Vec2 maxOffset = maxContainerOffset(); Vec2 minOffset = minContainerOffset(); offset.x = std::min(maxOffset.x, offset.x); offset.x = std::max(minOffset.x, offset.x); offset.y = std::min(maxOffset.y, offset.y); offset.y = std::max(minOffset.y, offset.y); offset.x = -offset.x; offset.y = -offset.y; maxIdx = std::max((long)cellsCount - 1, 0L); if (_vordering == VerticalFillOrder::TOP_DOWN) { offset.y = offset.y + _contentSize.height / _innerContainer->getScaleY(); } startIdx = this->_indexFromOffset(offset, cellsCount); if (startIdx == CC_INVALID_INDEX) { startIdx = cellsCount - 1; } if (_vordering == VerticalFillOrder::TOP_DOWN) { offset.y -= _contentSize.height / _innerContainer->getScaleY(); } else { offset.y += _contentSize.height / _innerContainer->getScaleY(); } offset.x += _contentSize.width / _innerContainer->getScaleX(); endIdx = this->_indexFromOffset(offset, cellsCount); if (endIdx == CC_INVALID_INDEX) { endIdx = cellsCount - 1; } #if 0 // For Testing. int i = 0; std::for_each(_cellsUsed.begin(), _cellsUsed.end(), [&i](TableViewCell* pCell) { log("cells Used index %d, value = %lu", i, pCell->getIdx()); ++i; }); log("---------------------------------------"); i = 0; std::for_each(_cellsFreed.begin(), _cellsFreed.end(), [&i](TableViewCell* pCell) { log("cells freed index %d, value = %lu", i, pCell->getIdx()); ++i; }); log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); #endif if (!_cellsUsed.empty()) { auto cell = _cellsUsed.at(0); idx = cell->getIdx(); while (idx < startIdx) { this->_moveCellOutOfSight(cell); CC_BREAK_IF(_cellsUsed.empty()); cell = _cellsUsed.at(0); idx = cell->getIdx(); } } if (!_cellsUsed.empty()) { auto cell = _cellsUsed.back(); idx = cell->getIdx(); while (idx <= maxIdx && idx > endIdx) { this->_moveCellOutOfSight(cell); CC_BREAK_IF(_cellsUsed.empty()); cell = _cellsUsed.back(); idx = cell->getIdx(); } } for (ssize_t i = startIdx; i <= endIdx; ++i) { if (_indices.find(i) == _indices.end()) { this->updateCellAtIndex(i); } } } void TableView::moveInnerContainer(const Vec2& deltaMove, bool canStartBounceBack) { ScrollView::moveInnerContainer(deltaMove, canStartBounceBack); ssize_t cellsCount = _delegate->numberOfCellsInTableView(this); _scrollViewDidScroll(cellsCount); } } <commit_msg>MAX->std::max<commit_after>#include "CWTableView.h" using namespace cocos2d; using namespace cocos2d::ui; namespace cw { TableView::TableView() : _vordering(VerticalFillOrder::BOTTOM_UP) , _isUsedCellsDirty(false) , _delegate(nullptr) { } TableView::~TableView() { } TableView *TableView::create() { TableView *table = new (std::nothrow) TableView(); if (table != nullptr && table->init()) { table->autorelease(); return table; } CC_SAFE_DELETE(table); return NULL; } bool TableView::init() { if (!ScrollView::init()) { return false; } _cellsPositions.clear(); _cellsUsed.clear(); _cellsFreed.clear(); _indices.clear(); _vordering = VerticalFillOrder::BOTTOM_UP; this->setDirection(Direction::VERTICAL); return true; } void TableView::onSizeChanged() { Size orginSize = _innerContainer->getContentSize(); Vec2 orginPos = _innerContainer->getPosition(); ScrollView::onSizeChanged(); if (orginSize.equals(_innerContainer->getContentSize())) { _innerContainer->setPosition(orginPos); } } void TableView::setVerticalFillOrder(VerticalFillOrder fillOrder) { if (_vordering != fillOrder) { _vordering = fillOrder; if (!_cellsUsed.empty()) { this->reloadData(); } } } TableView::VerticalFillOrder TableView::getVerticalFillOrder() { return _vordering; } void TableView::setDirection(Direction dir) { switch (_direction) { case Direction::NONE: case Direction::HORIZONTAL: case Direction::VERTICAL: _direction = dir; break; case Direction::BOTH: CCAssert(0, "TableView doesn't support both diretion!"); break; default: CCAssert(0, "Unknown diretion!"); break; } } void TableView::reloadData() { for (const auto &cell : _cellsUsed) { _delegate->tableCellWillRecycle(this, cell); _cellsFreed.pushBack(cell); cell->reset(); if (cell->getParent() == _innerContainer) { _innerContainer->removeChild(cell, true); } } _indices.clear(); _cellsUsed.clear(); ssize_t cellsCount = _delegate->numberOfCellsInTableView(this); this->_updateCellPositions(cellsCount); this->_updateContentSize(cellsCount); if (cellsCount > 0) { _scrollViewDidScroll(cellsCount); this->processScrollingEvent(); } } void TableView::reloadDataInplacement() { Vec2 pos = getInnerContainerPosition(); const Vec2 offset1 = minContainerOffset(); for (const auto &cell : _cellsUsed) { _delegate->tableCellWillRecycle(this, cell); _cellsFreed.pushBack(cell); cell->reset(); if (cell->getParent() == _innerContainer) { _innerContainer->removeChild(cell, true); } } _indices.clear(); _cellsUsed.clear(); ssize_t cellsCount = _delegate->numberOfCellsInTableView(this); this->_updateCellPositions(cellsCount); this->_updateContentSize(cellsCount); const Vec2 offset2 = minContainerOffset(); if (_direction == Direction::HORIZONTAL) { pos.x = std::max(pos.x, offset2.x); setInnerContainerPosition(pos); } else { if (_vordering == VerticalFillOrder::BOTTOM_UP) { pos.y = std::max(pos.y, offset2.y); setInnerContainerPosition(pos); } else { float temp = offset1.y - pos.y; pos.y = offset2.y - temp; pos.y = std::min(pos.y, 0.0f); setInnerContainerPosition(pos); } } if (cellsCount > 0) { _scrollViewDidScroll(cellsCount); this->processScrollingEvent(); } } TableViewCell *TableView::cellAtIndex(ssize_t idx) { if (_indices.find(idx) != _indices.end()) { for (const auto &cell : _cellsUsed) { if (cell->getIdx() == idx) { return cell; } } } return nullptr; } void TableView::updateCellAtIndex(ssize_t idx) { if (idx == CC_INVALID_INDEX) { return; } ssize_t countOfItems = _delegate->numberOfCellsInTableView(this); if (0 == countOfItems || idx > countOfItems-1) { return; } TableViewCell *cell = this->cellAtIndex(idx); if (cell != nullptr) { this->_moveCellOutOfSight(cell); } cell = _delegate->tableCellAtIndex(this, idx); this->_setIndexForCell(idx, cell); this->_addCellIfNecessary(cell); } void TableView::insertCellAtIndex(ssize_t idx) { if (idx == CC_INVALID_INDEX) { return; } ssize_t countOfItems = _delegate->numberOfCellsInTableView(this); if (0 == countOfItems || idx > countOfItems-1) { return; } long newIdx = 0; auto cell = cellAtIndex(idx); if (cell != nullptr) { newIdx = _cellsUsed.getIndex(cell); // Move all cells behind the inserted position for (ssize_t i = newIdx; i < _cellsUsed.size(); ++i) { cell = _cellsUsed.at(i); this->_setIndexForCell(cell->getIdx()+1, cell); } } //insert a new cell cell = _delegate->tableCellAtIndex(this, idx); this->_setIndexForCell(idx, cell); this->_addCellIfNecessary(cell); this->_updateCellPositions(countOfItems); this->_updateContentSize(countOfItems); if (countOfItems > 0) { _scrollViewDidScroll(countOfItems); this->processScrollingEvent(); } } void TableView::removeCellAtIndex(ssize_t idx) { if (idx == CC_INVALID_INDEX) { return; } ssize_t countOfItems = _delegate->numberOfCellsInTableView(this); if (0 == countOfItems || idx + 1 > countOfItems) { return; } TableViewCell* cell = this->cellAtIndex(idx); if (cell == nullptr) { return; } ssize_t newIdx = _cellsUsed.getIndex(cell); //remove first this->_moveCellOutOfSight(cell); _indices.erase(idx); this->_updateCellPositions(countOfItems); this->_updateContentSize(countOfItems); for (ssize_t i = _cellsUsed.size() - 1; i > newIdx; --i) { cell = _cellsUsed.at(i); this->_setIndexForCell(cell->getIdx() - 1, cell); } if (countOfItems > 0) { _scrollViewDidScroll(countOfItems); this->processScrollingEvent(); } } TableViewCell *TableView::dequeueCell() { TableViewCell *cell; if (_cellsFreed.empty()) { cell = nullptr; } else { cell = _cellsFreed.back(); cell->retain(); _cellsFreed.popBack(); cell->autorelease(); } return cell; } void TableView::_addCellIfNecessary(TableViewCell *cell) { if (cell->getParent() != _innerContainer) { _innerContainer->addChild(cell); } _cellsUsed.pushBack(cell); _indices.insert(cell->getIdx()); _isUsedCellsDirty = true; } void TableView::_updateContentSize(ssize_t cellsCount) { Size size = Size::ZERO; if (cellsCount > 0) { float maxPosition = _cellsPositions[cellsCount]; size = _contentSize; (_direction == Direction::HORIZONTAL ? size.width : size.height) = maxPosition; } this->setInnerContainerSize(size); } Vec2 TableView::_offsetFromIndex(ssize_t index) { Vec2 offset = this->__offsetFromIndex(index); Size cellSize = _delegate->tableCellSizeForIndex(this, index); if (_vordering == VerticalFillOrder::TOP_DOWN) { offset.y = _innerContainer->getContentSize().height - offset.y - cellSize.height; } return offset; } Vec2 TableView::__offsetFromIndex(ssize_t index) { Vec2 offset; (_direction == Direction::HORIZONTAL ? offset.x : offset.y) = _cellsPositions[index]; return offset; } long TableView::_indexFromOffset(Vec2 offset, ssize_t cellsCount) { long index = 0; const long maxIdx = cellsCount - 1; if (_vordering == VerticalFillOrder::TOP_DOWN) { offset.y = _innerContainer->getContentSize().height - offset.y; } index = this->__indexFromOffset(offset, cellsCount); if (index != -1) { index = std::max(0L, index); if (index > maxIdx) { index = CC_INVALID_INDEX; } } return index; } long TableView::__indexFromOffset(const Vec2 &offset, ssize_t cellsCount) { long low = 0; long high = cellsCount - 1; const float search = (_direction == Direction::HORIZONTAL ? offset.x : offset.y); // binary search while (high >= low) { long index = low + (high - low) / 2; const float cellStart = _cellsPositions[index]; const float cellEnd = _cellsPositions[index + 1]; if (search >= cellStart && search <= cellEnd) { return index; } else if (search < cellStart) { high = index - 1; } else { low = index + 1; } } return (low <= 0) ? 0 : -1; } void TableView::_moveCellOutOfSight(TableViewCell *cell) { _delegate->tableCellWillRecycle(this, cell); _cellsFreed.pushBack(cell); _cellsUsed.eraseObject(cell); _isUsedCellsDirty = true; _indices.erase(cell->getIdx()); cell->reset(); if (cell->getParent() == _innerContainer) { _innerContainer->removeChild(cell, true); } } void TableView::_setIndexForCell(ssize_t index, TableViewCell *cell) { cell->setAnchorPoint(Vec2(0.0f, 0.0f)); cell->setPosition(this->_offsetFromIndex(index)); cell->setIdx(index); } void TableView::_updateCellPositions(ssize_t cellsCount) { _cellsPositions.resize(cellsCount + 1, 0.0f); if (cellsCount > 0) { float currentPos = 0; Size cellSize; for (ssize_t i = 0; i < cellsCount; ++i) { _cellsPositions[i] = currentPos; cellSize = _delegate->tableCellSizeForIndex(this, i); currentPos += (_direction == Direction::HORIZONTAL ? cellSize.width : cellSize.height); } _cellsPositions[cellsCount] = currentPos;//1 extra value allows us to get right/bottom of the last cell } } Vec2 TableView::maxContainerOffset() { return Vec2(0, 0); } Vec2 TableView::minContainerOffset() { const Size &contentSize = _innerContainer->getContentSize(); const Size &viewSize = _contentSize; return Vec2(viewSize.width - contentSize.width * _innerContainer->getScaleX(), viewSize.height - contentSize.height * _innerContainer->getScaleY()); } void TableView::_scrollViewDidScroll(ssize_t cellsCount) { if (0 == cellsCount) { return; } if (_isUsedCellsDirty) { _isUsedCellsDirty = false; std::sort(_cellsUsed.begin(), _cellsUsed.end(), [](TableViewCell *a, TableViewCell *b) -> bool{ return a->getIdx() < b->getIdx(); }); } ssize_t startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0; Vec2 offset = _innerContainer->getPosition(); Vec2 maxOffset = maxContainerOffset(); Vec2 minOffset = minContainerOffset(); offset.x = std::min(maxOffset.x, offset.x); offset.x = std::max(minOffset.x, offset.x); offset.y = std::min(maxOffset.y, offset.y); offset.y = std::max(minOffset.y, offset.y); offset.x = -offset.x; offset.y = -offset.y; maxIdx = std::max((long)cellsCount - 1, 0L); if (_vordering == VerticalFillOrder::TOP_DOWN) { offset.y = offset.y + _contentSize.height / _innerContainer->getScaleY(); } startIdx = this->_indexFromOffset(offset, cellsCount); if (startIdx == CC_INVALID_INDEX) { startIdx = cellsCount - 1; } if (_vordering == VerticalFillOrder::TOP_DOWN) { offset.y -= _contentSize.height / _innerContainer->getScaleY(); } else { offset.y += _contentSize.height / _innerContainer->getScaleY(); } offset.x += _contentSize.width / _innerContainer->getScaleX(); endIdx = this->_indexFromOffset(offset, cellsCount); if (endIdx == CC_INVALID_INDEX) { endIdx = cellsCount - 1; } #if 0 // For Testing. int i = 0; std::for_each(_cellsUsed.begin(), _cellsUsed.end(), [&i](TableViewCell* pCell) { log("cells Used index %d, value = %lu", i, pCell->getIdx()); ++i; }); log("---------------------------------------"); i = 0; std::for_each(_cellsFreed.begin(), _cellsFreed.end(), [&i](TableViewCell* pCell) { log("cells freed index %d, value = %lu", i, pCell->getIdx()); ++i; }); log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); #endif if (!_cellsUsed.empty()) { auto cell = _cellsUsed.at(0); idx = cell->getIdx(); while (idx < startIdx) { this->_moveCellOutOfSight(cell); CC_BREAK_IF(_cellsUsed.empty()); cell = _cellsUsed.at(0); idx = cell->getIdx(); } } if (!_cellsUsed.empty()) { auto cell = _cellsUsed.back(); idx = cell->getIdx(); while (idx <= maxIdx && idx > endIdx) { this->_moveCellOutOfSight(cell); CC_BREAK_IF(_cellsUsed.empty()); cell = _cellsUsed.back(); idx = cell->getIdx(); } } for (ssize_t i = startIdx; i <= endIdx; ++i) { if (_indices.find(i) == _indices.end()) { this->updateCellAtIndex(i); } } } void TableView::moveInnerContainer(const Vec2& deltaMove, bool canStartBounceBack) { ScrollView::moveInnerContainer(deltaMove, canStartBounceBack); ssize_t cellsCount = _delegate->numberOfCellsInTableView(this); _scrollViewDidScroll(cellsCount); } } <|endoftext|>
<commit_before>#include <stdio.h> #include "../SynCommonLib/RelationsIterator.h" #include "../common/SyntaxHolder.h" void GetAnanlytForms(const CSentence& Sentence, string& Res) { for( int WordNo = 0; WordNo<Sentence.m_Words.size(); WordNo++ ) { const CSynWord& W = Sentence.m_Words[WordNo]; if (!W.m_MainVerbs.empty()) { Res += string("\t<analyt> ")+ W.m_strWord.c_str(); for (size_t i=0; i< W.m_MainVerbs.size(); i++) { Res += string(" ") + Sentence.m_Words[W.m_MainVerbs[i]].m_strWord; const CSynWord& W_1 = Sentence.m_Words[W.m_MainVerbs[i]]; for (size_t j=0; j< W_1.m_MainVerbs.size(); j++) Res += string(" ") + Sentence.m_Words[W_1.m_MainVerbs[j]].m_strWord; }; Res += "</analyt>\n"; } } } string GetWords(const CSentence& Sentence, const CPeriod& P) { string S; for (int WordNo = P.m_iFirstWord; WordNo <= P.m_iLastWord; WordNo++) { S += Sentence.m_Words[WordNo].m_strWord; if (WordNo < P.m_iLastWord) S += " "; }; return S; } void GetGroups(const CSentence& Sentence, const CAgramtab& A, string& Res) { int nClausesCount = Sentence.GetClausesCount(); for( int ClauseNo = 0; ClauseNo<nClausesCount; ClauseNo++ ) { const CClause& Clause = Sentence.GetClause(ClauseNo); int nCvar = Clause.m_SynVariants.size(); if (Clause.m_SynVariants.empty()) continue; int nVmax = Clause.m_SynVariants.begin()->m_iWeight; for( CSVI pSynVar=Clause.m_SynVariants.begin(); pSynVar != Clause.m_SynVariants.end(); pSynVar++ ) { if( pSynVar->m_iWeight < nVmax ) break; const CMorphVariant& V = *pSynVar; Res += Format("\t<synvar>\n"); // print the clause { int ClauseType = (V.m_ClauseTypeNo == -1) ? UnknownSyntaxElement : Clause.m_vectorTypes[V.m_ClauseTypeNo].m_Type;; string Type; if (ClauseType != UnknownSyntaxElement) Type = (const char*)A.GetClauseNameByType(ClauseType); else Type = "EMPTY"; Res += Format("\t\t<clause type=\"%s\">%s</clause>\n", Type.c_str(), GetWords(Sentence, Clause).c_str()); } for (int GroupNo = 0; GroupNo < V.m_vectorGroups.GetGroups().size(); GroupNo++) { const CGroup& G = V.m_vectorGroups.GetGroups()[GroupNo]; Res += Format("\t\t<group type=\"%s\">%s</group>\n", Sentence.GetOpt()->GetGroupNameByIndex(G.m_GroupType), GetWords(Sentence, G).c_str()); }; Res += Format("\t</synvar>\n"); } } } string GetNodeStr(const CSentence& Sentence, const CRelationsIterator& RelIt, int GroupNo, int WordNo) { if (GroupNo != -1) return GetWords(Sentence, RelIt.GetFirmGroups()[GroupNo]); else return Sentence.m_Words[WordNo].m_strWord; } void GetRelations(const CSentence& Sentence, string& Result) { CRelationsIterator RelIt; RelIt.SetSentence(&Sentence); for( int i = 0; i<Sentence.m_vectorPrClauseNo.size(); i++ ) RelIt.AddClauseNoAndVariantNo(Sentence.m_vectorPrClauseNo[i], 0); RelIt.BuildRelations(); for(long RelNo = 0 ; RelNo < RelIt.GetRelations().size() ; RelNo++ ) { const CSynOutputRelation& piRel = RelIt.GetRelations()[RelNo]; string RelName = Sentence.GetOpt()->GetGroupNameByIndex(piRel.m_Relation.type); string Src = GetNodeStr(Sentence, RelIt,piRel.m_iSourceGroup, piRel.m_Relation.m_iFirstWord); string Trg = GetNodeStr(Sentence, RelIt,piRel.m_iTargetGroup, piRel.m_Relation.m_iLastWord); string GramRel = Sentence.GetOpt()->GetGramTab()->GrammemsToStr(piRel.m_Relation.m_iGrammems); Result += Format("\t<rel name=\"%s\" gram=\"%s\"> %s -> %s </rel>\n", RelName.c_str(), GramRel.c_str(), Src.c_str(), Trg.c_str() ); } } string GetStringBySyntax(const CSentencesCollection& SC, const CAgramtab& A, string input) { string Result; Result += Format("<chunk>\n"); Result += Format("<input>%s</input>\n",input.c_str()); for (size_t nSent=0; nSent < SC.m_vectorSents.size(); nSent++) { const CSentence& Sentence = *SC.m_vectorSents[nSent]; int iWord=0,iClau=0,iCvar=0; Result += "<sent>\n"; GetAnanlytForms(Sentence, Result); GetGroups(Sentence, A, Result); GetRelations(Sentence, Result); Result += "</sent>\n"; } Result += Format("</chunk>\n"); fprintf (stderr, "sentences count: %i\n", SC.m_vectorSents.size()); return Result; }; void PrintUsage() { printf ("Dialing DWDS Command Line Syntax Parser(www.aot.ru, www.dwds.de)\n"); printf ("Usage: TestSynan (RUSSIAN|GERMAN) [filename.txt] - \n"); printf ("Example: TestSynan Russian\n"); exit(1); }; int main(int argc, char* argv[]) { try { MorphLanguageEnum langua = morphUnknown; string FileName; for (size_t i=1; i<argc; i++) { string s = argv[i]; EngMakeLower(s); if ( (s == "-help") || (s == "--help") || (s == "/?") ) PrintUsage(); else { if (langua == morphUnknown) { if (!GetLanguageByString(s, langua)) PrintUsage(); } else { FileName = argv[i]; if (!FileExists(FileName.c_str())) { fprintf (stderr, "cannot open file %s\n", FileName.c_str()); exit(1); } } } } if ((langua == morphUnknown)) PrintUsage(); CSyntaxHolder H; if (!H.LoadSyntax(langua)) { fprintf (stderr, "initialization error\n"); return 1; }; fprintf (stderr, "ok\n"); if (!FileName.empty()) { vector<string> Files; if ((FileName.length() > 4) && FileName.substr(FileName.length() -4) == ".lst") { FILE* fp = fopen(FileName.c_str(), "r"); if (!fp) { fprintf( stderr, "cannot open %s\n", FileName.c_str()); return 1; } char buffer[1024]; while (fgets (buffer, 1024, fp)) { rtrim (buffer); Files.push_back(buffer); } fclose (fp); } else Files.push_back(FileName); for (size_t i=0; i < Files.size(); i++) { fprintf( stderr, "File %s\n", Files[i].c_str()); fflush (stderr); H.m_bTimeStatis = true; H.GetSentencesFromSynAn(Files[i], true); string s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, Files[i].c_str()); printf ("%s\n\n", s.c_str()); } return 0; } // =============== WORKING =============== char buffer[10000] ; while (fgets(buffer, 10000, stdin)) { string s = buffer; Trim(s); if (s.empty()) continue; H.GetSentencesFromSynAn(s, false); s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, s); printf ("%s", s.c_str()); fflush(stdout); }; } catch(...) { fprintf (stderr, "an exception occurred!\n"); return 1; }; return 0; }; <commit_msg>output gram info<commit_after>#include <stdio.h> #include "../SynCommonLib/RelationsIterator.h" #include "../common/SyntaxHolder.h" void GetAnanlytForms(const CSentence& Sentence, string& Res) { for( int WordNo = 0; WordNo<Sentence.m_Words.size(); WordNo++ ) { const CSynWord& W = Sentence.m_Words[WordNo]; if (!W.m_MainVerbs.empty()) { Res += string("\t<analyt> ")+ W.m_strWord.c_str(); for (size_t i=0; i< W.m_MainVerbs.size(); i++) { Res += string(" ") + Sentence.m_Words[W.m_MainVerbs[i]].m_strWord; const CSynWord& W_1 = Sentence.m_Words[W.m_MainVerbs[i]]; for (size_t j=0; j< W_1.m_MainVerbs.size(); j++) Res += string(" ") + Sentence.m_Words[W_1.m_MainVerbs[j]].m_strWord; }; Res += "</analyt>\n"; } } } string GetWords(const CSentence& Sentence, const CPeriod& P) { string S; for (int WordNo = P.m_iFirstWord; WordNo <= P.m_iLastWord; WordNo++) { S += Sentence.m_Words[WordNo].m_strWord; if (WordNo < P.m_iLastWord) S += " "; }; return S; } void GetGroups(const CSentence& Sentence, const CAgramtab& A, string& Res) { int nClausesCount = Sentence.GetClausesCount(); for( int ClauseNo = 0; ClauseNo<nClausesCount; ClauseNo++ ) { const CClause& Clause = Sentence.GetClause(ClauseNo); int nCvar = Clause.m_SynVariants.size(); if (Clause.m_SynVariants.empty()) continue; int nVmax = Clause.m_SynVariants.begin()->m_iWeight; for( CSVI pSynVar=Clause.m_SynVariants.begin(); pSynVar != Clause.m_SynVariants.end(); pSynVar++ ) { if( pSynVar->m_iWeight < nVmax ) break; const CMorphVariant& V = *pSynVar; Res += Format("\t<synvar>\n"); // print the clause { int ClauseType = (V.m_ClauseTypeNo == -1) ? UnknownSyntaxElement : Clause.m_vectorTypes[V.m_ClauseTypeNo].m_Type;; string Type; if (ClauseType != UnknownSyntaxElement) Type = (const char*)A.GetClauseNameByType(ClauseType); else Type = "EMPTY"; Res += Format("\t\t<clause type=\"%s\">%s</clause>\n", Type.c_str(), GetWords(Sentence, Clause).c_str()); } for (int GroupNo = 0; GroupNo < V.m_vectorGroups.GetGroups().size(); GroupNo++) { const CGroup& G = V.m_vectorGroups.GetGroups()[GroupNo]; Res += Format("\t\t<group type=\"%s\">%s</group>\n", Sentence.GetOpt()->GetGroupNameByIndex(G.m_GroupType), GetWords(Sentence, G).c_str()); }; Res += Format("\t</synvar>\n"); } } } string GetNodeStr(const CSentence& Sentence, const CRelationsIterator& RelIt, int GroupNo, int WordNo) { if (GroupNo != -1) return GetWords(Sentence, RelIt.GetFirmGroups()[GroupNo]); else return Sentence.m_Words[WordNo].m_strWord; } string GetNodeGrmStr(const CSentence& Sentence, const CRelationsIterator& RelIt, int GroupNo, int WordNo, string& Lemma) { Lemma = ""; if (GroupNo != -1) return ""; else { size_t ClauseNo = Sentence.GetMinClauseByWordNo(WordNo); const CClause& Clause = Sentence.GetClause(ClauseNo); const CMorphVariant* pSynVar = &*Clause.GetSynVariantByNo(0); int UnitNo = pSynVar->UnitNoByWordNo(WordNo); const CSynUnit& U = pSynVar->m_SynUnits[UnitNo]; Lemma = Sentence.GetWords()[WordNo].GetHomonym(U.m_iHomonymNum)->m_strLemma; return Sentence.GetOpt()->GetGramTab()->GrammemsToStr(U.m_iGrammems|U.m_TypeGrammems); } } void GetRelations(const CSentence& Sentence, string& Result) { CRelationsIterator RelIt; RelIt.SetSentence(&Sentence); for( int i = 0; i<Sentence.m_vectorPrClauseNo.size(); i++ ) RelIt.AddClauseNoAndVariantNo(Sentence.m_vectorPrClauseNo[i], 0); RelIt.BuildRelations(); for(long RelNo = 0 ; RelNo < RelIt.GetRelations().size() ; RelNo++ ) { const CSynOutputRelation& piRel = RelIt.GetRelations()[RelNo]; string RelName = Sentence.GetOpt()->GetGroupNameByIndex(piRel.m_Relation.type); string Src = GetNodeStr(Sentence, RelIt,piRel.m_iSourceGroup, piRel.m_Relation.m_iFirstWord); string Trg = GetNodeStr(Sentence, RelIt,piRel.m_iTargetGroup, piRel.m_Relation.m_iLastWord); string SrcLemma, TrgLemma; string SrcGrm = GetNodeGrmStr(Sentence, RelIt,piRel.m_iSourceGroup, piRel.m_Relation.m_iFirstWord, SrcLemma); string TrgGrm = GetNodeGrmStr(Sentence, RelIt,piRel.m_iTargetGroup, piRel.m_Relation.m_iLastWord, TrgLemma); string GramRel = Sentence.GetOpt()->GetGramTab()->GrammemsToStr(piRel.m_Relation.m_iGrammems); Result += Format("\t<rel name=\"%s\" gramrel=\"%s\" lemmprnt=\"%s\" grmprnt=\"%s\" lemmchld=\"%s\" grmchld=\"%s\" > %s -> %s </rel>\n", RelName.c_str(), GramRel.c_str(), SrcLemma.c_str(), SrcGrm.c_str(), TrgLemma.c_str(), TrgGrm.c_str(), Src.c_str(), Trg.c_str() ); } } string GetStringBySyntax(const CSentencesCollection& SC, const CAgramtab& A, string input) { string Result; Result += Format("<chunk>\n"); Result += Format("<input>%s</input>\n",input.c_str()); for (size_t nSent=0; nSent < SC.m_vectorSents.size(); nSent++) { const CSentence& Sentence = *SC.m_vectorSents[nSent]; int iWord=0,iClau=0,iCvar=0; Result += "<sent>\n"; GetAnanlytForms(Sentence, Result); GetGroups(Sentence, A, Result); GetRelations(Sentence, Result); Result += "</sent>\n"; } Result += Format("</chunk>\n"); fprintf (stderr, "sentences count: %i\n", SC.m_vectorSents.size()); return Result; }; void PrintUsage() { printf ("Dialing DWDS Command Line Syntax Parser(www.aot.ru, www.dwds.de)\n"); printf ("Usage: TestSynan (RUSSIAN|GERMAN) [filename.txt] - \n"); printf ("Example: TestSynan Russian\n"); exit(1); }; int main(int argc, char* argv[]) { try { MorphLanguageEnum langua = morphUnknown; string FileName; for (size_t i=1; i<argc; i++) { string s = argv[i]; EngMakeLower(s); if ( (s == "-help") || (s == "--help") || (s == "/?") ) PrintUsage(); else { if (langua == morphUnknown) { if (!GetLanguageByString(s, langua)) PrintUsage(); } else { FileName = argv[i]; if (!FileExists(FileName.c_str())) { fprintf (stderr, "cannot open file %s\n", FileName.c_str()); exit(1); } } } } if ((langua == morphUnknown)) PrintUsage(); CSyntaxHolder H; if (!H.LoadSyntax(langua)) { fprintf (stderr, "initialization error\n"); return 1; }; fprintf (stderr, "ok\n"); if (!FileName.empty()) { vector<string> Files; if ((FileName.length() > 4) && FileName.substr(FileName.length() -4) == ".lst") { FILE* fp = fopen(FileName.c_str(), "r"); if (!fp) { fprintf( stderr, "cannot open %s\n", FileName.c_str()); return 1; } char buffer[1024]; while (fgets (buffer, 1024, fp)) { rtrim (buffer); Files.push_back(buffer); } fclose (fp); } else Files.push_back(FileName); for (size_t i=0; i < Files.size(); i++) { fprintf( stderr, "File %s\n", Files[i].c_str()); fflush (stderr); H.m_bTimeStatis = true; H.GetSentencesFromSynAn(Files[i], true); string s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, Files[i].c_str()); printf ("%s\n\n", s.c_str()); } return 0; } // =============== WORKING =============== char buffer[10000] ; while (fgets(buffer, 10000, stdin)) { string s = buffer; Trim(s); if (s.empty()) continue; H.GetSentencesFromSynAn(s, false); s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, s); printf ("%s", s.c_str()); fflush(stdout); }; } catch(...) { fprintf (stderr, "an exception occurred!\n"); return 1; }; return 0; }; <|endoftext|>
<commit_before>#include "WebPage.h" #include "JavascriptInvocation.h" #include "NetworkAccessManager.h" #include "NetworkCookieJar.h" #include "UnsupportedContentHandler.h" #include <QResource> #include <QtNetwork> #include <iostream> WebPage::WebPage(QObject *parent) : QWebPage(parent) { setForwardUnsupportedContent(true); loadJavascript(); setUserStylesheet(); m_loading = false; this->setCustomNetworkAccessManager(); connect(this, SIGNAL(loadStarted()), this, SLOT(loadStarted())); connect(this, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool))); connect(this, SIGNAL(frameCreated(QWebFrame *)), this, SLOT(frameCreated(QWebFrame *))); connect(this, SIGNAL(unsupportedContent(QNetworkReply*)), this, SLOT(handleUnsupportedContent(QNetworkReply*))); this->setViewportSize(QSize(1680, 1050)); } void WebPage::setCustomNetworkAccessManager() { NetworkAccessManager *manager = new NetworkAccessManager(); manager->setCookieJar(new NetworkCookieJar()); this->setNetworkAccessManager(manager); connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *))); connect(manager, SIGNAL(sslErrors(QNetworkReply *, QList<QSslError>)), this, SLOT(ignoreSslErrors(QNetworkReply *, QList<QSslError>))); } void WebPage::loadJavascript() { QResource javascript(":/capybara.js"); if (javascript.isCompressed()) { QByteArray uncompressedBytes(qUncompress(javascript.data(), javascript.size())); m_capybaraJavascript = QString(uncompressedBytes); } else { char * javascriptString = new char[javascript.size() + 1]; strcpy(javascriptString, (const char *)javascript.data()); javascriptString[javascript.size()] = 0; m_capybaraJavascript = javascriptString; } } void WebPage::setUserStylesheet() { QString data = QString("* { font-family: 'Arial' ! important; }").toUtf8().toBase64(); QUrl url = QUrl(QString("data:text/css;charset=utf-8;base64,") + data); settings()->setUserStyleSheetUrl(url); } QString WebPage::userAgentForUrl(const QUrl &url ) const { if (!m_userAgent.isEmpty()) { return m_userAgent; } else { return QWebPage::userAgentForUrl(url); } } QString WebPage::consoleMessages() { return m_consoleMessages.join("\n"); } void WebPage::setUserAgent(QString userAgent) { m_userAgent = userAgent; } void WebPage::frameCreated(QWebFrame * frame) { connect(frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(injectJavascriptHelpers())); } void WebPage::injectJavascriptHelpers() { QWebFrame* frame = qobject_cast<QWebFrame *>(QObject::sender()); frame->evaluateJavaScript(m_capybaraJavascript); } bool WebPage::shouldInterruptJavaScript() { return false; } QVariant WebPage::invokeCapybaraFunction(const char *name, QStringList &arguments) { QString qname(name); QString objectName("CapybaraInvocation"); JavascriptInvocation invocation(qname, arguments); currentFrame()->addToJavaScriptWindowObject(objectName, &invocation); QString javascript = QString("Capybara.invoke()"); return currentFrame()->evaluateJavaScript(javascript); } QVariant WebPage::invokeCapybaraFunction(QString &name, QStringList &arguments) { return invokeCapybaraFunction(name.toAscii().data(), arguments); } void WebPage::javaScriptConsoleMessage(const QString &message, int lineNumber, const QString &sourceID) { QString fullMessage = QString::number(lineNumber) + "|" + message; if (!sourceID.isEmpty()) fullMessage = sourceID + "|" + fullMessage; m_consoleMessages.append(fullMessage); std::cout << qPrintable(fullMessage) << std::endl; } void WebPage::javaScriptAlert(QWebFrame *frame, const QString &message) { Q_UNUSED(frame); std::cout << "ALERT: " << qPrintable(message) << std::endl; } bool WebPage::javaScriptConfirm(QWebFrame *frame, const QString &message) { Q_UNUSED(frame); Q_UNUSED(message); return true; } bool WebPage::javaScriptPrompt(QWebFrame *frame, const QString &message, const QString &defaultValue, QString *result) { Q_UNUSED(frame) Q_UNUSED(message) Q_UNUSED(defaultValue) Q_UNUSED(result) return false; } void WebPage::loadStarted() { m_loading = true; } void WebPage::loadFinished(bool success) { m_loading = false; emit pageFinished(success); } bool WebPage::isLoading() const { return m_loading; } QString WebPage::failureString() { return QString("Unable to load URL: ") + currentFrame()->requestedUrl().toString(); } bool WebPage::render(const QString &fileName) { QFileInfo fileInfo(fileName); QDir dir; dir.mkpath(fileInfo.absolutePath()); QSize viewportSize = this->viewportSize(); QSize pageSize = this->mainFrame()->contentsSize(); if (pageSize.isEmpty()) { return false; } QImage buffer(pageSize, QImage::Format_ARGB32); buffer.fill(qRgba(255, 255, 255, 0)); QPainter p(&buffer); p.setRenderHint( QPainter::Antialiasing, true); p.setRenderHint( QPainter::TextAntialiasing, true); p.setRenderHint( QPainter::SmoothPixmapTransform, true); this->setViewportSize(pageSize); this->mainFrame()->render(&p); p.end(); this->setViewportSize(viewportSize); return buffer.save(fileName); } QString WebPage::chooseFile(QWebFrame *parentFrame, const QString &suggestedFile) { Q_UNUSED(parentFrame); Q_UNUSED(suggestedFile); return getLastAttachedFileName(); } bool WebPage::extension(Extension extension, const ExtensionOption *option, ExtensionReturn *output) { Q_UNUSED(option); if (extension == ChooseMultipleFilesExtension) { QStringList names = QStringList() << getLastAttachedFileName(); static_cast<ChooseMultipleFilesExtensionReturn*>(output)->fileNames = names; return true; } return false; } QString WebPage::getLastAttachedFileName() { return currentFrame()->evaluateJavaScript(QString("Capybara.lastAttachedFile")).toString(); } void WebPage::replyFinished(QNetworkReply *reply) { if (reply->url() == this->currentFrame()->url()) { QStringList headers; m_lastStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QList<QByteArray> list = reply->rawHeaderList(); int length = list.size(); for(int i = 0; i < length; i++) { headers << list.at(i)+": "+reply->rawHeader(list.at(i)); } m_pageHeaders = headers.join("\n"); } } void WebPage::ignoreSslErrors(QNetworkReply *reply, const QList<QSslError> &errors) { if (m_ignoreSslErrors) reply->ignoreSslErrors(errors); } void WebPage::setIgnoreSslErrors(bool ignore) { m_ignoreSslErrors = ignore; } bool WebPage::ignoreSslErrors() { return m_ignoreSslErrors; } int WebPage::getLastStatus() { return m_lastStatus; } void WebPage::resetResponseHeaders() { m_lastStatus = 0; m_pageHeaders = QString(); } void WebPage::resetConsoleMessages() { m_consoleMessages.clear(); } QString WebPage::pageHeaders() { return m_pageHeaders; } void WebPage::handleUnsupportedContent(QNetworkReply *reply) { UnsupportedContentHandler *handler = new UnsupportedContentHandler(this, reply); Q_UNUSED(handler); } <commit_msg>Move the include to a header file<commit_after>#include "WebPage.h" #include "JavascriptInvocation.h" #include "NetworkAccessManager.h" #include "NetworkCookieJar.h" #include "UnsupportedContentHandler.h" #include <QResource> #include <iostream> WebPage::WebPage(QObject *parent) : QWebPage(parent) { setForwardUnsupportedContent(true); loadJavascript(); setUserStylesheet(); m_loading = false; this->setCustomNetworkAccessManager(); connect(this, SIGNAL(loadStarted()), this, SLOT(loadStarted())); connect(this, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool))); connect(this, SIGNAL(frameCreated(QWebFrame *)), this, SLOT(frameCreated(QWebFrame *))); connect(this, SIGNAL(unsupportedContent(QNetworkReply*)), this, SLOT(handleUnsupportedContent(QNetworkReply*))); this->setViewportSize(QSize(1680, 1050)); } void WebPage::setCustomNetworkAccessManager() { NetworkAccessManager *manager = new NetworkAccessManager(); manager->setCookieJar(new NetworkCookieJar()); this->setNetworkAccessManager(manager); connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *))); connect(manager, SIGNAL(sslErrors(QNetworkReply *, QList<QSslError>)), this, SLOT(ignoreSslErrors(QNetworkReply *, QList<QSslError>))); } void WebPage::loadJavascript() { QResource javascript(":/capybara.js"); if (javascript.isCompressed()) { QByteArray uncompressedBytes(qUncompress(javascript.data(), javascript.size())); m_capybaraJavascript = QString(uncompressedBytes); } else { char * javascriptString = new char[javascript.size() + 1]; strcpy(javascriptString, (const char *)javascript.data()); javascriptString[javascript.size()] = 0; m_capybaraJavascript = javascriptString; } } void WebPage::setUserStylesheet() { QString data = QString("* { font-family: 'Arial' ! important; }").toUtf8().toBase64(); QUrl url = QUrl(QString("data:text/css;charset=utf-8;base64,") + data); settings()->setUserStyleSheetUrl(url); } QString WebPage::userAgentForUrl(const QUrl &url ) const { if (!m_userAgent.isEmpty()) { return m_userAgent; } else { return QWebPage::userAgentForUrl(url); } } QString WebPage::consoleMessages() { return m_consoleMessages.join("\n"); } void WebPage::setUserAgent(QString userAgent) { m_userAgent = userAgent; } void WebPage::frameCreated(QWebFrame * frame) { connect(frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(injectJavascriptHelpers())); } void WebPage::injectJavascriptHelpers() { QWebFrame* frame = qobject_cast<QWebFrame *>(QObject::sender()); frame->evaluateJavaScript(m_capybaraJavascript); } bool WebPage::shouldInterruptJavaScript() { return false; } QVariant WebPage::invokeCapybaraFunction(const char *name, QStringList &arguments) { QString qname(name); QString objectName("CapybaraInvocation"); JavascriptInvocation invocation(qname, arguments); currentFrame()->addToJavaScriptWindowObject(objectName, &invocation); QString javascript = QString("Capybara.invoke()"); return currentFrame()->evaluateJavaScript(javascript); } QVariant WebPage::invokeCapybaraFunction(QString &name, QStringList &arguments) { return invokeCapybaraFunction(name.toAscii().data(), arguments); } void WebPage::javaScriptConsoleMessage(const QString &message, int lineNumber, const QString &sourceID) { QString fullMessage = QString::number(lineNumber) + "|" + message; if (!sourceID.isEmpty()) fullMessage = sourceID + "|" + fullMessage; m_consoleMessages.append(fullMessage); std::cout << qPrintable(fullMessage) << std::endl; } void WebPage::javaScriptAlert(QWebFrame *frame, const QString &message) { Q_UNUSED(frame); std::cout << "ALERT: " << qPrintable(message) << std::endl; } bool WebPage::javaScriptConfirm(QWebFrame *frame, const QString &message) { Q_UNUSED(frame); Q_UNUSED(message); return true; } bool WebPage::javaScriptPrompt(QWebFrame *frame, const QString &message, const QString &defaultValue, QString *result) { Q_UNUSED(frame) Q_UNUSED(message) Q_UNUSED(defaultValue) Q_UNUSED(result) return false; } void WebPage::loadStarted() { m_loading = true; } void WebPage::loadFinished(bool success) { m_loading = false; emit pageFinished(success); } bool WebPage::isLoading() const { return m_loading; } QString WebPage::failureString() { return QString("Unable to load URL: ") + currentFrame()->requestedUrl().toString(); } bool WebPage::render(const QString &fileName) { QFileInfo fileInfo(fileName); QDir dir; dir.mkpath(fileInfo.absolutePath()); QSize viewportSize = this->viewportSize(); QSize pageSize = this->mainFrame()->contentsSize(); if (pageSize.isEmpty()) { return false; } QImage buffer(pageSize, QImage::Format_ARGB32); buffer.fill(qRgba(255, 255, 255, 0)); QPainter p(&buffer); p.setRenderHint( QPainter::Antialiasing, true); p.setRenderHint( QPainter::TextAntialiasing, true); p.setRenderHint( QPainter::SmoothPixmapTransform, true); this->setViewportSize(pageSize); this->mainFrame()->render(&p); p.end(); this->setViewportSize(viewportSize); return buffer.save(fileName); } QString WebPage::chooseFile(QWebFrame *parentFrame, const QString &suggestedFile) { Q_UNUSED(parentFrame); Q_UNUSED(suggestedFile); return getLastAttachedFileName(); } bool WebPage::extension(Extension extension, const ExtensionOption *option, ExtensionReturn *output) { Q_UNUSED(option); if (extension == ChooseMultipleFilesExtension) { QStringList names = QStringList() << getLastAttachedFileName(); static_cast<ChooseMultipleFilesExtensionReturn*>(output)->fileNames = names; return true; } return false; } QString WebPage::getLastAttachedFileName() { return currentFrame()->evaluateJavaScript(QString("Capybara.lastAttachedFile")).toString(); } void WebPage::replyFinished(QNetworkReply *reply) { if (reply->url() == this->currentFrame()->url()) { QStringList headers; m_lastStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QList<QByteArray> list = reply->rawHeaderList(); int length = list.size(); for(int i = 0; i < length; i++) { headers << list.at(i)+": "+reply->rawHeader(list.at(i)); } m_pageHeaders = headers.join("\n"); } } void WebPage::ignoreSslErrors(QNetworkReply *reply, const QList<QSslError> &errors) { if (m_ignoreSslErrors) reply->ignoreSslErrors(errors); } void WebPage::setIgnoreSslErrors(bool ignore) { m_ignoreSslErrors = ignore; } bool WebPage::ignoreSslErrors() { return m_ignoreSslErrors; } int WebPage::getLastStatus() { return m_lastStatus; } void WebPage::resetResponseHeaders() { m_lastStatus = 0; m_pageHeaders = QString(); } void WebPage::resetConsoleMessages() { m_consoleMessages.clear(); } QString WebPage::pageHeaders() { return m_pageHeaders; } void WebPage::handleUnsupportedContent(QNetworkReply *reply) { UnsupportedContentHandler *handler = new UnsupportedContentHandler(this, reply); Q_UNUSED(handler); } <|endoftext|>
<commit_before>#include <stdarg.h> #include <string.h> #include <sys/time.h> #include "misc.h" #include "threading.h" #include "logging.h" namespace base { int Log::level_s = Log::DEBUG; FILE* Log::fp_s = stdout; Mutex Log::m_s; void Log::set_level(int level) { ScopedLock sl(&m_s); level_s = level; } void Log::set_file(FILE* fp) { verify(fp != NULL); ScopedLock sl(&m_s); fp_s = fp; } static const char* basename(const char* fpath) { if (fpath == nullptr) { return nullptr; } const char sep = '/'; int len = strlen(fpath); int idx = len - 1; while (idx > 0) { if (fpath[idx - 1] == sep) { break; } idx--; } verify(idx >= 0 && idx < len); return &fpath[idx]; } void Log::log_v(int level, int line, const char* file, const char* fmt, va_list args) { static char indicator[] = { 'F', 'E', 'W', 'I', 'D' }; assert(level <= Log::DEBUG); if (level <= level_s) { const char* filebase = basename(file); char now_str[TIME_NOW_STR_SIZE]; time_now_str(now_str); m_s.lock(); fprintf(fp_s, "%c ", indicator[level]); if (filebase != nullptr) { fprintf(fp_s, "[%s:%d] ", filebase, line); } fprintf(fp_s, "%s | ", now_str); vfprintf(fp_s, fmt, args); fprintf(fp_s, "\n"); m_s.unlock(); fflush(fp_s); } } void Log::log(int level, int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(level, line, file, fmt, args); va_end(args); } void Log::fatal(int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::FATAL, line, file, fmt, args); va_end(args); abort(); } void Log::error(int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::ERROR, line, file, fmt, args); va_end(args); } void Log::warn(int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::WARN, line, file, fmt, args); va_end(args); } void Log::info(int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::INFO, line, file, fmt, args); va_end(args); } void Log::debug(int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::DEBUG, line, file, fmt, args); va_end(args); } void Log::fatal(const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::FATAL, 0, nullptr, fmt, args); va_end(args); abort(); } void Log::error(const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::ERROR, 0, nullptr, fmt, args); va_end(args); } void Log::warn(const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::WARN, 0, nullptr, fmt, args); va_end(args); } void Log::info(const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::INFO, 0, nullptr, fmt, args); va_end(args); } void Log::debug(const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::DEBUG, 0, nullptr, fmt, args); va_end(args); } } // namespace base <commit_msg>prevent reordered log entry time<commit_after>#include <stdarg.h> #include <string.h> #include <sys/time.h> #include "misc.h" #include "threading.h" #include "logging.h" namespace base { int Log::level_s = Log::DEBUG; FILE* Log::fp_s = stdout; Mutex Log::m_s; void Log::set_level(int level) { ScopedLock sl(&m_s); level_s = level; } void Log::set_file(FILE* fp) { verify(fp != NULL); ScopedLock sl(&m_s); fp_s = fp; } static const char* basename(const char* fpath) { if (fpath == nullptr) { return nullptr; } const char sep = '/'; int len = strlen(fpath); int idx = len - 1; while (idx > 0) { if (fpath[idx - 1] == sep) { break; } idx--; } verify(idx >= 0 && idx < len); return &fpath[idx]; } void Log::log_v(int level, int line, const char* file, const char* fmt, va_list args) { static char indicator[] = { 'F', 'E', 'W', 'I', 'D' }; assert(level <= Log::DEBUG); if (level <= level_s) { const char* filebase = basename(file); char now_str[TIME_NOW_STR_SIZE]; m_s.lock(); time_now_str(now_str); fprintf(fp_s, "%c ", indicator[level]); if (filebase != nullptr) { fprintf(fp_s, "[%s:%d] ", filebase, line); } fprintf(fp_s, "%s | ", now_str); vfprintf(fp_s, fmt, args); fprintf(fp_s, "\n"); m_s.unlock(); fflush(fp_s); } } void Log::log(int level, int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(level, line, file, fmt, args); va_end(args); } void Log::fatal(int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::FATAL, line, file, fmt, args); va_end(args); abort(); } void Log::error(int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::ERROR, line, file, fmt, args); va_end(args); } void Log::warn(int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::WARN, line, file, fmt, args); va_end(args); } void Log::info(int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::INFO, line, file, fmt, args); va_end(args); } void Log::debug(int line, const char* file, const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::DEBUG, line, file, fmt, args); va_end(args); } void Log::fatal(const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::FATAL, 0, nullptr, fmt, args); va_end(args); abort(); } void Log::error(const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::ERROR, 0, nullptr, fmt, args); va_end(args); } void Log::warn(const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::WARN, 0, nullptr, fmt, args); va_end(args); } void Log::info(const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::INFO, 0, nullptr, fmt, args); va_end(args); } void Log::debug(const char* fmt, ...) { va_list args; va_start(args, fmt); log_v(Log::DEBUG, 0, nullptr, fmt, args); va_end(args); } } // namespace base <|endoftext|>
<commit_before>// Copyright © 2016 by Donald King <chronos@chronos-tachyon.net> // Available under the MIT License. See LICENSE for details. #include "base/logging.h" #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <condition_variable> #include <cstdint> #include <cstring> #include <deque> #include <map> #include <memory> #include <mutex> #include <thread> #include <vector> #include "base/concat.h" #include "base/debug.h" #include "base/mutex.h" #include "base/result.h" namespace base { static pid_t my_gettid() { return syscall(SYS_gettid); } namespace { struct Key { const char* file; unsigned int line; Key(const char* file, unsigned int line) noexcept : file(file), line(line) {} }; static bool operator==(Key a, Key b) noexcept __attribute__((unused)); static bool operator==(Key a, Key b) noexcept { return a.line == b.line && ::strcmp(a.file, b.file) == 0; } static bool operator<(Key a, Key b) noexcept { int cmp = ::strcmp(a.file, b.file); return cmp < 0 || (cmp == 0 && a.line < b.line); } using Map = std::map<Key, std::size_t>; using Vec = std::vector<LogTarget*>; using Queue = std::deque<LogEntry>; enum ThreadState { kThreadNotStarted = 0, kThreadStarted = 1, kSingleThreaded = 2, }; static std::once_flag g_once; static std::mutex g_mu; static std::mutex g_queue_mu; static level_t g_flush = LOG_LEVEL_ERROR; // protected by g_mu static level_t g_stderr = LOG_LEVEL_INFO; // protected by g_mu static GetTidFunc g_gtid = nullptr; // protected by g_mu static GetTimeOfDayFunc g_gtod = nullptr; // protected by g_mu static Map* g_map = nullptr; // protected by g_mu static Vec* g_vec = nullptr; // protected by g_mu static int g_thread_state = kThreadNotStarted; // protected by g_queue_mu static std::condition_variable g_queue_put_cv; // protected by g_queue_mu static std::condition_variable g_queue_empty_cv; // protected by g_queue_mu static Queue* g_queue = nullptr; // protected by g_queue_mu class LogSTDERR : public LogTarget { public: LogSTDERR() noexcept = default; bool want(const char* file, unsigned int line, level_t level) const override { // g_mu held by base::want() return level >= g_stderr; } void log(const LogEntry& entry) override { // g_mu held by base::thread_body() auto str = entry.as_string(); ::write(2, str.data(), str.size()); } void flush() override { ::fdatasync(2); } }; static base::LogTarget* make_stderr() { static base::LogTarget* const ptr = new LogSTDERR; return ptr; } template <typename F, typename... Args> static void ignore_exceptions(F func, Args&&... args) { try { func(std::forward<Args>(args)...); } catch (...) { // discard exception } } static void process(base::Lock& main_lock, const LogEntry& entry) { if (entry) { for (LogTarget* target : *g_vec) { ignore_exceptions([&entry, target] { if (target->want(entry.file, entry.line, entry.level)) { target->log(entry); } }); } } if (entry.level >= g_flush) { for (LogTarget* target : *g_vec) { ignore_exceptions([target] { target->flush(); }); } } if (entry.level >= LOG_LEVEL_DFATAL) { if (entry.level >= LOG_LEVEL_FATAL || debug()) { std::terminate(); } } } static void thread_body() noexcept { auto queue_lock = base::acquire_lock(g_queue_mu); while (true) { if (g_queue->empty()) { g_queue_empty_cv.notify_all(); while (g_queue->empty()) g_queue_put_cv.wait(queue_lock); } auto entry = std::move(g_queue->front()); g_queue->pop_front(); auto main_lock = base::acquire_lock(g_mu); process(main_lock, entry); } } static void log_wait(base::Lock& queue_lock) { while (!g_queue->empty()) g_queue_empty_cv.wait(queue_lock); } static void init() { auto queue_lock = acquire_lock(g_queue_mu); auto main_lock = acquire_lock(g_mu); if (!g_gtid) g_gtid = my_gettid; if (!g_gtod) g_gtod = gettimeofday; if (!g_map) g_map = new Map; if (!g_vec) g_vec = new Vec{make_stderr()}; if (!g_queue) g_queue = new Queue; if (g_thread_state == kThreadNotStarted) { g_thread_state = kThreadStarted; std::thread(thread_body).detach(); } } } // anonymous namespace LogEntry::LogEntry(const char* file, unsigned int line, level_t level, std::string message) noexcept : file(file), line(line), level(level), message(std::move(message)) { std::call_once(g_once, [] { init(); }); auto main_lock = acquire_lock(g_mu); ::bzero(&time, sizeof(time)); (*g_gtod)(&time, nullptr); tid = (*g_gtid)(); } void LogEntry::append_to(std::string* out) const { char ch; if (level >= LOG_LEVEL_DFATAL) { ch = 'F'; } else if (level >= LOG_LEVEL_ERROR) { ch = 'E'; } else if (level >= LOG_LEVEL_WARN) { ch = 'W'; } else if (level >= LOG_LEVEL_INFO) { ch = 'I'; } else { ch = 'D'; } struct tm tm; ::gmtime_r(&time.tv_sec, &tm); // "[IWEF]<mm><dd> <hh>:<mm>:<ss>.<uuuuuu> <tid> <file>:<line>] <message>" std::array<char, 24> buf; ::snprintf(buf.data(), buf.size(), "%c%02u%02u %02u:%02u:%02u.%06lu ", ch, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, time.tv_usec); concat_to(out, std::string(buf.data()), tid, ' ', file, ':', line, "] ", message, '\n'); } std::string LogEntry::as_string() const { std::string out; append_to(&out); return out; } static std::unique_ptr<std::ostringstream> make_ss(const char* file, unsigned int line, unsigned int n, level_t level) { if (file == nullptr) std::terminate(); if (line == 0) std::terminate(); if (n == 0) std::terminate(); std::unique_ptr<std::ostringstream> ptr; if (want(file, line, n, level)) ptr.reset(new std::ostringstream); return ptr; } Logger::Logger(const char* file, unsigned int line, unsigned int every_n, level_t level) : file_(file), line_(line), n_(every_n), level_(level), ss_(make_ss(file, line, every_n, level)) {} bool want(const char* file, unsigned int line, unsigned int n, level_t level) { std::call_once(g_once, [] { init(); }); if (level >= LOG_LEVEL_DFATAL) return true; auto main_lock = base::acquire_lock(g_mu); if (n > 1) { Key key(file, line); auto pair = g_map->insert(std::make_pair(key, 0)); auto& count = pair.first->second; bool x = (count == 0); count = (count + 1) % n; if (!x) return false; } bool result = false; for (const LogTarget* target : *g_vec) { ignore_exceptions([file, line, level, target, &result] { result = target->want(file, line, level); }); if (result) break; } return result; } void log(const LogEntry& entry) { std::call_once(g_once, [] { init(); }); auto queue_lock = base::acquire_lock(g_queue_mu); if (g_thread_state == kSingleThreaded) { auto main_lock = base::acquire_lock(g_mu); process(main_lock, entry); return; } g_queue->push_back(entry); g_queue_put_cv.notify_one(); if (entry.level >= LOG_LEVEL_DFATAL) log_wait(queue_lock); } void log_single_threaded() { auto queue_lock = acquire_lock(g_queue_mu); if (g_thread_state == kThreadStarted) throw std::logic_error("logging thread is already running!"); g_thread_state = kSingleThreaded; } void log_flush() { auto queue_lock = base::acquire_lock(g_queue_mu); log_wait(queue_lock); auto main_lock = base::acquire_lock(g_mu); for (LogTarget* target : *g_vec) { ignore_exceptions([target] { target->flush(); }); } } void log_flush_set_level(level_t level) { auto main_lock = acquire_lock(g_mu); g_flush = level; } void log_stderr_set_level(level_t level) { auto main_lock = acquire_lock(g_mu); g_stderr = level; } void log_target_add(LogTarget* target) { auto main_lock = acquire_lock(g_mu); g_vec->push_back(target); } void log_target_remove(LogTarget* target) { auto queue_lock = base::acquire_lock(g_queue_mu); log_wait(queue_lock); auto main_lock = acquire_lock(g_mu); auto& v = *g_vec; for (auto it = v.begin(), end = v.end(); it != end; ++it) { if (*it == target) { v.erase(it); break; } } } void log_set_gettid(GetTidFunc func) { auto main_lock = acquire_lock(g_mu); if (func) g_gtid = func; else g_gtid = my_gettid; } void log_set_gettimeofday(GetTimeOfDayFunc func) { auto main_lock = acquire_lock(g_mu); if (func) g_gtod = func; else g_gtod = gettimeofday; } namespace internal { void log_exception(const char* file, unsigned int line, std::exception_ptr e) { Logger logger(file, line, 1, LOG_LEVEL_ERROR); try { std::rethrow_exception(e); } catch (const std::system_error& e) { const auto& ecode = e.code(); logger << "caught std::system_error\n" << "\t" << ecode.category().name() << "(" << ecode.value() << "): " << e.what(); } catch (const std::exception& e) { logger << "caught std::exception\n" << "\t[" << typeid(e).name() << "]\n" << "\t" << e.what(); } catch (...) { logger << "caught unclassifiable exception!"; } } Logger log_check(const char* file, unsigned int line, const char* expr, bool cond) { if (cond) return Logger(); Logger logger(file, line, 1, LOG_LEVEL_DFATAL); logger << "CHECK FAILED: " << expr; return logger; } Logger log_check_ok(const char* file, unsigned int line, const char* expr, const Result& rslt) { if (rslt) return Logger(); Logger logger(file, line, 1, LOG_LEVEL_DFATAL); logger << "CHECK FAILED: " << expr << ": " << rslt.as_string(); return logger; } } // namespace internal } // namespace base <commit_msg>Call std::terminate from within the stack frame that provoked it.<commit_after>// Copyright © 2016 by Donald King <chronos@chronos-tachyon.net> // Available under the MIT License. See LICENSE for details. #include "base/logging.h" #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <condition_variable> #include <cstdint> #include <cstring> #include <deque> #include <map> #include <memory> #include <mutex> #include <thread> #include <vector> #include "base/concat.h" #include "base/debug.h" #include "base/mutex.h" #include "base/result.h" namespace base { static pid_t my_gettid() { return syscall(SYS_gettid); } inline namespace implementation { struct Key { const char* file; unsigned int line; Key(const char* file, unsigned int line) noexcept : file(file), line(line) {} }; static bool operator==(Key a, Key b) noexcept __attribute__((unused)); static bool operator==(Key a, Key b) noexcept { return a.line == b.line && ::strcmp(a.file, b.file) == 0; } static bool operator<(Key a, Key b) noexcept { int cmp = ::strcmp(a.file, b.file); return cmp < 0 || (cmp == 0 && a.line < b.line); } using Map = std::map<Key, std::size_t>; using Vec = std::vector<LogTarget*>; using Queue = std::deque<LogEntry>; enum ThreadState { kThreadNotStarted = 0, kThreadStarted = 1, kSingleThreaded = 2, }; static std::once_flag g_once; static std::mutex g_mu; static std::mutex g_queue_mu; static level_t g_flush = LOG_LEVEL_ERROR; // protected by g_mu static level_t g_stderr = LOG_LEVEL_INFO; // protected by g_mu static GetTidFunc g_gtid = nullptr; // protected by g_mu static GetTimeOfDayFunc g_gtod = nullptr; // protected by g_mu static Map* g_map = nullptr; // protected by g_mu static Vec* g_vec = nullptr; // protected by g_mu static int g_thread_state = kThreadNotStarted; // protected by g_queue_mu static std::condition_variable g_queue_put_cv; // protected by g_queue_mu static std::condition_variable g_queue_empty_cv; // protected by g_queue_mu static Queue* g_queue = nullptr; // protected by g_queue_mu class LogSTDERR : public LogTarget { public: LogSTDERR() noexcept = default; bool want(const char* file, unsigned int line, level_t level) const override { // g_mu held by base::want() return level >= g_stderr; } void log(const LogEntry& entry) override { // g_mu held by base::thread_body() auto str = entry.as_string(); ::write(2, str.data(), str.size()); } void flush() override { ::fdatasync(2); } }; static base::LogTarget* make_stderr() { static base::LogTarget* const ptr = new LogSTDERR; return ptr; } template <typename F, typename... Args> static void ignore_exceptions(F func, Args&&... args) { try { func(std::forward<Args>(args)...); } catch (...) { // discard exception } } static void process(base::Lock& main_lock, const LogEntry& entry) { if (entry) { for (LogTarget* target : *g_vec) { ignore_exceptions([&entry, target] { if (target->want(entry.file, entry.line, entry.level)) { target->log(entry); } }); } } if (entry.level >= g_flush) { for (LogTarget* target : *g_vec) { ignore_exceptions([target] { target->flush(); }); } } } static void thread_body() noexcept { auto queue_lock = base::acquire_lock(g_queue_mu); while (true) { if (g_queue->empty()) { g_queue_empty_cv.notify_all(); while (g_queue->empty()) g_queue_put_cv.wait(queue_lock); } auto entry = std::move(g_queue->front()); g_queue->pop_front(); auto main_lock = base::acquire_lock(g_mu); process(main_lock, entry); } } static void log_wait(base::Lock& queue_lock) { while (!g_queue->empty()) g_queue_empty_cv.wait(queue_lock); } static void init() { auto queue_lock = acquire_lock(g_queue_mu); auto main_lock = acquire_lock(g_mu); if (!g_gtid) g_gtid = my_gettid; if (!g_gtod) g_gtod = gettimeofday; if (!g_map) g_map = new Map; if (!g_vec) g_vec = new Vec{make_stderr()}; if (!g_queue) g_queue = new Queue; if (g_thread_state == kThreadNotStarted) { g_thread_state = kThreadStarted; std::thread(thread_body).detach(); } } static void maybe_terminate(const LogEntry& entry) { if (entry.level >= LOG_LEVEL_DFATAL) { if (entry.level >= LOG_LEVEL_FATAL || debug()) { std::terminate(); } } } } // inline namespace implementation LogEntry::LogEntry(const char* file, unsigned int line, level_t level, std::string message) noexcept : file(file), line(line), level(level), message(std::move(message)) { std::call_once(g_once, [] { init(); }); auto main_lock = acquire_lock(g_mu); ::bzero(&time, sizeof(time)); (*g_gtod)(&time, nullptr); tid = (*g_gtid)(); } void LogEntry::append_to(std::string* out) const { char ch; if (level >= LOG_LEVEL_DFATAL) { ch = 'F'; } else if (level >= LOG_LEVEL_ERROR) { ch = 'E'; } else if (level >= LOG_LEVEL_WARN) { ch = 'W'; } else if (level >= LOG_LEVEL_INFO) { ch = 'I'; } else { ch = 'D'; } struct tm tm; ::gmtime_r(&time.tv_sec, &tm); // "[IWEF]<mm><dd> <hh>:<mm>:<ss>.<uuuuuu> <tid> <file>:<line>] <message>" std::array<char, 24> buf; ::snprintf(buf.data(), buf.size(), "%c%02u%02u %02u:%02u:%02u.%06lu ", ch, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, time.tv_usec); concat_to(out, std::string(buf.data()), tid, ' ', file, ':', line, "] ", message, '\n'); } std::string LogEntry::as_string() const { std::string out; append_to(&out); return out; } static std::unique_ptr<std::ostringstream> make_ss(const char* file, unsigned int line, unsigned int n, level_t level) { if (file == nullptr) std::terminate(); if (line == 0) std::terminate(); if (n == 0) std::terminate(); std::unique_ptr<std::ostringstream> ptr; if (want(file, line, n, level)) ptr.reset(new std::ostringstream); return ptr; } Logger::Logger(const char* file, unsigned int line, unsigned int every_n, level_t level) : file_(file), line_(line), n_(every_n), level_(level), ss_(make_ss(file, line, every_n, level)) {} bool want(const char* file, unsigned int line, unsigned int n, level_t level) { std::call_once(g_once, [] { init(); }); if (level >= LOG_LEVEL_DFATAL) return true; auto main_lock = base::acquire_lock(g_mu); if (n > 1) { Key key(file, line); auto pair = g_map->insert(std::make_pair(key, 0)); auto& count = pair.first->second; bool x = (count == 0); count = (count + 1) % n; if (!x) return false; } bool result = false; for (const LogTarget* target : *g_vec) { ignore_exceptions([file, line, level, target, &result] { result = target->want(file, line, level); }); if (result) break; } return result; } void log(const LogEntry& entry) { std::call_once(g_once, [] { init(); }); auto queue_lock = base::acquire_lock(g_queue_mu); if (g_thread_state == kSingleThreaded) { auto main_lock = base::acquire_lock(g_mu); process(main_lock, entry); maybe_terminate(entry); return; } g_queue->push_back(entry); g_queue_put_cv.notify_one(); if (entry.level >= LOG_LEVEL_DFATAL) { log_wait(queue_lock); maybe_terminate(entry); } } void log_single_threaded() { auto queue_lock = acquire_lock(g_queue_mu); if (g_thread_state == kThreadStarted) throw std::logic_error("logging thread is already running!"); g_thread_state = kSingleThreaded; } void log_flush() { auto queue_lock = base::acquire_lock(g_queue_mu); log_wait(queue_lock); auto main_lock = base::acquire_lock(g_mu); for (LogTarget* target : *g_vec) { ignore_exceptions([target] { target->flush(); }); } } void log_flush_set_level(level_t level) { auto main_lock = acquire_lock(g_mu); g_flush = level; } void log_stderr_set_level(level_t level) { auto main_lock = acquire_lock(g_mu); g_stderr = level; } void log_target_add(LogTarget* target) { auto main_lock = acquire_lock(g_mu); g_vec->push_back(target); } void log_target_remove(LogTarget* target) { auto queue_lock = base::acquire_lock(g_queue_mu); log_wait(queue_lock); auto main_lock = acquire_lock(g_mu); auto& v = *g_vec; for (auto it = v.begin(), end = v.end(); it != end; ++it) { if (*it == target) { v.erase(it); break; } } } void log_set_gettid(GetTidFunc func) { auto main_lock = acquire_lock(g_mu); if (func) g_gtid = func; else g_gtid = my_gettid; } void log_set_gettimeofday(GetTimeOfDayFunc func) { auto main_lock = acquire_lock(g_mu); if (func) g_gtod = func; else g_gtod = gettimeofday; } namespace internal { void log_exception(const char* file, unsigned int line, std::exception_ptr e) { Logger logger(file, line, 1, LOG_LEVEL_ERROR); try { std::rethrow_exception(e); } catch (const std::system_error& e) { const auto& ecode = e.code(); logger << "caught std::system_error\n" << "\t" << ecode.category().name() << "(" << ecode.value() << "): " << e.what(); } catch (const std::exception& e) { logger << "caught std::exception\n" << "\t[" << typeid(e).name() << "]\n" << "\t" << e.what(); } catch (...) { logger << "caught unclassifiable exception!"; } } Logger log_check(const char* file, unsigned int line, const char* expr, bool cond) { if (cond) return Logger(); Logger logger(file, line, 1, LOG_LEVEL_DFATAL); logger << "CHECK FAILED: " << expr; return logger; } Logger log_check_ok(const char* file, unsigned int line, const char* expr, const Result& rslt) { if (rslt) return Logger(); Logger logger(file, line, 1, LOG_LEVEL_DFATAL); logger << "CHECK FAILED: " << expr << ": " << rslt.as_string(); return logger; } } // namespace internal } // namespace base <|endoftext|>
<commit_before> #include <cantera/Cantera.h> #include <cantera/IdealGasMix.h> // defines class IdealGasMix #include <iostream> #include <fstream> #include <vector> #include <map> #include <numeric> #include <string> #include <algorithm> using namespace std; using namespace Cantera; // The program is put into a function so that error handling code can // be conveniently put around the whole thing. See main() below. void demoprog() { printf("\n\n**** Testing modifying NASA polynomial coefficients ****\n\n"); IdealGasMix gas("h2o2.cti","ohmech"); int nsp = gas.nSpecies(); int type; doublereal c[15]; doublereal minTemp, maxTemp, refPressure; // get a reference to the species thermo property manager SpeciesThermo& sp = gas.speciesThermo(); int n, j; // these constants define the location of coefficient "a6" in the // cofficient array c. The c array contains Tmid in the first // location, followed by the 7 low-temperature coefficients, then // the seven high-temperature ones. const int LOW_A6 = 6; //const int HIGH_A6 = 13; for (n = 0; n < nsp; n++) { printf("\n\n %s (original):", gas.speciesName(n).c_str()); // get the NASA coefficients in array c sp.reportParams(n, type, c, minTemp, maxTemp, refPressure); // print the unmodified NASA coefficients printf("\n "); for (j = 1; j < 8; j++) printf(" A%d ", j); printf("\n low:"); for (j = 1; j < 8; j++) printf(" %10.4E ", c[j]); printf("\n high:"); for (j = 8; j < 15; j++) printf(" %10.4E ", c[j]); printf("\n "); // modify coefficient A6 of the low-temperature polynomial // Note that since we are not modifying the high-temperature // polynomial, a warning will be printed about a discontinuity // in enthalpy at Tmid. c[LOW_A6] += 1.0e4; sp.modifyParams(n, c); sp.reportParams(n, type, c, minTemp, maxTemp, refPressure); // print the modified NASA coefficients printf("\n\n %s (modified):", gas.speciesName(n).c_str()); printf("\n "); for (j = 1; j < 8; j++) printf(" A%d ", j); printf("\n low:"); for (j = 1; j < 8; j++) printf(" %10.4E ", c[j]); printf("\n high:"); for (j = 8; j < 15; j++) printf(" %10.4E ", c[j]); printf("\n "); } } int main() { try { demoprog(); } catch (CanteraError) { showErrors(cout); } } <commit_msg>Added namespace to get it to compile<commit_after> #include <cantera/Cantera.h> #include <cantera/IdealGasMix.h> // defines class IdealGasMix #include <iostream> #include <fstream> #include <vector> #include <map> #include <numeric> #include <string> #include <algorithm> using namespace std; using namespace Cantera; using namespace Cantera_CXX; // The program is put into a function so that error handling code can // be conveniently put around the whole thing. See main() below. void demoprog() { printf("\n\n**** Testing modifying NASA polynomial coefficients ****\n\n"); IdealGasMix gas("h2o2.cti","ohmech"); int nsp = gas.nSpecies(); int type; doublereal c[15]; doublereal minTemp, maxTemp, refPressure; // get a reference to the species thermo property manager SpeciesThermo& sp = gas.speciesThermo(); int n, j; // these constants define the location of coefficient "a6" in the // cofficient array c. The c array contains Tmid in the first // location, followed by the 7 low-temperature coefficients, then // the seven high-temperature ones. const int LOW_A6 = 6; //const int HIGH_A6 = 13; for (n = 0; n < nsp; n++) { printf("\n\n %s (original):", gas.speciesName(n).c_str()); // get the NASA coefficients in array c sp.reportParams(n, type, c, minTemp, maxTemp, refPressure); // print the unmodified NASA coefficients printf("\n "); for (j = 1; j < 8; j++) printf(" A%d ", j); printf("\n low:"); for (j = 1; j < 8; j++) printf(" %10.4E ", c[j]); printf("\n high:"); for (j = 8; j < 15; j++) printf(" %10.4E ", c[j]); printf("\n "); // modify coefficient A6 of the low-temperature polynomial // Note that since we are not modifying the high-temperature // polynomial, a warning will be printed about a discontinuity // in enthalpy at Tmid. c[LOW_A6] += 1.0e4; sp.modifyParams(n, c); sp.reportParams(n, type, c, minTemp, maxTemp, refPressure); // print the modified NASA coefficients printf("\n\n %s (modified):", gas.speciesName(n).c_str()); printf("\n "); for (j = 1; j < 8; j++) printf(" A%d ", j); printf("\n low:"); for (j = 1; j < 8; j++) printf(" %10.4E ", c[j]); printf("\n high:"); for (j = 8; j < 15; j++) printf(" %10.4E ", c[j]); printf("\n "); } } int main() { try { demoprog(); } catch (CanteraError) { showErrors(cout); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 - 2013 Jolla Ltd. ** Contact: http://jolla.com/ ** ** This file is part of Qt Creator. ** ** 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. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Digia. ** ****************************************************************************/ #include "mertargetkitinformation.h" #include "mersdkkitinformation.h" #include "merconstants.h" #include "merdevicefactory.h" #include "mersdk.h" #include "mersdkmanager.h" #include "meroptionspage.h" #include <projectexplorer/projectexplorerconstants.h> #include <extensionsystem/pluginmanager.h> #include <coreplugin/icore.h> #include <QPushButton> #include <QComboBox> namespace Mer { namespace Internal { MerTargetKitInformation::MerTargetKitInformation() { } Core::Id MerTargetKitInformation::dataId() const { return Core::Id(Constants::MER_TARGET_KIT_INFORMATION); } unsigned int MerTargetKitInformation::priority() const { return 23; } QVariant MerTargetKitInformation::defaultValue(ProjectExplorer::Kit *kit) const { return MerTargetKitInformation::targetName(kit); } QList<ProjectExplorer::Task> MerTargetKitInformation::validate(const ProjectExplorer::Kit *kit) const { if (MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(kit))) { const MerSdk *sdk = MerSdkKitInformation::sdk(kit); const QString &target = kit->value(Core::Id(Constants::TARGET)).toString(); if (sdk && !sdk->targetNames().contains(target)) { const QString message = QCoreApplication::translate("MerTarget", "No valid MerTarget for %1 sdk found").arg(sdk->virtualMachineName()); return QList<ProjectExplorer::Task>() << ProjectExplorer::Task(ProjectExplorer::Task::Error, message, Utils::FileName(), -1, Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)); } } return QList<ProjectExplorer::Task>(); } QString MerTargetKitInformation::targetName(const ProjectExplorer::Kit *kit) { if (!kit) return QString(); return kit->value(Core::Id(Constants::TARGET)).toString(); } ProjectExplorer::KitInformation::ItemList MerTargetKitInformation::toUserOutput(const ProjectExplorer::Kit *kit) const { if (MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(kit))) { QString targetName = MerTargetKitInformation::targetName(kit); return ProjectExplorer::KitInformation::ItemList() << qMakePair(tr("MerTarget"),targetName); } return ProjectExplorer::KitInformation::ItemList(); } ProjectExplorer::KitConfigWidget *MerTargetKitInformation::createConfigWidget(ProjectExplorer::Kit *kit) const { return new MerTargetKitInformationWidget(kit); } void MerTargetKitInformation::setTargetName(ProjectExplorer::Kit *kit, const QString& targetName) { if(kit->value(Core::Id(Constants::TARGET)) != targetName) kit->setValue(Core::Id(Constants::TARGET),targetName); } void MerTargetKitInformation::addToEnvironment(const ProjectExplorer::Kit *kit, Utils::Environment &env) const { const QString targetName = MerTargetKitInformation::targetName(kit); env.appendOrSet(QLatin1String(Constants::MER_SSH_TARGET_NAME),targetName); } //////////////////////////////////////////////////////////////////////////////////////////// MerTargetKitInformationWidget::MerTargetKitInformationWidget(ProjectExplorer::Kit *kit, bool sticky) : ProjectExplorer::KitConfigWidget(kit,sticky), m_combo(new QComboBox), m_manageButton(new QPushButton(tr("Manage..."))) { refresh(); connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentIndexChanged())); connect(m_manageButton, SIGNAL(clicked()), this, SLOT(handleManageClicked())); connect(MerSdkManager::instance(), SIGNAL(sdksUpdated()), this, SLOT(handleSdksUpdated())); } QString MerTargetKitInformationWidget::displayName() const { return tr("Mer Target:"); } QString MerTargetKitInformationWidget::toolTip() const { return tr("Name of traget used by sb2."); } void MerTargetKitInformationWidget::makeReadOnly() { m_combo->setEnabled(false); } void MerTargetKitInformationWidget::refresh() { const MerSdk* sdk = MerSdkKitInformation::sdk(m_kit); QString targetName = MerTargetKitInformation::targetName(m_kit); int i = -1; m_combo->blockSignals(true); m_combo->clear(); if (sdk && !targetName.isEmpty()) { foreach (const QString& targetName, sdk->targetNames()) { m_combo->addItem(targetName); } } for (i = m_combo->count() - 1; i >= 0; --i) { if (targetName == m_combo->itemText(i)) break; } if(m_combo->count() == 0) { m_combo->addItem(tr("None")); i=0; } m_combo->blockSignals(false); m_combo->setCurrentIndex(i); } bool MerTargetKitInformationWidget::visibleInKit() { return MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(m_kit)); } QWidget *MerTargetKitInformationWidget::mainWidget() const { return m_combo; } QWidget *MerTargetKitInformationWidget::buttonWidget() const { return m_manageButton; } void MerTargetKitInformationWidget::handleManageClicked() { MerOptionsPage *page = ExtensionSystem::PluginManager::getObject<MerOptionsPage>(); if (page) { const MerSdk* sdk = MerSdkKitInformation::sdk(m_kit); if(sdk) page->setSdk(m_combo->currentText()); } Core::ICore::showOptionsDialog(Constants::MER_OPTIONS_CATEGORY,Constants::MER_OPTIONS_ID); } void MerTargetKitInformationWidget::handleCurrentIndexChanged() { const MerSdk* sdk = MerSdkKitInformation::sdk(m_kit); if (sdk && sdk->targetNames().contains(m_combo->currentText())) MerTargetKitInformation::setTargetName(m_kit,m_combo->currentText()); } void MerTargetKitInformationWidget::handleSdksUpdated() { refresh(); } } } <commit_msg>Fix typo<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 - 2013 Jolla Ltd. ** Contact: http://jolla.com/ ** ** This file is part of Qt Creator. ** ** 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. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Digia. ** ****************************************************************************/ #include "mertargetkitinformation.h" #include "mersdkkitinformation.h" #include "merconstants.h" #include "merdevicefactory.h" #include "mersdk.h" #include "mersdkmanager.h" #include "meroptionspage.h" #include <projectexplorer/projectexplorerconstants.h> #include <extensionsystem/pluginmanager.h> #include <coreplugin/icore.h> #include <QPushButton> #include <QComboBox> namespace Mer { namespace Internal { MerTargetKitInformation::MerTargetKitInformation() { } Core::Id MerTargetKitInformation::dataId() const { return Core::Id(Constants::MER_TARGET_KIT_INFORMATION); } unsigned int MerTargetKitInformation::priority() const { return 23; } QVariant MerTargetKitInformation::defaultValue(ProjectExplorer::Kit *kit) const { return MerTargetKitInformation::targetName(kit); } QList<ProjectExplorer::Task> MerTargetKitInformation::validate(const ProjectExplorer::Kit *kit) const { if (MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(kit))) { const MerSdk *sdk = MerSdkKitInformation::sdk(kit); const QString &target = kit->value(Core::Id(Constants::TARGET)).toString(); if (sdk && !sdk->targetNames().contains(target)) { const QString message = QCoreApplication::translate("MerTarget", "No valid MerTarget for %1 sdk found").arg(sdk->virtualMachineName()); return QList<ProjectExplorer::Task>() << ProjectExplorer::Task(ProjectExplorer::Task::Error, message, Utils::FileName(), -1, Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)); } } return QList<ProjectExplorer::Task>(); } QString MerTargetKitInformation::targetName(const ProjectExplorer::Kit *kit) { if (!kit) return QString(); return kit->value(Core::Id(Constants::TARGET)).toString(); } ProjectExplorer::KitInformation::ItemList MerTargetKitInformation::toUserOutput(const ProjectExplorer::Kit *kit) const { if (MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(kit))) { QString targetName = MerTargetKitInformation::targetName(kit); return ProjectExplorer::KitInformation::ItemList() << qMakePair(tr("MerTarget"),targetName); } return ProjectExplorer::KitInformation::ItemList(); } ProjectExplorer::KitConfigWidget *MerTargetKitInformation::createConfigWidget(ProjectExplorer::Kit *kit) const { return new MerTargetKitInformationWidget(kit); } void MerTargetKitInformation::setTargetName(ProjectExplorer::Kit *kit, const QString& targetName) { if(kit->value(Core::Id(Constants::TARGET)) != targetName) kit->setValue(Core::Id(Constants::TARGET),targetName); } void MerTargetKitInformation::addToEnvironment(const ProjectExplorer::Kit *kit, Utils::Environment &env) const { const QString targetName = MerTargetKitInformation::targetName(kit); env.appendOrSet(QLatin1String(Constants::MER_SSH_TARGET_NAME),targetName); } //////////////////////////////////////////////////////////////////////////////////////////// MerTargetKitInformationWidget::MerTargetKitInformationWidget(ProjectExplorer::Kit *kit, bool sticky) : ProjectExplorer::KitConfigWidget(kit,sticky), m_combo(new QComboBox), m_manageButton(new QPushButton(tr("Manage..."))) { refresh(); connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentIndexChanged())); connect(m_manageButton, SIGNAL(clicked()), this, SLOT(handleManageClicked())); connect(MerSdkManager::instance(), SIGNAL(sdksUpdated()), this, SLOT(handleSdksUpdated())); } QString MerTargetKitInformationWidget::displayName() const { return tr("Mer Target:"); } QString MerTargetKitInformationWidget::toolTip() const { return tr("Name of target used by sb2."); } void MerTargetKitInformationWidget::makeReadOnly() { m_combo->setEnabled(false); } void MerTargetKitInformationWidget::refresh() { const MerSdk* sdk = MerSdkKitInformation::sdk(m_kit); QString targetName = MerTargetKitInformation::targetName(m_kit); int i = -1; m_combo->blockSignals(true); m_combo->clear(); if (sdk && !targetName.isEmpty()) { foreach (const QString& targetName, sdk->targetNames()) { m_combo->addItem(targetName); } } for (i = m_combo->count() - 1; i >= 0; --i) { if (targetName == m_combo->itemText(i)) break; } if(m_combo->count() == 0) { m_combo->addItem(tr("None")); i=0; } m_combo->blockSignals(false); m_combo->setCurrentIndex(i); } bool MerTargetKitInformationWidget::visibleInKit() { return MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(m_kit)); } QWidget *MerTargetKitInformationWidget::mainWidget() const { return m_combo; } QWidget *MerTargetKitInformationWidget::buttonWidget() const { return m_manageButton; } void MerTargetKitInformationWidget::handleManageClicked() { MerOptionsPage *page = ExtensionSystem::PluginManager::getObject<MerOptionsPage>(); if (page) { const MerSdk* sdk = MerSdkKitInformation::sdk(m_kit); if(sdk) page->setSdk(m_combo->currentText()); } Core::ICore::showOptionsDialog(Constants::MER_OPTIONS_CATEGORY,Constants::MER_OPTIONS_ID); } void MerTargetKitInformationWidget::handleCurrentIndexChanged() { const MerSdk* sdk = MerSdkKitInformation::sdk(m_kit); if (sdk && sdk->targetNames().contains(m_combo->currentText())) MerTargetKitInformation::setTargetName(m_kit,m_combo->currentText()); } void MerTargetKitInformationWidget::handleSdksUpdated() { refresh(); } } } <|endoftext|>
<commit_before>#include "qmlcodecompletion.h" #include "qmleditor.h" #include "qmlmodelmanagerinterface.h" #include "qmlexpressionundercursor.h" #include "qmllookupcontext.h" #include "qmlresolveexpression.h" #include "qmlsymbol.h" #include <texteditor/basetexteditor.h> #include <QtDebug> using namespace QmlEditor::Internal; QmlCodeCompletion::QmlCodeCompletion(QmlModelManagerInterface *modelManager,QObject *parent) : TextEditor::ICompletionCollector(parent), m_modelManager(modelManager), m_editor(0), m_startPosition(0), m_caseSensitivity(Qt::CaseSensitive) { Q_ASSERT(modelManager); } QmlCodeCompletion::~QmlCodeCompletion() { } Qt::CaseSensitivity QmlCodeCompletion::caseSensitivity() const { return m_caseSensitivity; } void QmlCodeCompletion::setCaseSensitivity(Qt::CaseSensitivity caseSensitivity) { m_caseSensitivity = caseSensitivity; } bool QmlCodeCompletion::supportsEditor(TextEditor::ITextEditable *editor) { if (qobject_cast<ScriptEditor *>(editor->widget())) return true; return false; } bool QmlCodeCompletion::triggersCompletion(TextEditor::ITextEditable *) { return false; } int QmlCodeCompletion::startCompletion(TextEditor::ITextEditable *editor) { m_editor = editor; ScriptEditor *edit = qobject_cast<ScriptEditor *>(m_editor->widget()); if (! edit) return -1; int pos = editor->position(); while (editor->characterAt(pos - 1).isLetterOrNumber() || editor->characterAt(pos - 1) == QLatin1Char('_')) --pos; m_startPosition = pos; m_completions.clear(); // foreach (const QString &word, edit->keywords()) { // TextEditor::CompletionItem item(this); // item.m_text = word; // m_completions.append(item); // } // // foreach (const QString &word, edit->words()) { // TextEditor::CompletionItem item(this); // item.m_text = word; // m_completions.append(item); // } QmlDocument::Ptr qmlDocument = edit->qmlDocument(); // qDebug() << "*** document:" << qmlDocument; if (qmlDocument.isNull()) return pos; if (!qmlDocument->program()) qmlDocument = m_modelManager->snapshot().value(qmlDocument->fileName()); if (qmlDocument->program()) { QmlJS::AST::UiProgram *program = qmlDocument->program(); // qDebug() << "*** program:" << program; if (program) { QmlExpressionUnderCursor expressionUnderCursor; QTextCursor cursor(edit->document()); cursor.setPosition(pos); expressionUnderCursor(cursor, qmlDocument); QmlLookupContext context(expressionUnderCursor.expressionScopes(), qmlDocument, m_modelManager->snapshot()); QmlResolveExpression resolver(context); QList<QmlSymbol*> symbols = resolver.visibleSymbols(expressionUnderCursor.expressionNode()); foreach (QmlSymbol *symbol, symbols) { QString word; if (symbol->isIdSymbol()) { word = symbol->asIdSymbol()->id(); } else { word = symbol->name(); } if (word.isEmpty()) continue; TextEditor::CompletionItem item(this); item.m_text = word; m_completions.append(item); } } } return pos; } void QmlCodeCompletion::completions(QList<TextEditor::CompletionItem> *completions) { // ### FIXME: this code needs to be generalized. const int length = m_editor->position() - m_startPosition; if (length == 0) *completions = m_completions; else if (length > 0) { const QString key = m_editor->textAt(m_startPosition, length); /* * This code builds a regular expression in order to more intelligently match * camel-case style. This means upper-case characters will be rewritten as follows: * * A => [a-z0-9_]*A (for any but the first capital letter) * * Meaning it allows any sequence of lower-case characters to preceed an * upper-case character. So for example gAC matches getActionController. */ QString keyRegExp; keyRegExp += QLatin1Char('^'); bool first = true; foreach (const QChar &c, key) { if (c.isUpper() && !first) { keyRegExp += QLatin1String("[a-z0-9_]*"); keyRegExp += c; } else if (m_caseSensitivity == Qt::CaseInsensitive && c.isLower()) { keyRegExp += QLatin1Char('['); keyRegExp += c; keyRegExp += c.toUpper(); keyRegExp += QLatin1Char(']'); } else { keyRegExp += QRegExp::escape(c); } first = false; } const QRegExp regExp(keyRegExp, Qt::CaseSensitive); foreach (TextEditor::CompletionItem item, m_completions) { if (regExp.indexIn(item.m_text) == 0) { item.m_relevance = (key.length() > 0 && item.m_text.startsWith(key, Qt::CaseInsensitive)) ? 1 : 0; (*completions) << item; } } } } void QmlCodeCompletion::complete(const TextEditor::CompletionItem &item) { const QString toInsert = item.m_text; const int length = m_editor->position() - m_startPosition; m_editor->setCurPos(m_startPosition); m_editor->replace(length, toInsert); } bool QmlCodeCompletion::partiallyComplete(const QList<TextEditor::CompletionItem> &completionItems) { if (completionItems.count() == 1) { complete(completionItems.first()); return true; } else { // Compute common prefix QString firstKey = completionItems.first().m_text; QString lastKey = completionItems.last().m_text; const int length = qMin(firstKey.length(), lastKey.length()); firstKey.truncate(length); lastKey.truncate(length); while (firstKey != lastKey) { firstKey.chop(1); lastKey.chop(1); } int typedLength = m_editor->position() - m_startPosition; if (!firstKey.isEmpty() && firstKey.length() > typedLength) { m_editor->setCurPos(m_startPosition); m_editor->replace(typedLength, firstKey); } } return false; } void QmlCodeCompletion::cleanup() { m_editor = 0; m_startPosition = 0; m_completions.clear(); } <commit_msg>QmlEditor: Fix compilation on Windows.<commit_after>#include "qmlcodecompletion.h" #include "qmleditor.h" #include "qmlmodelmanagerinterface.h" #include "qmlexpressionundercursor.h" #include "qmllookupcontext.h" #include "qmlresolveexpression.h" #include "qmlsymbol.h" #include <texteditor/basetexteditor.h> #include <QtDebug> using namespace QmlEditor; using namespace QmlEditor::Internal; QmlCodeCompletion::QmlCodeCompletion(QmlModelManagerInterface *modelManager,QObject *parent) : TextEditor::ICompletionCollector(parent), m_modelManager(modelManager), m_editor(0), m_startPosition(0), m_caseSensitivity(Qt::CaseSensitive) { Q_ASSERT(modelManager); } QmlCodeCompletion::~QmlCodeCompletion() { } Qt::CaseSensitivity QmlCodeCompletion::caseSensitivity() const { return m_caseSensitivity; } void QmlCodeCompletion::setCaseSensitivity(Qt::CaseSensitivity caseSensitivity) { m_caseSensitivity = caseSensitivity; } bool QmlCodeCompletion::supportsEditor(TextEditor::ITextEditable *editor) { if (qobject_cast<ScriptEditor *>(editor->widget())) return true; return false; } bool QmlCodeCompletion::triggersCompletion(TextEditor::ITextEditable *) { return false; } int QmlCodeCompletion::startCompletion(TextEditor::ITextEditable *editor) { m_editor = editor; ScriptEditor *edit = qobject_cast<ScriptEditor *>(m_editor->widget()); if (! edit) return -1; int pos = editor->position(); while (editor->characterAt(pos - 1).isLetterOrNumber() || editor->characterAt(pos - 1) == QLatin1Char('_')) --pos; m_startPosition = pos; m_completions.clear(); // foreach (const QString &word, edit->keywords()) { // TextEditor::CompletionItem item(this); // item.m_text = word; // m_completions.append(item); // } // // foreach (const QString &word, edit->words()) { // TextEditor::CompletionItem item(this); // item.m_text = word; // m_completions.append(item); // } QmlDocument::Ptr qmlDocument = edit->qmlDocument(); // qDebug() << "*** document:" << qmlDocument; if (qmlDocument.isNull()) return pos; if (!qmlDocument->program()) qmlDocument = m_modelManager->snapshot().value(qmlDocument->fileName()); if (qmlDocument->program()) { QmlJS::AST::UiProgram *program = qmlDocument->program(); // qDebug() << "*** program:" << program; if (program) { QmlExpressionUnderCursor expressionUnderCursor; QTextCursor cursor(edit->document()); cursor.setPosition(pos); expressionUnderCursor(cursor, qmlDocument); QmlLookupContext context(expressionUnderCursor.expressionScopes(), qmlDocument, m_modelManager->snapshot()); QmlResolveExpression resolver(context); QList<QmlSymbol*> symbols = resolver.visibleSymbols(expressionUnderCursor.expressionNode()); foreach (QmlSymbol *symbol, symbols) { QString word; if (symbol->isIdSymbol()) { word = symbol->asIdSymbol()->id(); } else { word = symbol->name(); } if (word.isEmpty()) continue; TextEditor::CompletionItem item(this); item.m_text = word; m_completions.append(item); } } } return pos; } void QmlCodeCompletion::completions(QList<TextEditor::CompletionItem> *completions) { // ### FIXME: this code needs to be generalized. const int length = m_editor->position() - m_startPosition; if (length == 0) *completions = m_completions; else if (length > 0) { const QString key = m_editor->textAt(m_startPosition, length); /* * This code builds a regular expression in order to more intelligently match * camel-case style. This means upper-case characters will be rewritten as follows: * * A => [a-z0-9_]*A (for any but the first capital letter) * * Meaning it allows any sequence of lower-case characters to preceed an * upper-case character. So for example gAC matches getActionController. */ QString keyRegExp; keyRegExp += QLatin1Char('^'); bool first = true; foreach (const QChar &c, key) { if (c.isUpper() && !first) { keyRegExp += QLatin1String("[a-z0-9_]*"); keyRegExp += c; } else if (m_caseSensitivity == Qt::CaseInsensitive && c.isLower()) { keyRegExp += QLatin1Char('['); keyRegExp += c; keyRegExp += c.toUpper(); keyRegExp += QLatin1Char(']'); } else { keyRegExp += QRegExp::escape(c); } first = false; } const QRegExp regExp(keyRegExp, Qt::CaseSensitive); foreach (TextEditor::CompletionItem item, m_completions) { if (regExp.indexIn(item.m_text) == 0) { item.m_relevance = (key.length() > 0 && item.m_text.startsWith(key, Qt::CaseInsensitive)) ? 1 : 0; (*completions) << item; } } } } void QmlCodeCompletion::complete(const TextEditor::CompletionItem &item) { const QString toInsert = item.m_text; const int length = m_editor->position() - m_startPosition; m_editor->setCurPos(m_startPosition); m_editor->replace(length, toInsert); } bool QmlCodeCompletion::partiallyComplete(const QList<TextEditor::CompletionItem> &completionItems) { if (completionItems.count() == 1) { complete(completionItems.first()); return true; } else { // Compute common prefix QString firstKey = completionItems.first().m_text; QString lastKey = completionItems.last().m_text; const int length = qMin(firstKey.length(), lastKey.length()); firstKey.truncate(length); lastKey.truncate(length); while (firstKey != lastKey) { firstKey.chop(1); lastKey.chop(1); } int typedLength = m_editor->position() - m_startPosition; if (!firstKey.isEmpty() && firstKey.length() > typedLength) { m_editor->setCurPos(m_startPosition); m_editor->replace(typedLength, firstKey); } } return false; } void QmlCodeCompletion::cleanup() { m_editor = 0; m_startPosition = 0; m_completions.clear(); } <|endoftext|>
<commit_before>//===-- DebugInfoProbe.cpp - DebugInfo Probe ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements DebugInfoProbe. This probe can be used by a pass // manager to analyze how optimizer is treating debugging information. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "debuginfoprobe" #include "llvm/DebugInfoProbe.h" #include "llvm/Function.h" #include "llvm/IntrinsicInst.h" #include "llvm/Metadata.h" #include "llvm/PassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/DebugLoc.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/StringRef.h" #include <set> #include <string> using namespace llvm; static cl::opt<bool> EnableDebugInfoProbe("enable-debug-info-probe", cl::Hidden, cl::desc("Enable debug info probe")); // CreateInfoOutputFile - Return a file stream to print our output on. namespace llvm { extern raw_ostream *CreateInfoOutputFile(); } //===----------------------------------------------------------------------===// // DebugInfoProbeImpl - This class implements a interface to monitor // how an optimization pass is preserving debugging information. namespace llvm { class DebugInfoProbeImpl { public: DebugInfoProbeImpl() : NumDbgLineLost(0),NumDbgValueLost(0) {} void initialize(StringRef PName, Function &F); void finalize(Function &F); void report(); private: unsigned NumDbgLineLost, NumDbgValueLost; std::string PassName; Function *TheFn; std::set<unsigned> LineNos; std::set<MDNode *> DbgVariables; }; } //===----------------------------------------------------------------------===// // DebugInfoProbeImpl static void collect(Function &F, std::set<unsigned> &Lines) { for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) { const DebugLoc &DL = BI->getDebugLoc(); unsigned LineNo = 0; if (!DL.isUnknown()) { if (MDNode *N = DL.getInlinedAt(F.getContext())) LineNo = DebugLoc::getFromDILocation(N).getLine(); else LineNo = DL.getLine(); Lines.insert(LineNo); } } } /// initialize - Collect information before running an optimization pass. void DebugInfoProbeImpl::initialize(StringRef PName, Function &F) { if (!EnableDebugInfoProbe) return; PassName = PName; LineNos.clear(); DbgVariables.clear(); TheFn = &F; collect(F, LineNos); for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) { if (!isa<DbgInfoIntrinsic>(BI)) continue; Value *Addr = NULL; MDNode *Node = NULL; if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI)) { Addr = DDI->getAddress(); Node = DDI->getVariable(); } else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) { Addr = DVI->getValue(); Node = DVI->getVariable(); } if (Addr) DbgVariables.insert(Node); } } /// report - Report findings. This should be invoked after finalize. void DebugInfoProbeImpl::report() { if (!EnableDebugInfoProbe) return; if (NumDbgLineLost || NumDbgValueLost) { raw_ostream *OutStream = CreateInfoOutputFile(); if (NumDbgLineLost) *OutStream << NumDbgLineLost << "\t times line number info lost by " << PassName << "\n"; if (NumDbgValueLost) *OutStream << NumDbgValueLost << "\t times variable info lost by " << PassName << "\n"; delete OutStream; } NumDbgLineLost = 0; NumDbgValueLost = 0; } /// finalize - Collect information after running an optimization pass. This /// must be used after initialization. void DebugInfoProbeImpl::finalize(Function &F) { if (!EnableDebugInfoProbe) return; std::set<unsigned> LineNos2; collect(F, LineNos2); assert (TheFn == &F && "Invalid function to measure!"); for (std::set<unsigned>::iterator I = LineNos.begin(), E = LineNos.end(); I != E; ++I) { unsigned LineNo = *I; if (LineNos2.count(LineNo) == 0) { DEBUG(dbgs() << "DebugInfoProbe(" << PassName << "): Losing dbg info for source line " << LineNo << "\n"); ++NumDbgLineLost; } } std::set<MDNode *>DbgVariables2; for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) { if (!isa<DbgInfoIntrinsic>(BI)) continue; Value *Addr = NULL; MDNode *Node = NULL; if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI)) { Addr = DDI->getAddress(); Node = DDI->getVariable(); } else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) { Addr = DVI->getValue(); Node = DVI->getVariable(); } if (Addr) DbgVariables2.insert(Node); } for (std::set<MDNode *>::iterator I = DbgVariables.begin(), E = DbgVariables.end(); I != E; ++I) { if (DbgVariables2.count(*I) == 0 && (*I)->getNumOperands() >= 2) { DEBUG(dbgs() << "DebugInfoProbe(" << PassName << "): Losing dbg info for variable: "); if (MDString *MDS = dyn_cast_or_null<MDString>((*I)->getOperand(2))) DEBUG(dbgs() << MDS->getString()); else DEBUG(dbgs() << "..."); DEBUG(dbgs() << "\n"); ++NumDbgValueLost; } } } //===----------------------------------------------------------------------===// // DebugInfoProbe DebugInfoProbe::DebugInfoProbe() { pImpl = new DebugInfoProbeImpl(); } DebugInfoProbe::~DebugInfoProbe() { delete pImpl; } /// initialize - Collect information before running an optimization pass. void DebugInfoProbe::initialize(StringRef PName, Function &F) { pImpl->initialize(PName, F); } /// finalize - Collect information after running an optimization pass. This /// must be used after initialization. void DebugInfoProbe::finalize(Function &F) { pImpl->finalize(F); } /// report - Report findings. This should be invoked after finalize. void DebugInfoProbe::report() { pImpl->report(); } //===----------------------------------------------------------------------===// // DebugInfoProbeInfo /// ~DebugInfoProbeInfo - Report data collected by all probes before deleting /// them. DebugInfoProbeInfo::~DebugInfoProbeInfo() { if (!EnableDebugInfoProbe) return; for (StringMap<DebugInfoProbe*>::iterator I = Probes.begin(), E = Probes.end(); I != E; ++I) { I->second->report(); delete I->second; } } /// initialize - Collect information before running an optimization pass. void DebugInfoProbeInfo::initialize(Pass *P, Function &F) { if (!EnableDebugInfoProbe) return; if (P->getAsPMDataManager()) return; StringMapEntry<DebugInfoProbe *> &Entry = Probes.GetOrCreateValue(P->getPassName()); DebugInfoProbe *&Probe = Entry.getValue(); if (!Probe) Probe = new DebugInfoProbe(); Probe->initialize(P->getPassName(), F); } /// finalize - Collect information after running an optimization pass. This /// must be used after initialization. void DebugInfoProbeInfo::finalize(Pass *P, Function &F) { if (!EnableDebugInfoProbe) return; if (P->getAsPMDataManager()) return; StringMapEntry<DebugInfoProbe *> &Entry = Probes.GetOrCreateValue(P->getPassName()); DebugInfoProbe *&Probe = Entry.getValue(); assert (Probe && "DebugInfoProbe is not initialized!"); Probe->finalize(F); } <commit_msg>Coalesce some DEBUGs (moving an only-used-in-DEBUG variable's declaration into the DEBUG)<commit_after>//===-- DebugInfoProbe.cpp - DebugInfo Probe ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements DebugInfoProbe. This probe can be used by a pass // manager to analyze how optimizer is treating debugging information. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "debuginfoprobe" #include "llvm/DebugInfoProbe.h" #include "llvm/Function.h" #include "llvm/IntrinsicInst.h" #include "llvm/Metadata.h" #include "llvm/PassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/DebugLoc.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/StringRef.h" #include <set> #include <string> using namespace llvm; static cl::opt<bool> EnableDebugInfoProbe("enable-debug-info-probe", cl::Hidden, cl::desc("Enable debug info probe")); // CreateInfoOutputFile - Return a file stream to print our output on. namespace llvm { extern raw_ostream *CreateInfoOutputFile(); } //===----------------------------------------------------------------------===// // DebugInfoProbeImpl - This class implements a interface to monitor // how an optimization pass is preserving debugging information. namespace llvm { class DebugInfoProbeImpl { public: DebugInfoProbeImpl() : NumDbgLineLost(0),NumDbgValueLost(0) {} void initialize(StringRef PName, Function &F); void finalize(Function &F); void report(); private: unsigned NumDbgLineLost, NumDbgValueLost; std::string PassName; Function *TheFn; std::set<unsigned> LineNos; std::set<MDNode *> DbgVariables; }; } //===----------------------------------------------------------------------===// // DebugInfoProbeImpl static void collect(Function &F, std::set<unsigned> &Lines) { for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) { const DebugLoc &DL = BI->getDebugLoc(); unsigned LineNo = 0; if (!DL.isUnknown()) { if (MDNode *N = DL.getInlinedAt(F.getContext())) LineNo = DebugLoc::getFromDILocation(N).getLine(); else LineNo = DL.getLine(); Lines.insert(LineNo); } } } /// initialize - Collect information before running an optimization pass. void DebugInfoProbeImpl::initialize(StringRef PName, Function &F) { if (!EnableDebugInfoProbe) return; PassName = PName; LineNos.clear(); DbgVariables.clear(); TheFn = &F; collect(F, LineNos); for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) { if (!isa<DbgInfoIntrinsic>(BI)) continue; Value *Addr = NULL; MDNode *Node = NULL; if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI)) { Addr = DDI->getAddress(); Node = DDI->getVariable(); } else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) { Addr = DVI->getValue(); Node = DVI->getVariable(); } if (Addr) DbgVariables.insert(Node); } } /// report - Report findings. This should be invoked after finalize. void DebugInfoProbeImpl::report() { if (!EnableDebugInfoProbe) return; if (NumDbgLineLost || NumDbgValueLost) { raw_ostream *OutStream = CreateInfoOutputFile(); if (NumDbgLineLost) *OutStream << NumDbgLineLost << "\t times line number info lost by " << PassName << "\n"; if (NumDbgValueLost) *OutStream << NumDbgValueLost << "\t times variable info lost by " << PassName << "\n"; delete OutStream; } NumDbgLineLost = 0; NumDbgValueLost = 0; } /// finalize - Collect information after running an optimization pass. This /// must be used after initialization. void DebugInfoProbeImpl::finalize(Function &F) { if (!EnableDebugInfoProbe) return; std::set<unsigned> LineNos2; collect(F, LineNos2); assert (TheFn == &F && "Invalid function to measure!"); for (std::set<unsigned>::iterator I = LineNos.begin(), E = LineNos.end(); I != E; ++I) { unsigned LineNo = *I; if (LineNos2.count(LineNo) == 0) { DEBUG(dbgs() << "DebugInfoProbe(" << PassName << "): Losing dbg info for source line " << LineNo << "\n"); ++NumDbgLineLost; } } std::set<MDNode *>DbgVariables2; for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) { if (!isa<DbgInfoIntrinsic>(BI)) continue; Value *Addr = NULL; MDNode *Node = NULL; if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI)) { Addr = DDI->getAddress(); Node = DDI->getVariable(); } else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) { Addr = DVI->getValue(); Node = DVI->getVariable(); } if (Addr) DbgVariables2.insert(Node); } for (std::set<MDNode *>::iterator I = DbgVariables.begin(), E = DbgVariables.end(); I != E; ++I) { if (DbgVariables2.count(*I) == 0 && (*I)->getNumOperands() >= 2) { DEBUG(dbgs() << "DebugInfoProbe(" << PassName << "): Losing dbg info for variable: "; if (MDString *MDS = dyn_cast_or_null<MDString>( (*I)->getOperand(2))) dbgs() << MDS->getString(); else dbgs() << "..."; dbgs() << "\n"); ++NumDbgValueLost; } } } //===----------------------------------------------------------------------===// // DebugInfoProbe DebugInfoProbe::DebugInfoProbe() { pImpl = new DebugInfoProbeImpl(); } DebugInfoProbe::~DebugInfoProbe() { delete pImpl; } /// initialize - Collect information before running an optimization pass. void DebugInfoProbe::initialize(StringRef PName, Function &F) { pImpl->initialize(PName, F); } /// finalize - Collect information after running an optimization pass. This /// must be used after initialization. void DebugInfoProbe::finalize(Function &F) { pImpl->finalize(F); } /// report - Report findings. This should be invoked after finalize. void DebugInfoProbe::report() { pImpl->report(); } //===----------------------------------------------------------------------===// // DebugInfoProbeInfo /// ~DebugInfoProbeInfo - Report data collected by all probes before deleting /// them. DebugInfoProbeInfo::~DebugInfoProbeInfo() { if (!EnableDebugInfoProbe) return; for (StringMap<DebugInfoProbe*>::iterator I = Probes.begin(), E = Probes.end(); I != E; ++I) { I->second->report(); delete I->second; } } /// initialize - Collect information before running an optimization pass. void DebugInfoProbeInfo::initialize(Pass *P, Function &F) { if (!EnableDebugInfoProbe) return; if (P->getAsPMDataManager()) return; StringMapEntry<DebugInfoProbe *> &Entry = Probes.GetOrCreateValue(P->getPassName()); DebugInfoProbe *&Probe = Entry.getValue(); if (!Probe) Probe = new DebugInfoProbe(); Probe->initialize(P->getPassName(), F); } /// finalize - Collect information after running an optimization pass. This /// must be used after initialization. void DebugInfoProbeInfo::finalize(Pass *P, Function &F) { if (!EnableDebugInfoProbe) return; if (P->getAsPMDataManager()) return; StringMapEntry<DebugInfoProbe *> &Entry = Probes.GetOrCreateValue(P->getPassName()); DebugInfoProbe *&Probe = Entry.getValue(); assert (Probe && "DebugInfoProbe is not initialized!"); Probe->finalize(F); } <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // 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 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "StringHelper.h" #include <stdlib.h> #include <ctype.h> #include <algorithm> using namespace std; namespace avg { bool isWhitespace(const string& s) { return s.find_first_not_of(" \n\r\t") == s.npos; } void skipWhitespace(std::istream& is) { string sWhitespace(" \n\r\t"); bool bWhitespace; do { int i = is.peek(); if (i == EOF) { bWhitespace = false; } else { bWhitespace = (sWhitespace.find(char(i)) != sWhitespace.npos); } if (bWhitespace) { is.ignore(); } } while (bWhitespace); } void skipToken(std::istream& is, char token) { skipWhitespace(is); int i = is.peek(); if (i == token) { is.ignore(); } else { is.setstate(ios::failbit); } } int stringToInt(const string& s) { int i; fromString(s, i); return i; } double stringToDouble(const string& s) { double d; fromString(s, d); return d; } bool stringToBool(const string& s) { // avg usually wants xml attributes in lowercase, but python only // sees 'True' as true, so we'll accept that too. Also, python 2.3 // has 1 as true, so that has to be ok too. if (s == "True" || s == "true" || s == "1") { return true; } if (s == "False" || s == "false" || s == "0") { return false; } throw (Exception(AVG_ERR_TYPE, string("Could not convert ")+s+" to bool.")); } DPoint stringToDPoint(const std::string& s) { DPoint pt; fromString(s, pt); return pt; } std::string removeStartEndSpaces(const string& s) { string sResult = s; while (sResult[0] == ' ' || sResult[0] == '\n' || sResult[0] == '\r' || sResult[0] == '\t') { sResult.erase(0, 1); } char c = sResult[sResult.length()-1]; while (c == ' ' || c == '\n' || c == '\r' || c == '\t') { sResult.erase(sResult.length()-1, 1); c = sResult[sResult.length()-1]; } return sResult; } string tolower(const string& s) { string sResult; char lower[2]; lower[1] = 0; for (unsigned i=0; i<s.length(); ++i) { sResult.push_back(::tolower(s[i])); } return sResult; } bool equalIgnoreCase(const string& s1, const string& s2) { if (s1.length() != s2.length()) { return false; } string sUpper1; string sUpper2; transform(s1.begin(), s1.end(), std::back_inserter(sUpper1), (int(*)(int)) toupper); transform(s2.begin(), s2.end(), std::back_inserter(sUpper2), (int(*)(int)) toupper); return sUpper1 == sUpper2; } } <commit_msg>gcc 4.4 fix.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // 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 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "StringHelper.h" #include <stdlib.h> #include <ctype.h> #include <algorithm> #include <cstdio> using namespace std; namespace avg { bool isWhitespace(const string& s) { return s.find_first_not_of(" \n\r\t") == s.npos; } void skipWhitespace(std::istream& is) { string sWhitespace(" \n\r\t"); bool bWhitespace; do { int i = is.peek(); if (i == EOF) { bWhitespace = false; } else { bWhitespace = (sWhitespace.find(char(i)) != sWhitespace.npos); } if (bWhitespace) { is.ignore(); } } while (bWhitespace); } void skipToken(std::istream& is, char token) { skipWhitespace(is); int i = is.peek(); if (i == token) { is.ignore(); } else { is.setstate(ios::failbit); } } int stringToInt(const string& s) { int i; fromString(s, i); return i; } double stringToDouble(const string& s) { double d; fromString(s, d); return d; } bool stringToBool(const string& s) { // avg usually wants xml attributes in lowercase, but python only // sees 'True' as true, so we'll accept that too. Also, python 2.3 // has 1 as true, so that has to be ok too. if (s == "True" || s == "true" || s == "1") { return true; } if (s == "False" || s == "false" || s == "0") { return false; } throw (Exception(AVG_ERR_TYPE, string("Could not convert ")+s+" to bool.")); } DPoint stringToDPoint(const std::string& s) { DPoint pt; fromString(s, pt); return pt; } std::string removeStartEndSpaces(const string& s) { string sResult = s; while (sResult[0] == ' ' || sResult[0] == '\n' || sResult[0] == '\r' || sResult[0] == '\t') { sResult.erase(0, 1); } char c = sResult[sResult.length()-1]; while (c == ' ' || c == '\n' || c == '\r' || c == '\t') { sResult.erase(sResult.length()-1, 1); c = sResult[sResult.length()-1]; } return sResult; } string tolower(const string& s) { string sResult; char lower[2]; lower[1] = 0; for (unsigned i=0; i<s.length(); ++i) { sResult.push_back(::tolower(s[i])); } return sResult; } bool equalIgnoreCase(const string& s1, const string& s2) { if (s1.length() != s2.length()) { return false; } string sUpper1; string sUpper2; transform(s1.begin(), s1.end(), std::back_inserter(sUpper1), (int(*)(int)) toupper); transform(s2.begin(), s2.end(), std::back_inserter(sUpper2), (int(*)(int)) toupper); return sUpper1 == sUpper2; } } <|endoftext|>
<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */ #include "clients/lifetime/metadata.h" #include "clients/lifetime/instrument.h" using namespace granary; namespace client { // A function invoked on every memory read of a watched address `addr`. void on_read(uintptr_t addr, int num_bytes) { auto obj_meta = wp::descriptor_of(addr); auto ds_meta = obj_meta->data_structure; auto byte_offset_in_struct = addr - obj_meta->base_addr; granary::printf( "Reading %d bytes from address %lx, %u bytes into struct of size %u\n", num_bytes, addr, byte_offset_in_struct, ds_meta->num_bytes); // TODO(akshay): // 1) Update read counter for the associated bytes. // 2) Determine the value being read. This will required using // the `unwatched_addr` function on `addr`, then casting it to an // pointer to an integral type whose size matches `num_bytes`, de- // referencing the pointer (to read the data). // 3) Store the value being read into the `ds_meta` somehow. // a) We might want to store some number of values and the number of // times we saw that value. If the number of distinct values seen // exceeds some small threshold, then treat the field as non- // constant. } // A function invoked on every memory write to a watched address `addr`. void on_write(uintptr_t addr, unsigned long num_bytes) { auto obj_meta = wp::descriptor_of(addr); auto ds_meta = obj_meta->data_structure; auto byte_offset_in_struct = addr - obj_meta->base_addr; granary::printf( "Writing %d bytes to address %lx, %u bytes into struct of size %u\n", num_bytes, addr, byte_offset_in_struct, ds_meta->num_bytes); } // Versions of the above functions that are safe to call from within // instrumented code. app_pc on_read_func = nullptr; app_pc on_write_func = nullptr; // Initialize this client / tool. This creates the safe/clean-callable versions // of the `on_read` and `on_write` callback functions. void init(void) { cpu_state_handle cpu; IF_TEST( cpu->in_granary = false; ) cpu.free_transient_allocators(); on_read_func = generate_clean_callable_address(on_read); cpu.free_transient_allocators(); on_write_func = generate_clean_callable_address(on_write); } DEFINE_READ_VISITOR(lifetime, { insert_clean_call_after(ls, label, on_read_func, op, (unsigned long) size); }) DEFINE_WRITE_VISITOR(lifetime, { insert_clean_call_after(ls, label, on_write_func, op, (unsigned long) size); }) DEFINE_INTERRUPT_VISITOR(lifetime, {}) } // namespace client <commit_msg>Minor updates.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */ #include "clients/lifetime/metadata.h" #include "clients/lifetime/instrument.h" using namespace granary; namespace client { // A function invoked on every memory read of a watched address `addr`. void on_read(uintptr_t addr, unsigned long num_bytes) { auto obj_meta = wp::descriptor_of(addr); auto ds_meta = obj_meta->data_structure; auto byte_offset_in_struct = addr - obj_meta->base_addr; granary::printf( "Reading %d bytes from address %lx, %u bytes into struct of size %u\n", num_bytes, addr, byte_offset_in_struct, ds_meta->num_bytes); // TODO(akshay): // 1) Update read counter for the associated bytes. // 2) Determine the value being read. This will required using // the `unwatched_addr` function on `addr`, then casting it to an // pointer to an integral type whose size matches `num_bytes`, de- // referencing the pointer (to read the data). // 3) Store the value being read into the `ds_meta` somehow. // a) We might want to store some number of values and the number of // times we saw that value. If the number of distinct values seen // exceeds some small threshold, then treat the field as non- // constant. } // A function invoked on every memory write to a watched address `addr`. void on_write(uintptr_t addr, unsigned long num_bytes) { auto obj_meta = wp::descriptor_of(addr); auto ds_meta = obj_meta->data_structure; auto byte_offset_in_struct = addr - obj_meta->base_addr; granary::printf( "Writing %d bytes to address %lx, %u bytes into struct of size %u\n", num_bytes, addr, byte_offset_in_struct, ds_meta->num_bytes); // TODO(akshay): Similar to above, but for writes. For writes we don't care // about the value being written, because specializing on writes // is unlikely to lead very far at a large scale. } // Versions of the above functions that are safe to call from within // instrumented code. app_pc on_read_func = nullptr; app_pc on_write_func = nullptr; // Initialize this client / tool. This creates the safe/clean-callable versions // of the `on_read` and `on_write` callback functions. void init(void) { cpu_state_handle cpu; IF_TEST( cpu->in_granary = false; ) cpu.free_transient_allocators(); on_read_func = generate_clean_callable_address(on_read); cpu.free_transient_allocators(); on_write_func = generate_clean_callable_address(on_write); } // Inject a function call to `on_read` before every memory read of a // watched address. DEFINE_READ_VISITOR(lifetime, { insert_clean_call_after(ls, label, on_read_func, op, (unsigned long) size); }) // Inject a function call to `on_write` before every memory write to a // watched address. DEFINE_WRITE_VISITOR(lifetime, { insert_clean_call_after(ls, label, on_write_func, op, (unsigned long) size); }) DEFINE_INTERRUPT_VISITOR(lifetime, {}) } // namespace client <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2012,2015,2017 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * 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. * * Authors: Ron Dreslinski * Andreas Hansson * William Wang */ /** * @file * Port Object Declaration. */ #ifndef __SIM_PORT_HH__ #define __SIM_PORT_HH__ #include <string> #include "base/types.hh" /** * Ports are used to interface objects to each other. */ class Port { private: /** Descriptive name (for DPRINTF output) */ const std::string portName; protected: /** * A numeric identifier to distinguish ports in a vector, and set * to InvalidPortID in case this port is not part of a vector. */ const PortID id; /** * A pointer to this port's peer. */ Port *_peer; /** * Whether this port is currently connected to a peer port. */ bool _connected; /** * Abstract base class for ports * * @param _name Port name including the owners name * @param _id A port identifier for vector ports */ Port(const std::string& _name, PortID _id); /** * Virtual destructor due to inheritance. */ virtual ~Port(); public: /** Return a reference to this port's peer. */ Port &getPeer() { return *_peer; } /** Return port name (for DPRINTF). */ const std::string name() const { return portName; } /** Get the port id. */ PortID getId() const { return id; } /** Attach to a peer port. */ virtual void bind(Port &peer) { _peer = &peer; _connected = true; } /** Dettach from a peer port. */ virtual void unbind() { _peer = nullptr; _connected = false; } /** Is this port currently connected to a peer? */ bool isConnected() const { return _connected; } /** A utility function to make it easier to swap out ports. */ void takeOverFrom(Port *old) { assert(old); assert(old->isConnected()); assert(!isConnected()); Port &peer = old->getPeer(); assert(peer.isConnected()); // Disconnect the original binding. old->unbind(); peer.unbind(); // Connect the new binding. peer.bind(*this); bind(peer); } }; static inline std::ostream & operator << (std::ostream &os, const Port &port) { os << port.name(); return os; } #endif //__SIM_PORT_HH__ <commit_msg>sim: Move destructor of Port to public<commit_after>/* * Copyright (c) 2011-2012,2015,2017 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * 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. * * Authors: Ron Dreslinski * Andreas Hansson * William Wang */ /** * @file * Port Object Declaration. */ #ifndef __SIM_PORT_HH__ #define __SIM_PORT_HH__ #include <string> #include "base/types.hh" /** * Ports are used to interface objects to each other. */ class Port { private: /** Descriptive name (for DPRINTF output) */ const std::string portName; protected: /** * A numeric identifier to distinguish ports in a vector, and set * to InvalidPortID in case this port is not part of a vector. */ const PortID id; /** * A pointer to this port's peer. */ Port *_peer; /** * Whether this port is currently connected to a peer port. */ bool _connected; /** * Abstract base class for ports * * @param _name Port name including the owners name * @param _id A port identifier for vector ports */ Port(const std::string& _name, PortID _id); public: /** * Virtual destructor due to inheritance. */ virtual ~Port(); /** Return a reference to this port's peer. */ Port &getPeer() { return *_peer; } /** Return port name (for DPRINTF). */ const std::string name() const { return portName; } /** Get the port id. */ PortID getId() const { return id; } /** Attach to a peer port. */ virtual void bind(Port &peer) { _peer = &peer; _connected = true; } /** Dettach from a peer port. */ virtual void unbind() { _peer = nullptr; _connected = false; } /** Is this port currently connected to a peer? */ bool isConnected() const { return _connected; } /** A utility function to make it easier to swap out ports. */ void takeOverFrom(Port *old) { assert(old); assert(old->isConnected()); assert(!isConnected()); Port &peer = old->getPeer(); assert(peer.isConnected()); // Disconnect the original binding. old->unbind(); peer.unbind(); // Connect the new binding. peer.bind(*this); bind(peer); } }; static inline std::ostream & operator << (std::ostream &os, const Port &port) { os << port.name(); return os; } #endif //__SIM_PORT_HH__ <|endoftext|>
<commit_before>/* * Copyright (C) 2019 ScyllaDB */ #include "build_id.hh" #include <fmt/printf.h> #include <link.h> #include <seastar/core/align.hh> #include <sstream> using namespace seastar; static const Elf64_Phdr* get_pt_note(dl_phdr_info* info) { const auto* h = info->dlpi_phdr; auto num_headers = info->dlpi_phnum; for (int i = 0; i != num_headers; ++i, ++h) { if (h->p_type == PT_NOTE) { return h; } } assert(0 && "no PT_NOTE programe header"); } static const Elf64_Nhdr* get_nt_build_id(dl_phdr_info* info) { auto* h = get_pt_note(info); auto base = info->dlpi_addr; auto* p = reinterpret_cast<const char*>(base) + h->p_vaddr; auto* e = p + h->p_memsz; while (p != e) { const auto* n = reinterpret_cast<const Elf64_Nhdr*>(p); if (n->n_type == NT_GNU_BUILD_ID) { return n; } p += sizeof(Elf64_Nhdr); p += n->n_namesz; p = align_up(p, 4); p += n->n_descsz; p = align_up(p, 4); } assert(0 && "no NT_GNU_BUILD_ID note"); } static int callback(dl_phdr_info* info, size_t size, void* data) { std::string& ret = *(std::string*)data; std::ostringstream os; // The first DSO is always the main program, which has an empty name. assert(strlen(info->dlpi_name) == 0); auto* n = get_nt_build_id(info); auto* p = reinterpret_cast<const char*>(n); p += sizeof(Elf64_Nhdr); p += n->n_namesz; p = align_up(p, 4); const char* desc = p; for (unsigned i = 0; i < n->n_descsz; ++i) { fmt::fprintf(os, "%02x", (unsigned char)*(desc + i)); } ret = os.str(); return 1; } std::string get_build_id() { std::string ret; int r = dl_iterate_phdr(callback, &ret); assert(r == 1); return ret; } <commit_msg>build-id: Handle the binary having multiple PT_NOTE headers<commit_after>/* * Copyright (C) 2019 ScyllaDB */ #include "build_id.hh" #include <fmt/printf.h> #include <link.h> #include <seastar/core/align.hh> #include <sstream> using namespace seastar; static const Elf64_Nhdr* get_nt_build_id(dl_phdr_info* info) { auto base = info->dlpi_addr; const auto* h = info->dlpi_phdr; auto num_headers = info->dlpi_phnum; for (int i = 0; i != num_headers; ++i, ++h) { if (h->p_type != PT_NOTE) { continue; } auto* p = reinterpret_cast<const char*>(base) + h->p_vaddr; auto* e = p + h->p_memsz; while (p != e) { const auto* n = reinterpret_cast<const Elf64_Nhdr*>(p); if (n->n_type == NT_GNU_BUILD_ID) { return n; } p += sizeof(Elf64_Nhdr); p += n->n_namesz; p = align_up(p, 4); p += n->n_descsz; p = align_up(p, 4); } } assert(0 && "no NT_GNU_BUILD_ID note"); } static int callback(dl_phdr_info* info, size_t size, void* data) { std::string& ret = *(std::string*)data; std::ostringstream os; // The first DSO is always the main program, which has an empty name. assert(strlen(info->dlpi_name) == 0); auto* n = get_nt_build_id(info); auto* p = reinterpret_cast<const char*>(n); p += sizeof(Elf64_Nhdr); p += n->n_namesz; p = align_up(p, 4); const char* desc = p; for (unsigned i = 0; i < n->n_descsz; ++i) { fmt::fprintf(os, "%02x", (unsigned char)*(desc + i)); } ret = os.str(); return 1; } std::string get_build_id() { std::string ret; int r = dl_iterate_phdr(callback, &ret); assert(r == 1); return ret; } <|endoftext|>
<commit_before>// Copyright (c) 2016 Baidu, Inc. // // 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. // Authors: Ge,Jun (gejun@baidu.com) #include "brpc/retry_policy.h" namespace brpc { RetryPolicy::~RetryPolicy() {} class RpcRetryPolicy : public RetryPolicy { public: bool DoRetry(const Controller* controller) const { const int error_code = controller->ErrorCode(); if (!error_code) { return false; } return (EFAILEDSOCKET == error_code || EEOF == error_code || EHOSTDOWN == error_code || ELOGOFF == error_code || ETIMEDOUT == error_code // This is not timeout of RPC. || ELIMIT == error_code || ENOENT == error_code || EPIPE == error_code || ECONNREFUSED == error_code || ECONNRESET == error_code || ENODATA == error_code || EOVERCROWDED == error_code); } }; // NOTE(gejun): g_default_policy can't be deleted on process's exit because // concurrent processing of responses at client-side may trigger retry and // use the policy. static pthread_once_t g_default_policy_once = PTHREAD_ONCE_INIT; static RpcRetryPolicy* g_default_policy = NULL; static void init_default_policy() { g_default_policy = new RpcRetryPolicy; } const RetryPolicy* DefaultRetryPolicy() { pthread_once(&g_default_policy_once, init_default_policy); return g_default_policy; } } // namespace brpc <commit_msg>Retry for EH2RUNOUTSTREAMS<commit_after>// Copyright (c) 2016 Baidu, Inc. // // 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. // Authors: Ge,Jun (gejun@baidu.com) #include "brpc/retry_policy.h" namespace brpc { RetryPolicy::~RetryPolicy() {} class RpcRetryPolicy : public RetryPolicy { public: bool DoRetry(const Controller* controller) const { const int error_code = controller->ErrorCode(); if (!error_code) { return false; } return (EFAILEDSOCKET == error_code || EEOF == error_code || EHOSTDOWN == error_code || ELOGOFF == error_code || ETIMEDOUT == error_code // This is not timeout of RPC. || ELIMIT == error_code || ENOENT == error_code || EPIPE == error_code || ECONNREFUSED == error_code || ECONNRESET == error_code || ENODATA == error_code || EOVERCROWDED == error_code || EH2RUNOUTSTREAMS == error_code); } }; // NOTE(gejun): g_default_policy can't be deleted on process's exit because // client-side may still retry and use the policy at exit static pthread_once_t g_default_policy_once = PTHREAD_ONCE_INIT; static RpcRetryPolicy* g_default_policy = NULL; static void init_default_policy() { g_default_policy = new RpcRetryPolicy; } const RetryPolicy* DefaultRetryPolicy() { pthread_once(&g_default_policy_once, init_default_policy); return g_default_policy; } } // namespace brpc <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "BZAdminClient.h" #include "BZAdminUI.h" void BZAdminUI::handleNewPacket(uint16_t) { if (client.getLastMessage().first.size() > 0) outputMessage(client.getLastMessage().first, client.getLastMessage().second); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>get rid of mangling to long warnings<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _WIN32 #pragma warning(4:4786) #endif #include "BZAdminClient.h" #include "BZAdminUI.h" void BZAdminUI::handleNewPacket(uint16_t) { if (client.getLastMessage().first.size() > 0) outputMessage(client.getLastMessage().first, client.getLastMessage().second); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2009 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "ServerMenu.h" /* common implementation headers */ #include "FontManager.h" #include "StateDatabase.h" /* local implementation headers */ #include "FontSizer.h" #include "MainMenu.h" #include "HUDDialogStack.h" #include "clientConfig.h" #include "ConfigFileManager.h" #include "bzflag.h" #include "LocalFontFace.h" #include "playing.h" bool ServerMenuDefaultKey::keyPress(const BzfKeyEvent& key) { ServerList &serverList = ServerList::instance(); HUDuiServerList* activeTab( dynamic_cast<HUDuiServerList*>(menu->tabbedControl->getActiveTab())); // This may be a bit Draconian, since not all the tests below // actually depend on the active tab being of type HUDuiServerList*, // but they were all blindly casting before, so assume this is a SNH // condition if (activeTab == 0) return false; // Note that many of the if statments below test for this condition // as well and have a different return. Seems like a logic error. if (activeTab == static_cast<HUDuiControl*>(menu->customTabControl)) return MenuDefaultKey::keyPress(key); if (key.chr == 'f') { if ((activeTab == menu->favoritesList) || (activeTab->hasFocus()) || (menu->tabbedControl->hasFocus())) return false; if (activeTab != 0) { serverList.markAsFavorite(activeTab->getSelectedServer()); return true; } return false; } if (key.chr == 'c') { if ((activeTab == static_cast<HUDuiControl*>(menu->customTabControl)) || (activeTab == menu->normalList)) return false; if (activeTab == menu->favoritesList) { for (size_t i=0; i<activeTab->getSize(); i++) { serverList.unmarkAsFavorite(activeTab->get(i)->getServer()); } } if (activeTab == menu->recentList) { for (size_t i=0; i<activeTab->getSize(); i++) { serverList.unmarkAsRecent(activeTab->get(i)->getServer()); } } activeTab->clearList(); return true; } if (key.chr == 'v') { if ((activeTab == menu->favoritesList) || (activeTab == menu->normalList) || (activeTab == menu->recentList)) return false; std::string tabName = menu->tabbedControl->getActiveTabName(); HUDuiServerListCache::instance().removeList(activeTab, tabName); menu->tabbedControl->removeTab(activeTab, tabName); } if (key.chr == 'r') { ServerList::instance().clear(); ServerList::instance().startServerPings(getStartupInfo()); return true; } if (key.chr == 'h') { if ((activeTab == menu->normalList) || (activeTab->hasFocus()) || (menu->tabbedControl->hasFocus())) return false; if (activeTab == menu->favoritesList) serverList.unmarkAsFavorite(activeTab->getSelectedServer()); if (activeTab == menu->recentList) serverList.unmarkAsRecent(activeTab->getSelectedServer()); activeTab->removeItem(activeTab->getSelectedServer()); return true; } return MenuDefaultKey::keyPress(key); } bool ServerMenuDefaultKey::keyRelease(const BzfKeyEvent& key) { switch (key.chr) { case 27: // escape case 13: // return return true; } return false; } ServerMenu::PingsMap ServerMenu::activePings; ServerMenu::ServerMenu() : normalList(0) , recentList(0) , favoritesList(0) , tabbedControl(0) , serverInfo(new HUDuiServerInfo()) , customTabControl(new HUDuiServerListCustomTab()) , listsCache(HUDuiServerListCache::instance()) , serverList(ServerList::instance()) , defaultKey(this) , title(0) , help(0) { // cache font face ID const LocalFontFace* fontFace = MainMenu::getFontFace(); addPlayingCallback(&playingCB, this); serverList.updateFromCache(); serverList.startServerPings(getStartupInfo()); listsCache.loadCache(); std::vector<std::pair<HUDuiServerList*, std::string> > cachedLists = listsCache.readCachedLists(); if (cachedLists.size() > (size_t) 0) { normalList = cachedLists[0].first; recentList = cachedLists[1].first; favoritesList = cachedLists[2].first; } else { normalList = new HUDuiServerList; favoritesList = new HUDuiServerList; recentList = new HUDuiServerList; listsCache.addNewList(normalList, ""); listsCache.addNewList(favoritesList, ""); listsCache.addNewList(recentList, ""); } normalList->setFontFace(fontFace); favoritesList->setFontFace(fontFace); recentList->setFontFace(fontFace); serverInfo->setFontFace(fontFace); customTabControl->setFontFace(fontFace); title = new HUDuiLabel(); title->setString("Servers"); title->setFontFace(fontFace); help = new HUDuiLabel(); help->setString("f - add server to favorites h - remove server from tab c - clear tab v - delete tab r - refresh server list"); help->setFontFace(fontFace); tabbedControl = new HUDuiTabbedControl; tabbedControl->setFontFace(fontFace); tabbedControl->addTab(normalList, "All"); tabbedControl->addTab(recentList, "Recent"); tabbedControl->addTab(favoritesList, "Favorites"); for (size_t i=3; i<cachedLists.size(); i++) { cachedLists[i].first->setFontFace(fontFace); tabbedControl->addTab(cachedLists[i].first, cachedLists[i].second); } tabbedControl->addTab(customTabControl, "Create New Tab"); tabbedControl->setActiveTab(0); serverList.addServerCallback(newServer, normalList); serverList.addFavoriteServerCallback(newServer, favoritesList); serverList.addRecentServerCallback(newServer, recentList); addControl(title, false); addControl(tabbedControl); addControl(serverInfo); addControl(help, false); initNavigation(); } ServerMenu::~ServerMenu() { serverList.removeServerCallback(newServer, normalList); serverList.removeFavoriteServerCallback(newServer, favoritesList); serverList.removeRecentServerCallback(newServer, recentList); } void ServerMenu::newServer(ServerItem* addedServer, void* data) { HUDuiServerList* serverData( static_cast<HUDuiServerList*>(data) ); // Server already has a ping if (addedServer->ping.pingTime != 0) { serverData->addItem(addedServer); return; } // Pinging in process, add on to the list vector if (addedServer->ping.pinging) { ServerMenu::activePings[addedServer->getServerKey()].second.push_back(serverData); } ServerPing* newping = new ServerPing(addedServer->ping.serverId.serverHost, ntohs(addedServer->ping.serverId.port)); newping->start(); std::vector<HUDuiServerList*> serverListsVector; serverListsVector.push_back(serverData); ServerMenu::activePings.insert(PingsMap::value_type(addedServer->getServerKey(), std::pair<ServerPing*, std::vector<HUDuiServerList*> >(newping, serverListsVector))); addedServer->ping.pinging = true; } void ServerMenu::execute() { if ((tabbedControl->getActiveTab() == customTabControl) && (dynamic_cast<HUDuiServerListCustomTab*>(tabbedControl->getActiveTab())->createNew->hasFocus())) { HUDuiServerList* newServerList = customTabControl->createServerList(); listsCache.addNewList(newServerList, customTabControl->tabName->getString()); tabbedControl->addTab(newServerList, customTabControl->tabName->getString(), tabbedControl->getTabCount() - 1); for (size_t i=0; i<serverList.size(); i++) { newServerList->addItem(serverList.getServerAt(i)); } //newServerList->searchServers(customTabControl->serverName->getString()); dynamic_cast<HUDuiNestedContainer*>(tabbedControl->getTab(tabbedControl->getTabCount() - 2))->getNav().set(1); return; } if ((tabbedControl->hasFocus())|| (tabbedControl->getActiveTab()->hasFocus())|| (tabbedControl->getActiveTabName() == "Create New Tab")) return; // update startup info StartupInfo* info = getStartupInfo(); ServerItem* selectedServer = dynamic_cast<HUDuiServerList*>(tabbedControl->getActiveTab())->getSelectedServer(); strncpy(info->serverName, selectedServer->name.c_str(), ServerNameLen-1); info->serverPort = ntohs((unsigned short) selectedServer->ping.serverId.port); // all done HUDDialogStack::get()->pop(); } void ServerMenu::resize(int _width, int _height) { HUDDialog::resize(_width, _height); FontSizer fs = FontSizer(_width, _height); FontManager &fm = FontManager::instance(); const LocalFontFace* fontFace = MainMenu::getFontFace(); // reposition title float x, y; // use a big font for title, smaller font for the rest fs.setMin(0, (int)(1.0 / BZDB.eval("headerFontSize") / 2.0)); const float titleFontSize = fs.getFontSize(fontFace->getFMFace(), "headerFontSize"); title->setFontSize(titleFontSize); const float titleWidth = fm.getStringWidth(fontFace->getFMFace(), titleFontSize, title->getString().c_str()); const float titleHeight = fm.getStringHeight(fontFace->getFMFace(), titleFontSize); x = 0.5f * ((float)_width - titleWidth); y = (float)_height - titleHeight; title->setPosition(x, y); fs.setMin(40,10); const float fontSize = fs.getFontSize(fontFace->getFMFace(), "alertFontSize"); float edgeSpacer = fm.getStringWidth(fontFace->getFMFace(), fontSize, "X"); float bottomSpacer = fm.getStringHeight(fontFace->getFMFace(), fontSize); float remainingSpace = y - bottomSpacer*2; float listHeight = remainingSpace*0.65f; tabbedControl->setSize((_width - (2*edgeSpacer)),listHeight); serverInfo->setSize((_width - (2*edgeSpacer)), (remainingSpace - 4*bottomSpacer)*0.35f); y = y - (titleHeight/2) - tabbedControl->getHeight(); float helpLength = fm.getStringWidth(fontFace->getFMFace(), fontSize, help->getString().c_str()); tabbedControl->setPosition(edgeSpacer, y); serverInfo->setPosition(edgeSpacer, bottomSpacer/2 + bottomSpacer); help->setPosition((_width - helpLength)/2, bottomSpacer/2); tabbedControl->setFontSize(fontSize); serverInfo->setFontSize(fontSize); help->setFontSize(fontSize); } void ServerMenu::updateStatus() { if (tabbedControl->hasFocus() || tabbedControl->getActiveTab()->hasFocus() || tabbedControl->getActiveTabName() == "Create New Tab") serverInfo->setServerItem(NULL); else serverInfo->setServerItem(dynamic_cast<HUDuiServerList*>(tabbedControl->getActiveTab())->getSelectedServer()); } void ServerMenu::playingCB(void* _self) { ServerList &list = ServerList::instance(); for (PingsMap::iterator i = ServerMenu::activePings.begin(); i != ServerMenu::activePings.end();) { i->second.first->doPings(); if (i->second.first->done()) { ServerItem* server = list.lookupServer(i->first); if (server == NULL) break; server->ping.pingTime = i->second.first->calcLag(); server->ping.pinging = false; for (size_t j=0; j<(i->second.second.size()); j++) { i->second.second[j]->addItem(server); } delete i->second.first; ServerMenu::activePings.erase(i++); continue; } ++i; } static_cast<ServerMenu*>(_self)->serverList.checkEchos(getStartupInfo()); static_cast<ServerMenu*>(_self)->updateStatus(); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Bug fix for creating new tabs in the server listing. Also adds some comments to the changed code.<commit_after>/* bzflag * Copyright (c) 1993 - 2009 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "ServerMenu.h" /* common implementation headers */ #include "FontManager.h" #include "StateDatabase.h" /* local implementation headers */ #include "FontSizer.h" #include "MainMenu.h" #include "HUDDialogStack.h" #include "clientConfig.h" #include "ConfigFileManager.h" #include "bzflag.h" #include "LocalFontFace.h" #include "playing.h" bool ServerMenuDefaultKey::keyPress(const BzfKeyEvent& key) { ServerList &serverList = ServerList::instance(); HUDuiControl* activeTabControl = menu->tabbedControl->getActiveTab(); HUDuiServerList* activeServerList = NULL; // The currently active tab is the custom tab creation control. We don't handle // any key presses for that here, so pass it on, and return the result we get. if (activeTabControl == menu->customTabControl) // Is this the right way to check? return MenuDefaultKey::keyPress(key); // The currently active tab is NOT the custom tab, so let's try casting it as a // HUDuiServerList control. For the server browser we only expect controls of type // HUDuiServerListCustomTab, or HUDuiServerList. However, since we are using a // HUDuiTabbedControl, we could have any subclass of HUDuiControl, so we have to // be careful to check what class we are dealing with when executing key presses. else activeServerList = dynamic_cast<HUDuiServerList*>(activeTabControl); // The active tab is not the custom tab control, and is not a HUDuiServerList // Right now we're handling input that affects either custom tab creation, or // server list browsing. Since this is neither, return false, we don't handle it. if ((activeServerList == 0)||(activeServerList == NULL)) // dynamic_cast returns 0 if it fails return false; // These key presses should only be processed when the user has a server selected. // As such, we should check to see if the server list, or the tabbed control have // focus, and if they do, ignore these key presses for now. Also check that the // user has a server selected. if ((!activeServerList->hasFocus())&&(!menu->tabbedControl->hasFocus())&& (activeServerList->getSelectedServer() != NULL)){ // The favorite key was pressed if (key.chr == 'f') { // Check to see if we're on the favorites list, if we are, ignore keypress if (activeServerList == menu->favoritesList) { return false; } else { // Mark it as a favorite server serverList.markAsFavorite(activeServerList->getSelectedServer()); return true; } } // The remove server key was pressed if (key.chr == 'h') { // Design decision: Don't let users remove any servers from the normal server // list. Let's keep this as a pure representation of all the available servers if (activeServerList == menu->normalList) return false; // If we're on the favorites list, we need to unmark the server // as a favorite server in order to remove it from the list if (activeServerList == menu->favoritesList) serverList.unmarkAsFavorite(activeServerList->getSelectedServer()); // If we're on the recents list, we need to unmark the server // as a recent server in order to remove it from the list if (activeServerList == menu->recentList) serverList.unmarkAsRecent(activeServerList->getSelectedServer()); // Remove the selected server from the active server list activeServerList->removeItem(activeServerList->getSelectedServer()); return true; } } // The clear server list key was pressed if (key.chr == 'c') { // Design decision: Don't let users remove any servers from the normal server // list. Let's keep this as a pure representation of all the available servers if (activeServerList == menu->normalList) return false; // If we're on the favorites list, cycle through all favorite servers and unmark // them as favorites. This may be a bad idea, it's fairly easy to accidentally // clear your favorites list using this functionality. if (activeServerList == menu->favoritesList) { for (size_t i=0; i<activeServerList->getSize(); i++) { serverList.unmarkAsFavorite(activeServerList->get(i)->getServer()); } } // If we're on the recent server list, cycle through all // recent servers and unmark them as a recent server. if (activeServerList == menu->recentList) { for (size_t i=0; i<activeServerList->getSize(); i++) { serverList.unmarkAsRecent(activeServerList->get(i)->getServer()); } } // Clear the list activeServerList->clearList(); return true; } // Remove the current tab. This can be pressed at any // time, but only works if the user is on a custom tab. if (key.chr == 'v') { // Do nothing if the user is on any of the standard tabs if ((activeServerList == menu->favoritesList) || (activeServerList == menu->normalList) || (activeServerList == menu->recentList)) return false; // Remove the current tab from the tabbed control std::string tabName = menu->tabbedControl->getActiveTabName(); HUDuiServerListCache::instance().removeList(activeServerList, tabName); menu->tabbedControl->removeTab(activeServerList, tabName); return true; } // Refresh the server list. This can be done at any time. if (key.chr == 'r') { ServerList::instance().clear(); ServerList::instance().startServerPings(getStartupInfo()); return true; } return MenuDefaultKey::keyPress(key); } bool ServerMenuDefaultKey::keyRelease(const BzfKeyEvent& key) { switch (key.chr) { case 27: // escape case 13: // return return true; } return false; } ServerMenu::PingsMap ServerMenu::activePings; ServerMenu::ServerMenu() : normalList(0) , recentList(0) , favoritesList(0) , tabbedControl(0) , serverInfo(new HUDuiServerInfo()) , customTabControl(new HUDuiServerListCustomTab()) , listsCache(HUDuiServerListCache::instance()) , serverList(ServerList::instance()) , defaultKey(this) , title(0) , help(0) { // cache font face ID const LocalFontFace* fontFace = MainMenu::getFontFace(); addPlayingCallback(&playingCB, this); serverList.updateFromCache(); serverList.startServerPings(getStartupInfo()); listsCache.loadCache(); std::vector<std::pair<HUDuiServerList*, std::string> > cachedLists = listsCache.readCachedLists(); if (cachedLists.size() > (size_t) 0) { normalList = cachedLists[0].first; recentList = cachedLists[1].first; favoritesList = cachedLists[2].first; } else { normalList = new HUDuiServerList; favoritesList = new HUDuiServerList; recentList = new HUDuiServerList; listsCache.addNewList(normalList, ""); listsCache.addNewList(favoritesList, ""); listsCache.addNewList(recentList, ""); } normalList->setFontFace(fontFace); favoritesList->setFontFace(fontFace); recentList->setFontFace(fontFace); serverInfo->setFontFace(fontFace); customTabControl->setFontFace(fontFace); title = new HUDuiLabel(); title->setString("Servers"); title->setFontFace(fontFace); help = new HUDuiLabel(); help->setString("f - add server to favorites h - remove server from tab c - clear tab v - delete tab r - refresh server list"); help->setFontFace(fontFace); tabbedControl = new HUDuiTabbedControl; tabbedControl->setFontFace(fontFace); tabbedControl->addTab(normalList, "All"); tabbedControl->addTab(recentList, "Recent"); tabbedControl->addTab(favoritesList, "Favorites"); for (size_t i=3; i<cachedLists.size(); i++) { cachedLists[i].first->setFontFace(fontFace); tabbedControl->addTab(cachedLists[i].first, cachedLists[i].second); } tabbedControl->addTab(customTabControl, "Create New Tab"); tabbedControl->setActiveTab(0); serverList.addServerCallback(newServer, normalList); serverList.addFavoriteServerCallback(newServer, favoritesList); serverList.addRecentServerCallback(newServer, recentList); addControl(title, false); addControl(tabbedControl); addControl(serverInfo); addControl(help, false); initNavigation(); } ServerMenu::~ServerMenu() { serverList.removeServerCallback(newServer, normalList); serverList.removeFavoriteServerCallback(newServer, favoritesList); serverList.removeRecentServerCallback(newServer, recentList); } void ServerMenu::newServer(ServerItem* addedServer, void* data) { HUDuiServerList* serverData( static_cast<HUDuiServerList*>(data) ); // Server already has a ping if (addedServer->ping.pingTime != 0) { serverData->addItem(addedServer); return; } // Pinging in process, add on to the list vector if (addedServer->ping.pinging) { ServerMenu::activePings[addedServer->getServerKey()].second.push_back(serverData); } ServerPing* newping = new ServerPing(addedServer->ping.serverId.serverHost, ntohs(addedServer->ping.serverId.port)); newping->start(); std::vector<HUDuiServerList*> serverListsVector; serverListsVector.push_back(serverData); ServerMenu::activePings.insert(PingsMap::value_type(addedServer->getServerKey(), std::pair<ServerPing*, std::vector<HUDuiServerList*> >(newping, serverListsVector))); addedServer->ping.pinging = true; } void ServerMenu::execute() { if ((tabbedControl->getActiveTab() == customTabControl) && (dynamic_cast<HUDuiServerListCustomTab*>(tabbedControl->getActiveTab())->createNew->hasFocus())) { HUDuiServerList* newServerList = customTabControl->createServerList(); listsCache.addNewList(newServerList, customTabControl->tabName->getString()); tabbedControl->addTab(newServerList, customTabControl->tabName->getString(), tabbedControl->getTabCount() - 1); for (size_t i=0; i<serverList.size(); i++) { newServerList->addItem(serverList.getServerAt(i)); } //newServerList->searchServers(customTabControl->serverName->getString()); dynamic_cast<HUDuiNestedContainer*>(tabbedControl->getTab(tabbedControl->getTabCount() - 2))->getNav().set(1); return; } if ((tabbedControl->hasFocus())|| (tabbedControl->getActiveTab()->hasFocus())|| (tabbedControl->getActiveTabName() == "Create New Tab")) return; // update startup info StartupInfo* info = getStartupInfo(); ServerItem* selectedServer = dynamic_cast<HUDuiServerList*>(tabbedControl->getActiveTab())->getSelectedServer(); strncpy(info->serverName, selectedServer->name.c_str(), ServerNameLen-1); info->serverPort = ntohs((unsigned short) selectedServer->ping.serverId.port); // all done HUDDialogStack::get()->pop(); } void ServerMenu::resize(int _width, int _height) { HUDDialog::resize(_width, _height); FontSizer fs = FontSizer(_width, _height); FontManager &fm = FontManager::instance(); const LocalFontFace* fontFace = MainMenu::getFontFace(); // reposition title float x, y; // use a big font for title, smaller font for the rest fs.setMin(0, (int)(1.0 / BZDB.eval("headerFontSize") / 2.0)); const float titleFontSize = fs.getFontSize(fontFace->getFMFace(), "headerFontSize"); title->setFontSize(titleFontSize); const float titleWidth = fm.getStringWidth(fontFace->getFMFace(), titleFontSize, title->getString().c_str()); const float titleHeight = fm.getStringHeight(fontFace->getFMFace(), titleFontSize); x = 0.5f * ((float)_width - titleWidth); y = (float)_height - titleHeight; title->setPosition(x, y); fs.setMin(40,10); const float fontSize = fs.getFontSize(fontFace->getFMFace(), "alertFontSize"); float edgeSpacer = fm.getStringWidth(fontFace->getFMFace(), fontSize, "X"); float bottomSpacer = fm.getStringHeight(fontFace->getFMFace(), fontSize); float remainingSpace = y - bottomSpacer*2; float listHeight = remainingSpace*0.65f; tabbedControl->setSize((_width - (2*edgeSpacer)),listHeight); serverInfo->setSize((_width - (2*edgeSpacer)), (remainingSpace - 4*bottomSpacer)*0.35f); y = y - (titleHeight/2) - tabbedControl->getHeight(); float helpLength = fm.getStringWidth(fontFace->getFMFace(), fontSize, help->getString().c_str()); tabbedControl->setPosition(edgeSpacer, y); serverInfo->setPosition(edgeSpacer, bottomSpacer/2 + bottomSpacer); help->setPosition((_width - helpLength)/2, bottomSpacer/2); tabbedControl->setFontSize(fontSize); serverInfo->setFontSize(fontSize); help->setFontSize(fontSize); } void ServerMenu::updateStatus() { if (tabbedControl->hasFocus() || tabbedControl->getActiveTab()->hasFocus() || tabbedControl->getActiveTabName() == "Create New Tab") serverInfo->setServerItem(NULL); else serverInfo->setServerItem(dynamic_cast<HUDuiServerList*>(tabbedControl->getActiveTab())->getSelectedServer()); } void ServerMenu::playingCB(void* _self) { ServerList &list = ServerList::instance(); for (PingsMap::iterator i = ServerMenu::activePings.begin(); i != ServerMenu::activePings.end();) { i->second.first->doPings(); if (i->second.first->done()) { ServerItem* server = list.lookupServer(i->first); if (server == NULL) break; server->ping.pingTime = i->second.first->calcLag(); server->ping.pinging = false; for (size_t j=0; j<(i->second.second.size()); j++) { i->second.second[j]->addItem(server); } delete i->second.first; ServerMenu::activePings.erase(i++); continue; } ++i; } static_cast<ServerMenu*>(_self)->serverList.checkEchos(getStartupInfo()); static_cast<ServerMenu*>(_self)->updateStatus(); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include <pthread.h> #include "barrier.h" /* * Initialize the barrier. */ Barrier::Barrier(int threads) : num_threads(threads), num_waiting(threads) { pthread_cond_init(&waiting_queue, NULL); pthread_mutex_init(&lock, NULL); } /* * Destroy the barrier. */ Barrier::~Barrier() { pthread_cond_broadcast(&waiting_queue); pthread_mutex_destroy(&lock); pthread_cond_destroy(&waiting_queue); } /* * Synchronize threads. */ void Barrier::wait() { pthread_mutex_lock(&lock); if (--num_waiting > 0) { pthread_cond_wait(&waiting_queue, &lock); } else { num_waiting = num_threads; pthread_cond_broadcast(&waiting_queue); } pthread_mutex_unlock(&lock); } <commit_msg>temporary hack to work around the race conditions for servers<commit_after>#include <pthread.h> #include <time.h> #include "barrier.h" /* * Initialize the barrier. */ Barrier::Barrier(int threads) : num_threads(threads), num_waiting(threads) { pthread_cond_init(&waiting_queue, NULL); pthread_mutex_init(&lock, NULL); } /* * Destroy the barrier. */ Barrier::~Barrier() { pthread_cond_broadcast(&waiting_queue); pthread_mutex_destroy(&lock); pthread_cond_destroy(&waiting_queue); } /* * Synchronize threads. */ void Barrier::wait() { pthread_mutex_lock(&lock); if (num_threads == 1) { // Only one thread, artificially wait for 750 ms // FIXME: This is just an ugly hack to prevent the race condition for servers timespec timeout = {0, 750000000L}; pthread_yield(); nanosleep(&timeout, NULL); } if (--num_waiting > 0) { // Wait until all threads reach this point pthread_cond_wait(&waiting_queue, &lock); } else { // We are the last thread, wake everybody up and continue num_waiting = num_threads; pthread_cond_broadcast(&waiting_queue); } pthread_mutex_unlock(&lock); } <|endoftext|>
<commit_before>#include "basecpu.h" #include "errors.h" BaseCPU::BaseCPU(const System &sys): sys(sys), running(false) { } void BaseCPU::stop() { running = false; } bool BaseCPU::startup() { bool started = false; if (!running) { started = true; reset(); while(running) { tick(); } } return started; } int BaseCPU::readMemory(SizeType offset, SizeType len, void *data) const { return sys.readMemory(offset, len, data); } int BaseCPU::writeMemory(SizeType offset, SizeType len, const void *data) const { return sys.writeMemory(offset, len, data); } int BaseCPU::readPort(PortType port, SizeType len, void *data) const { return sys.readPort(port, len, data); } int BaseCPU::writePort(PortType port, SizeType len, const void *data) const { return sys.writePort(port, len, data); } void Interruptable::signalInterrupt(Interrupt interrupt) { queue.push(interrupt); } bool Interruptable::serviceNextInterrupt() { bool ret = false; if(!queue.empty()) { serviceInterrupt(queue.front()); queue.pop(); ret = true; } return ret; } GenericCPU::GenericCPU(const System &sys, const InstructionSet &set, Interrupt badInstruction, Interrupt badOperand) : BaseCPU(sys), set(set), badInstruction(badInstruction), badOperand(badOperand) { } void GenericCPU::tick() { if(!(interruptsEnabled() && serviceNextInterrupt())) { nextInstruction(); } } bool GenericCPU::loadNextByte(ByteString &buffer, const void * const base) { bool ret = false; byte next; SizeType nextAddr = ((SizeType)base) + buffer.size(); if(readMemory(nextAddr, 1, &next) != ERR_SUCCESS) { ret = false; } else { buffer.push_back(next); ret = true; } return ret; } bool GenericCPU::readBytes(ByteString &buffer, const void * const base, SizeType length) { buffer.reserve(length); return readMemory((SizeType)base, length, buffer.data()) == ERR_SUCCESS; } void GenericCPU::nextInstruction() { ByteString opcode; int decodeRc = ERR_SUCCESS; const void * const instructionBase = instructionPointer(); // FIXME: Shouldn't HAVE to be const const Instruction *inst; do { if(loadNextByte(opcode, instructionBase)) { signalInterrupt(badOperand); } else { decodeRc = set.decode(opcode, &inst); } } while(decodeRc == ERR_CONFLICT || decodeRc == ERR_INCOMPLETE); if(decodeRc != ERR_SUCCESS) { signalInterrupt(badInstruction); } else { SizeType operandLength = inst->length; SizeType offset = opcode.size(); ByteString operands; if(!readBytes(operands, instructionBase, operandLength)) { signalInterrupt(badOperand); } else { inst->execute(*this, operands); } } }<commit_msg>Set running state in startup<commit_after>#include "basecpu.h" #include "errors.h" BaseCPU::BaseCPU(const System &sys): sys(sys), running(false) { } void BaseCPU::stop() { running = false; } bool BaseCPU::startup() { bool started = false; if (!running) { running = true; started = true; reset(); while(running) { tick(); } } return started; } int BaseCPU::readMemory(SizeType offset, SizeType len, void *data) const { return sys.readMemory(offset, len, data); } int BaseCPU::writeMemory(SizeType offset, SizeType len, const void *data) const { return sys.writeMemory(offset, len, data); } int BaseCPU::readPort(PortType port, SizeType len, void *data) const { return sys.readPort(port, len, data); } int BaseCPU::writePort(PortType port, SizeType len, const void *data) const { return sys.writePort(port, len, data); } void Interruptable::signalInterrupt(Interrupt interrupt) { queue.push(interrupt); } bool Interruptable::serviceNextInterrupt() { bool ret = false; if(!queue.empty()) { serviceInterrupt(queue.front()); queue.pop(); ret = true; } return ret; } GenericCPU::GenericCPU(const System &sys, const InstructionSet &set, Interrupt badInstruction, Interrupt badOperand) : BaseCPU(sys), set(set), badInstruction(badInstruction), badOperand(badOperand) { } void GenericCPU::tick() { if(!(interruptsEnabled() && serviceNextInterrupt())) { nextInstruction(); } } bool GenericCPU::loadNextByte(ByteString &buffer, const void * const base) { bool ret = false; byte next; SizeType nextAddr = ((SizeType)base) + buffer.size(); if(readMemory(nextAddr, 1, &next) != ERR_SUCCESS) { ret = false; } else { buffer.push_back(next); ret = true; } return ret; } bool GenericCPU::readBytes(ByteString &buffer, const void * const base, SizeType length) { buffer.reserve(length); return readMemory((SizeType)base, length, buffer.data()) == ERR_SUCCESS; } void GenericCPU::nextInstruction() { ByteString opcode; int decodeRc = ERR_SUCCESS; const void * const instructionBase = instructionPointer(); // FIXME: Shouldn't HAVE to be const const Instruction *inst; do { if(loadNextByte(opcode, instructionBase)) { signalInterrupt(badOperand); } else { decodeRc = set.decode(opcode, &inst); } } while(decodeRc == ERR_CONFLICT || decodeRc == ERR_INCOMPLETE); if(decodeRc != ERR_SUCCESS) { signalInterrupt(badInstruction); } else { SizeType operandLength = inst->length; SizeType offset = opcode.size(); ByteString operands; if(!readBytes(operands, instructionBase, operandLength)) { signalInterrupt(badOperand); } else { inst->execute(*this, operands); } } }<|endoftext|>
<commit_before>#include "JobHandler/PathPlanningHandler.h" #include <cmath> using namespace std; bool PathPlanningHandler::registered = JobHandler::RegisterJobHandler("path-planning", [](string command) { return (ptr<JobHandler>) std::make_shared<PathPlanningHandler>(); }); PathPlanningHandler::PathPlanningHandler() { g = Grid(1000, 1000, 13, 13, 13, 0); shortPath = Dijkstra(500, 500); path = Path(); track = 0; } PathPlanningHandler::PathPlanningHandler(float w, float h, float scal, float startx, float starty, float startAngle, float goalx, float goaly) { g = Grid(w, h, scal, startx, starty, startAngle); shortPath = Dijkstra(goalx, goaly); path = Path(); track = 0; } PathPlanningHandler::~PathPlanningHandler() { } void PathPlanningHandler::execute(deque<Job>& jobs, SensorData & data, ControllerData & outputs) { Obstacle newObs; auto usInfo = data.find("ULTRASOUNDF"); if (usInfo != data.end()) { //Add obstacle information to grid for (int i = 1; i <= 7; i++) { float inches = static_pointer_cast<UltrasoundData>(usInfo->second)->distance[i - 1]; newObs = Obstacle(g.R2Pos.x, g.R2Pos.y, g.r2Angle, 3.14159265/4, inches); g.addObstacle(newObs); } //Recalculate path path = shortPath.calcPath(&g); track = 0; } else if(track < path.path.size()){ //Extract next coordinate from shortest path and calculate motor commands Coord moveTo = path.path[track]; float xdist = moveTo.x - g.R2Pos.x; float ydist = moveTo.y - g.R2Pos.y; float radius = sqrt(pow(xdist, 2) + pow(ydist, 2)); float angle = atan2(ydist, xdist) - g.r2Angle; int l = (int)(radius * cos(angle)); int r = (int)(radius * sin(angle)); track++; g.updatePos(moveTo.x, moveTo.y); ptr<MotorData> output = std::make_shared<MotorData>(); output->leftMotor = l; output->rightMotor = r; outputs["MOTOR"] = output; } else { //Stop motors if no path or goal reached ptr<MotorData> output = std::make_shared<MotorData>(); output->leftMotor = 0; output->rightMotor = 0; outputs["MOTOR"] = output; } } <commit_msg>Changed default scale of grid<commit_after>#include "JobHandler/PathPlanningHandler.h" #include <cmath> using namespace std; bool PathPlanningHandler::registered = JobHandler::RegisterJobHandler("path-planning", [](string command) { return (ptr<JobHandler>) std::make_shared<PathPlanningHandler>(); }); PathPlanningHandler::PathPlanningHandler() { g = Grid(1000, 1000, 15, 13, 13, 0); shortPath = Dijkstra(500, 500); path = Path(); track = 0; } PathPlanningHandler::PathPlanningHandler(float w, float h, float scal, float startx, float starty, float startAngle, float goalx, float goaly) { g = Grid(w, h, scal, startx, starty, startAngle); shortPath = Dijkstra(goalx, goaly); path = Path(); track = 0; } PathPlanningHandler::~PathPlanningHandler() { } void PathPlanningHandler::execute(deque<Job>& jobs, SensorData & data, ControllerData & outputs) { Obstacle newObs; auto usInfo = data.find("ULTRASOUNDF"); if (usInfo != data.end()) { //Add obstacle information to grid for (int i = 1; i <= 7; i++) { float inches = static_pointer_cast<UltrasoundData>(usInfo->second)->distance[i - 1]; newObs = Obstacle(g.R2Pos.x, g.R2Pos.y, g.r2Angle, 3.14159265/4, inches); g.addObstacle(newObs); } //Recalculate path path = shortPath.calcPath(&g); track = 0; } else if(track < path.path.size()){ //Extract next coordinate from shortest path and calculate motor commands Coord moveTo = path.path[track]; float xdist = moveTo.x - g.R2Pos.x; float ydist = moveTo.y - g.R2Pos.y; float radius = sqrt(pow(xdist, 2) + pow(ydist, 2)); float angle = atan2(ydist, xdist) - g.r2Angle; int l = (int)(radius * cos(angle)); int r = (int)(radius * sin(angle)); track++; g.updatePos(moveTo.x, moveTo.y); ptr<MotorData> output = std::make_shared<MotorData>(); output->leftMotor = l; output->rightMotor = r; outputs["MOTOR"] = output; } else { //Stop motors if no path or goal reached ptr<MotorData> output = std::make_shared<MotorData>(); output->leftMotor = 0; output->rightMotor = 0; outputs["MOTOR"] = output; } } <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2017 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "vk_state.h" #include "vk_core.h" #include "vk_info.h" #include "vk_resources.h" VulkanRenderState::VulkanRenderState(WrappedVulkan *driver, VulkanCreationInfo *createInfo) : m_CreationInfo(createInfo), m_pDriver(driver) { compute.pipeline = graphics.pipeline = renderPass = framebuffer = ResourceId(); compute.descSets.clear(); graphics.descSets.clear(); views.clear(); scissors.clear(); lineWidth = 1.0f; RDCEraseEl(bias); RDCEraseEl(blendConst); mindepth = 0.0f; maxdepth = 1.0f; RDCEraseEl(front); RDCEraseEl(back); RDCEraseEl(pushconsts); renderPass = ResourceId(); subpass = 0; RDCEraseEl(renderArea); RDCEraseEl(ibuffer); vbuffers.clear(); } VulkanRenderState &VulkanRenderState::operator=(const VulkanRenderState &o) { views = o.views; scissors = o.scissors; lineWidth = o.lineWidth; bias = o.bias; memcpy(blendConst, o.blendConst, sizeof(blendConst)); mindepth = o.mindepth; maxdepth = o.maxdepth; front = o.front; back = o.back; memcpy(pushconsts, o.pushconsts, sizeof(pushconsts)); renderPass = o.renderPass; subpass = o.subpass; framebuffer = o.framebuffer; renderArea = o.renderArea; compute.pipeline = o.compute.pipeline; compute.descSets = o.compute.descSets; graphics.pipeline = o.graphics.pipeline; graphics.descSets = o.graphics.descSets; ibuffer = o.ibuffer; vbuffers = o.vbuffers; return *this; } void VulkanRenderState::BeginRenderPassAndApplyState(VkCommandBuffer cmd, PipelineBinding binding) { RDCASSERT(renderPass != ResourceId()); // clear values don't matter as we're using the load renderpass here, that // has all load ops set to load (as we're doing a partial replay - can't // just clear the targets that are partially written to). VkClearValue empty[16] = {}; RDCASSERT(ARRAY_COUNT(empty) >= m_CreationInfo->m_RenderPass[renderPass].attachments.size()); VkRenderPassBeginInfo rpbegin = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, NULL, Unwrap(m_CreationInfo->m_RenderPass[renderPass].loadRPs[subpass]), Unwrap(GetResourceManager()->GetCurrentHandle<VkFramebuffer>(framebuffer)), renderArea, (uint32_t)m_CreationInfo->m_RenderPass[renderPass].attachments.size(), empty, }; ObjDisp(cmd)->CmdBeginRenderPass(Unwrap(cmd), &rpbegin, VK_SUBPASS_CONTENTS_INLINE); BindPipeline(cmd, binding, true); if(ibuffer.buf != ResourceId()) ObjDisp(cmd)->CmdBindIndexBuffer( Unwrap(cmd), Unwrap(GetResourceManager()->GetCurrentHandle<VkBuffer>(ibuffer.buf)), ibuffer.offs, ibuffer.bytewidth == 4 ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_UINT16); for(size_t i = 0; i < vbuffers.size(); i++) ObjDisp(cmd)->CmdBindVertexBuffers( Unwrap(cmd), (uint32_t)i, 1, UnwrapPtr(GetResourceManager()->GetCurrentHandle<VkBuffer>(vbuffers[i].buf)), &vbuffers[i].offs); } void VulkanRenderState::BindPipeline(VkCommandBuffer cmd, PipelineBinding binding, bool subpass0) { if(graphics.pipeline != ResourceId() && binding == BindGraphics) { VkPipeline pipe = GetResourceManager()->GetCurrentHandle<VkPipeline>(graphics.pipeline); if(subpass0 && m_CreationInfo->m_Pipeline[graphics.pipeline].subpass0pipe != VK_NULL_HANDLE) pipe = m_CreationInfo->m_Pipeline[graphics.pipeline].subpass0pipe; ObjDisp(cmd)->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(pipe)); ResourceId pipeLayoutId = m_CreationInfo->m_Pipeline[graphics.pipeline].layout; VkPipelineLayout layout = GetResourceManager()->GetCurrentHandle<VkPipelineLayout>(pipeLayoutId); const vector<VkPushConstantRange> &pushRanges = m_CreationInfo->m_PipelineLayout[pipeLayoutId].pushRanges; bool dynamicStates[VK_DYNAMIC_STATE_RANGE_SIZE] = {0}; memcpy(dynamicStates, m_CreationInfo->m_Pipeline[graphics.pipeline].dynamicStates, sizeof(dynamicStates)); RDCCOMPILE_ASSERT(sizeof(dynamicStates) == sizeof(m_CreationInfo->m_Pipeline[graphics.pipeline].dynamicStates), "Dynamic states array size is out of sync"); if(!views.empty() && dynamicStates[VK_DYNAMIC_STATE_VIEWPORT]) ObjDisp(cmd)->CmdSetViewport(Unwrap(cmd), 0, (uint32_t)views.size(), &views[0]); if(!scissors.empty() && dynamicStates[VK_DYNAMIC_STATE_SCISSOR]) ObjDisp(cmd)->CmdSetScissor(Unwrap(cmd), 0, (uint32_t)scissors.size(), &scissors[0]); if(dynamicStates[VK_DYNAMIC_STATE_LINE_WIDTH]) ObjDisp(cmd)->CmdSetLineWidth(Unwrap(cmd), lineWidth); if(dynamicStates[VK_DYNAMIC_STATE_DEPTH_BIAS]) ObjDisp(cmd)->CmdSetDepthBias(Unwrap(cmd), bias.depth, bias.biasclamp, bias.slope); if(dynamicStates[VK_DYNAMIC_STATE_BLEND_CONSTANTS]) ObjDisp(cmd)->CmdSetBlendConstants(Unwrap(cmd), blendConst); if(dynamicStates[VK_DYNAMIC_STATE_DEPTH_BOUNDS]) ObjDisp(cmd)->CmdSetDepthBounds(Unwrap(cmd), mindepth, maxdepth); if(dynamicStates[VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK]) { ObjDisp(cmd)->CmdSetStencilCompareMask(Unwrap(cmd), VK_STENCIL_FACE_BACK_BIT, back.compare); ObjDisp(cmd)->CmdSetStencilCompareMask(Unwrap(cmd), VK_STENCIL_FACE_FRONT_BIT, front.compare); } if(dynamicStates[VK_DYNAMIC_STATE_STENCIL_WRITE_MASK]) { ObjDisp(cmd)->CmdSetStencilWriteMask(Unwrap(cmd), VK_STENCIL_FACE_BACK_BIT, back.write); ObjDisp(cmd)->CmdSetStencilWriteMask(Unwrap(cmd), VK_STENCIL_FACE_FRONT_BIT, front.write); } if(dynamicStates[VK_DYNAMIC_STATE_STENCIL_REFERENCE]) { ObjDisp(cmd)->CmdSetStencilReference(Unwrap(cmd), VK_STENCIL_FACE_BACK_BIT, back.ref); ObjDisp(cmd)->CmdSetStencilReference(Unwrap(cmd), VK_STENCIL_FACE_FRONT_BIT, front.ref); } // only set push constant ranges that the layout uses for(size_t i = 0; i < pushRanges.size(); i++) ObjDisp(cmd)->CmdPushConstants(Unwrap(cmd), Unwrap(layout), pushRanges[i].stageFlags, pushRanges[i].offset, pushRanges[i].size, pushconsts + pushRanges[i].offset); const vector<ResourceId> &descSetLayouts = m_CreationInfo->m_PipelineLayout[pipeLayoutId].descSetLayouts; // only iterate over the desc sets that this layout actually uses, not all that were bound for(size_t i = 0; i < descSetLayouts.size(); i++) { const DescSetLayout &descLayout = m_CreationInfo->m_DescSetLayout[descSetLayouts[i]]; if(i < graphics.descSets.size() && graphics.descSets[i].descSet != ResourceId()) { // if we come to a descriptor set that isn't compatible, stop setting descriptor sets from // here on. // We can get into this situation if for example we have many sets bound at some point, then // there's a pipeline change that causes most or all of them to be invalidated as // incompatible, then the program only re-binds some subset that it knows is statically used // by the next drawcall. The remaining sets are invalid, but also unused and this is // explicitly allowed by the spec. We just have to make sure we don't try to actively bind // an incompatible descriptor set. ResourceId createdDescSetLayoutId = m_pDriver->GetDescLayoutForDescSet(graphics.descSets[i].descSet); if(descSetLayouts[i] != createdDescSetLayoutId) { const DescSetLayout &createdDescLayout = m_CreationInfo->m_DescSetLayout[createdDescSetLayoutId]; if(descLayout != createdDescLayout) break; } // if there are dynamic buffers, pass along the offsets uint32_t *dynamicOffsets = NULL; if(descLayout.dynamicCount > 0) { dynamicOffsets = &graphics.descSets[i].offsets[0]; if(graphics.descSets[i].offsets.size() < descLayout.dynamicCount) { dynamicOffsets = new uint32_t[descLayout.dynamicCount]; for(uint32_t o = 0; o < descLayout.dynamicCount; o++) { if(o < graphics.descSets[i].offsets.size()) { dynamicOffsets[o] = graphics.descSets[i].offsets[o]; } else { dynamicOffsets[o] = 0; RDCWARN("Missing dynamic offset for set %u!", (uint32_t)i); } } } } ObjDisp(cmd)->CmdBindDescriptorSets( Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(layout), (uint32_t)i, 1, UnwrapPtr(GetResourceManager()->GetCurrentHandle<VkDescriptorSet>( graphics.descSets[i].descSet)), descLayout.dynamicCount, dynamicOffsets); if(graphics.descSets[i].offsets.size() < descLayout.dynamicCount) SAFE_DELETE_ARRAY(dynamicOffsets); } else { RDCWARN("Descriptor set is not bound but pipeline layout expects one"); } } } if(compute.pipeline != ResourceId() && binding == BindCompute) { ObjDisp(cmd)->CmdBindPipeline( Unwrap(cmd), VK_PIPELINE_BIND_POINT_COMPUTE, Unwrap(GetResourceManager()->GetCurrentHandle<VkPipeline>(compute.pipeline))); ResourceId pipeLayoutId = m_CreationInfo->m_Pipeline[compute.pipeline].layout; VkPipelineLayout layout = GetResourceManager()->GetCurrentHandle<VkPipelineLayout>(pipeLayoutId); const vector<VkPushConstantRange> &pushRanges = m_CreationInfo->m_PipelineLayout[pipeLayoutId].pushRanges; // only set push constant ranges that the layout uses for(size_t i = 0; i < pushRanges.size(); i++) ObjDisp(cmd)->CmdPushConstants(Unwrap(cmd), Unwrap(layout), pushRanges[i].stageFlags, pushRanges[i].offset, pushRanges[i].size, pushconsts + pushRanges[i].offset); const vector<ResourceId> &descSetLayouts = m_CreationInfo->m_PipelineLayout[pipeLayoutId].descSetLayouts; for(size_t i = 0; i < descSetLayouts.size(); i++) { const DescSetLayout &descLayout = m_CreationInfo->m_DescSetLayout[descSetLayouts[i]]; if(i < compute.descSets.size() && compute.descSets[i].descSet != ResourceId()) { // if there are dynamic buffers, pass along the offsets uint32_t *dynamicOffsets = NULL; if(descLayout.dynamicCount > 0) { dynamicOffsets = &compute.descSets[i].offsets[0]; if(compute.descSets[i].offsets.size() < descLayout.dynamicCount) { dynamicOffsets = new uint32_t[descLayout.dynamicCount]; for(uint32_t o = 0; o < descLayout.dynamicCount; o++) { if(o < compute.descSets[i].offsets.size()) { dynamicOffsets[o] = compute.descSets[i].offsets[o]; } else { dynamicOffsets[o] = 0; RDCWARN("Missing dynamic offset for set %u!", (uint32_t)i); } } } } ObjDisp(cmd)->CmdBindDescriptorSets( Unwrap(cmd), VK_PIPELINE_BIND_POINT_COMPUTE, Unwrap(layout), (uint32_t)i, 1, UnwrapPtr(GetResourceManager()->GetCurrentHandle<VkDescriptorSet>( compute.descSets[i].descSet)), descLayout.dynamicCount, dynamicOffsets); if(compute.descSets[i].offsets.size() < descLayout.dynamicCount) SAFE_DELETE_ARRAY(dynamicOffsets); } } } } void VulkanRenderState::EndRenderPass(VkCommandBuffer cmd) { ObjDisp(cmd)->CmdEndRenderPass(Unwrap(cmd)); } VulkanResourceManager *VulkanRenderState::GetResourceManager() { return m_pDriver->GetResourceManager(); } <commit_msg>Bind all compatible descriptor sets, don't bail at the first one<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2017 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "vk_state.h" #include "vk_core.h" #include "vk_info.h" #include "vk_resources.h" VulkanRenderState::VulkanRenderState(WrappedVulkan *driver, VulkanCreationInfo *createInfo) : m_CreationInfo(createInfo), m_pDriver(driver) { compute.pipeline = graphics.pipeline = renderPass = framebuffer = ResourceId(); compute.descSets.clear(); graphics.descSets.clear(); views.clear(); scissors.clear(); lineWidth = 1.0f; RDCEraseEl(bias); RDCEraseEl(blendConst); mindepth = 0.0f; maxdepth = 1.0f; RDCEraseEl(front); RDCEraseEl(back); RDCEraseEl(pushconsts); renderPass = ResourceId(); subpass = 0; RDCEraseEl(renderArea); RDCEraseEl(ibuffer); vbuffers.clear(); } VulkanRenderState &VulkanRenderState::operator=(const VulkanRenderState &o) { views = o.views; scissors = o.scissors; lineWidth = o.lineWidth; bias = o.bias; memcpy(blendConst, o.blendConst, sizeof(blendConst)); mindepth = o.mindepth; maxdepth = o.maxdepth; front = o.front; back = o.back; memcpy(pushconsts, o.pushconsts, sizeof(pushconsts)); renderPass = o.renderPass; subpass = o.subpass; framebuffer = o.framebuffer; renderArea = o.renderArea; compute.pipeline = o.compute.pipeline; compute.descSets = o.compute.descSets; graphics.pipeline = o.graphics.pipeline; graphics.descSets = o.graphics.descSets; ibuffer = o.ibuffer; vbuffers = o.vbuffers; return *this; } void VulkanRenderState::BeginRenderPassAndApplyState(VkCommandBuffer cmd, PipelineBinding binding) { RDCASSERT(renderPass != ResourceId()); // clear values don't matter as we're using the load renderpass here, that // has all load ops set to load (as we're doing a partial replay - can't // just clear the targets that are partially written to). VkClearValue empty[16] = {}; RDCASSERT(ARRAY_COUNT(empty) >= m_CreationInfo->m_RenderPass[renderPass].attachments.size()); VkRenderPassBeginInfo rpbegin = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, NULL, Unwrap(m_CreationInfo->m_RenderPass[renderPass].loadRPs[subpass]), Unwrap(GetResourceManager()->GetCurrentHandle<VkFramebuffer>(framebuffer)), renderArea, (uint32_t)m_CreationInfo->m_RenderPass[renderPass].attachments.size(), empty, }; ObjDisp(cmd)->CmdBeginRenderPass(Unwrap(cmd), &rpbegin, VK_SUBPASS_CONTENTS_INLINE); BindPipeline(cmd, binding, true); if(ibuffer.buf != ResourceId()) ObjDisp(cmd)->CmdBindIndexBuffer( Unwrap(cmd), Unwrap(GetResourceManager()->GetCurrentHandle<VkBuffer>(ibuffer.buf)), ibuffer.offs, ibuffer.bytewidth == 4 ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_UINT16); for(size_t i = 0; i < vbuffers.size(); i++) ObjDisp(cmd)->CmdBindVertexBuffers( Unwrap(cmd), (uint32_t)i, 1, UnwrapPtr(GetResourceManager()->GetCurrentHandle<VkBuffer>(vbuffers[i].buf)), &vbuffers[i].offs); } void VulkanRenderState::BindPipeline(VkCommandBuffer cmd, PipelineBinding binding, bool subpass0) { if(graphics.pipeline != ResourceId() && binding == BindGraphics) { VkPipeline pipe = GetResourceManager()->GetCurrentHandle<VkPipeline>(graphics.pipeline); if(subpass0 && m_CreationInfo->m_Pipeline[graphics.pipeline].subpass0pipe != VK_NULL_HANDLE) pipe = m_CreationInfo->m_Pipeline[graphics.pipeline].subpass0pipe; ObjDisp(cmd)->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(pipe)); ResourceId pipeLayoutId = m_CreationInfo->m_Pipeline[graphics.pipeline].layout; VkPipelineLayout layout = GetResourceManager()->GetCurrentHandle<VkPipelineLayout>(pipeLayoutId); const vector<VkPushConstantRange> &pushRanges = m_CreationInfo->m_PipelineLayout[pipeLayoutId].pushRanges; bool dynamicStates[VK_DYNAMIC_STATE_RANGE_SIZE] = {0}; memcpy(dynamicStates, m_CreationInfo->m_Pipeline[graphics.pipeline].dynamicStates, sizeof(dynamicStates)); RDCCOMPILE_ASSERT(sizeof(dynamicStates) == sizeof(m_CreationInfo->m_Pipeline[graphics.pipeline].dynamicStates), "Dynamic states array size is out of sync"); if(!views.empty() && dynamicStates[VK_DYNAMIC_STATE_VIEWPORT]) ObjDisp(cmd)->CmdSetViewport(Unwrap(cmd), 0, (uint32_t)views.size(), &views[0]); if(!scissors.empty() && dynamicStates[VK_DYNAMIC_STATE_SCISSOR]) ObjDisp(cmd)->CmdSetScissor(Unwrap(cmd), 0, (uint32_t)scissors.size(), &scissors[0]); if(dynamicStates[VK_DYNAMIC_STATE_LINE_WIDTH]) ObjDisp(cmd)->CmdSetLineWidth(Unwrap(cmd), lineWidth); if(dynamicStates[VK_DYNAMIC_STATE_DEPTH_BIAS]) ObjDisp(cmd)->CmdSetDepthBias(Unwrap(cmd), bias.depth, bias.biasclamp, bias.slope); if(dynamicStates[VK_DYNAMIC_STATE_BLEND_CONSTANTS]) ObjDisp(cmd)->CmdSetBlendConstants(Unwrap(cmd), blendConst); if(dynamicStates[VK_DYNAMIC_STATE_DEPTH_BOUNDS]) ObjDisp(cmd)->CmdSetDepthBounds(Unwrap(cmd), mindepth, maxdepth); if(dynamicStates[VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK]) { ObjDisp(cmd)->CmdSetStencilCompareMask(Unwrap(cmd), VK_STENCIL_FACE_BACK_BIT, back.compare); ObjDisp(cmd)->CmdSetStencilCompareMask(Unwrap(cmd), VK_STENCIL_FACE_FRONT_BIT, front.compare); } if(dynamicStates[VK_DYNAMIC_STATE_STENCIL_WRITE_MASK]) { ObjDisp(cmd)->CmdSetStencilWriteMask(Unwrap(cmd), VK_STENCIL_FACE_BACK_BIT, back.write); ObjDisp(cmd)->CmdSetStencilWriteMask(Unwrap(cmd), VK_STENCIL_FACE_FRONT_BIT, front.write); } if(dynamicStates[VK_DYNAMIC_STATE_STENCIL_REFERENCE]) { ObjDisp(cmd)->CmdSetStencilReference(Unwrap(cmd), VK_STENCIL_FACE_BACK_BIT, back.ref); ObjDisp(cmd)->CmdSetStencilReference(Unwrap(cmd), VK_STENCIL_FACE_FRONT_BIT, front.ref); } // only set push constant ranges that the layout uses for(size_t i = 0; i < pushRanges.size(); i++) ObjDisp(cmd)->CmdPushConstants(Unwrap(cmd), Unwrap(layout), pushRanges[i].stageFlags, pushRanges[i].offset, pushRanges[i].size, pushconsts + pushRanges[i].offset); const vector<ResourceId> &descSetLayouts = m_CreationInfo->m_PipelineLayout[pipeLayoutId].descSetLayouts; // only iterate over the desc sets that this layout actually uses, not all that were bound for(size_t i = 0; i < descSetLayouts.size(); i++) { const DescSetLayout &descLayout = m_CreationInfo->m_DescSetLayout[descSetLayouts[i]]; if(i < graphics.descSets.size() && graphics.descSets[i].descSet != ResourceId()) { // if we come to a descriptor set that isn't compatible, stop setting descriptor sets from // here on. // We can get into this situation if for example we have many sets bound at some point, then // there's a pipeline change that causes most or all of them to be invalidated as // incompatible, then the program only re-binds some subset that it knows is statically used // by the next drawcall. The remaining sets are invalid, but also unused and this is // explicitly allowed by the spec. We just have to make sure we don't try to actively bind // an incompatible descriptor set. ResourceId createdDescSetLayoutId = m_pDriver->GetDescLayoutForDescSet(graphics.descSets[i].descSet); if(descSetLayouts[i] != createdDescSetLayoutId) { const DescSetLayout &createdDescLayout = m_CreationInfo->m_DescSetLayout[createdDescSetLayoutId]; if(descLayout != createdDescLayout) { // this set is incompatible, don't rebind it. Assume the application knows the shader // doesn't need this set, and the binding is just stale continue; } } // if there are dynamic buffers, pass along the offsets uint32_t *dynamicOffsets = NULL; if(descLayout.dynamicCount > 0) { dynamicOffsets = &graphics.descSets[i].offsets[0]; if(graphics.descSets[i].offsets.size() < descLayout.dynamicCount) { dynamicOffsets = new uint32_t[descLayout.dynamicCount]; for(uint32_t o = 0; o < descLayout.dynamicCount; o++) { if(o < graphics.descSets[i].offsets.size()) { dynamicOffsets[o] = graphics.descSets[i].offsets[o]; } else { dynamicOffsets[o] = 0; RDCWARN("Missing dynamic offset for set %u!", (uint32_t)i); } } } } ObjDisp(cmd)->CmdBindDescriptorSets( Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(layout), (uint32_t)i, 1, UnwrapPtr(GetResourceManager()->GetCurrentHandle<VkDescriptorSet>( graphics.descSets[i].descSet)), descLayout.dynamicCount, dynamicOffsets); if(graphics.descSets[i].offsets.size() < descLayout.dynamicCount) SAFE_DELETE_ARRAY(dynamicOffsets); } else { RDCWARN("Descriptor set is not bound but pipeline layout expects one"); } } } if(compute.pipeline != ResourceId() && binding == BindCompute) { ObjDisp(cmd)->CmdBindPipeline( Unwrap(cmd), VK_PIPELINE_BIND_POINT_COMPUTE, Unwrap(GetResourceManager()->GetCurrentHandle<VkPipeline>(compute.pipeline))); ResourceId pipeLayoutId = m_CreationInfo->m_Pipeline[compute.pipeline].layout; VkPipelineLayout layout = GetResourceManager()->GetCurrentHandle<VkPipelineLayout>(pipeLayoutId); const vector<VkPushConstantRange> &pushRanges = m_CreationInfo->m_PipelineLayout[pipeLayoutId].pushRanges; // only set push constant ranges that the layout uses for(size_t i = 0; i < pushRanges.size(); i++) ObjDisp(cmd)->CmdPushConstants(Unwrap(cmd), Unwrap(layout), pushRanges[i].stageFlags, pushRanges[i].offset, pushRanges[i].size, pushconsts + pushRanges[i].offset); const vector<ResourceId> &descSetLayouts = m_CreationInfo->m_PipelineLayout[pipeLayoutId].descSetLayouts; for(size_t i = 0; i < descSetLayouts.size(); i++) { const DescSetLayout &descLayout = m_CreationInfo->m_DescSetLayout[descSetLayouts[i]]; if(i < compute.descSets.size() && compute.descSets[i].descSet != ResourceId()) { // if there are dynamic buffers, pass along the offsets uint32_t *dynamicOffsets = NULL; if(descLayout.dynamicCount > 0) { dynamicOffsets = &compute.descSets[i].offsets[0]; if(compute.descSets[i].offsets.size() < descLayout.dynamicCount) { dynamicOffsets = new uint32_t[descLayout.dynamicCount]; for(uint32_t o = 0; o < descLayout.dynamicCount; o++) { if(o < compute.descSets[i].offsets.size()) { dynamicOffsets[o] = compute.descSets[i].offsets[o]; } else { dynamicOffsets[o] = 0; RDCWARN("Missing dynamic offset for set %u!", (uint32_t)i); } } } } ObjDisp(cmd)->CmdBindDescriptorSets( Unwrap(cmd), VK_PIPELINE_BIND_POINT_COMPUTE, Unwrap(layout), (uint32_t)i, 1, UnwrapPtr(GetResourceManager()->GetCurrentHandle<VkDescriptorSet>( compute.descSets[i].descSet)), descLayout.dynamicCount, dynamicOffsets); if(compute.descSets[i].offsets.size() < descLayout.dynamicCount) SAFE_DELETE_ARRAY(dynamicOffsets); } } } } void VulkanRenderState::EndRenderPass(VkCommandBuffer cmd) { ObjDisp(cmd)->CmdEndRenderPass(Unwrap(cmd)); } VulkanResourceManager *VulkanRenderState::GetResourceManager() { return m_pDriver->GetResourceManager(); } <|endoftext|>
<commit_before># include "rrdb.server.impl.h" # include <boost/filesystem.hpp> namespace dsn { namespace apps { rrdb_service_impl::rrdb_service_impl(::dsn::replication::replica* replica, ::dsn::configuration_ptr& config) : rrdb_service(replica, config) { _is_open = false; // // disable write ahead logging as replication handles logging instead now // _wt_opts.disableWAL = true; } void rrdb_service_impl::on_put(const update_request& update, ::dsn::service::rpc_replier<int>& reply) { if (_is_open) { rocksdb::WriteOptions opts = _wt_opts; opts.given_sequence_number = static_cast<rocksdb::SequenceNumber>(_last_committed_decree + 1); rocksdb::Slice skey(update.key.data(), update.key.length()); rocksdb::Slice svalue(update.value.data(), update.value.length()); rocksdb::Status status = _db->Put(opts, skey, svalue); reply(status.code()); } else { reply(ERR_SERVICE_NOT_ACTIVE); } } void rrdb_service_impl::on_remove(const ::dsn::blob& key, ::dsn::service::rpc_replier<int>& reply) { if (_is_open) { rocksdb::WriteOptions opts = _wt_opts; opts.given_sequence_number = static_cast<rocksdb::SequenceNumber>(_last_committed_decree + 1); rocksdb::Slice skey(key.data(), key.length()); rocksdb::Status status = _db->Delete(opts, skey); reply(status.code()); } else { reply(ERR_SERVICE_NOT_ACTIVE); } } void rrdb_service_impl::on_merge(const update_request& update, ::dsn::service::rpc_replier<int>& reply) { if (_is_open) { rocksdb::WriteOptions opts = _wt_opts; opts.given_sequence_number = static_cast<rocksdb::SequenceNumber>(_last_committed_decree + 1); rocksdb::Slice skey(update.key.data(), update.key.length()); rocksdb::Slice svalue(update.value.data(), update.value.length()); rocksdb::Status status = _db->Merge(opts, skey, svalue); reply(status.code()); } else { reply(ERR_SERVICE_NOT_ACTIVE); } } void rrdb_service_impl::on_get(const ::dsn::blob& key, ::dsn::service::rpc_replier<read_response>& reply) { read_response resp; if (_is_open) { rocksdb::Slice skey(key.data(), key.length()); rocksdb::Status status = _db->Get(_rd_opts, skey, &resp.value); resp.error = status.code(); } else { resp.error = ERR_SERVICE_NOT_ACTIVE; } reply(resp); } int rrdb_service_impl::open(bool create_new) { if (_is_open) return ERR_SERVICE_ALREADY_RUNNING; rocksdb::Options opts; opts.create_if_missing = create_new; opts.error_if_exists = create_new; opts.write_buffer_size = 40 * 1024; // 40 K for testing now auto status = rocksdb::DB::Open(opts, data_dir() + "/rdb", &_db); if (status.ok()) { _is_open = true; _last_committed_decree = last_durable_decree(); } return status.code(); } int rrdb_service_impl::close(bool clear_state) { if (!_is_open) return ERR_SERVICE_NOT_ACTIVE; _is_open = false; delete _db; _db = nullptr; if (clear_state) { boost::filesystem::path lp = data_dir(); ::boost::filesystem::remove_all(lp); ::boost::filesystem::create_directory(lp); } return 0; } int rrdb_service_impl::flush(bool force) { if (!_is_open) return ERR_SERVICE_NOT_ACTIVE; rocksdb::FlushOptions opts; opts.wait = force; auto status = _db->Flush(opts); return status.code(); } void rrdb_service_impl::prepare_learning_request(__out_param blob& learn_req) { // nothing to do } int rrdb_service_impl::get_learn_state( ::dsn::replication::decree start, const blob& learn_req, __out_param::dsn::replication::learn_state& state) { if (!_is_open) return ERR_SERVICE_NOT_ACTIVE; rocksdb::SequenceNumber start0 = start; rocksdb::SequenceNumber end; std::string mem_state; std::string edit; auto status = _db->GetLearningState(start0, end, mem_state, edit, state.files); if (status.ok()) { binary_writer writer; writer.write(start0); writer.write(end); writer.write(edit); writer.write(mem_state); printf("GetLearningState result size = %d\n", writer.total_size()); state.meta.push_back(writer.get_buffer()); } return status.code(); } int rrdb_service_impl::apply_learn_state(::dsn::replication::learn_state& state) { if (!_is_open) return ERR_SERVICE_NOT_ACTIVE; binary_reader reader(state.meta[0]); printf("ApplyLearningState result size = %d\n", reader.total_size()); rocksdb::SequenceNumber start; rocksdb::SequenceNumber end; std::string edit; std::string mem_state; reader.read(start); reader.read(end); reader.read(edit); reader.read(mem_state); if (mem_state.size() == 0 && state.files.size() == 0) return ERR_SUCCESS; else { if (start == 0) { close(true); open(true); } for (auto &f : state.files) { boost::filesystem::path old_p = learn_dir() + f; boost::filesystem::path new_p = data_dir() + f; // create directory recursively if necessary boost::filesystem::path path = new_p; path = path.remove_filename(); if (!boost::filesystem::exists(path)) boost::filesystem::create_directories(path); boost::filesystem::rename(old_p, new_p); } auto status = _db->ApplyLearningState(start, mem_state, edit); if (status.ok()) { _last_committed_decree = end; printf("ApplyLeraningState lastcommitted in DB %s, <C,D> to <%lld, %lld> with <start,end> as <%lld, %lld>\n", data_dir().c_str(), static_cast<long long int>(last_committed_decree()), static_cast<long long int>(last_durable_decree()), static_cast<long long int>(start), static_cast<long long int>(end) ); } return status.code(); } } ::dsn::replication::decree rrdb_service_impl::last_durable_decree() const { if (_is_open) return _db->GetLatestDurableSequenceNumber(); else return 0; } } } <commit_msg>increase last commit number as now the replication app base does not do that automatically and requires the local app itself to do that to ensure atomicity.<commit_after># include "rrdb.server.impl.h" # include <boost/filesystem.hpp> namespace dsn { namespace apps { rrdb_service_impl::rrdb_service_impl(::dsn::replication::replica* replica, ::dsn::configuration_ptr& config) : rrdb_service(replica, config) { _is_open = false; // // disable write ahead logging as replication handles logging instead now // _wt_opts.disableWAL = true; } void rrdb_service_impl::on_put(const update_request& update, ::dsn::service::rpc_replier<int>& reply) { if (_is_open) { rocksdb::WriteOptions opts = _wt_opts; opts.given_sequence_number = static_cast<rocksdb::SequenceNumber>(_last_committed_decree + 1); rocksdb::Slice skey(update.key.data(), update.key.length()); rocksdb::Slice svalue(update.value.data(), update.value.length()); rocksdb::Status status = _db->Put(opts, skey, svalue); reply(status.code()); ++_last_committed_decree; } else { reply(ERR_SERVICE_NOT_ACTIVE); } } void rrdb_service_impl::on_remove(const ::dsn::blob& key, ::dsn::service::rpc_replier<int>& reply) { if (_is_open) { rocksdb::WriteOptions opts = _wt_opts; opts.given_sequence_number = static_cast<rocksdb::SequenceNumber>(_last_committed_decree + 1); rocksdb::Slice skey(key.data(), key.length()); rocksdb::Status status = _db->Delete(opts, skey); reply(status.code()); ++_last_committed_decree; } else { reply(ERR_SERVICE_NOT_ACTIVE); } } void rrdb_service_impl::on_merge(const update_request& update, ::dsn::service::rpc_replier<int>& reply) { if (_is_open) { rocksdb::WriteOptions opts = _wt_opts; opts.given_sequence_number = static_cast<rocksdb::SequenceNumber>(_last_committed_decree + 1); rocksdb::Slice skey(update.key.data(), update.key.length()); rocksdb::Slice svalue(update.value.data(), update.value.length()); rocksdb::Status status = _db->Merge(opts, skey, svalue); reply(status.code()); ++_last_committed_decree; } else { reply(ERR_SERVICE_NOT_ACTIVE); } } void rrdb_service_impl::on_get(const ::dsn::blob& key, ::dsn::service::rpc_replier<read_response>& reply) { read_response resp; if (_is_open) { rocksdb::Slice skey(key.data(), key.length()); rocksdb::Status status = _db->Get(_rd_opts, skey, &resp.value); resp.error = status.code(); } else { resp.error = ERR_SERVICE_NOT_ACTIVE; } reply(resp); } int rrdb_service_impl::open(bool create_new) { if (_is_open) return ERR_SERVICE_ALREADY_RUNNING; rocksdb::Options opts; opts.create_if_missing = create_new; opts.error_if_exists = create_new; opts.write_buffer_size = 40 * 1024; // 40 K for testing now auto status = rocksdb::DB::Open(opts, data_dir() + "/rdb", &_db); if (status.ok()) { _is_open = true; _last_committed_decree = last_durable_decree(); } return status.code(); } int rrdb_service_impl::close(bool clear_state) { if (!_is_open) return ERR_SERVICE_NOT_ACTIVE; _is_open = false; delete _db; _db = nullptr; if (clear_state) { boost::filesystem::path lp = data_dir(); ::boost::filesystem::remove_all(lp); ::boost::filesystem::create_directory(lp); } return 0; } int rrdb_service_impl::flush(bool force) { if (!_is_open) return ERR_SERVICE_NOT_ACTIVE; rocksdb::FlushOptions opts; opts.wait = force; auto status = _db->Flush(opts); return status.code(); } void rrdb_service_impl::prepare_learning_request(__out_param blob& learn_req) { // nothing to do } int rrdb_service_impl::get_learn_state( ::dsn::replication::decree start, const blob& learn_req, __out_param::dsn::replication::learn_state& state) { if (!_is_open) return ERR_SERVICE_NOT_ACTIVE; rocksdb::SequenceNumber start0 = start; rocksdb::SequenceNumber end; std::string mem_state; std::string edit; auto status = _db->GetLearningState(start0, end, mem_state, edit, state.files); if (status.ok()) { binary_writer writer; writer.write(start0); writer.write(end); writer.write(edit); writer.write(mem_state); printf("GetLearningState result size = %d\n", writer.total_size()); state.meta.push_back(writer.get_buffer()); } return status.code(); } int rrdb_service_impl::apply_learn_state(::dsn::replication::learn_state& state) { if (!_is_open) return ERR_SERVICE_NOT_ACTIVE; binary_reader reader(state.meta[0]); printf("ApplyLearningState result size = %d\n", reader.total_size()); rocksdb::SequenceNumber start; rocksdb::SequenceNumber end; std::string edit; std::string mem_state; reader.read(start); reader.read(end); reader.read(edit); reader.read(mem_state); if (mem_state.size() == 0 && state.files.size() == 0) return ERR_SUCCESS; else { if (start == 0) { close(true); open(true); } for (auto &f : state.files) { boost::filesystem::path old_p = learn_dir() + f; boost::filesystem::path new_p = data_dir() + f; // create directory recursively if necessary boost::filesystem::path path = new_p; path = path.remove_filename(); if (!boost::filesystem::exists(path)) boost::filesystem::create_directories(path); boost::filesystem::rename(old_p, new_p); } auto status = _db->ApplyLearningState(start, mem_state, edit); if (status.ok()) { _last_committed_decree = end; printf("ApplyLeraningState lastcommitted in DB %s, <C,D> to <%lld, %lld> with <start,end> as <%lld, %lld>\n", data_dir().c_str(), static_cast<long long int>(last_committed_decree()), static_cast<long long int>(last_durable_decree()), static_cast<long long int>(start), static_cast<long long int>(end) ); } return status.code(); } } ::dsn::replication::decree rrdb_service_impl::last_durable_decree() const { if (_is_open) return _db->GetLatestDurableSequenceNumber(); else return 0; } } } <|endoftext|>
<commit_before>#include "comparison_thread.h" #include "freetype_interface.h" FrameWinner::FrameWinner(char symb, uint_fast8_t diff) : symbol(symb) , grayLvlDiff(diff) { } SymbolMatches::SymbolMatches(size_t framesQuantity, const std::string& set) : progress(0) , symbolSet(set) { frameWinners.reserve(framesQuantity); } SymbolMatches::SymbolMatches(const SymbolMatches& toCopy) : frameWinners(toCopy.frameWinners) , progress(toCopy.progress.load()) , symbolSet(toCopy.symbolSet) { } static uint_fast8_t calculateGrayLevelDiff( const FrameSlider& imgPart, const GrayscaleBitmap& glyph) { if (imgPart.size() != glyph.rows * glyph.columns) { throw std::runtime_error("Sizes of image part and symbol glyph do not match"); } size_t pixelCount = imgPart.size(); size_t diffAcc = 0; for (size_t pixelNum = 0; pixelNum < pixelCount; ++pixelNum) { diffAcc += abs(static_cast<int>(imgPart.at(pixelNum)) - glyph.pixels->at(pixelNum)); } return diffAcc / pixelCount; } static FrameWinner chooseMatchingSymbol(const FrameSlider& imgPart, const std::string& symbolSet) { uint_fast8_t minDiff = 0xFF; char bestMatch = symbolSet.front(); symbol_map vocabulary = getVocabulary(); for (char symbol : symbolSet) { uint_fast8_t diff = calculateGrayLevelDiff(imgPart, vocabulary.at(symbol)); if (diff < minDiff) { bestMatch = symbol; minDiff = diff; } } return FrameWinner(bestMatch, minDiff); } #include <iostream> #include <exception> void processVocabularyPart(const FramedBitmap* map, SymbolMatches* matches) { try { const FrameSlider lastFrame = map->lastFrame(); FrameSlider frame = map->firstFrame(); for (; frame != lastFrame; frame.slide()) { FrameWinner winner = chooseMatchingSymbol(frame, matches->symbolSet); matches->frameWinners.push_back(winner); ++matches->progress; } FrameWinner winner = chooseMatchingSymbol(lastFrame, matches->symbolSet); matches->frameWinners.push_back(winner); ++matches->progress; } catch (std::exception& err) { std::cerr << err.what() << std::endl; } catch (...) { std::cerr << "Unknown exception caught" << std::endl; } } <commit_msg>simpler cycle #9<commit_after>#include "comparison_thread.h" #include "freetype_interface.h" FrameWinner::FrameWinner(char symb, uint_fast8_t diff) : symbol(symb) , grayLvlDiff(diff) { } SymbolMatches::SymbolMatches(size_t framesQuantity, const std::string& set) : progress(0) , symbolSet(set) { frameWinners.reserve(framesQuantity); } SymbolMatches::SymbolMatches(const SymbolMatches& toCopy) : frameWinners(toCopy.frameWinners) , progress(toCopy.progress.load()) , symbolSet(toCopy.symbolSet) { } static uint_fast8_t calculateGrayLevelDiff( const FrameSlider& imgPart, const GrayscaleBitmap& glyph) { if (imgPart.size() != glyph.rows * glyph.columns) { throw std::runtime_error("Sizes of image part and symbol glyph do not match"); } size_t pixelCount = imgPart.size(); size_t diffAcc = 0; for (size_t pixelNum = 0; pixelNum < pixelCount; ++pixelNum) { diffAcc += abs(static_cast<int>(imgPart.at(pixelNum)) - glyph.pixels->at(pixelNum)); } return diffAcc / pixelCount; } static FrameWinner chooseMatchingSymbol(const FrameSlider& imgPart, const std::string& symbolSet) { uint_fast8_t minDiff = 0xFF; char bestMatch = symbolSet.front(); symbol_map vocabulary = getVocabulary(); for (char symbol : symbolSet) { uint_fast8_t diff = calculateGrayLevelDiff(imgPart, vocabulary.at(symbol)); if (diff < minDiff) { bestMatch = symbol; minDiff = diff; } } return FrameWinner(bestMatch, minDiff); } #include <iostream> #include <exception> void processVocabularyPart(const FramedBitmap* map, SymbolMatches* matches) { try { const FrameSlider lastFrame = map->lastFrame(); for (FrameSlider frame = map->firstFrame(); frame != lastFrame; frame.slide()) { FrameWinner winner = chooseMatchingSymbol(frame, matches->symbolSet); matches->frameWinners.push_back(winner); ++matches->progress; } FrameWinner winner = chooseMatchingSymbol(lastFrame, matches->symbolSet); matches->frameWinners.push_back(winner); ++matches->progress; } catch (std::exception& err) { std::cerr << err.what() << std::endl; } catch (...) { std::cerr << "Unknown exception caught" << std::endl; } } <|endoftext|>
<commit_before>// Copyright 2015 Google Inc. 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 "components/player.h" #include "btBulletDynamicsCommon.h" #include "component_library/physics.h" #include "component_library/transform.h" #include "components/player_projectile.h" #include "components/rail_denizen.h" #include "components/services.h" #include "entity/entity_common.h" #include "event/event_manager.h" #include "events/parse_action.h" #include "fplbase/flatbuffer_utils.h" #include "fplbase/utilities.h" #include "mathfu/constants.h" #include "mathfu/glsl_mappings.h" #include "world.h" FPL_ENTITY_DEFINE_COMPONENT(fpl::fpl_project::PlayerComponent, fpl::fpl_project::PlayerData) namespace fpl { namespace fpl_project { using fpl::component_library::PhysicsComponent; using fpl::component_library::PhysicsData; using fpl::component_library::TransformComponent; using fpl::component_library::TransformData; static const float kDegreesToRadians = M_PI / 180.0f; void PlayerComponent::Init() { config_ = entity_manager_->GetComponent<ServicesComponent>()->config(); event_manager_ = entity_manager_->GetComponent<ServicesComponent>()->event_manager(); } void PlayerComponent::UpdateAllEntities(entity::WorldTime /*delta_time*/) { for (auto iter = component_data_.begin(); iter != component_data_.end(); ++iter) { PlayerData* player_data = Data<PlayerData>(iter->entity); TransformData* transform_data = Data<TransformData>(iter->entity); if (active_) { player_data->input_controller()->Update(); } transform_data->orientation = mathfu::quat::RotateFromTo(player_data->GetFacing(), mathfu::kAxisY3f); if (player_data->input_controller()->Button(kFireProjectile).Value() && player_data->input_controller()->Button(kFireProjectile).HasChanged()) { SpawnProjectile(iter->entity); EventContext context; context.source = iter->entity; context.raft = entity_manager_->GetComponent<ServicesComponent>()->raft_entity(); ParseAction(player_data->on_fire(), &context, event_manager_, entity_manager_); } } } void PlayerComponent::AddFromRawData(entity::EntityRef& entity, const void* raw_data) { auto player_def = static_cast<const PlayerDef*>(raw_data); PlayerData* player_data = AddEntity(entity); player_data->set_on_fire(player_def->on_fire()); } void PlayerComponent::InitEntity(entity::EntityRef& entity) { entity_manager_->AddEntityToComponent<TransformComponent>(entity); } entity::EntityRef PlayerComponent::SpawnProjectile(entity::EntityRef source) { entity::EntityRef projectile = entity_manager_->GetComponent<ServicesComponent>() ->entity_factory() ->CreateEntityFromPrototype("Projectile", entity_manager_); TransformData* transform_data = Data<TransformData>(projectile); PhysicsData* physics_data = Data<PhysicsData>(projectile); PlayerProjectileData* projectile_data = Data<PlayerProjectileData>(projectile); TransformComponent* transform_component = GetComponent<TransformComponent>(); transform_data->position = transform_component->WorldPosition(source) + LoadVec3(config_->projectile_offset()); transform_data->orientation = transform_component->WorldOrientation(source); vec3 forward = transform_data->orientation.Inverse() * mathfu::kAxisY3f; vec3 velocity = config_->projectile_speed() * forward + config_->projectile_upkick() * mathfu::kAxisZ3f; // Include the raft's current velocity to the thrown sushi. auto raft_entity = entity_manager_->GetComponent<ServicesComponent>()->raft_entity(); auto raft_rail = raft_entity ? Data<RailDenizenData>(raft_entity) : nullptr; if (raft_rail != nullptr) velocity += raft_rail->Velocity(); physics_data->SetVelocity(velocity); physics_data->SetAngularVelocity(vec3(mathfu::RandomInRange(3.0f, 6.0f), mathfu::RandomInRange(3.0f, 6.0f), mathfu::RandomInRange(3.0f, 6.0f))); auto physics_component = entity_manager_->GetComponent<PhysicsComponent>(); physics_component->UpdatePhysicsFromTransform(projectile); projectile_data->owner = source; return entity::EntityRef(); } entity::ComponentInterface::RawDataUniquePtr PlayerComponent::ExportRawData( entity::EntityRef& entity) const { const PlayerData* data = GetComponentData(entity); if (data == nullptr) return nullptr; flatbuffers::FlatBufferBuilder fbb; // TODO: output the on_fire events. PlayerDefBuilder builder(fbb); fbb.Finish(builder.Finish()); return fbb.ReleaseBufferPointer(); } } // fpl_project } // fpl <commit_msg>Removing unused constant in player<commit_after>// Copyright 2015 Google Inc. 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 "components/player.h" #include "btBulletDynamicsCommon.h" #include "component_library/physics.h" #include "component_library/transform.h" #include "components/player_projectile.h" #include "components/rail_denizen.h" #include "components/services.h" #include "entity/entity_common.h" #include "event/event_manager.h" #include "events/parse_action.h" #include "fplbase/flatbuffer_utils.h" #include "fplbase/utilities.h" #include "mathfu/constants.h" #include "mathfu/glsl_mappings.h" #include "world.h" FPL_ENTITY_DEFINE_COMPONENT(fpl::fpl_project::PlayerComponent, fpl::fpl_project::PlayerData) namespace fpl { namespace fpl_project { using fpl::component_library::PhysicsComponent; using fpl::component_library::PhysicsData; using fpl::component_library::TransformComponent; using fpl::component_library::TransformData; void PlayerComponent::Init() { config_ = entity_manager_->GetComponent<ServicesComponent>()->config(); event_manager_ = entity_manager_->GetComponent<ServicesComponent>()->event_manager(); } void PlayerComponent::UpdateAllEntities(entity::WorldTime /*delta_time*/) { for (auto iter = component_data_.begin(); iter != component_data_.end(); ++iter) { PlayerData* player_data = Data<PlayerData>(iter->entity); TransformData* transform_data = Data<TransformData>(iter->entity); if (active_) { player_data->input_controller()->Update(); } transform_data->orientation = mathfu::quat::RotateFromTo(player_data->GetFacing(), mathfu::kAxisY3f); if (player_data->input_controller()->Button(kFireProjectile).Value() && player_data->input_controller()->Button(kFireProjectile).HasChanged()) { SpawnProjectile(iter->entity); EventContext context; context.source = iter->entity; context.raft = entity_manager_->GetComponent<ServicesComponent>()->raft_entity(); ParseAction(player_data->on_fire(), &context, event_manager_, entity_manager_); } } } void PlayerComponent::AddFromRawData(entity::EntityRef& entity, const void* raw_data) { auto player_def = static_cast<const PlayerDef*>(raw_data); PlayerData* player_data = AddEntity(entity); player_data->set_on_fire(player_def->on_fire()); } void PlayerComponent::InitEntity(entity::EntityRef& entity) { entity_manager_->AddEntityToComponent<TransformComponent>(entity); } entity::EntityRef PlayerComponent::SpawnProjectile(entity::EntityRef source) { entity::EntityRef projectile = entity_manager_->GetComponent<ServicesComponent>() ->entity_factory() ->CreateEntityFromPrototype("Projectile", entity_manager_); TransformData* transform_data = Data<TransformData>(projectile); PhysicsData* physics_data = Data<PhysicsData>(projectile); PlayerProjectileData* projectile_data = Data<PlayerProjectileData>(projectile); TransformComponent* transform_component = GetComponent<TransformComponent>(); transform_data->position = transform_component->WorldPosition(source) + LoadVec3(config_->projectile_offset()); transform_data->orientation = transform_component->WorldOrientation(source); vec3 forward = transform_data->orientation.Inverse() * mathfu::kAxisY3f; vec3 velocity = config_->projectile_speed() * forward + config_->projectile_upkick() * mathfu::kAxisZ3f; // Include the raft's current velocity to the thrown sushi. auto raft_entity = entity_manager_->GetComponent<ServicesComponent>()->raft_entity(); auto raft_rail = raft_entity ? Data<RailDenizenData>(raft_entity) : nullptr; if (raft_rail != nullptr) velocity += raft_rail->Velocity(); physics_data->SetVelocity(velocity); physics_data->SetAngularVelocity(vec3(mathfu::RandomInRange(3.0f, 6.0f), mathfu::RandomInRange(3.0f, 6.0f), mathfu::RandomInRange(3.0f, 6.0f))); auto physics_component = entity_manager_->GetComponent<PhysicsComponent>(); physics_component->UpdatePhysicsFromTransform(projectile); projectile_data->owner = source; return entity::EntityRef(); } entity::ComponentInterface::RawDataUniquePtr PlayerComponent::ExportRawData( entity::EntityRef& entity) const { const PlayerData* data = GetComponentData(entity); if (data == nullptr) return nullptr; flatbuffers::FlatBufferBuilder fbb; // TODO: output the on_fire events. PlayerDefBuilder builder(fbb); fbb.Finish(builder.Finish()); return fbb.ReleaseBufferPointer(); } } // fpl_project } // fpl <|endoftext|>
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/ir/conv_elementwise_add_mkldnn_fuse_pass.h" #include <functional> #include "paddle/fluid/framework/ir/graph_traits.h" namespace paddle { namespace framework { namespace ir { namespace { void CorrectGraphEdges(Graph* graph, Node* from, Node* to) { for (auto& node : GraphTraits::DFS(*graph)) { auto from_in_inputs = std::find(std::begin(node.inputs), std::end(node.inputs), from); if (from_in_inputs != std::end(node.inputs)) { IR_NODE_LINK_TO(to, (&node)); auto inputs = node.Op()->Inputs(); using input_type = VariableNameMap::value_type; std::for_each(std::begin(inputs), std::end(inputs), [from, to, &node](const input_type& i) -> void { auto param_names = i.second; auto pi = std::find(std::begin(param_names), std::end(param_names), from->Name()); if (pi != std::end(param_names)) { node.Op()->SetInput(i.first, {to->Name()}); } }); } } } } // namespace using graph_ptr = std::unique_ptr<ir::Graph>; graph_ptr ConvElementwiseAddMKLDNNFusePass::ApplyImpl(graph_ptr graph) const { FusePassBase::Init("conv_elementwise_add_mkldnn_fuse_pass", graph.get()); GraphPatternDetector gpd; auto pattern = gpd.mutable_pattern(); patterns::Conv conv_pattern{pattern, "skip_connections_fusion"}; auto conv_output = conv_pattern(); patterns::ElementwiseAdd elementwise_add_pattern{pattern, "skip_connections_fusion"}; elementwise_add_pattern(conv_output); conv_output->AsIntermediate(); auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* g) { GET_IR_NODE_FROM_SUBGRAPH(conv_op, conv_op, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_input, conv_input, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_bias, conv_bias, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_filter, conv_filter, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_output, conv_output, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_op, elementwise_add_op, elementwise_add_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_x, elementwise_add_x, elementwise_add_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_out, elementwise_add_out, elementwise_add_pattern); OpDesc op_desc; op_desc.SetType("conv2d"); op_desc.SetInput("Input", {conv_input->Name()}); op_desc.SetInput("Bias", {conv_bias->Name()}); op_desc.SetInput("Filter", {conv_filter->Name()}); op_desc.SetInput("ResidualData", {elementwise_add_x->Name()}); op_desc.SetOutput("Output", {conv_output->Name()}); for (const auto& attr : conv_op->Op()->GetAttrMap()) { op_desc.SetAttr(attr.first, attr.second); } op_desc.SetAttr("fuse_residual_connection", true); auto fused_conv_op = g->CreateOpNode(&op_desc); IR_NODE_LINK_TO(conv_input, fused_conv_op); IR_NODE_LINK_TO(conv_bias, fused_conv_op); IR_NODE_LINK_TO(conv_filter, fused_conv_op); IR_NODE_LINK_TO(elementwise_add_x, fused_conv_op); IR_NODE_LINK_TO(fused_conv_op, conv_output); CorrectGraphEdges(g, elementwise_add_out, conv_output); GraphSafeRemoveNodes(g, {elementwise_add_out, conv_op, elementwise_add_op}); }; gpd(graph.get(), handler); return graph; } } // namespace ir } // namespace framework } // namespace paddle REGISTER_PASS(conv_elementwise_add_mkldnn_fuse_pass, paddle::framework::ir::ConvElementwiseAddMKLDNNFusePass); <commit_msg>MKLDNN conv + elementwise_add fusion: comment explaining CorrectGraphEdges added<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/ir/conv_elementwise_add_mkldnn_fuse_pass.h" #include <functional> #include "paddle/fluid/framework/ir/graph_traits.h" namespace paddle { namespace framework { namespace ir { namespace { // The function keeps the graph consistent by replacing // a node 'from' in the set of inputs nodes // of the visited node by a node 'to'. void CorrectGraphEdges(Graph* graph, Node* from, Node* to) { for (auto& node : GraphTraits::DFS(*graph)) { auto from_in_inputs = std::find(std::begin(node.inputs), std::end(node.inputs), from); if (from_in_inputs != std::end(node.inputs)) { IR_NODE_LINK_TO(to, (&node)); auto inputs = node.Op()->Inputs(); using input_type = VariableNameMap::value_type; std::for_each(std::begin(inputs), std::end(inputs), [from, to, &node](const input_type& i) -> void { auto param_names = i.second; auto pi = std::find(std::begin(param_names), std::end(param_names), from->Name()); if (pi != std::end(param_names)) { node.Op()->SetInput(i.first, {to->Name()}); } }); } } } } // namespace using graph_ptr = std::unique_ptr<ir::Graph>; graph_ptr ConvElementwiseAddMKLDNNFusePass::ApplyImpl(graph_ptr graph) const { FusePassBase::Init("conv_elementwise_add_mkldnn_fuse_pass", graph.get()); GraphPatternDetector gpd; auto pattern = gpd.mutable_pattern(); patterns::Conv conv_pattern{pattern, "skip_connections_fusion"}; auto conv_output = conv_pattern(); patterns::ElementwiseAdd elementwise_add_pattern{pattern, "skip_connections_fusion"}; elementwise_add_pattern(conv_output); conv_output->AsIntermediate(); auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* g) { GET_IR_NODE_FROM_SUBGRAPH(conv_op, conv_op, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_input, conv_input, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_bias, conv_bias, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_filter, conv_filter, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(conv_output, conv_output, conv_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_op, elementwise_add_op, elementwise_add_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_x, elementwise_add_x, elementwise_add_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_out, elementwise_add_out, elementwise_add_pattern); OpDesc op_desc; op_desc.SetType("conv2d"); op_desc.SetInput("Input", {conv_input->Name()}); op_desc.SetInput("Bias", {conv_bias->Name()}); op_desc.SetInput("Filter", {conv_filter->Name()}); op_desc.SetInput("ResidualData", {elementwise_add_x->Name()}); op_desc.SetOutput("Output", {conv_output->Name()}); for (const auto& attr : conv_op->Op()->GetAttrMap()) { op_desc.SetAttr(attr.first, attr.second); } op_desc.SetAttr("fuse_residual_connection", true); auto fused_conv_op = g->CreateOpNode(&op_desc); IR_NODE_LINK_TO(conv_input, fused_conv_op); IR_NODE_LINK_TO(conv_bias, fused_conv_op); IR_NODE_LINK_TO(conv_filter, fused_conv_op); IR_NODE_LINK_TO(elementwise_add_x, fused_conv_op); IR_NODE_LINK_TO(fused_conv_op, conv_output); CorrectGraphEdges(g, elementwise_add_out, conv_output); GraphSafeRemoveNodes(g, {elementwise_add_out, conv_op, elementwise_add_op}); }; gpd(graph.get(), handler); return graph; } } // namespace ir } // namespace framework } // namespace paddle REGISTER_PASS(conv_elementwise_add_mkldnn_fuse_pass, paddle::framework::ir::ConvElementwiseAddMKLDNNFusePass); <|endoftext|>
<commit_before>// Catch #include <catch.hpp> // C++ Standard Library #include <memory> #include <iostream> // Boost #include <boost/filesystem.hpp> // Armadillo #include <armadillo> // HOP #include <hop> extern boost::filesystem::path testDirectory; static std::string dataPath_ = "/data/optimisationAlgorithm/trajectoryBasedAlgrorithm/hillClimbing/"; class TestHillClimbing : public hop::HillClimbing { public: TestHillClimbing( const std::shared_ptr<hop::OptimisationProblem> optimisationProblem) : HillClimbing(optimisationProblem), velocityIndex_(0){ } arma::Col<double> getVelocity() { return velocities_.col(velocityIndex_++); } void setVelocitys(arma::mat velocities){ velocities_ = velocities; } protected: unsigned int velocityIndex_; arma::mat velocities_; }; class TestHillClimbingProblem : public hop::OptimisationProblem { public: TestHillClimbingProblem( const unsigned int numberOfDimensions) : OptimisationProblem(numberOfDimensions), ValueIndex_(0) { } std::vector<arma::Col<double>> getParameterHistory() const noexcept { return parameterHistory_; } void setObjectiveValues(arma::Col<double> objectiveValues){ objectiveValues_ = objectiveValues; } void setSoftConstraintsValues(arma::Col<double> softConstraintsValues){ softConstraintsValues_ = softConstraintsValues; } protected: unsigned int ValueIndex_; arma::Col<double> objectiveValues_; arma::Col<double> softConstraintsValues_; static std::vector<arma::Col<double>> parameterHistory_; double getObjectiveValueImplementation( const arma::Col<double>& parameter) const override { parameterHistory_.push_back(parameter); return objectiveValues_.at(ValueIndex_); } double getSoftConstraintsValueImplementation( const arma::Col<double>& parameter) const override { return softConstraintsValues_.at(ValueIndex_); } std::string to_string() const noexcept { return "TestHillClimbing"; } }; decltype(TestHillClimbingProblem::parameterHistory_) TestHillClimbingProblem::parameterHistory_; TEST_CASE("Hill climbing", "") { // Set OptimisationProblem values arma::Col<double> upperBounds; upperBounds.load(testDirectory.string() + dataPath_ + "upperBounds.mat"); //the parametre is optional arma::Col<double> lowerBounds; lowerBounds.load(testDirectory.string() + dataPath_ + "lowerBounds.mat"); //the parametre is optional arma::Col<double> objectiveValues; objectiveValues.load(testDirectory.string() + dataPath_ + "objectiveValues[2.0].mat"); arma::Col<double> softConstraintsValues; softConstraintsValues.load(testDirectory.string() + dataPath_ + "softConstraintsValues[2.0].mat"); // Init OptimisationProblem std::shared_ptr<TestHillClimbingProblem> testHillClimbingProblem(new TestHillClimbingProblem(upperBounds.n_elem)); testHillClimbingProblem->setUpperBounds(upperBounds); testHillClimbingProblem->setLowerBounds(lowerBounds); testHillClimbingProblem->setObjectiveValues(objectiveValues); testHillClimbingProblem->setSoftConstraintsValues(softConstraintsValues); // Set OptimisationAlgorithm values arma::mat velocities; velocities.load(testDirectory.string() + dataPath_ + "velocities[2.0].mat"); arma::Col<double> initialParameter; initialParameter.load(testDirectory.string() + dataPath_ + "initialParameter[null].mat"); //the parametre is optional arma::Col<double> maximalStepSize; maximalStepSize.load(testDirectory.string() + dataPath_ + "maximalStepSize[2.1].mat"); //the parametre is optional // Init OptimisationAlgorithm TestHillClimbing testHillClimbing(testHillClimbingProblem); testHillClimbing.setVelocitys(velocities); testHillClimbing.setInitialParameter(initialParameter); testHillClimbing.setMaximalStepSize(maximalStepSize); // Set Expected values arma::Mat<double> expectedParameterHistory; expectedParameterHistory.load(testDirectory.string() + dataPath_ + "expected[2.1].mat"); // Run hill climbing algorithm testHillClimbing.optimise(); // Comparing of candidateParameters std::vector<arma::Col<double>> actualParameterHistory = testHillClimbingProblem->getParameterHistory(); for(std::size_t n = 0; n < expectedParameterHistory.n_cols; ++n) { arma::Col<double> expectedParameter = expectedParameterHistory.col(n); arma::Col<double> actualParameter = actualParameterHistory.at(n); for (std::size_t k = 0; k < expectedParameter.n_elem; ++k) { CHECK(actualParameter.at(k) == Approx(expectedParameter.at(k))); } } } TEST_CASE("Hill climbing (init Test)", "") { // Set OptimisationProblem values arma::Col<double> upperBounds; upperBounds.load(testDirectory.string() + dataPath_ + "upperBounds.mat"); //the parametre is optional arma::Col<double> lowerBounds; lowerBounds.load(testDirectory.string() + dataPath_ + "lowerBounds.mat"); //the parametre is optional arma::Col<double> objectiveValues; objectiveValues.load(testDirectory.string() + dataPath_ + "objectiveValues[1.0].mat"); arma::Col<double> softConstraintsValues; softConstraintsValues.load(testDirectory.string() + dataPath_ + "softConstraintsValues[1.0].mat"); // Init OptimisationProblem std::shared_ptr<TestHillClimbingProblem> testHillClimbingProblem(new TestHillClimbingProblem(upperBounds.n_elem)); testHillClimbingProblem->setUpperBounds(upperBounds); testHillClimbingProblem->setLowerBounds(lowerBounds); testHillClimbingProblem->setObjectiveValues(objectiveValues); testHillClimbingProblem->setSoftConstraintsValues(softConstraintsValues); // Set OptimisationAlgorithm values arma::mat velocities; velocities.load(testDirectory.string() + dataPath_ + "velocities[1.0].mat"); // Init OptimisationAlgorithm TestHillClimbing testHillClimbing(testHillClimbingProblem); testHillClimbing.setVelocitys(velocities); arma::Mat<double> expectedParameterHistory; SECTION("Check MaximalStepSize"){ arma::Col<double> initialParameter; initialParameter.load(testDirectory.string() + dataPath_ + "initialParameter[null].mat"); //the parametre is optional //arma::Col<double> maximalStepSize; //maximalStepSize.load(testDirectory.string() + dataPath_ + "maximalStepSize[1.1].mat"); //the parametre is optional expectedParameterHistory.load(testDirectory.string() + dataPath_ + "expected[1.1].mat"); testHillClimbing.setInitialParameter(initialParameter); //testHillClimbing.setMaximalStepSize(maximalStepSize); testHillClimbing.optimise(); // Comparing of candidateParameters std::vector<arma::Col<double>> actualParameterHistory = testHillClimbingProblem->getParameterHistory(); for(std::size_t n = 0; n < expectedParameterHistory.n_cols; ++n) { arma::Col<double> expectedParameter = expectedParameterHistory.col(n); arma::Col<double> actualParameter = actualParameterHistory.at(n); for (std::size_t k = 0; k < expectedParameter.n_elem; ++k) { CHECK(actualParameter.at(k) == Approx(expectedParameter.at(k))); } } } } <commit_msg>test: Added test for HillClimbing<commit_after>// Catch #include <catch.hpp> // C++ Standard Library #include <memory> #include <iostream> // Boost #include <boost/filesystem.hpp> // Armadillo #include <armadillo> // HOP #include <hop> extern boost::filesystem::path testDirectory; static std::string dataPath_ = "/data/optimisationAlgorithm/trajectoryBasedAlgrorithm/hillClimbing/"; class TestHillClimbing : public hop::HillClimbing { public: TestHillClimbing( const std::shared_ptr<hop::OptimisationProblem> optimisationProblem) : HillClimbing(optimisationProblem), velocityIndex_(0){ } arma::Col<double> getVelocity() override { return velocities_.col(velocityIndex_++); } void setVelocitys(arma::mat velocities){ velocities_ = velocities; } protected: unsigned int velocityIndex_; arma::mat velocities_; }; class TestHillClimbingProblem : public hop::OptimisationProblem { public: TestHillClimbingProblem( const unsigned int numberOfDimensions) : OptimisationProblem(numberOfDimensions) { softConstraintsValuesIndex_ = 0; objectiveValuesIndex_ = 0; } std::vector<arma::Col<double>> getParameterHistory() const noexcept { return parameterHistory_; } void setObjectiveValues(arma::Col<double> objectiveValues){ objectiveValues_ = objectiveValues; } void setSoftConstraintsValues(arma::Col<double> softConstraintsValues){ softConstraintsValues_ = softConstraintsValues; } protected: static unsigned int softConstraintsValuesIndex_; static unsigned int objectiveValuesIndex_; arma::Col<double> objectiveValues_; arma::Col<double> softConstraintsValues_; static std::vector<arma::Col<double>> parameterHistory_; double getSoftConstraintsValueImplementation( const arma::Col<double>& parameter) const override { return softConstraintsValues_.at(softConstraintsValuesIndex_++); } double getObjectiveValueImplementation( const arma::Col<double>& parameter) const override { parameterHistory_.push_back(parameter); return objectiveValues_.at(objectiveValuesIndex_++); } std::string to_string() const noexcept { return "TestHillClimbing"; } }; decltype(TestHillClimbingProblem::parameterHistory_) TestHillClimbingProblem::parameterHistory_; decltype(TestHillClimbingProblem::softConstraintsValuesIndex_) TestHillClimbingProblem::softConstraintsValuesIndex_; decltype(TestHillClimbingProblem::objectiveValuesIndex_) TestHillClimbingProblem::objectiveValuesIndex_; TEST_CASE("Hill climbing", "") { // Set OptimisationProblem values arma::Col<double> upperBounds; upperBounds.load(testDirectory.string() + dataPath_ + "upperBounds.mat"); //the parametre is optional arma::Col<double> lowerBounds; lowerBounds.load(testDirectory.string() + dataPath_ + "lowerBounds.mat"); //the parametre is optional arma::Col<double> objectiveValues; objectiveValues.load(testDirectory.string() + dataPath_ + "objectiveValues[2.0].mat"); arma::Col<double> softConstraintsValues; softConstraintsValues.load(testDirectory.string() + dataPath_ + "softConstraintsValues[2.0].mat"); // Init OptimisationProblem std::shared_ptr<TestHillClimbingProblem> testHillClimbingProblem(new TestHillClimbingProblem(upperBounds.n_elem)); testHillClimbingProblem->setUpperBounds(upperBounds); testHillClimbingProblem->setLowerBounds(lowerBounds); testHillClimbingProblem->setObjectiveValues(objectiveValues); testHillClimbingProblem->setSoftConstraintsValues(softConstraintsValues); // Set OptimisationAlgorithm values arma::mat velocities; velocities.load(testDirectory.string() + dataPath_ + "velocities[2.0].mat"); arma::Col<double> initialParameter; initialParameter.load(testDirectory.string() + dataPath_ + "initialParameter[null].mat"); //the parametre is optional arma::Col<double> maximalStepSize; maximalStepSize.load(testDirectory.string() + dataPath_ + "maximalStepSize[2.1].mat"); //the parametre is optional // Init OptimisationAlgorithm TestHillClimbing testHillClimbing(testHillClimbingProblem); testHillClimbing.setVelocitys(velocities); testHillClimbing.setInitialParameter(initialParameter); testHillClimbing.setMaximalStepSize(maximalStepSize); // Set Expected values arma::Mat<double> expectedParameterHistory; expectedParameterHistory.load(testDirectory.string() + dataPath_ + "expected[2.1].mat"); // Run hill climbing algorithm testHillClimbing.optimise(); // Comparing of candidateParameters std::vector<arma::Col<double>> actualParameterHistory = testHillClimbingProblem->getParameterHistory(); for(std::size_t n = 0; n < expectedParameterHistory.n_cols; ++n) { arma::Col<double> expectedParameter = expectedParameterHistory.col(n); arma::Col<double> actualParameter = actualParameterHistory.at(n); for (std::size_t k = 0; k < expectedParameter.n_elem; ++k) { CHECK(actualParameter.at(k) == Approx(expectedParameter.at(k))); } } } TEST_CASE("Hill climbing (init Test)", "") { // Set OptimisationProblem values arma::Col<double> upperBounds; upperBounds.load(testDirectory.string() + dataPath_ + "upperBounds.mat"); //the parametre is optional arma::Col<double> lowerBounds; lowerBounds.load(testDirectory.string() + dataPath_ + "lowerBounds.mat"); //the parametre is optional arma::Col<double> objectiveValues; objectiveValues.load(testDirectory.string() + dataPath_ + "objectiveValues[1.0].mat"); arma::Col<double> softConstraintsValues; softConstraintsValues.load(testDirectory.string() + dataPath_ + "softConstraintsValues[1.0].mat"); // Init OptimisationProblem std::shared_ptr<TestHillClimbingProblem> testHillClimbingProblem(new TestHillClimbingProblem(upperBounds.n_elem)); testHillClimbingProblem->setUpperBounds(upperBounds); testHillClimbingProblem->setLowerBounds(lowerBounds); testHillClimbingProblem->setObjectiveValues(objectiveValues); testHillClimbingProblem->setSoftConstraintsValues(softConstraintsValues); // Set OptimisationAlgorithm values arma::mat velocities; velocities.load(testDirectory.string() + dataPath_ + "velocities[1.0].mat"); // Init OptimisationAlgorithm TestHillClimbing testHillClimbing(testHillClimbingProblem); testHillClimbing.setVelocitys(velocities); arma::Mat<double> expectedParameterHistory; SECTION("Check MaximalStepSize"){ arma::Col<double> initialParameter; initialParameter.load(testDirectory.string() + dataPath_ + "initialParameter[null].mat"); //the parametre is optional //arma::Col<double> maximalStepSize; //maximalStepSize.load(testDirectory.string() + dataPath_ + "maximalStepSize[1.1].mat"); //the parametre is optional expectedParameterHistory.load(testDirectory.string() + dataPath_ + "expected[1.1].mat"); testHillClimbing.setInitialParameter(initialParameter); //testHillClimbing.setMaximalStepSize(maximalStepSize); testHillClimbing.optimise(); // Comparing of candidateParameters std::vector<arma::Col<double>> actualParameterHistory = testHillClimbingProblem->getParameterHistory(); for(std::size_t n = 0; n < expectedParameterHistory.n_cols; ++n) { arma::Col<double> expectedParameter = expectedParameterHistory.col(n); arma::Col<double> actualParameter = actualParameterHistory.at(n); for (std::size_t k = 0; k < expectedParameter.n_elem; ++k) { CHECK(actualParameter.at(k) == Approx(expectedParameter.at(k))); } } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtQml/qqmlengine.h> #include <QtQml/qqmlcomponent.h> #include <QtQuick/private/qquicksmoothedanimation_p.h> #include <QtQuick/private/qquickrectangle_p.h> #include <private/qqmlvaluetype_p.h> #include "../../shared/util.h" class tst_qquicksmoothedanimation : public QQmlDataTest { Q_OBJECT public: tst_qquicksmoothedanimation(); private slots: void defaultValues(); void values(); void disabled(); void simpleAnimation(); void valueSource(); void behavior(); void deleteOnUpdate(); void zeroDuration(); private: QQmlEngine engine; }; tst_qquicksmoothedanimation::tst_qquicksmoothedanimation() { } void tst_qquicksmoothedanimation::defaultValues() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimation1.qml")); QQuickSmoothedAnimation *obj = qobject_cast<QQuickSmoothedAnimation*>(c.create()); QVERIFY(obj != 0); QCOMPARE(obj->to(), 0.); QCOMPARE(obj->velocity(), 200.); QCOMPARE(obj->duration(), -1); QCOMPARE(obj->maximumEasingTime(), -1); QCOMPARE(obj->reversingMode(), QQuickSmoothedAnimation::Eased); delete obj; } void tst_qquicksmoothedanimation::values() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimation2.qml")); QQuickSmoothedAnimation *obj = qobject_cast<QQuickSmoothedAnimation*>(c.create()); QVERIFY(obj != 0); QCOMPARE(obj->to(), 10.); QCOMPARE(obj->velocity(), 200.); QCOMPARE(obj->duration(), 300); QCOMPARE(obj->maximumEasingTime(), -1); QCOMPARE(obj->reversingMode(), QQuickSmoothedAnimation::Immediate); delete obj; } void tst_qquicksmoothedanimation::disabled() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimation3.qml")); QQuickSmoothedAnimation *obj = qobject_cast<QQuickSmoothedAnimation*>(c.create()); QVERIFY(obj != 0); QCOMPARE(obj->to(), 10.); QCOMPARE(obj->velocity(), 250.); QCOMPARE(obj->maximumEasingTime(), 150); QCOMPARE(obj->reversingMode(), QQuickSmoothedAnimation::Sync); delete obj; } void tst_qquicksmoothedanimation::simpleAnimation() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("simpleanimation.qml")); QObject *obj = c.create(); QVERIFY(obj); QQuickRectangle *rect = obj->findChild<QQuickRectangle*>("rect"); QVERIFY(rect); QQuickSmoothedAnimation *animation = obj->findChild<QQuickSmoothedAnimation*>("anim"); QVERIFY(animation); animation->setTargetObject(rect); animation->setProperty("x"); animation->setTo(200); animation->setDuration(250); QVERIFY(animation->target() == rect); QVERIFY(animation->property() == "x"); QVERIFY(animation->to() == 200); animation->start(); QVERIFY(animation->isRunning()); QTest::qWait(animation->duration()); QTRY_COMPARE(rect->x(), qreal(200)); QTest::qWait(100); //smoothed animation doesn't report stopped until delayed timer fires QVERIFY(!animation->isRunning()); rect->setX(0); animation->start(); QVERIFY(animation->isRunning()); animation->pause(); QVERIFY(animation->isRunning()); QVERIFY(animation->isPaused()); animation->setCurrentTime(125); QVERIFY(animation->currentTime() == 125); QCOMPARE(rect->x(), qreal(100)); } void tst_qquicksmoothedanimation::valueSource() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimationValueSource.qml")); QQuickRectangle *rect = qobject_cast<QQuickRectangle*>(c.create()); QVERIFY(rect); QQuickRectangle *theRect = rect->findChild<QQuickRectangle*>("theRect"); QVERIFY(theRect); QQuickSmoothedAnimation *easeX = rect->findChild<QQuickSmoothedAnimation*>("easeX"); QVERIFY(easeX); QVERIFY(easeX->isRunning()); QQuickSmoothedAnimation *easeY = rect->findChild<QQuickSmoothedAnimation*>("easeY"); QVERIFY(easeY); QVERIFY(easeY->isRunning()); // XXX get the proper duration QTest::qWait(100); QTRY_VERIFY(!easeX->isRunning()); QTRY_VERIFY(!easeY->isRunning()); QTRY_COMPARE(theRect->x(), qreal(200)); QTRY_COMPARE(theRect->y(), qreal(200)); delete rect; } void tst_qquicksmoothedanimation::behavior() { #ifdef Q_CC_MINGW QSKIP("QTBUG-36290 - MinGW Animation tests are flaky."); #endif QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimationBehavior.qml")); QQuickRectangle *rect = qobject_cast<QQuickRectangle*>(c.create()); QVERIFY(rect); QQuickRectangle *theRect = rect->findChild<QQuickRectangle*>("theRect"); QVERIFY(theRect); QQuickSmoothedAnimation *easeX = rect->findChild<QQuickSmoothedAnimation*>("easeX"); QVERIFY(easeX); QQuickSmoothedAnimation *easeY = rect->findChild<QQuickSmoothedAnimation*>("easeY"); QVERIFY(easeY); // XXX get the proper duration QTest::qWait(400); QTRY_VERIFY(!easeX->isRunning()); QTRY_VERIFY(!easeY->isRunning()); QTRY_COMPARE(theRect->x(), qreal(200)); QTRY_COMPARE(theRect->y(), qreal(200)); delete rect; } void tst_qquicksmoothedanimation::deleteOnUpdate() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("deleteOnUpdate.qml")); QQuickRectangle *rect = qobject_cast<QQuickRectangle*>(c.create()); QVERIFY(rect); QQuickSmoothedAnimation *anim = rect->findChild<QQuickSmoothedAnimation*>("anim"); QVERIFY(anim); //don't crash QTest::qWait(500); delete rect; } void tst_qquicksmoothedanimation::zeroDuration() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimationZeroDuration.qml")); QQuickRectangle *rect = qobject_cast<QQuickRectangle*>(c.create()); QVERIFY(rect); QQuickRectangle *theRect = rect->findChild<QQuickRectangle*>("theRect"); QVERIFY(theRect); QQuickSmoothedAnimation *easeX = rect->findChild<QQuickSmoothedAnimation*>("easeX"); QVERIFY(easeX); QVERIFY(easeX->isRunning()); QTRY_VERIFY(!easeX->isRunning()); QTRY_COMPARE(theRect->x(), qreal(200)); delete rect; } QTEST_MAIN(tst_qquicksmoothedanimation) #include "tst_qquicksmoothedanimation.moc" <commit_msg>Verify empty SmoothedAnimation doesn't keep animation system running.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtQml/qqmlengine.h> #include <QtQml/qqmlcomponent.h> #include <QtQuick/private/qquicksmoothedanimation_p.h> #include <QtQuick/private/qquickrectangle_p.h> #include <private/qqmlvaluetype_p.h> #include "../../shared/util.h" class tst_qquicksmoothedanimation : public QQmlDataTest { Q_OBJECT public: tst_qquicksmoothedanimation(); private slots: void defaultValues(); void values(); void disabled(); void simpleAnimation(); void valueSource(); void behavior(); void deleteOnUpdate(); void zeroDuration(); void noStart(); private: QQmlEngine engine; }; tst_qquicksmoothedanimation::tst_qquicksmoothedanimation() { } void tst_qquicksmoothedanimation::defaultValues() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimation1.qml")); QQuickSmoothedAnimation *obj = qobject_cast<QQuickSmoothedAnimation*>(c.create()); QVERIFY(obj != 0); QCOMPARE(obj->to(), 0.); QCOMPARE(obj->velocity(), 200.); QCOMPARE(obj->duration(), -1); QCOMPARE(obj->maximumEasingTime(), -1); QCOMPARE(obj->reversingMode(), QQuickSmoothedAnimation::Eased); delete obj; } void tst_qquicksmoothedanimation::values() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimation2.qml")); QQuickSmoothedAnimation *obj = qobject_cast<QQuickSmoothedAnimation*>(c.create()); QVERIFY(obj != 0); QCOMPARE(obj->to(), 10.); QCOMPARE(obj->velocity(), 200.); QCOMPARE(obj->duration(), 300); QCOMPARE(obj->maximumEasingTime(), -1); QCOMPARE(obj->reversingMode(), QQuickSmoothedAnimation::Immediate); delete obj; } void tst_qquicksmoothedanimation::disabled() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimation3.qml")); QQuickSmoothedAnimation *obj = qobject_cast<QQuickSmoothedAnimation*>(c.create()); QVERIFY(obj != 0); QCOMPARE(obj->to(), 10.); QCOMPARE(obj->velocity(), 250.); QCOMPARE(obj->maximumEasingTime(), 150); QCOMPARE(obj->reversingMode(), QQuickSmoothedAnimation::Sync); delete obj; } void tst_qquicksmoothedanimation::simpleAnimation() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("simpleanimation.qml")); QObject *obj = c.create(); QVERIFY(obj); QQuickRectangle *rect = obj->findChild<QQuickRectangle*>("rect"); QVERIFY(rect); QQuickSmoothedAnimation *animation = obj->findChild<QQuickSmoothedAnimation*>("anim"); QVERIFY(animation); animation->setTargetObject(rect); animation->setProperty("x"); animation->setTo(200); animation->setDuration(250); QVERIFY(animation->target() == rect); QVERIFY(animation->property() == "x"); QVERIFY(animation->to() == 200); animation->start(); QVERIFY(animation->isRunning()); QTest::qWait(animation->duration()); QTRY_COMPARE(rect->x(), qreal(200)); QTest::qWait(100); //smoothed animation doesn't report stopped until delayed timer fires QVERIFY(!animation->isRunning()); rect->setX(0); animation->start(); QVERIFY(animation->isRunning()); animation->pause(); QVERIFY(animation->isRunning()); QVERIFY(animation->isPaused()); animation->setCurrentTime(125); QVERIFY(animation->currentTime() == 125); QCOMPARE(rect->x(), qreal(100)); } void tst_qquicksmoothedanimation::valueSource() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimationValueSource.qml")); QQuickRectangle *rect = qobject_cast<QQuickRectangle*>(c.create()); QVERIFY(rect); QQuickRectangle *theRect = rect->findChild<QQuickRectangle*>("theRect"); QVERIFY(theRect); QQuickSmoothedAnimation *easeX = rect->findChild<QQuickSmoothedAnimation*>("easeX"); QVERIFY(easeX); QVERIFY(easeX->isRunning()); QQuickSmoothedAnimation *easeY = rect->findChild<QQuickSmoothedAnimation*>("easeY"); QVERIFY(easeY); QVERIFY(easeY->isRunning()); // XXX get the proper duration QTest::qWait(100); QTRY_VERIFY(!easeX->isRunning()); QTRY_VERIFY(!easeY->isRunning()); QTRY_COMPARE(theRect->x(), qreal(200)); QTRY_COMPARE(theRect->y(), qreal(200)); delete rect; } void tst_qquicksmoothedanimation::behavior() { #ifdef Q_CC_MINGW QSKIP("QTBUG-36290 - MinGW Animation tests are flaky."); #endif QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimationBehavior.qml")); QQuickRectangle *rect = qobject_cast<QQuickRectangle*>(c.create()); QVERIFY(rect); QQuickRectangle *theRect = rect->findChild<QQuickRectangle*>("theRect"); QVERIFY(theRect); QQuickSmoothedAnimation *easeX = rect->findChild<QQuickSmoothedAnimation*>("easeX"); QVERIFY(easeX); QQuickSmoothedAnimation *easeY = rect->findChild<QQuickSmoothedAnimation*>("easeY"); QVERIFY(easeY); // XXX get the proper duration QTest::qWait(400); QTRY_VERIFY(!easeX->isRunning()); QTRY_VERIFY(!easeY->isRunning()); QTRY_COMPARE(theRect->x(), qreal(200)); QTRY_COMPARE(theRect->y(), qreal(200)); delete rect; } void tst_qquicksmoothedanimation::deleteOnUpdate() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("deleteOnUpdate.qml")); QQuickRectangle *rect = qobject_cast<QQuickRectangle*>(c.create()); QVERIFY(rect); QQuickSmoothedAnimation *anim = rect->findChild<QQuickSmoothedAnimation*>("anim"); QVERIFY(anim); //don't crash QTest::qWait(500); delete rect; } void tst_qquicksmoothedanimation::zeroDuration() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimationZeroDuration.qml")); QQuickRectangle *rect = qobject_cast<QQuickRectangle*>(c.create()); QVERIFY(rect); QQuickRectangle *theRect = rect->findChild<QQuickRectangle*>("theRect"); QVERIFY(theRect); QQuickSmoothedAnimation *easeX = rect->findChild<QQuickSmoothedAnimation*>("easeX"); QVERIFY(easeX); QVERIFY(easeX->isRunning()); QTRY_VERIFY(!easeX->isRunning()); QTRY_COMPARE(theRect->x(), qreal(200)); delete rect; } //verify that an empty SmoothedAnimation does not fire up the animation system //and keep it running forever void tst_qquicksmoothedanimation::noStart() { QQmlEngine engine; QQmlComponent c(&engine, testFileUrl("smoothedanimation1.qml")); QQuickSmoothedAnimation *obj = qobject_cast<QQuickSmoothedAnimation*>(c.create()); QVERIFY(obj != 0); obj->start(); QCOMPARE(obj->isRunning(), false); QTest::qWait(100); QCOMPARE(obj->isRunning(), false); //this could fail if the test is being run in parallel with other tests //or if an earlier test failed and didn't clean up (left an animation running) //QCOMPARE(QUnifiedTimer::instance()->runningAnimationCount(), 0); delete obj; } QTEST_MAIN(tst_qquicksmoothedanimation) #include "tst_qquicksmoothedanimation.moc" <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "debug.h" #include "condor_daemon_core.h" debug_level_t debug_level = DEBUG_NORMAL; const char * debug_progname = NULL; /*--------------------------------------------------------------------------*/ void debug_printf( debug_level_t level, char *fmt, ... ) { if( DEBUG_LEVEL( level ) ) { va_list args; va_start( args, fmt ); _condor_dprintf_va( D_ALWAYS, fmt, args ); va_end( args ); } } /*--------------------------------------------------------------------------*/ void debug_dprintf( int flags, debug_level_t level, char *fmt, ... ) { if( DEBUG_LEVEL( level ) ) { va_list args; va_start( args, fmt ); _condor_dprintf_va( flags, fmt, args ); va_end( args ); } } /*--------------------------------------------------------------------------*/ void debug_error( int error, debug_level_t level, char *fmt, ... ) { if( DEBUG_LEVEL( level ) ) { va_list args; va_start( args, fmt ); _condor_dprintf_va( D_ALWAYS, fmt, args ); va_end( args ); } DC_Exit( error ); } <commit_msg>Partial implementation of open/close caching layer.<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "debug.h" #include "condor_daemon_core.h" #include "MyString.h" #define DEFAULT_CACHE_SIZE ((1024 * 1024) * 5) debug_level_t debug_level = DEBUG_NORMAL; const char * debug_progname = NULL; // sometimes we want to keep a cache for our log message when DAGMan is // emitting thousands of them quickly and we could be writing the log to // and NFS server. static bool cache_enabled = false; static MyString cache; static unsigned int cache_size = DEFAULT_CACHE_SIZE; void debug_cache_disable(void); void debug_cache_enable(void); void debug_cache_flush(void); void debug_cache_insert(int flags, const char *fmt, va_list args); /*--------------------------------------------------------------------------*/ void debug_printf( debug_level_t level, char *fmt, ... ) { if( DEBUG_LEVEL( level ) ) { if (cache_enabled == false) { va_list args; va_start( args, fmt ); _condor_dprintf_va( D_ALWAYS, fmt, args ); va_end( args ); } else { va_list args; va_start( args, fmt ); debug_cache_insert( D_ALWAYS, fmt, args ); va_end( args ); } } } /*--------------------------------------------------------------------------*/ void debug_dprintf( int flags, debug_level_t level, char *fmt, ... ) { if( DEBUG_LEVEL( level ) ) { if (cache_enabled == false) { va_list args; va_start( args, fmt ); _condor_dprintf_va( flags, fmt, args ); va_end( args ); } else { } } } /*--------------------------------------------------------------------------*/ void debug_error( int error, debug_level_t level, char *fmt, ... ) { // make sure these come out before emitting the error debug_cache_flush(); debug_cache_disable(); if( DEBUG_LEVEL( level ) ) { va_list args; va_start( args, fmt ); _condor_dprintf_va( D_ALWAYS, fmt, args ); va_end( args ); } DC_Exit( error ); } /*--------------------------------------------------------------------------*/ void debug_cache_enable(void) { cache_enabled = true; } /*--------------------------------------------------------------------------*/ void debug_cache_disable(void) { debug_cache_flush(); cache_enabled = false; } /*--------------------------------------------------------------------------*/ void debug_cache_insert(int flags, const char *fmt, va_list args) { // from condor_util_lib/dprintf.c extern int DebugUseTimestamps; /* create the header */ // XXX TODO // Make the header, add it first to the string, then cache.vsnprintf the // args and crap into itself. // if the cache has surpassed the highwater mark, then flush it. if (cache.Length() > cache_size) { debug_cache_flush(); } } /*--------------------------------------------------------------------------*/ void debug_cache_flush(void) { // This emits ONE dprintf call which could write out up to the maximum // size of the cache. The lines in the cache are newline delimited. if (cache != "") { dprintf(D_ALWAYS, "%s", cache.Value()); cache = ""; } } <|endoftext|>
<commit_before>/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* * ibun - bundle files operation */ #include "irods_client_api_table.hpp" #include "irods_pack_table.hpp" #include "rodsClient.hpp" #include "parseCommandLine.hpp" #include "rodsPath.hpp" #include "bunUtil.hpp" void usage(); int main( int argc, char **argv ) { int status; rodsEnv myEnv; rErrMsg_t errMsg; rcComm_t *conn; rodsArguments_t myRodsArgs; char *optStr; rodsPathInp_t rodsPathInp; int nArgv; optStr = "bhR:cxD:fZ"; // JMC - backport 4643 status = parseCmdLineOpt( argc, argv, optStr, 1, &myRodsArgs ); // JMC - backport 4643 if ( status < 0 ) { printf( "use -h for help.\n" ); exit( 1 ); } if ( myRodsArgs.help == True ) { usage(); exit( 0 ); } nArgv = argc - optind; if ( nArgv != 2 ) { /* must have 2 inputs */ usage(); exit( 1 ); } status = getRodsEnv( &myEnv ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " ); exit( 1 ); } status = parseCmdLinePath( argc, argv, optind, &myEnv, UNKNOWN_OBJ_T, UNKNOWN_OBJ_T, 0, &rodsPathInp ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "main: parseCmdLinePath error. " ); printf( "use -h for help.\n" ); exit( 1 ); } // =-=-=-=-=-=-=- // initialize pluggable api table irods::api_entry_table& api_tbl = irods::get_client_api_table(); irods::pack_entry_table& pk_tbl = irods::get_pack_table(); init_api_table( api_tbl, pk_tbl ); conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName, myEnv.rodsZone, 1, &errMsg ); if ( conn == NULL ) { exit( 2 ); } status = clientLogin( conn ); if ( status != 0 ) { rcDisconnect( conn ); exit( 7 ); } status = bunUtil( conn, &myEnv, &myRodsArgs, &rodsPathInp ); printErrorStack( conn->rError ); rcDisconnect( conn ); if ( status < 0 ) { exit( 3 ); } else { exit( 0 ); } } void usage() { char *msgs[] = { "Usage : ibun -x [-hfb] [-R resource] structFilePath", " irodsCollection", "Usage : ibun -c [-hf] [-R resource] [-D dataType] structFilePath", " irodsCollection", "Usage : ibun --add [-h] structFilePath irodsCollection", " ", "Bundle file operations. This command allows structured files such as ", "tar files to be uploaded and downloaded to/from iRODS.", " ", "A tar file containing many small files can be created with normal unix", "tar command on the client and then uploaded to the iRODS server as a", "normal iRODS file. The 'ibun -x' command can then be used to extract/untar", "the uploaded tar file. The extracted subfiles and subdirectories will", "appeared as normal iRODS files and sub-collections. The 'ibun -c' command", "can be used to tar/bundle an iRODS collection into a tar file.", " ", "For example, to upload a directory mydir to iRODS:", " ", " tar -chlf mydir.tar -C /x/y/z/mydir .", " iput -Dtar mydir.tar .", " ibun -x mydir.tar mydir", " ", "Note the use of -C option with the tar command which will tar the", "content of mydir but without including the directory mydir in the paths.", "The 'ibun -x' command extracts the tar file into the mydir collection.", "The target mydir collection does not have to exist nor be empty.", "If a subfile already exists in the target collection, the ingestion", "of this subfile will fail (unless the -f flag is set) but the process", "will continue.", " ", "It is generally a good practice to tag the tar file using the -Dtar flag", "when uploading the file using iput. But if the tag is not made,", "the server assumes it is a tar dataType. The dataType tag can be added", "afterward with the isysmeta command. For example:", " isysmeta mod /tempZone/home/rods/mydir.tar datatype 'tar file'", " ", "The following command bundles the iRods collection mydir into a tar file:", " ", " ibun -cDtar mydir1.tar mydir", " ", "If a copy of a file to be bundled does not exist on the target resource,", "a replica will automatically be made on the target resource.", "Again, if the -D flag is not used, the bundling will be done using tar.", " ", "The -b option when used with the -x option, specifies bulk registration", "which does up to 50 rgistrations at a time to reduce overhead.", " ", "Options are:", " -b bulk registration when used with -x to reduce overhead", " -R resource - specifies the resource to store to. This is optional", " in your environment", " -D dataType - the structFile data type. Valid only for -c option for", " specifying the target data type. Valid dataTypes are - t|tar|'tar file'", " for tar file. g|gzip|gzipTar for gzipped tar file, b|bzip2|bzip2Tar for", " bzip2 file, and z|zip|zipFile for an archive using 'zip'. If -D is not", " specified, the default is the tar dataType", " -x extract the structFile and register the extracted files and directories", " under the input irodsCollection", " -c bundle the files and sub-collection underneath the input irodsCollection", " and store it in the structFilePath", " -f force overwrite the structFile (-c) or the subfiles (-x).", " --add add or append to existing structFile.", " -h this help", "" }; int i; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { break; } printf( "%s\n", msgs[i] ); } printReleaseInfo( "ibun" ); } <commit_msg>[#858] spelling<commit_after>/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* * ibun - bundle files operation */ #include "irods_client_api_table.hpp" #include "irods_pack_table.hpp" #include "rodsClient.hpp" #include "parseCommandLine.hpp" #include "rodsPath.hpp" #include "bunUtil.hpp" void usage(); int main( int argc, char **argv ) { int status; rodsEnv myEnv; rErrMsg_t errMsg; rcComm_t *conn; rodsArguments_t myRodsArgs; char *optStr; rodsPathInp_t rodsPathInp; int nArgv; optStr = "bhR:cxD:fZ"; // JMC - backport 4643 status = parseCmdLineOpt( argc, argv, optStr, 1, &myRodsArgs ); // JMC - backport 4643 if ( status < 0 ) { printf( "use -h for help.\n" ); exit( 1 ); } if ( myRodsArgs.help == True ) { usage(); exit( 0 ); } nArgv = argc - optind; if ( nArgv != 2 ) { /* must have 2 inputs */ usage(); exit( 1 ); } status = getRodsEnv( &myEnv ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " ); exit( 1 ); } status = parseCmdLinePath( argc, argv, optind, &myEnv, UNKNOWN_OBJ_T, UNKNOWN_OBJ_T, 0, &rodsPathInp ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "main: parseCmdLinePath error. " ); printf( "use -h for help.\n" ); exit( 1 ); } // =-=-=-=-=-=-=- // initialize pluggable api table irods::api_entry_table& api_tbl = irods::get_client_api_table(); irods::pack_entry_table& pk_tbl = irods::get_pack_table(); init_api_table( api_tbl, pk_tbl ); conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName, myEnv.rodsZone, 1, &errMsg ); if ( conn == NULL ) { exit( 2 ); } status = clientLogin( conn ); if ( status != 0 ) { rcDisconnect( conn ); exit( 7 ); } status = bunUtil( conn, &myEnv, &myRodsArgs, &rodsPathInp ); printErrorStack( conn->rError ); rcDisconnect( conn ); if ( status < 0 ) { exit( 3 ); } else { exit( 0 ); } } void usage() { char *msgs[] = { "Usage : ibun -x [-hfb] [-R resource] structFilePath", " irodsCollection", "Usage : ibun -c [-hf] [-R resource] [-D dataType] structFilePath", " irodsCollection", "Usage : ibun --add [-h] structFilePath irodsCollection", " ", "Bundle file operations. This command allows structured files such as ", "tar files to be uploaded and downloaded to/from iRODS.", " ", "A tar file containing many small files can be created with normal unix", "tar command on the client and then uploaded to the iRODS server as a", "normal iRODS file. The 'ibun -x' command can then be used to extract/untar", "the uploaded tar file. The extracted subfiles and subdirectories will", "appeared as normal iRODS files and sub-collections. The 'ibun -c' command", "can be used to tar/bundle an iRODS collection into a tar file.", " ", "For example, to upload a directory mydir to iRODS:", " ", " tar -chlf mydir.tar -C /x/y/z/mydir .", " iput -Dtar mydir.tar .", " ibun -x mydir.tar mydir", " ", "Note the use of -C option with the tar command which will tar the", "content of mydir but without including the directory mydir in the paths.", "The 'ibun -x' command extracts the tar file into the mydir collection.", "The target mydir collection does not have to exist nor be empty.", "If a subfile already exists in the target collection, the ingestion", "of this subfile will fail (unless the -f flag is set) but the process", "will continue.", " ", "It is generally a good practice to tag the tar file using the -Dtar flag", "when uploading the file using iput. But if the tag is not made,", "the server assumes it is a tar dataType. The dataType tag can be added", "afterward with the isysmeta command. For example:", " isysmeta mod /tempZone/home/rods/mydir.tar datatype 'tar file'", " ", "The following command bundles the iRods collection mydir into a tar file:", " ", " ibun -cDtar mydir1.tar mydir", " ", "If a copy of a file to be bundled does not exist on the target resource,", "a replica will automatically be made on the target resource.", "Again, if the -D flag is not used, the bundling will be done using tar.", " ", "The -b option when used with the -x option, specifies bulk registration", "which does up to 50 registrations at a time to reduce overhead.", " ", "Options are:", " -b bulk registration when used with -x to reduce overhead", " -R resource - specifies the resource to store to. This is optional", " in your environment", " -D dataType - the structFile data type. Valid only for -c option for", " specifying the target data type. Valid dataTypes are - t|tar|'tar file'", " for tar file. g|gzip|gzipTar for gzipped tar file, b|bzip2|bzip2Tar for", " bzip2 file, and z|zip|zipFile for an archive using 'zip'. If -D is not", " specified, the default is the tar dataType", " -x extract the structFile and register the extracted files and directories", " under the input irodsCollection", " -c bundle the files and sub-collection underneath the input irodsCollection", " and store it in the structFilePath", " -f force overwrite the structFile (-c) or the subfiles (-x).", " --add add or append to existing structFile.", " -h this help", "" }; int i; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { break; } printf( "%s\n", msgs[i] ); } printReleaseInfo( "ibun" ); } <|endoftext|>
<commit_before>#include <opencv2/opencv.hpp> namespace image_manip { // TODO(lucasw) mirror initUndistortRectifyMap as much as makes sense // Add m1type parameter // And R rectification matrix? // Need to investigate non-floating point version. void initDistortMap(const cv::Mat& cameraMatrix, const cv::Mat distCoeffs, const cv::Size size, cv::Mat& map1, cv::Mat& map2) { cv::Mat pixel_locations_src = cv::Mat(size.width * size.height, 1, CV_32FC2); int ind = 0; for (int i = 0; i < size.height; i++) { for (int j = 0; j < size.width; j++) { // TODO(lucasw) maybe would want x and y offsets here to make the output // image bigger or smaller than the input? pixel_locations_src.at<cv::Point2f>(ind, 0) = cv::Point2f(j,i); ++ind; } } cv::Mat fractional_locations_dst = cv::Mat(pixel_locations_src.size(), CV_32FC2); cv::undistortPoints(pixel_locations_src, fractional_locations_dst, cameraMatrix, distCoeffs); const float fx = cameraMatrix.at<double>(0, 0); const float fy = cameraMatrix.at<double>(1, 1); const float cx = cameraMatrix.at<double>(0, 2); const float cy = cameraMatrix.at<double>(1, 2); // TODO(lucasw) is there a faster way to do this? // A matrix operation? // If the x and y were separate matrices it would be possible, // and remap does take separate x and y maps. cv::Mat pixel_locations_dst = cv::Mat(size, CV_32FC2); ind = 0; for (int i = 0; i < size.height; i++) { for (int j = 0; j < size.width; j++) { const float x = fractional_locations_dst.at<cv::Point2f>(ind, 0).x * fx + cx; const float y = fractional_locations_dst.at<cv::Point2f>(ind, 0).y * fy + cy; pixel_locations_dst.at<cv::Point2f>(i,j) = cv::Point2f(x,y); // if ((i == 0) && (j == 0)) // ROS_INFO_STREAM(ind << ": " << i << " " << j << ", " << y << " " << x); ++ind; } } map1 = pixel_locations_dst; map2 = cv::Mat(); } // adapted from http://code.opencv.org/issues/1387 (which had errors) // TODO(lucasw) I think this can make use of convertMaps to make it even more efficient void distort(const cv::Mat& src, cv::Mat& image_dst, const cv::Mat& cameraMatrix, const cv::Mat& distCoeffs) { cv::Mat map1; cv::Mat map2; // TODO(lucasw) will passing in a different size work as expected? // or will it require adjustment of cx/cy? initDistortMap(cameraMatrix, distCoeffs, src.size(), map1, map2); cv::remap(src, image_dst, map1, map2, CV_INTER_LINEAR); } } // namespace image_manip <commit_msg>OpenCV4 compatibility for noetic 20.04<commit_after>#include <opencv2/opencv.hpp> namespace image_manip { // TODO(lucasw) mirror initUndistortRectifyMap as much as makes sense // Add m1type parameter // And R rectification matrix? // Need to investigate non-floating point version. void initDistortMap(const cv::Mat& cameraMatrix, const cv::Mat distCoeffs, const cv::Size size, cv::Mat& map1, cv::Mat& map2) { cv::Mat pixel_locations_src = cv::Mat(size.width * size.height, 1, CV_32FC2); int ind = 0; for (int i = 0; i < size.height; i++) { for (int j = 0; j < size.width; j++) { // TODO(lucasw) maybe would want x and y offsets here to make the output // image bigger or smaller than the input? pixel_locations_src.at<cv::Point2f>(ind, 0) = cv::Point2f(j,i); ++ind; } } cv::Mat fractional_locations_dst = cv::Mat(pixel_locations_src.size(), CV_32FC2); cv::undistortPoints(pixel_locations_src, fractional_locations_dst, cameraMatrix, distCoeffs); const float fx = cameraMatrix.at<double>(0, 0); const float fy = cameraMatrix.at<double>(1, 1); const float cx = cameraMatrix.at<double>(0, 2); const float cy = cameraMatrix.at<double>(1, 2); // TODO(lucasw) is there a faster way to do this? // A matrix operation? // If the x and y were separate matrices it would be possible, // and remap does take separate x and y maps. cv::Mat pixel_locations_dst = cv::Mat(size, CV_32FC2); ind = 0; for (int i = 0; i < size.height; i++) { for (int j = 0; j < size.width; j++) { const float x = fractional_locations_dst.at<cv::Point2f>(ind, 0).x * fx + cx; const float y = fractional_locations_dst.at<cv::Point2f>(ind, 0).y * fy + cy; pixel_locations_dst.at<cv::Point2f>(i,j) = cv::Point2f(x,y); // if ((i == 0) && (j == 0)) // ROS_INFO_STREAM(ind << ": " << i << " " << j << ", " << y << " " << x); ++ind; } } map1 = pixel_locations_dst; map2 = cv::Mat(); } // adapted from http://code.opencv.org/issues/1387 (which had errors) // TODO(lucasw) I think this can make use of convertMaps to make it even more efficient void distort(const cv::Mat& src, cv::Mat& image_dst, const cv::Mat& cameraMatrix, const cv::Mat& distCoeffs) { cv::Mat map1; cv::Mat map2; // TODO(lucasw) will passing in a different size work as expected? // or will it require adjustment of cx/cy? initDistortMap(cameraMatrix, distCoeffs, src.size(), map1, map2); cv::remap(src, image_dst, map1, map2, cv::INTER_LINEAR); } } // namespace image_manip <|endoftext|>
<commit_before>namespace Bull { template<typename T> Vector2<T> Vector2<T>::normalize(const Vector2<T>& vector) { return Vector2<T>(vector).normalize(); } template<typename T> T Vector2<T>::dotProduct(const Vector2& left, const Vector2& right) { return (left.x * right.x) + (left.y * right.y); } template<typename T> Vector2<T>::Vector2() { set(0); } template<typename T> Vector2<T>::Vector2(T value) { set(value); } template<typename T> Vector2<T>::Vector2(T x, T y) { set(x, y); } template<typename T> Vector2<T>& Vector2<T>::set(T value) { x = y = value; return (*this); } template<typename T> Vector2<T>& Vector2<T>::set(T x, T y) { this->x = x; this->y = y; return (*this); } template<typename T> Vector2<T>& Vector2<T>::set(const Vector2<T>& copy) { x = copy.x; y = copy.y; return (*this); } template<typename T> float Vector2<T>::getLength() const { return std::sqrt(std::pow(x, 2) + std::pow(y, 2)); } template<typename T> Vector2<T>& Vector2<T>::normalize() { x /= getLength(); y /= getLength(); return (*this); } template<typename T> T Vector2<T>::dotProduct(const Vector2& right) { return (x * right.x) + (y * right.y); } template<typename T> bool Vector2<T>::operator==(const Vector2& right) const { return (x == right.x) && (y == right.y); } template<typename T> bool Vector2<T>::operator!=(const Vector2& right) const { return !((*this) == right); } template<typename T> Vector2<T>& Vector2<T>::operator+=(const Vector2& right) { x += right.x; y += right.y; return (*this); } template<typename T> Vector2<T>& Vector2<T>::operator-=(const Vector2& right) { x -= right.x; y -= right.y; return (*this); } template<typename T> Vector2<T> operator+(const Vector2<T>& left, const Vector2<T>& right) { return Vector2<T>(left) += right; } template<typename T> Vector2<T> operator+(float left, const Vector2<T>& right) { return Vector2<T>(left) += right; } template<typename T> Vector2<T> operator+(const Vector2<T>& left, float right) { return Vector2<T>(left) += Vector2<T>(right); } template<typename T> Vector2<T> operator-(const Vector2<T>& left, const Vector2<T>& right) { return Vector2<T>(left) -= right; } template<typename T> Vector2<T> operator-(float left, const Vector2<T>& right) { return Vector2<T>(left) -= right; } template<typename T> Vector2<T> operator-(const Vector2<T>& left, float right) { return Vector2<T>(left) -= Vector2<T>(right); } } <commit_msg>Math/Vector2 Implement negation method<commit_after>namespace Bull { template<typename T> Vector2<T> Vector2<T>::normalize(const Vector2<T>& vector) { return Vector2<T>(vector).normalize(); } template<typename T> T Vector2<T>::dotProduct(const Vector2& left, const Vector2& right) { return (left.x * right.x) + (left.y * right.y); } template<typename T> Vector2<T>::Vector2() { set(0); } template<typename T> Vector2<T>::Vector2(T value) { set(value); } template<typename T> Vector2<T>::Vector2(T x, T y) { set(x, y); } template<typename T> Vector2<T>& Vector2<T>::set(T value) { x = y = value; return (*this); } template<typename T> Vector2<T>& Vector2<T>::set(T x, T y) { this->x = x; this->y = y; return (*this); } template<typename T> Vector2<T>& Vector2<T>::set(const Vector2<T>& copy) { x = copy.x; y = copy.y; return (*this); } template<typename T> float Vector2<T>::getLength() const { return std::sqrt(std::pow(x, 2) + std::pow(y, 2)); } template<typename T> Vector2<T>& Vector2<T>::normalize() { x /= getLength(); y /= getLength(); return (*this); } template<typename T> T Vector2<T>::dotProduct(const Vector2& right) { return (x * right.x) + (y * right.y); } template<typename T> bool Vector2<T>::operator==(const Vector2& right) const { return (x == right.x) && (y == right.y); } template<typename T> bool Vector2<T>::operator!=(const Vector2& right) const { return !((*this) == right); } template<typename T> Vector2<T>& Vector2<T>::operator+=(const Vector2& right) { x += right.x; y += right.y; return (*this); } template<typename T> Vector2<T> Vector2<T>::operator-() const { return Vector2<T>(-x, -y); } template<typename T> Vector2<T>& Vector2<T>::operator-=(const Vector2& right) { x -= right.x; y -= right.y; return (*this); } template<typename T> Vector2<T> operator+(const Vector2<T>& left, const Vector2<T>& right) { return Vector2<T>(left) += right; } template<typename T> Vector2<T> operator+(float left, const Vector2<T>& right) { return Vector2<T>(left) += right; } template<typename T> Vector2<T> operator+(const Vector2<T>& left, float right) { return Vector2<T>(left) += Vector2<T>(right); } template<typename T> Vector2<T> operator-(const Vector2<T>& left, const Vector2<T>& right) { return Vector2<T>(left) -= right; } template<typename T> Vector2<T> operator-(float left, const Vector2<T>& right) { return Vector2<T>(left) -= right; } template<typename T> Vector2<T> operator-(const Vector2<T>& left, float right) { return Vector2<T>(left) -= Vector2<T>(right); } } <|endoftext|>
<commit_before>// Copyright 2017 Adam Smith // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ASMITH_REFLECTION_MASTER_HPP #define ASMITH_REFLECTION_MASTER_HPP #include "reflection_class.hpp" #include "reflection_constructor.hpp" #include "reflection_destructor.hpp" #include "reflection_function.hpp" #include "reflection_variable.hpp" #include "reflection_modifier.hpp" namespace asmith { #define MACRO_JOIN2(a, b) a##b #define MACRO_JOIN(a, b) MACRO_JOIN2(a , b) #define MACRO_STRING(a) #a #define ASMITH_BEGIN_REFLECTION \ class MACRO_JOIN(ASMITH_REFLECTION_CLASS_NAME,_reflection) : public asmith::reflection_class {\ const char* get_name() const override { return MACRO_STRING(ASMITH_REFLECTION_CLASS_NAME); };\ size_t get_size() const override { return sizeof(ASMITH_REFLECTION_CLASS_NAME); }\ size_t get_variable_count() const override { return ASMITH_REFLECTION_VARIABLE_COUNT; }\ size_t get_constructor_count() const override { return ASMITH_REFLECTION_CONSTRUCTOR_COUNT; }\ size_t get_function_count() const override { return ASMITH_REFLECTION_FUNCTION_COUNT; }\ size_t get_parent_count() const override { return ASMITH_REFLECTION_PARENT_COUNT; } #define ASMITH_END_REFLECTION }; #define ASMITH_REFLECTION_VARIABLE(aName, aMods) \ class MACRO_JOIN(aName,_var_class) : public asmith::reflection_variable {\ public:\ typedef decltype(ASMITH_REFLECTION_CLASS_NAME::aName) type;\ const asmith::reflection_class& get_class() const override { return asmith::get_reflection_class<type>(); }\ const char* get_name() const override { return MACRO_STRING(aName); }\ uint32_t get_modifiers() const override { return aMods; }\ void set(void* aObject, const void* aInput) const override { static_cast<ASMITH_REFLECTION_CLASS_NAME*>(aObject)->*&ASMITH_REFLECTION_CLASS_NAME::aName = *static_cast<const type*>(aInput); }\ void get(const void* aObject, void* aOutput) const override { *static_cast<type*>(aOutput), static_cast<const ASMITH_REFLECTION_CLASS_NAME*>(aObject)->*&ASMITH_REFLECTION_CLASS_NAME::aName; }\ };\ static MACRO_JOIN(aName,_var_class) MACRO_JOIN(aName,_var);\ if(i == currentVar) return MACRO_JOIN(aName,_var);\ ++currentVar; #define ASMITH_BEGIN_REFLECTION_VARIABLES const asmith::reflection_variable& get_variable(size_t i) const override { int currentVar = 0; #define ASMITH_END_REFLECTION_VARIABLES throw std::runtime_error("asmith::reflection_variable::get_function : Index out of bounds"); } #define ASMITH_REFLECTION_DESTRUCTOR(aMods)\ const asmith::reflection_destructor& get_destructor() const override { \ class destructor : public reflection_destructor {\ public:\ size_t get_modifiers() const override { return aMods; }\ void call(void* aObject) const override { static_cast<ASMITH_REFLECTION_CLASS_NAME*>(aObject)->~ASMITH_REFLECTION_CLASS_NAME(); }\ };\ static destructor DESTRUCTOR;\ return DESTRUCTOR;\ } #define ASMITH_BEGIN_REFLECTION_CONSTRUCTORS const asmith::reflection_constructor& get_constructor(size_t i) const override { int currentConstructor = 0; #define ASMITH_END_REFLECTION_CONSTRUCTORS throw std::runtime_error("asmith::reflection_variable::get_constructor : Index out of bounds"); } namespace implementation { template<class C, uint32_t MODS, class ...PARAMS> class reflection_constructor_implementation : public reflection_constructor { private: template<class A> void call__(void* aObject, const void* aParams) { const A* a = static_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); new(aObject) C(*a); } template<class A, class B> void call__(void* aObject, const void* aParams) { const A* a = static_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); const B* b = static_cast<const B*>(reinterpret_cast<const uint8_t*>(a) + sizeof(A)); new(aObject) C(*a, *b); } template<class A, class B, class C> void call__(void* aObject, const void* aParams) { const A* a = static_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); const B* b = static_cast<const B*>(reinterpret_cast<const uint8_t*>(a) + sizeof(A)); const C* c = static_cast<const C*>(reinterpret_cast<const uint8_t*>(b) + sizeof(B)); new(aObject) C(*a, *b, *c); } template<class A, class B, class C, class D> void call__(void* aObject, const void* aParams) { const A* a = static_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); const B* b = static_cast<const B*>(reinterpret_cast<const uint8_t*>(a) + sizeof(A)); const C* c = static_cast<const C*>(reinterpret_cast<const uint8_t*>(b) + sizeof(B)); const D* d = static_cast<const D*>(reinterpret_cast<const uint8_t*>(c) + sizeof(C)); new(aObject) C(*a, *b, *c, *d); } template<class A, class B, class C, class D, class E> void call__(void* aObject, const void* aParams) { const A* a = static_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); const B* b = static_cast<const B*>(reinterpret_cast<const uint8_t*>(a) + sizeof(A)); const C* c = static_cast<const C*>(reinterpret_cast<const uint8_t*>(b) + sizeof(B)); const D* d = static_cast<const D*>(reinterpret_cast<const uint8_t*>(c) + sizeof(C)); const E* e = static_cast<const E*>(reinterpret_cast<const uint8_t*>(d) + sizeof(D)); new(aObject) C(*a, *b, *c, *d, *e); } template<class A, class B, class C, class D, class E, class F> void call__(void* aObject, const void* aParams) { const A* a = static_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); const B* b = static_cast<const B*>(reinterpret_cast<const uint8_t*>(a) + sizeof(A)); const C* c = static_cast<const C*>(reinterpret_cast<const uint8_t*>(b) + sizeof(B)); const D* d = static_cast<const D*>(reinterpret_cast<const uint8_t*>(c) + sizeof(C)); const E* e = static_cast<const E*>(reinterpret_cast<const uint8_t*>(d) + sizeof(D)); const F* f = static_cast<const F*>(reinterpret_cast<const uint8_t*>(e) + sizeof(E)); new(aObject) C(*a, *b, *c, *d, *e, *f); } template<size_t I = sizeof...(PARAMS)> typename std::enable_if<I == 0, void>::type call_(void* aObject, const void* aParams) const { new(aObject) C(); } template<size_t I = sizeof...(PARAMS)> typename std::enable_if<I != 0, void>::type call_(void* aObject, const void* aParams) const { call__<PARAMS...>(aObject, aParams); } public: // Inherited from reflection_constructor size_t get_parameter_count() const override { return sizeof...(PARAMS); } const asmith::reflection_class& get_parameter(size_t i) const override { //! \todo Implement throw std::runtime_error("asmith::reflection_constructor_implementation::get_parameter : Not yet implemented"); } size_t get_modifiers() const override { return MODS; } void call(void* aObject, const void* aParams) const override { call_<PARAMS...>(aObject, aParams); } }; } #define ASMITH_REFLECTION_TRIVIAL_CONSTRUCTOR(aMods) \ static implementation::reflection_constructor_implementation<ASMITH_REFLECTION_CLASS_NAME, aMods> trivial_constructor;\ if(i == currentConstructor) return trivial_constructor;\ ++currentConstructor; class reflection_test { private: std::string name; int dimensions; float lower_bound; float upper_bound; public: std::string get_name() { return name; } int get_dimensions() { return dimensions; } float get_lower_bound() { return lower_bound; } float get_upper_bound() { return upper_bound; } #define ASMITH_REFLECTION_CLASS_NAME reflection_test #define ASMITH_REFLECTION_VARIABLE_COUNT 4 #define ASMITH_REFLECTION_CONSTRUCTOR_COUNT 0 #define ASMITH_REFLECTION_FUNCTION_COUNT 0 #define ASMITH_REFLECTION_PARENT_COUNT 0 ASMITH_BEGIN_REFLECTION const asmith::reflection_function& get_function(size_t) const override { throw 0; } const reflection_class& get_parent_class(size_t) const override { throw 0; } ASMITH_REFLECTION_DESTRUCTOR(REFLECTION_PUBLIC) ASMITH_BEGIN_REFLECTION_CONSTRUCTORS ASMITH_REFLECTION_TRIVIAL_CONSTRUCTOR(REFLECTION_PUBLIC) ASMITH_END_REFLECTION_CONSTRUCTORS ASMITH_BEGIN_REFLECTION_VARIABLES ASMITH_REFLECTION_VARIABLE(name, REFLECTION_PRIVATE); ASMITH_REFLECTION_VARIABLE(dimensions, REFLECTION_PRIVATE); ASMITH_REFLECTION_VARIABLE(lower_bound, REFLECTION_PRIVATE); ASMITH_REFLECTION_VARIABLE(upper_bound, REFLECTION_PRIVATE); ASMITH_END_REFLECTION_VARIABLES ASMITH_END_REFLECTION #undef ASMITH_REFLECTION_CLASS_NAME #undef ASMITH_REFLECTION_VARIABLE_COUNT #undef ASMITH_REFLECTION_CONSTRUCTOR_COUNT #undef ASMITH_REFLECTION_FUNCTION_COUNT #undef ASMITH_REFLECTION_PARENT_COUNT }; } #endif<commit_msg>Fixed constructors with arguments<commit_after>// Copyright 2017 Adam Smith // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ASMITH_REFLECTION_MASTER_HPP #define ASMITH_REFLECTION_MASTER_HPP #include "reflection_class.hpp" #include "reflection_constructor.hpp" #include "reflection_destructor.hpp" #include "reflection_function.hpp" #include "reflection_variable.hpp" #include "reflection_modifier.hpp" namespace asmith { #define MACRO_JOIN2(a, b) a##b #define MACRO_JOIN(a, b) MACRO_JOIN2(a , b) #define MACRO_STRING(a) #a #define ASMITH_BEGIN_REFLECTION \ class MACRO_JOIN(ASMITH_REFLECTION_CLASS_NAME,_reflection) : public asmith::reflection_class {\ const char* get_name() const override { return MACRO_STRING(ASMITH_REFLECTION_CLASS_NAME); };\ size_t get_size() const override { return sizeof(ASMITH_REFLECTION_CLASS_NAME); }\ size_t get_variable_count() const override { return ASMITH_REFLECTION_VARIABLE_COUNT; }\ size_t get_constructor_count() const override { return ASMITH_REFLECTION_CONSTRUCTOR_COUNT; }\ size_t get_function_count() const override { return ASMITH_REFLECTION_FUNCTION_COUNT; }\ size_t get_parent_count() const override { return ASMITH_REFLECTION_PARENT_COUNT; } #define ASMITH_END_REFLECTION }; #define ASMITH_REFLECTION_VARIABLE(aName, aMods) \ class MACRO_JOIN(aName,_var_class) : public asmith::reflection_variable {\ public:\ typedef decltype(ASMITH_REFLECTION_CLASS_NAME::aName) type;\ const asmith::reflection_class& get_class() const override { return asmith::get_reflection_class<type>(); }\ const char* get_name() const override { return MACRO_STRING(aName); }\ uint32_t get_modifiers() const override { return aMods; }\ void set(void* aObject, const void* aInput) const override { static_cast<ASMITH_REFLECTION_CLASS_NAME*>(aObject)->*&ASMITH_REFLECTION_CLASS_NAME::aName = *static_cast<const type*>(aInput); }\ void get(const void* aObject, void* aOutput) const override { *static_cast<type*>(aOutput), static_cast<const ASMITH_REFLECTION_CLASS_NAME*>(aObject)->*&ASMITH_REFLECTION_CLASS_NAME::aName; }\ };\ static MACRO_JOIN(aName,_var_class) MACRO_JOIN(aName,_var);\ if(i == currentVar) return MACRO_JOIN(aName,_var);\ ++currentVar; #define ASMITH_BEGIN_REFLECTION_VARIABLES const asmith::reflection_variable& get_variable(size_t i) const override { int currentVar = 0; #define ASMITH_END_REFLECTION_VARIABLES throw std::runtime_error("asmith::reflection_variable::get_function : Index out of bounds"); } #define ASMITH_REFLECTION_DESTRUCTOR(aMods)\ const asmith::reflection_destructor& get_destructor() const override { \ class destructor : public reflection_destructor {\ public:\ size_t get_modifiers() const override { return aMods; }\ void call(void* aObject) const override { static_cast<ASMITH_REFLECTION_CLASS_NAME*>(aObject)->~ASMITH_REFLECTION_CLASS_NAME(); }\ };\ static destructor DESTRUCTOR;\ return DESTRUCTOR;\ } #define ASMITH_BEGIN_REFLECTION_CONSTRUCTORS const asmith::reflection_constructor& get_constructor(size_t i) const override { int currentConstructor = 0; #define ASMITH_END_REFLECTION_CONSTRUCTORS throw std::runtime_error("asmith::reflection_variable::get_constructor : Index out of bounds"); } namespace implementation { template<class C, uint32_t MODS, class ...PARAMS> class reflection_constructor_implementation : public reflection_constructor { private: template<class A> void call__(void* aObject, const void* aParams) const { const A* a = reinterpret_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); new(aObject) C(*a); } template<class A, class B> void call__(void* aObject, const void* aParams) const { const A* a = reinterpret_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); const B* b = reinterpret_cast<const B*>(reinterpret_cast<const uint8_t*>(a) + sizeof(A)); new(aObject) C(*a, *b); } template<class A, class B, class C> void call__(void* aObject, const void* aParams) const { const A* a = reinterpret_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); const B* b = reinterpret_cast<const B*>(reinterpret_cast<const uint8_t*>(a) + sizeof(A)); const C* c = reinterpret_cast<const C*>(reinterpret_cast<const uint8_t*>(b) + sizeof(B)); new(aObject) C(*a, *b, *c); } template<class A, class B, class C, class D> void call__(void* aObject, const void* aParams) const { const A* a = reinterpret_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); const B* b = reinterpret_cast<const B*>(reinterpret_cast<const uint8_t*>(a) + sizeof(A)); const C* c = reinterpret_cast<const C*>(reinterpret_cast<const uint8_t*>(b) + sizeof(B)); const D* d = reinterpret_cast<const D*>(reinterpret_cast<const uint8_t*>(c) + sizeof(C)); new(aObject) C(*a, *b, *c, *d); } template<class A, class B, class C, class D, class E> void call__(void* aObject, const void* aParams) const { const A* a = reinterpret_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); const B* b = reinterpret_cast<const B*>(reinterpret_cast<const uint8_t*>(a) + sizeof(A)); const C* c = reinterpret_cast<const C*>(reinterpret_cast<const uint8_t*>(b) + sizeof(B)); const D* d = reinterpret_cast<const D*>(reinterpret_cast<const uint8_t*>(c) + sizeof(C)); const E* e = reinterpret_cast<const E*>(reinterpret_cast<const uint8_t*>(d) + sizeof(D)); new(aObject) C(*a, *b, *c, *d, *e); } template<class A, class B, class C, class D, class E, class F> void call__(void* aObject, const void* aParams) const { const A* a = reinterpret_cast<const A*>(reinterpret_cast<const uint8_t*>(aParams) + 0); const B* b = reinterpret_cast<const B*>(reinterpret_cast<const uint8_t*>(a) + sizeof(A)); const C* c = reinterpret_cast<const C*>(reinterpret_cast<const uint8_t*>(b) + sizeof(B)); const D* d = reinterpret_cast<const D*>(reinterpret_cast<const uint8_t*>(c) + sizeof(C)); const E* e = reinterpret_cast<const E*>(reinterpret_cast<const uint8_t*>(d) + sizeof(D)); const F* f = reinterpret_cast<const F*>(reinterpret_cast<const uint8_t*>(e) + sizeof(E)); new(aObject) C(*a, *b, *c, *d, *e, *f); } template<class... P> typename std::enable_if<sizeof...(P) == 0, void>::type call_(void* aObject, const void* aParams) const { new(aObject) C(); } template<class... P> typename std::enable_if<sizeof...(P) != 0, void>::type call_(void* aObject, const void* aParams) const { call__<P...>(aObject, aParams); } public: // Inherited from reflection_constructor size_t get_parameter_count() const override { return sizeof...(PARAMS); } const asmith::reflection_class& get_parameter(size_t i) const override { //! \todo Implement throw std::runtime_error("asmith::reflection_constructor_implementation::get_parameter : Not yet implemented"); } size_t get_modifiers() const override { return MODS; } void call(void* aObject, const void* aParams) const override { call_<PARAMS...>(aObject, aParams); } }; } #define ASMITH_REFLECTION_TRIVIAL_CONSTRUCTOR(aMods) \ if(i == currentConstructor) {\ static implementation::reflection_constructor_implementation<ASMITH_REFLECTION_CLASS_NAME, aMods> constructor; \ return constructor; \ }\ ++currentConstructor; #define ASMITH_REFLECTION_CONSTRUCTOR(aMods, aParams) \ if(i == currentConstructor) {\ static implementation::reflection_constructor_implementation<ASMITH_REFLECTION_CLASS_NAME, aMods, aParams> constructor; \ return constructor; \ }\ ++currentConstructor; #define ASMITH_REFLECTION_COPY_CONSTRUCTOR(aMods) ASMITH_REFLECTION_CONSTRUCTOR(aMods, ASMITH_REFLECTION_CLASS_NAME) class reflection_test { private: std::string name; int dimensions; float lower_bound; float upper_bound; public: std::string get_name() { return name; } int get_dimensions() { return dimensions; } float get_lower_bound() { return lower_bound; } float get_upper_bound() { return upper_bound; } #define ASMITH_REFLECTION_CLASS_NAME reflection_test #define ASMITH_REFLECTION_VARIABLE_COUNT 4 #define ASMITH_REFLECTION_CONSTRUCTOR_COUNT 0 #define ASMITH_REFLECTION_FUNCTION_COUNT 0 #define ASMITH_REFLECTION_PARENT_COUNT 0 ASMITH_BEGIN_REFLECTION const asmith::reflection_function& get_function(size_t) const override { throw 0; } const reflection_class& get_parent_class(size_t) const override { throw 0; } ASMITH_REFLECTION_DESTRUCTOR(REFLECTION_PUBLIC) ASMITH_BEGIN_REFLECTION_CONSTRUCTORS ASMITH_REFLECTION_TRIVIAL_CONSTRUCTOR(REFLECTION_PUBLIC) ASMITH_REFLECTION_COPY_CONSTRUCTOR(REFLECTION_PUBLIC) ASMITH_END_REFLECTION_CONSTRUCTORS ASMITH_BEGIN_REFLECTION_VARIABLES ASMITH_REFLECTION_VARIABLE(name, REFLECTION_PRIVATE); ASMITH_REFLECTION_VARIABLE(dimensions, REFLECTION_PRIVATE); ASMITH_REFLECTION_VARIABLE(lower_bound, REFLECTION_PRIVATE); ASMITH_REFLECTION_VARIABLE(upper_bound, REFLECTION_PRIVATE); ASMITH_END_REFLECTION_VARIABLES ASMITH_END_REFLECTION #undef ASMITH_REFLECTION_CLASS_NAME #undef ASMITH_REFLECTION_VARIABLE_COUNT #undef ASMITH_REFLECTION_CONSTRUCTOR_COUNT #undef ASMITH_REFLECTION_FUNCTION_COUNT #undef ASMITH_REFLECTION_PARENT_COUNT }; } #endif<|endoftext|>
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc. // // 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 "rclcpp/context.hpp" #include <memory> #include <mutex> #include <sstream> #include <string> #include <vector> #include <utility> #include "rcl/init.h" #include "rclcpp/detail/utilities.hpp" #include "rclcpp/exceptions.hpp" #include "rclcpp/logging.hpp" #include "rmw/impl/cpp/demangle.hpp" /// Mutex to protect initialized contexts. static std::mutex g_contexts_mutex; /// Weak list of context to be shutdown by the signal handler. static std::vector<std::weak_ptr<rclcpp::Context>> g_contexts; using rclcpp::Context; Context::Context() : rcl_context_(nullptr), shutdown_reason_("") {} Context::~Context() { // acquire the init lock to prevent race conditions with init and shutdown // this will not prevent errors, but will maybe make them easier to reproduce std::lock_guard<std::recursive_mutex> lock(init_mutex_); try { this->shutdown("context destructor was called while still not shutdown"); // at this point it is shutdown and cannot reinit // clean_up will finalize the rcl context this->clean_up(); } catch (const std::exception & exc) { RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "unhandled exception in ~Context(): %s", exc.what()); } catch (...) { RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "unhandled exception in ~Context()"); } } RCLCPP_LOCAL void __delete_context(rcl_context_t * context) { if (context) { if (rcl_context_is_valid(context)) { RCLCPP_ERROR( rclcpp::get_logger("rclcpp"), "rcl context unexpectedly not shutdown during cleanup"); } else { // if context pointer is not null and is shutdown, then it's ready for fini rcl_ret_t ret = rcl_context_fini(context); if (RCL_RET_OK != ret) { RCLCPP_ERROR( rclcpp::get_logger("rclcpp"), "failed to finalize context: %s", rcl_get_error_string().str); rcl_reset_error(); } } delete context; } } void Context::init( int argc, char const * const argv[], const rclcpp::InitOptions & init_options) { std::lock_guard<std::recursive_mutex> init_lock(init_mutex_); if (this->is_valid()) { throw rclcpp::ContextAlreadyInitialized(); } this->clean_up(); rcl_context_.reset(new rcl_context_t, __delete_context); *rcl_context_.get() = rcl_get_zero_initialized_context(); rcl_ret_t ret = rcl_init(argc, argv, init_options.get_rcl_init_options(), rcl_context_.get()); if (RCL_RET_OK != ret) { rcl_context_.reset(); rclcpp::exceptions::throw_from_rcl_error(ret, "failed to initialize rcl"); } try { std::vector<std::string> unparsed_ros_arguments = detail::get_unparsed_ros_arguments(argc, argv, &(rcl_context_->global_arguments), rcl_get_default_allocator()); if (!unparsed_ros_arguments.empty()) { throw exceptions::UnknownROSArgsError(std::move(unparsed_ros_arguments)); } init_options_ = init_options; std::lock_guard<std::mutex> lock(g_contexts_mutex); g_contexts.push_back(this->shared_from_this()); } catch (const std::exception & e) { ret = rcl_shutdown(rcl_context_.get()); rcl_context_.reset(); if (RCL_RET_OK != ret) { std::ostringstream oss; oss << "While handling: " << e.what() << std::endl << " another exception was thrown"; rclcpp::exceptions::throw_from_rcl_error(ret, oss.str()); } throw; } } bool Context::is_valid() const { // Take a local copy of the shared pointer to avoid it getting nulled under our feet. auto local_rcl_context = rcl_context_; if (!local_rcl_context) { return false; } return rcl_context_is_valid(local_rcl_context.get()); } const rclcpp::InitOptions & Context::get_init_options() const { return init_options_; } rclcpp::InitOptions Context::get_init_options() { return init_options_; } std::string Context::shutdown_reason() { std::lock_guard<std::recursive_mutex> lock(init_mutex_); return shutdown_reason_; } bool Context::shutdown(const std::string & reason) { // prevent races std::lock_guard<std::recursive_mutex> init_lock(init_mutex_); // ensure validity if (!this->is_valid()) { // if it is not valid, then it cannot be shutdown return false; } // rcl shutdown rcl_ret_t ret = rcl_shutdown(rcl_context_.get()); if (RCL_RET_OK != ret) { rclcpp::exceptions::throw_from_rcl_error(ret); } // set shutdown reason shutdown_reason_ = reason; // call each shutdown callback for (const auto & callback : on_shutdown_callbacks_) { callback(); } // interrupt all blocking sleep_for() and all blocking executors or wait sets this->interrupt_all_sleep_for(); this->interrupt_all_wait_sets(); // remove self from the global contexts std::lock_guard<std::mutex> context_lock(g_contexts_mutex); for (auto it = g_contexts.begin(); it != g_contexts.end(); ) { auto shared_context = it->lock(); if (shared_context.get() == this) { it = g_contexts.erase(it); break; } else { ++it; } } return true; } rclcpp::Context::OnShutdownCallback Context::on_shutdown(OnShutdownCallback callback) { on_shutdown_callbacks_.push_back(callback); return callback; } const std::vector<rclcpp::Context::OnShutdownCallback> & Context::get_on_shutdown_callbacks() const { return on_shutdown_callbacks_; } std::vector<rclcpp::Context::OnShutdownCallback> & Context::get_on_shutdown_callbacks() { return on_shutdown_callbacks_; } std::shared_ptr<rcl_context_t> Context::get_rcl_context() { return rcl_context_; } bool Context::sleep_for(const std::chrono::nanoseconds & nanoseconds) { std::chrono::nanoseconds time_left = nanoseconds; { std::unique_lock<std::mutex> lock(interrupt_mutex_); auto start = std::chrono::steady_clock::now(); // this will release the lock while waiting interrupt_condition_variable_.wait_for(lock, nanoseconds); time_left -= std::chrono::steady_clock::now() - start; } if (time_left > std::chrono::nanoseconds::zero() && this->is_valid()) { return sleep_for(time_left); } // Return true if the timeout elapsed successfully, otherwise false. return this->is_valid(); } void Context::interrupt_all_sleep_for() { interrupt_condition_variable_.notify_all(); } rcl_guard_condition_t * Context::get_interrupt_guard_condition(rcl_wait_set_t * wait_set) { std::lock_guard<std::mutex> lock(interrupt_guard_cond_handles_mutex_); auto kv = interrupt_guard_cond_handles_.find(wait_set); if (kv != interrupt_guard_cond_handles_.end()) { return &kv->second; } else { rcl_guard_condition_t handle = rcl_get_zero_initialized_guard_condition(); rcl_guard_condition_options_t options = rcl_guard_condition_get_default_options(); auto ret = rcl_guard_condition_init(&handle, this->get_rcl_context().get(), options); if (RCL_RET_OK != ret) { rclcpp::exceptions::throw_from_rcl_error(ret, "Couldn't initialize guard condition"); } interrupt_guard_cond_handles_.emplace(wait_set, handle); return &interrupt_guard_cond_handles_[wait_set]; } } void Context::release_interrupt_guard_condition(rcl_wait_set_t * wait_set) { std::lock_guard<std::mutex> lock(interrupt_guard_cond_handles_mutex_); auto kv = interrupt_guard_cond_handles_.find(wait_set); if (kv != interrupt_guard_cond_handles_.end()) { rcl_ret_t ret = rcl_guard_condition_fini(&kv->second); if (RCL_RET_OK != ret) { rclcpp::exceptions::throw_from_rcl_error(ret, "Failed to destroy sigint guard condition"); } interrupt_guard_cond_handles_.erase(kv); } else { throw std::runtime_error("Tried to release sigint guard condition for nonexistent wait set"); } } void Context::release_interrupt_guard_condition( rcl_wait_set_t * wait_set, const std::nothrow_t &) noexcept { try { this->release_interrupt_guard_condition(wait_set); } catch (const std::exception & exc) { RCLCPP_ERROR( rclcpp::get_logger("rclcpp"), "caught %s exception when releasing interrupt guard condition: %s", rmw::impl::cpp::demangle(exc).c_str(), exc.what()); } catch (...) { RCLCPP_ERROR( rclcpp::get_logger("rclcpp"), "caught unknown exception when releasing interrupt guard condition"); } } void Context::interrupt_all_wait_sets() { std::lock_guard<std::mutex> lock(interrupt_guard_cond_handles_mutex_); for (auto & kv : interrupt_guard_cond_handles_) { rcl_ret_t status = rcl_trigger_guard_condition(&(kv.second)); if (status != RCL_RET_OK) { RCUTILS_LOG_ERROR_NAMED( "rclcpp", "failed to trigger guard condition in Context::interrupt_all_wait_sets(): %s", rcl_get_error_string().str); } } } void Context::clean_up() { shutdown_reason_ = ""; rcl_context_.reset(); } std::vector<Context::SharedPtr> rclcpp::get_contexts() { std::lock_guard<std::mutex> lock(g_contexts_mutex); std::vector<Context::SharedPtr> shared_contexts; for (auto it = g_contexts.begin(); it != g_contexts.end(); /* noop */) { auto context_ptr = it->lock(); if (!context_ptr) { // remove invalid weak context pointers it = g_contexts.erase(it); } else { ++it; shared_contexts.push_back(context_ptr); } } return shared_contexts; } <commit_msg>Clear sub contexts when starting another init-shutdown cycle (#947)<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc. // // 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 "rclcpp/context.hpp" #include <memory> #include <mutex> #include <sstream> #include <string> #include <vector> #include <utility> #include "rcl/init.h" #include "rclcpp/detail/utilities.hpp" #include "rclcpp/exceptions.hpp" #include "rclcpp/logging.hpp" #include "rmw/impl/cpp/demangle.hpp" /// Mutex to protect initialized contexts. static std::mutex g_contexts_mutex; /// Weak list of context to be shutdown by the signal handler. static std::vector<std::weak_ptr<rclcpp::Context>> g_contexts; using rclcpp::Context; Context::Context() : rcl_context_(nullptr), shutdown_reason_("") {} Context::~Context() { // acquire the init lock to prevent race conditions with init and shutdown // this will not prevent errors, but will maybe make them easier to reproduce std::lock_guard<std::recursive_mutex> lock(init_mutex_); try { this->shutdown("context destructor was called while still not shutdown"); // at this point it is shutdown and cannot reinit // clean_up will finalize the rcl context this->clean_up(); } catch (const std::exception & exc) { RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "unhandled exception in ~Context(): %s", exc.what()); } catch (...) { RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "unhandled exception in ~Context()"); } } RCLCPP_LOCAL void __delete_context(rcl_context_t * context) { if (context) { if (rcl_context_is_valid(context)) { RCLCPP_ERROR( rclcpp::get_logger("rclcpp"), "rcl context unexpectedly not shutdown during cleanup"); } else { // if context pointer is not null and is shutdown, then it's ready for fini rcl_ret_t ret = rcl_context_fini(context); if (RCL_RET_OK != ret) { RCLCPP_ERROR( rclcpp::get_logger("rclcpp"), "failed to finalize context: %s", rcl_get_error_string().str); rcl_reset_error(); } } delete context; } } void Context::init( int argc, char const * const argv[], const rclcpp::InitOptions & init_options) { std::lock_guard<std::recursive_mutex> init_lock(init_mutex_); if (this->is_valid()) { throw rclcpp::ContextAlreadyInitialized(); } this->clean_up(); rcl_context_.reset(new rcl_context_t, __delete_context); *rcl_context_.get() = rcl_get_zero_initialized_context(); rcl_ret_t ret = rcl_init(argc, argv, init_options.get_rcl_init_options(), rcl_context_.get()); if (RCL_RET_OK != ret) { rcl_context_.reset(); rclcpp::exceptions::throw_from_rcl_error(ret, "failed to initialize rcl"); } try { std::vector<std::string> unparsed_ros_arguments = detail::get_unparsed_ros_arguments(argc, argv, &(rcl_context_->global_arguments), rcl_get_default_allocator()); if (!unparsed_ros_arguments.empty()) { throw exceptions::UnknownROSArgsError(std::move(unparsed_ros_arguments)); } init_options_ = init_options; std::lock_guard<std::mutex> lock(g_contexts_mutex); g_contexts.push_back(this->shared_from_this()); } catch (const std::exception & e) { ret = rcl_shutdown(rcl_context_.get()); rcl_context_.reset(); if (RCL_RET_OK != ret) { std::ostringstream oss; oss << "While handling: " << e.what() << std::endl << " another exception was thrown"; rclcpp::exceptions::throw_from_rcl_error(ret, oss.str()); } throw; } } bool Context::is_valid() const { // Take a local copy of the shared pointer to avoid it getting nulled under our feet. auto local_rcl_context = rcl_context_; if (!local_rcl_context) { return false; } return rcl_context_is_valid(local_rcl_context.get()); } const rclcpp::InitOptions & Context::get_init_options() const { return init_options_; } rclcpp::InitOptions Context::get_init_options() { return init_options_; } std::string Context::shutdown_reason() { std::lock_guard<std::recursive_mutex> lock(init_mutex_); return shutdown_reason_; } bool Context::shutdown(const std::string & reason) { // prevent races std::lock_guard<std::recursive_mutex> init_lock(init_mutex_); // ensure validity if (!this->is_valid()) { // if it is not valid, then it cannot be shutdown return false; } // rcl shutdown rcl_ret_t ret = rcl_shutdown(rcl_context_.get()); if (RCL_RET_OK != ret) { rclcpp::exceptions::throw_from_rcl_error(ret); } // set shutdown reason shutdown_reason_ = reason; // call each shutdown callback for (const auto & callback : on_shutdown_callbacks_) { callback(); } // interrupt all blocking sleep_for() and all blocking executors or wait sets this->interrupt_all_sleep_for(); this->interrupt_all_wait_sets(); // remove self from the global contexts std::lock_guard<std::mutex> context_lock(g_contexts_mutex); for (auto it = g_contexts.begin(); it != g_contexts.end(); ) { auto shared_context = it->lock(); if (shared_context.get() == this) { it = g_contexts.erase(it); break; } else { ++it; } } return true; } rclcpp::Context::OnShutdownCallback Context::on_shutdown(OnShutdownCallback callback) { on_shutdown_callbacks_.push_back(callback); return callback; } const std::vector<rclcpp::Context::OnShutdownCallback> & Context::get_on_shutdown_callbacks() const { return on_shutdown_callbacks_; } std::vector<rclcpp::Context::OnShutdownCallback> & Context::get_on_shutdown_callbacks() { return on_shutdown_callbacks_; } std::shared_ptr<rcl_context_t> Context::get_rcl_context() { return rcl_context_; } bool Context::sleep_for(const std::chrono::nanoseconds & nanoseconds) { std::chrono::nanoseconds time_left = nanoseconds; { std::unique_lock<std::mutex> lock(interrupt_mutex_); auto start = std::chrono::steady_clock::now(); // this will release the lock while waiting interrupt_condition_variable_.wait_for(lock, nanoseconds); time_left -= std::chrono::steady_clock::now() - start; } if (time_left > std::chrono::nanoseconds::zero() && this->is_valid()) { return sleep_for(time_left); } // Return true if the timeout elapsed successfully, otherwise false. return this->is_valid(); } void Context::interrupt_all_sleep_for() { interrupt_condition_variable_.notify_all(); } rcl_guard_condition_t * Context::get_interrupt_guard_condition(rcl_wait_set_t * wait_set) { std::lock_guard<std::mutex> lock(interrupt_guard_cond_handles_mutex_); auto kv = interrupt_guard_cond_handles_.find(wait_set); if (kv != interrupt_guard_cond_handles_.end()) { return &kv->second; } else { rcl_guard_condition_t handle = rcl_get_zero_initialized_guard_condition(); rcl_guard_condition_options_t options = rcl_guard_condition_get_default_options(); auto ret = rcl_guard_condition_init(&handle, this->get_rcl_context().get(), options); if (RCL_RET_OK != ret) { rclcpp::exceptions::throw_from_rcl_error(ret, "Couldn't initialize guard condition"); } interrupt_guard_cond_handles_.emplace(wait_set, handle); return &interrupt_guard_cond_handles_[wait_set]; } } void Context::release_interrupt_guard_condition(rcl_wait_set_t * wait_set) { std::lock_guard<std::mutex> lock(interrupt_guard_cond_handles_mutex_); auto kv = interrupt_guard_cond_handles_.find(wait_set); if (kv != interrupt_guard_cond_handles_.end()) { rcl_ret_t ret = rcl_guard_condition_fini(&kv->second); if (RCL_RET_OK != ret) { rclcpp::exceptions::throw_from_rcl_error(ret, "Failed to destroy sigint guard condition"); } interrupt_guard_cond_handles_.erase(kv); } else { throw std::runtime_error("Tried to release sigint guard condition for nonexistent wait set"); } } void Context::release_interrupt_guard_condition( rcl_wait_set_t * wait_set, const std::nothrow_t &) noexcept { try { this->release_interrupt_guard_condition(wait_set); } catch (const std::exception & exc) { RCLCPP_ERROR( rclcpp::get_logger("rclcpp"), "caught %s exception when releasing interrupt guard condition: %s", rmw::impl::cpp::demangle(exc).c_str(), exc.what()); } catch (...) { RCLCPP_ERROR( rclcpp::get_logger("rclcpp"), "caught unknown exception when releasing interrupt guard condition"); } } void Context::interrupt_all_wait_sets() { std::lock_guard<std::mutex> lock(interrupt_guard_cond_handles_mutex_); for (auto & kv : interrupt_guard_cond_handles_) { rcl_ret_t status = rcl_trigger_guard_condition(&(kv.second)); if (status != RCL_RET_OK) { RCUTILS_LOG_ERROR_NAMED( "rclcpp", "failed to trigger guard condition in Context::interrupt_all_wait_sets(): %s", rcl_get_error_string().str); } } } void Context::clean_up() { shutdown_reason_ = ""; rcl_context_.reset(); sub_contexts_.clear(); } std::vector<Context::SharedPtr> rclcpp::get_contexts() { std::lock_guard<std::mutex> lock(g_contexts_mutex); std::vector<Context::SharedPtr> shared_contexts; for (auto it = g_contexts.begin(); it != g_contexts.end(); /* noop */) { auto context_ptr = it->lock(); if (!context_ptr) { // remove invalid weak context pointers it = g_contexts.erase(it); } else { ++it; shared_contexts.push_back(context_ptr); } } return shared_contexts; } <|endoftext|>
<commit_before>/* Copyright (c) 2006, 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. */ #ifndef NODE_HPP #define NODE_HPP #include <algorithm> #include <map> #include <set> #include <libtorrent/config.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/msg.hpp> #include <libtorrent/kademlia/find_data.hpp> #include <libtorrent/io.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/assert.hpp> #include <libtorrent/thread.hpp> #include <libtorrent/bloom_filter.hpp> #include <boost/cstdint.hpp> #include <boost/ref.hpp> #include "libtorrent/socket.hpp" namespace libtorrent { class alert_manager; struct alert_dispatcher; } namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DECLARE_LOG(node); #endif struct traversal_algorithm; struct key_desc_t { char const* name; int type; int size; int flags; enum { // this argument is optional, parsing will not // fail if it's not present optional = 1, // for dictionaries, the following entries refer // to child nodes to this node, up until and including // the next item that has the last_child flag set. // these flags are nestable parse_children = 2, // this is the last item in a child dictionary last_child = 4, // the size argument refers to that the size // has to be divisible by the number, instead // of having that exact size size_divisible = 8 }; }; bool TORRENT_EXTRA_EXPORT verify_message(lazy_entry const* msg, key_desc_t const desc[] , lazy_entry const* ret[], int size , char* error, int error_size); // this is the entry for every peer // the timestamp is there to make it possible // to remove stale peers struct peer_entry { tcp::endpoint addr; ptime added; bool seed; }; // this is a group. It contains a set of group members struct torrent_entry { std::string name; std::set<peer_entry> peers; }; struct dht_immutable_item { dht_immutable_item() : value(0), num_announcers(0) {} // malloced space for the actual value char* value; // this counts the number of IPs we have seen // announcing this item, this is used to determine // popularity if we reach the limit of items to store bloom_filter<128> ips; // the last time we heard about this ptime last_seen; // number of IPs in the bloom filter int num_announcers; // size of malloced space pointed to by value int size; }; struct dht_mutable_item : dht_immutable_item { char sig[256]; int seq; }; struct rsa_key { char bytes[268]; }; inline bool operator<(rsa_key const& lhs, rsa_key const& rhs) { return memcmp(lhs.bytes, rhs.bytes, sizeof(lhs.bytes)) < 0; } inline bool operator<(peer_entry const& lhs, peer_entry const& rhs) { return lhs.addr.address() == rhs.addr.address() ? lhs.addr.port() < rhs.addr.port() : lhs.addr.address() < rhs.addr.address(); } struct null_type {}; class announce_observer : public observer { public: announce_observer(boost::intrusive_ptr<traversal_algorithm> const& algo , udp::endpoint const& ep, node_id const& id) : observer(algo, ep, id) {} void reply(msg const&) { flags |= flag_done; } }; struct count_peers { int& count; count_peers(int& c): count(c) {} void operator()(std::pair<libtorrent::dht::node_id , libtorrent::dht::torrent_entry> const& t) { count += t.second.peers.size(); } }; struct udp_socket_interface { virtual bool send_packet(entry& e, udp::endpoint const& addr, int flags) = 0; }; class TORRENT_EXTRA_EXPORT node_impl : boost::noncopyable { typedef std::map<node_id, torrent_entry> table_t; typedef std::map<node_id, dht_immutable_item> dht_immutable_table_t; typedef std::map<rsa_key, dht_mutable_item> dht_mutable_table_t; public: node_impl(alert_dispatcher* alert_disp, udp_socket_interface* sock , dht_settings const& settings, node_id nid, address const& external_address , dht_observer* observer); virtual ~node_impl() {} void tick(); void refresh(node_id const& id, find_data::nodes_callback const& f); void bootstrap(std::vector<udp::endpoint> const& nodes , find_data::nodes_callback const& f); void add_router_node(udp::endpoint router); void unreachable(udp::endpoint const& ep); void incoming(msg const& m); int num_torrents() const { return m_map.size(); } int num_peers() const { int ret = 0; std::for_each(m_map.begin(), m_map.end(), count_peers(ret)); return ret; } int bucket_size(int bucket); node_id const& nid() const { return m_id; } boost::tuple<int, int> size() const{ return m_table.size(); } size_type num_global_nodes() const { return m_table.num_global_nodes(); } int data_size() const { return int(m_map.size()); } #ifdef TORRENT_DHT_VERBOSE_LOGGING void print_state(std::ostream& os) const { m_table.print_state(os); } #endif void announce(sha1_hash const& info_hash, int listen_port, bool seed , boost::function<void(std::vector<tcp::endpoint> const&)> f); bool verify_token(std::string const& token, char const* info_hash , udp::endpoint const& addr); std::string generate_token(udp::endpoint const& addr, char const* info_hash); // the returned time is the delay until connection_timeout() // should be called again the next time time_duration connection_timeout(); // generates a new secret number used to generate write tokens void new_write_key(); // pings the given node, and adds it to // the routing table if it respons and if the // bucket is not full. void add_node(udp::endpoint node); void replacement_cache(bucket_t& nodes) const { m_table.replacement_cache(nodes); } int branch_factor() const { return m_settings.search_branching; } void add_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.insert(a); } void remove_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.erase(a); } void status(libtorrent::session_status& s); dht_settings const& settings() const { return m_settings; } protected: void lookup_peers(sha1_hash const& info_hash, int prefix, entry& reply , bool noseed, bool scrape) const; bool lookup_torrents(sha1_hash const& target, entry& reply , char* tags) const; dht_settings const& m_settings; private: typedef libtorrent::mutex mutex_t; mutex_t m_mutex; // this list must be destructed after the rpc manager // since it might have references to it std::set<traversal_algorithm*> m_running_requests; void incoming_request(msg const& h, entry& e); node_id m_id; public: routing_table m_table; rpc_manager m_rpc; private: table_t m_map; dht_immutable_table_t m_immutable_table; dht_mutable_table_t m_mutable_table; ptime m_last_tracker_tick; // secret random numbers used to create write tokens int m_secret[2]; alert_dispatcher* m_post_alert; udp_socket_interface* m_sock; }; } } // namespace libtorrent::dht #endif // NODE_HPP <commit_msg>one more uninitialized member<commit_after>/* Copyright (c) 2006, 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. */ #ifndef NODE_HPP #define NODE_HPP #include <algorithm> #include <map> #include <set> #include <libtorrent/config.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/msg.hpp> #include <libtorrent/kademlia/find_data.hpp> #include <libtorrent/io.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/assert.hpp> #include <libtorrent/thread.hpp> #include <libtorrent/bloom_filter.hpp> #include <boost/cstdint.hpp> #include <boost/ref.hpp> #include "libtorrent/socket.hpp" namespace libtorrent { class alert_manager; struct alert_dispatcher; } namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DECLARE_LOG(node); #endif struct traversal_algorithm; struct key_desc_t { char const* name; int type; int size; int flags; enum { // this argument is optional, parsing will not // fail if it's not present optional = 1, // for dictionaries, the following entries refer // to child nodes to this node, up until and including // the next item that has the last_child flag set. // these flags are nestable parse_children = 2, // this is the last item in a child dictionary last_child = 4, // the size argument refers to that the size // has to be divisible by the number, instead // of having that exact size size_divisible = 8 }; }; bool TORRENT_EXTRA_EXPORT verify_message(lazy_entry const* msg, key_desc_t const desc[] , lazy_entry const* ret[], int size , char* error, int error_size); // this is the entry for every peer // the timestamp is there to make it possible // to remove stale peers struct peer_entry { tcp::endpoint addr; ptime added; bool seed; }; // this is a group. It contains a set of group members struct torrent_entry { std::string name; std::set<peer_entry> peers; }; struct dht_immutable_item { dht_immutable_item() : value(0), num_announcers(0), size(0) {} // malloced space for the actual value char* value; // this counts the number of IPs we have seen // announcing this item, this is used to determine // popularity if we reach the limit of items to store bloom_filter<128> ips; // the last time we heard about this ptime last_seen; // number of IPs in the bloom filter int num_announcers; // size of malloced space pointed to by value int size; }; struct dht_mutable_item : dht_immutable_item { char sig[256]; int seq; }; struct rsa_key { char bytes[268]; }; inline bool operator<(rsa_key const& lhs, rsa_key const& rhs) { return memcmp(lhs.bytes, rhs.bytes, sizeof(lhs.bytes)) < 0; } inline bool operator<(peer_entry const& lhs, peer_entry const& rhs) { return lhs.addr.address() == rhs.addr.address() ? lhs.addr.port() < rhs.addr.port() : lhs.addr.address() < rhs.addr.address(); } struct null_type {}; class announce_observer : public observer { public: announce_observer(boost::intrusive_ptr<traversal_algorithm> const& algo , udp::endpoint const& ep, node_id const& id) : observer(algo, ep, id) {} void reply(msg const&) { flags |= flag_done; } }; struct count_peers { int& count; count_peers(int& c): count(c) {} void operator()(std::pair<libtorrent::dht::node_id , libtorrent::dht::torrent_entry> const& t) { count += t.second.peers.size(); } }; struct udp_socket_interface { virtual bool send_packet(entry& e, udp::endpoint const& addr, int flags) = 0; }; class TORRENT_EXTRA_EXPORT node_impl : boost::noncopyable { typedef std::map<node_id, torrent_entry> table_t; typedef std::map<node_id, dht_immutable_item> dht_immutable_table_t; typedef std::map<rsa_key, dht_mutable_item> dht_mutable_table_t; public: node_impl(alert_dispatcher* alert_disp, udp_socket_interface* sock , dht_settings const& settings, node_id nid, address const& external_address , dht_observer* observer); virtual ~node_impl() {} void tick(); void refresh(node_id const& id, find_data::nodes_callback const& f); void bootstrap(std::vector<udp::endpoint> const& nodes , find_data::nodes_callback const& f); void add_router_node(udp::endpoint router); void unreachable(udp::endpoint const& ep); void incoming(msg const& m); int num_torrents() const { return m_map.size(); } int num_peers() const { int ret = 0; std::for_each(m_map.begin(), m_map.end(), count_peers(ret)); return ret; } int bucket_size(int bucket); node_id const& nid() const { return m_id; } boost::tuple<int, int> size() const{ return m_table.size(); } size_type num_global_nodes() const { return m_table.num_global_nodes(); } int data_size() const { return int(m_map.size()); } #ifdef TORRENT_DHT_VERBOSE_LOGGING void print_state(std::ostream& os) const { m_table.print_state(os); } #endif void announce(sha1_hash const& info_hash, int listen_port, bool seed , boost::function<void(std::vector<tcp::endpoint> const&)> f); bool verify_token(std::string const& token, char const* info_hash , udp::endpoint const& addr); std::string generate_token(udp::endpoint const& addr, char const* info_hash); // the returned time is the delay until connection_timeout() // should be called again the next time time_duration connection_timeout(); // generates a new secret number used to generate write tokens void new_write_key(); // pings the given node, and adds it to // the routing table if it respons and if the // bucket is not full. void add_node(udp::endpoint node); void replacement_cache(bucket_t& nodes) const { m_table.replacement_cache(nodes); } int branch_factor() const { return m_settings.search_branching; } void add_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.insert(a); } void remove_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.erase(a); } void status(libtorrent::session_status& s); dht_settings const& settings() const { return m_settings; } protected: void lookup_peers(sha1_hash const& info_hash, int prefix, entry& reply , bool noseed, bool scrape) const; bool lookup_torrents(sha1_hash const& target, entry& reply , char* tags) const; dht_settings const& m_settings; private: typedef libtorrent::mutex mutex_t; mutex_t m_mutex; // this list must be destructed after the rpc manager // since it might have references to it std::set<traversal_algorithm*> m_running_requests; void incoming_request(msg const& h, entry& e); node_id m_id; public: routing_table m_table; rpc_manager m_rpc; private: table_t m_map; dht_immutable_table_t m_immutable_table; dht_mutable_table_t m_mutable_table; ptime m_last_tracker_tick; // secret random numbers used to create write tokens int m_secret[2]; alert_dispatcher* m_post_alert; udp_socket_interface* m_sock; }; } } // namespace libtorrent::dht #endif // NODE_HPP <|endoftext|>
<commit_before>/* Copyright (c) 2006, 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. */ #ifndef NODE_HPP #define NODE_HPP #include <algorithm> #include <map> #include <set> #include <libtorrent/config.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/msg.hpp> #include <libtorrent/kademlia/find_data.hpp> #include <libtorrent/io.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/assert.hpp> #include <libtorrent/thread.hpp> #include <libtorrent/bloom_filter.hpp> #include <boost/cstdint.hpp> #include <boost/ref.hpp> #include "libtorrent/socket.hpp" namespace libtorrent { class alert_manager; struct alert_dispatcher; } namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DECLARE_LOG(node); #endif struct traversal_algorithm; struct key_desc_t { char const* name; int type; int size; int flags; enum { // this argument is optional, parsing will not // fail if it's not present optional = 1, // for dictionaries, the following entries refer // to child nodes to this node, up until and including // the next item that has the last_child flag set. // these flags are nestable parse_children = 2, // this is the last item in a child dictionary last_child = 4, // the size argument refers to that the size // has to be divisible by the number, instead // of having that exact size size_divisible = 8 }; }; bool TORRENT_EXTRA_EXPORT verify_message(lazy_entry const* msg, key_desc_t const desc[] , lazy_entry const* ret[], int size , char* error, int error_size); // this is the entry for every peer // the timestamp is there to make it possible // to remove stale peers struct peer_entry { tcp::endpoint addr; ptime added; bool seed; }; // this is a group. It contains a set of group members struct torrent_entry { std::string name; std::set<peer_entry> peers; }; struct dht_immutable_item { dht_immutable_item() : value(0), num_announcers(0) {} // malloced space for the actual value char* value; // this counts the number of IPs we have seen // announcing this item, this is used to determine // popularity if we reach the limit of items to store bloom_filter<128> ips; // the last time we heard about this ptime last_seen; // number of IPs in the bloom filter int num_announcers; // size of malloced space pointed to by value int size; }; struct dht_mutable_item : dht_immutable_item { char sig[256]; int seq; }; struct rsa_key { char bytes[268]; }; inline bool operator<(rsa_key const& lhs, rsa_key const& rhs) { return memcmp(lhs.bytes, rhs.bytes, sizeof(lhs.bytes)) < 0; } inline bool operator<(peer_entry const& lhs, peer_entry const& rhs) { return lhs.addr.address() == rhs.addr.address() ? lhs.addr.port() < rhs.addr.port() : lhs.addr.address() < rhs.addr.address(); } struct null_type {}; class announce_observer : public observer { public: announce_observer(boost::intrusive_ptr<traversal_algorithm> const& algo , udp::endpoint const& ep, node_id const& id) : observer(algo, ep, id) {} void reply(msg const&) { flags |= flag_done; } }; struct count_peers { int& count; count_peers(int& c): count(c) {} void operator()(std::pair<libtorrent::dht::node_id , libtorrent::dht::torrent_entry> const& t) { count += t.second.peers.size(); } }; struct udp_socket_interface { virtual bool send_packet(entry& e, udp::endpoint const& addr, int flags) = 0; }; class TORRENT_EXTRA_EXPORT node_impl : boost::noncopyable { typedef std::map<node_id, torrent_entry> table_t; typedef std::map<node_id, dht_immutable_item> dht_immutable_table_t; typedef std::map<rsa_key, dht_mutable_item> dht_mutable_table_t; public: node_impl(alert_dispatcher* alert_disp, udp_socket_interface* sock , dht_settings const& settings, node_id nid, address const& external_address , dht_observer* observer); virtual ~node_impl() {} void tick(); void refresh(node_id const& id, find_data::nodes_callback const& f); void bootstrap(std::vector<udp::endpoint> const& nodes , find_data::nodes_callback const& f); void add_router_node(udp::endpoint router); void unreachable(udp::endpoint const& ep); void incoming(msg const& m); int num_torrents() const { return m_map.size(); } int num_peers() const { int ret = 0; std::for_each(m_map.begin(), m_map.end(), count_peers(ret)); return ret; } int bucket_size(int bucket); node_id const& nid() const { return m_id; } boost::tuple<int, int> size() const{ return m_table.size(); } size_type num_global_nodes() const { return m_table.num_global_nodes(); } int data_size() const { return int(m_map.size()); } #ifdef TORRENT_DHT_VERBOSE_LOGGING void print_state(std::ostream& os) const { m_table.print_state(os); } #endif void announce(sha1_hash const& info_hash, int listen_port, bool seed , boost::function<void(std::vector<tcp::endpoint> const&)> f); bool verify_token(std::string const& token, char const* info_hash , udp::endpoint const& addr); std::string generate_token(udp::endpoint const& addr, char const* info_hash); // the returned time is the delay until connection_timeout() // should be called again the next time time_duration connection_timeout(); // generates a new secret number used to generate write tokens void new_write_key(); // pings the given node, and adds it to // the routing table if it respons and if the // bucket is not full. void add_node(udp::endpoint node); void replacement_cache(bucket_t& nodes) const { m_table.replacement_cache(nodes); } int branch_factor() const { return m_settings.search_branching; } void add_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.insert(a); } void remove_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.erase(a); } void status(libtorrent::session_status& s); dht_settings const& settings() const { return m_settings; } protected: void lookup_peers(sha1_hash const& info_hash, int prefix, entry& reply , bool noseed, bool scrape) const; bool lookup_torrents(sha1_hash const& target, entry& reply , char* tags) const; dht_settings const& m_settings; private: typedef libtorrent::mutex mutex_t; mutex_t m_mutex; // this list must be destructed after the rpc manager // since it might have references to it std::set<traversal_algorithm*> m_running_requests; void incoming_request(msg const& h, entry& e); node_id m_id; public: routing_table m_table; rpc_manager m_rpc; private: table_t m_map; dht_immutable_table_t m_immutable_table; dht_mutable_table_t m_mutable_table; ptime m_last_tracker_tick; // secret random numbers used to create write tokens int m_secret[2]; alert_dispatcher* m_post_alert; udp_socket_interface* m_sock; }; } } // namespace libtorrent::dht #endif // NODE_HPP <commit_msg>one more uninitialized member<commit_after>/* Copyright (c) 2006, 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. */ #ifndef NODE_HPP #define NODE_HPP #include <algorithm> #include <map> #include <set> #include <libtorrent/config.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/msg.hpp> #include <libtorrent/kademlia/find_data.hpp> #include <libtorrent/io.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/assert.hpp> #include <libtorrent/thread.hpp> #include <libtorrent/bloom_filter.hpp> #include <boost/cstdint.hpp> #include <boost/ref.hpp> #include "libtorrent/socket.hpp" namespace libtorrent { class alert_manager; struct alert_dispatcher; } namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DECLARE_LOG(node); #endif struct traversal_algorithm; struct key_desc_t { char const* name; int type; int size; int flags; enum { // this argument is optional, parsing will not // fail if it's not present optional = 1, // for dictionaries, the following entries refer // to child nodes to this node, up until and including // the next item that has the last_child flag set. // these flags are nestable parse_children = 2, // this is the last item in a child dictionary last_child = 4, // the size argument refers to that the size // has to be divisible by the number, instead // of having that exact size size_divisible = 8 }; }; bool TORRENT_EXTRA_EXPORT verify_message(lazy_entry const* msg, key_desc_t const desc[] , lazy_entry const* ret[], int size , char* error, int error_size); // this is the entry for every peer // the timestamp is there to make it possible // to remove stale peers struct peer_entry { tcp::endpoint addr; ptime added; bool seed; }; // this is a group. It contains a set of group members struct torrent_entry { std::string name; std::set<peer_entry> peers; }; struct dht_immutable_item { dht_immutable_item() : value(0), num_announcers(0), size(0) {} // malloced space for the actual value char* value; // this counts the number of IPs we have seen // announcing this item, this is used to determine // popularity if we reach the limit of items to store bloom_filter<128> ips; // the last time we heard about this ptime last_seen; // number of IPs in the bloom filter int num_announcers; // size of malloced space pointed to by value int size; }; struct dht_mutable_item : dht_immutable_item { char sig[256]; int seq; }; struct rsa_key { char bytes[268]; }; inline bool operator<(rsa_key const& lhs, rsa_key const& rhs) { return memcmp(lhs.bytes, rhs.bytes, sizeof(lhs.bytes)) < 0; } inline bool operator<(peer_entry const& lhs, peer_entry const& rhs) { return lhs.addr.address() == rhs.addr.address() ? lhs.addr.port() < rhs.addr.port() : lhs.addr.address() < rhs.addr.address(); } struct null_type {}; class announce_observer : public observer { public: announce_observer(boost::intrusive_ptr<traversal_algorithm> const& algo , udp::endpoint const& ep, node_id const& id) : observer(algo, ep, id) {} void reply(msg const&) { flags |= flag_done; } }; struct count_peers { int& count; count_peers(int& c): count(c) {} void operator()(std::pair<libtorrent::dht::node_id , libtorrent::dht::torrent_entry> const& t) { count += t.second.peers.size(); } }; struct udp_socket_interface { virtual bool send_packet(entry& e, udp::endpoint const& addr, int flags) = 0; }; class TORRENT_EXTRA_EXPORT node_impl : boost::noncopyable { typedef std::map<node_id, torrent_entry> table_t; typedef std::map<node_id, dht_immutable_item> dht_immutable_table_t; typedef std::map<rsa_key, dht_mutable_item> dht_mutable_table_t; public: node_impl(alert_dispatcher* alert_disp, udp_socket_interface* sock , dht_settings const& settings, node_id nid, address const& external_address , dht_observer* observer); virtual ~node_impl() {} void tick(); void refresh(node_id const& id, find_data::nodes_callback const& f); void bootstrap(std::vector<udp::endpoint> const& nodes , find_data::nodes_callback const& f); void add_router_node(udp::endpoint router); void unreachable(udp::endpoint const& ep); void incoming(msg const& m); int num_torrents() const { return m_map.size(); } int num_peers() const { int ret = 0; std::for_each(m_map.begin(), m_map.end(), count_peers(ret)); return ret; } int bucket_size(int bucket); node_id const& nid() const { return m_id; } boost::tuple<int, int> size() const{ return m_table.size(); } size_type num_global_nodes() const { return m_table.num_global_nodes(); } int data_size() const { return int(m_map.size()); } #ifdef TORRENT_DHT_VERBOSE_LOGGING void print_state(std::ostream& os) const { m_table.print_state(os); } #endif void announce(sha1_hash const& info_hash, int listen_port, bool seed , boost::function<void(std::vector<tcp::endpoint> const&)> f); bool verify_token(std::string const& token, char const* info_hash , udp::endpoint const& addr); std::string generate_token(udp::endpoint const& addr, char const* info_hash); // the returned time is the delay until connection_timeout() // should be called again the next time time_duration connection_timeout(); // generates a new secret number used to generate write tokens void new_write_key(); // pings the given node, and adds it to // the routing table if it respons and if the // bucket is not full. void add_node(udp::endpoint node); void replacement_cache(bucket_t& nodes) const { m_table.replacement_cache(nodes); } int branch_factor() const { return m_settings.search_branching; } void add_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.insert(a); } void remove_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.erase(a); } void status(libtorrent::session_status& s); dht_settings const& settings() const { return m_settings; } protected: void lookup_peers(sha1_hash const& info_hash, int prefix, entry& reply , bool noseed, bool scrape) const; bool lookup_torrents(sha1_hash const& target, entry& reply , char* tags) const; dht_settings const& m_settings; private: typedef libtorrent::mutex mutex_t; mutex_t m_mutex; // this list must be destructed after the rpc manager // since it might have references to it std::set<traversal_algorithm*> m_running_requests; void incoming_request(msg const& h, entry& e); node_id m_id; public: routing_table m_table; rpc_manager m_rpc; private: table_t m_map; dht_immutable_table_t m_immutable_table; dht_mutable_table_t m_mutable_table; ptime m_last_tracker_tick; // secret random numbers used to create write tokens int m_secret[2]; alert_dispatcher* m_post_alert; udp_socket_interface* m_sock; }; } } // namespace libtorrent::dht #endif // NODE_HPP <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #ifndef _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_ #define _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Execution/Exceptions.h" #include "BadFormatException.h" namespace Stroika { namespace Foundation { namespace DataExchangeFormat { /* ******************************************************************************** ******************* ObjectVariantMapper::StructureFieldInfo ******************** ******************************************************************************** */ inline ObjectVariantMapper::StructureFieldInfo::StructureFieldInfo (size_t fieldOffset, type_index typeInfo, const String& serializedFieldName) : fOffset (fieldOffset) , fTypeInfo (typeInfo) , fSerializedFieldName (serializedFieldName) { } /* ******************************************************************************** ******************************** ObjectVariantMapper *************************** ******************************************************************************** */ inline Set<ObjectVariantMapper::TypeMappingDetails> ObjectVariantMapper::GetTypeMappingRegistry () const { return fSerializers_; } inline void ObjectVariantMapper::SetTypeMappingRegistry (const Set<TypeMappingDetails>& s) { fSerializers_ = s; } template <typename CLASS> inline void ObjectVariantMapper::RegisterClass (const Sequence<StructureFieldInfo>& fieldDescriptions) { RegisterTypeMapper (TypeMappingDetails (typeid (CLASS), sizeof (CLASS), fieldDescriptions)); } template <typename CLASS> inline void ObjectVariantMapper::ToObject (const Memory::VariantValue& v, CLASS* into) const { ToObject (typeid (CLASS), v, reinterpret_cast<Byte*> (into)); } template <typename CLASS> inline CLASS ObjectVariantMapper::ToObject (const Memory::VariantValue& v) const { CLASS tmp; ToObject (v, &tmp); return tmp; } template <typename CLASS> inline VariantValue ObjectVariantMapper::FromObject (const CLASS& from) const { return FromObject (typeid (CLASS), reinterpret_cast<const Byte*> (&from)); } template <typename T, size_t SZ> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Array () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const T* actualMember = reinterpret_cast<const T*> (fromObjOfTypeT); for (auto i = actualMember; i < actualMember + SZ; ++i) { s.Append (mapper->FromObject<T> (*i)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<T>> (); T* actualMember = reinterpret_cast<T*> (intoObjOfTypeT); if (s.size () > SZ) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } size_t idx = 0; for (auto i : s) { actualMember[idx++] = mapper->ToObject<T> (i); } while (idx < SZ) { actualMember[idx++] = T (); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper); } template <typename T> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Sequence () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const Sequence<T>* actualMember = reinterpret_cast<const Sequence<T>*> (fromObjOfTypeT); for (auto i : *actualMember) { s.Append (mapper->FromObject<T> (i)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<T>> (); Sequence<T>* actualInto = reinterpret_cast<Sequence<T>*> (intoObjOfTypeT); actualInto->clear (); for (auto i : s) { actualInto->Append (mapper->ToObject<T> (i)); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper); } template <typename KEY_TYPE, typename VALUE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Mapping () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const Mapping<KEY_TYPE, VALUE_TYPE>* actualMember = reinterpret_cast<const Mapping<KEY_TYPE, VALUE_TYPE>*> (fromObjOfTypeT); for (auto i : *actualMember) { Sequence<VariantValue> encodedPair; encodedPair.Append (mapper->FromObject<KEY_TYPE> (i.fKey)); encodedPair.Append (mapper->FromObject<VALUE_TYPE> (i.fValue)); s.Append (VariantValue (encodedPair)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<VariantValue>> (); Mapping<KEY_TYPE, VALUE_TYPE>* actualInto = reinterpret_cast<Mapping<KEY_TYPE, VALUE_TYPE>*> (intoObjOfTypeT); actualInto->clear (); for (VariantValue encodedPair : s) { Sequence<VariantValue> p = p.As<Sequence<VariantValue>> (); if (p.size () != 2) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } actualInto->Add (mapper->ToObject<KEY_TYPE> (p[0]), mapper->ToObject<VALUE_TYPE> (p[1])); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Mapping<KEY_TYPE, VALUE_TYPE>), toVariantMapper, fromVariantMapper); } template <typename KEY_TYPE, typename VALUE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_MappingWithStringishKey () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { const Mapping<KEY_TYPE, VALUE_TYPE>* actualMember = reinterpret_cast<const Mapping<KEY_TYPE, VALUE_TYPE>*> (fromObjOfTypeT); Mapping<String, VariantValue> m; for (Common::KeyValuePair<KEY_TYPE, VALUE_TYPE> i : *actualMember) { m.Add (mapper->FromObject<KEY_TYPE> (i.fKey).template As<String> (), mapper->FromObject<VALUE_TYPE> (i.fValue)); } return VariantValue (m); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); Mapping<KEY_TYPE, VALUE_TYPE>* actualInto = reinterpret_cast<Mapping<KEY_TYPE, VALUE_TYPE>*> (intoObjOfTypeT); actualInto->clear (); for (Common::KeyValuePair<String, VariantValue> p : m) { actualInto->Add (mapper->ToObject<KEY_TYPE> (p.fKey), mapper->ToObject<VALUE_TYPE> (p.fValue)); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Mapping<KEY_TYPE, VALUE_TYPE>), toVariantMapper, fromVariantMapper); } template <typename RANGE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Range () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { typedef typename RANGE_TYPE::ElementType ElementType; Mapping<String, VariantValue> m; const RANGE_TYPE* actualMember = reinterpret_cast<const RANGE_TYPE*> (fromObjOfTypeT); m.Add (L"Begin", mapper->FromObject<ElementType> (actualMember->begin ())); m.Add (L"End", mapper->FromObject<ElementType> (actualMember->end ())); return VariantValue (m); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { typedef typename RANGE_TYPE::ElementType ElementType; Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); RANGE_TYPE* actualInto = reinterpret_cast<RANGE_TYPE*> (intoObjOfTypeT); if (m.size () != 2) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } if (not m.ContainsKey (L"Begin") or not m.ContainsKey (L"End")) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } ElementType from = mapper->ToObject<ElementType> (*m.Lookup (L"Begin")); ElementType to = mapper->ToObject<ElementType> (*m.Lookup (L"End")); if (not (RANGE_TYPE::TraitsType::kMin <= from and from < RANGE_TYPE::TraitsType::kMax)) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } if (not (RANGE_TYPE::TraitsType::kMin <= to and to < RANGE_TYPE::TraitsType::kMax)) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } * actualInto = RANGE_TYPE (from, to); }; return ObjectVariantMapper::TypeMappingDetails (typeid (RANGE_TYPE), toVariantMapper, fromVariantMapper); } template <typename ENUM_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Enumeration () { /* * Note: we cannot get the enumeration print names - in general. That would be nicer to read, but we dont have * the data, and this is simple and efficient. */ Require (std::is_enum<ENUM_TYPE>::value); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type typedef typename std::underlying_type<ENUM_TYPE>::type SerializeAsType; #else typedef long long SerializeAsType; #endif auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { const ENUM_TYPE* actualMember = reinterpret_cast<const ENUM_TYPE*> (fromObjOfTypeT); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type Assert (sizeof (SerializeAsType) == sizeof (ENUM_TYPE)); #endif Assert (static_cast<ENUM_TYPE> (static_cast<SerializeAsType> (*actualMember)) == *actualMember); // no round-trip loss return VariantValue (static_cast<SerializeAsType> (*actualMember)); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { ENUM_TYPE* actualInto = reinterpret_cast<ENUM_TYPE*> (intoObjOfTypeT); * actualInto = static_cast<ENUM_TYPE> (d.As<SerializeAsType> ()); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type Assert (sizeof (SerializeAsType) == sizeof (ENUM_TYPE)); #endif Assert (static_cast<SerializeAsType> (*actualInto) == d.As<SerializeAsType> ()); // no round-trip loss if (not (ENUM_TYPE::eSTART <= *actualInto and * actualInto <= ENUM_TYPE::eEND)) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (ENUM_TYPE), toVariantMapper, fromVariantMapper); } #if 0 template <typename T> inline ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Sequence<T>> () { return mkSerializerInfoFor_Sequence_<T> (); } #endif } } } #endif /*_Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_*/ <commit_msg>Fixed DataExchangeFormat/ObjectVariantMapper code to use CheckedConverter_Range<RANGE_TYPE> () instead of its own manual checking<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #ifndef _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_ #define _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Execution/Exceptions.h" #include "BadFormatException.h" #include "CheckedConverter.h" namespace Stroika { namespace Foundation { namespace DataExchangeFormat { /* ******************************************************************************** ******************* ObjectVariantMapper::StructureFieldInfo ******************** ******************************************************************************** */ inline ObjectVariantMapper::StructureFieldInfo::StructureFieldInfo (size_t fieldOffset, type_index typeInfo, const String& serializedFieldName) : fOffset (fieldOffset) , fTypeInfo (typeInfo) , fSerializedFieldName (serializedFieldName) { } /* ******************************************************************************** ******************************** ObjectVariantMapper *************************** ******************************************************************************** */ inline Set<ObjectVariantMapper::TypeMappingDetails> ObjectVariantMapper::GetTypeMappingRegistry () const { return fSerializers_; } inline void ObjectVariantMapper::SetTypeMappingRegistry (const Set<TypeMappingDetails>& s) { fSerializers_ = s; } template <typename CLASS> inline void ObjectVariantMapper::RegisterClass (const Sequence<StructureFieldInfo>& fieldDescriptions) { RegisterTypeMapper (TypeMappingDetails (typeid (CLASS), sizeof (CLASS), fieldDescriptions)); } template <typename CLASS> inline void ObjectVariantMapper::ToObject (const Memory::VariantValue& v, CLASS* into) const { ToObject (typeid (CLASS), v, reinterpret_cast<Byte*> (into)); } template <typename CLASS> inline CLASS ObjectVariantMapper::ToObject (const Memory::VariantValue& v) const { CLASS tmp; ToObject (v, &tmp); return tmp; } template <typename CLASS> inline VariantValue ObjectVariantMapper::FromObject (const CLASS& from) const { return FromObject (typeid (CLASS), reinterpret_cast<const Byte*> (&from)); } template <typename T, size_t SZ> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Array () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const T* actualMember = reinterpret_cast<const T*> (fromObjOfTypeT); for (auto i = actualMember; i < actualMember + SZ; ++i) { s.Append (mapper->FromObject<T> (*i)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<T>> (); T* actualMember = reinterpret_cast<T*> (intoObjOfTypeT); if (s.size () > SZ) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } size_t idx = 0; for (auto i : s) { actualMember[idx++] = mapper->ToObject<T> (i); } while (idx < SZ) { actualMember[idx++] = T (); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper); } template <typename T> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Sequence () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const Sequence<T>* actualMember = reinterpret_cast<const Sequence<T>*> (fromObjOfTypeT); for (auto i : *actualMember) { s.Append (mapper->FromObject<T> (i)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<T>> (); Sequence<T>* actualInto = reinterpret_cast<Sequence<T>*> (intoObjOfTypeT); actualInto->clear (); for (auto i : s) { actualInto->Append (mapper->ToObject<T> (i)); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper); } template <typename KEY_TYPE, typename VALUE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Mapping () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const Mapping<KEY_TYPE, VALUE_TYPE>* actualMember = reinterpret_cast<const Mapping<KEY_TYPE, VALUE_TYPE>*> (fromObjOfTypeT); for (auto i : *actualMember) { Sequence<VariantValue> encodedPair; encodedPair.Append (mapper->FromObject<KEY_TYPE> (i.fKey)); encodedPair.Append (mapper->FromObject<VALUE_TYPE> (i.fValue)); s.Append (VariantValue (encodedPair)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<VariantValue>> (); Mapping<KEY_TYPE, VALUE_TYPE>* actualInto = reinterpret_cast<Mapping<KEY_TYPE, VALUE_TYPE>*> (intoObjOfTypeT); actualInto->clear (); for (VariantValue encodedPair : s) { Sequence<VariantValue> p = p.As<Sequence<VariantValue>> (); if (p.size () != 2) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } actualInto->Add (mapper->ToObject<KEY_TYPE> (p[0]), mapper->ToObject<VALUE_TYPE> (p[1])); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Mapping<KEY_TYPE, VALUE_TYPE>), toVariantMapper, fromVariantMapper); } template <typename KEY_TYPE, typename VALUE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_MappingWithStringishKey () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { const Mapping<KEY_TYPE, VALUE_TYPE>* actualMember = reinterpret_cast<const Mapping<KEY_TYPE, VALUE_TYPE>*> (fromObjOfTypeT); Mapping<String, VariantValue> m; for (Common::KeyValuePair<KEY_TYPE, VALUE_TYPE> i : *actualMember) { m.Add (mapper->FromObject<KEY_TYPE> (i.fKey).template As<String> (), mapper->FromObject<VALUE_TYPE> (i.fValue)); } return VariantValue (m); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); Mapping<KEY_TYPE, VALUE_TYPE>* actualInto = reinterpret_cast<Mapping<KEY_TYPE, VALUE_TYPE>*> (intoObjOfTypeT); actualInto->clear (); for (Common::KeyValuePair<String, VariantValue> p : m) { actualInto->Add (mapper->ToObject<KEY_TYPE> (p.fKey), mapper->ToObject<VALUE_TYPE> (p.fValue)); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Mapping<KEY_TYPE, VALUE_TYPE>), toVariantMapper, fromVariantMapper); } template <typename RANGE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Range () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { typedef typename RANGE_TYPE::ElementType ElementType; Mapping<String, VariantValue> m; const RANGE_TYPE* actualMember = reinterpret_cast<const RANGE_TYPE*> (fromObjOfTypeT); m.Add (L"Begin", mapper->FromObject<ElementType> (actualMember->begin ())); m.Add (L"End", mapper->FromObject<ElementType> (actualMember->end ())); return VariantValue (m); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { typedef typename RANGE_TYPE::ElementType ElementType; Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); RANGE_TYPE* actualInto = reinterpret_cast<RANGE_TYPE*> (intoObjOfTypeT); if (m.size () != 2) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } if (not m.ContainsKey (L"Begin") or not m.ContainsKey (L"End")) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } ElementType from = mapper->ToObject<ElementType> (*m.Lookup (L"Begin")); ElementType to = mapper->ToObject<ElementType> (*m.Lookup (L"End")); * actualInto = CheckedConverter_Range<RANGE_TYPE> (from, to); }; return ObjectVariantMapper::TypeMappingDetails (typeid (RANGE_TYPE), toVariantMapper, fromVariantMapper); } template <typename ENUM_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Enumeration () { /* * Note: we cannot get the enumeration print names - in general. That would be nicer to read, but we dont have * the data, and this is simple and efficient. */ Require (std::is_enum<ENUM_TYPE>::value); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type typedef typename std::underlying_type<ENUM_TYPE>::type SerializeAsType; #else typedef long long SerializeAsType; #endif auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { const ENUM_TYPE* actualMember = reinterpret_cast<const ENUM_TYPE*> (fromObjOfTypeT); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type Assert (sizeof (SerializeAsType) == sizeof (ENUM_TYPE)); #endif Assert (static_cast<ENUM_TYPE> (static_cast<SerializeAsType> (*actualMember)) == *actualMember); // no round-trip loss return VariantValue (static_cast<SerializeAsType> (*actualMember)); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { ENUM_TYPE* actualInto = reinterpret_cast<ENUM_TYPE*> (intoObjOfTypeT); * actualInto = static_cast<ENUM_TYPE> (d.As<SerializeAsType> ()); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type Assert (sizeof (SerializeAsType) == sizeof (ENUM_TYPE)); #endif Assert (static_cast<SerializeAsType> (*actualInto) == d.As<SerializeAsType> ()); // no round-trip loss if (not (ENUM_TYPE::eSTART <= *actualInto and * actualInto <= ENUM_TYPE::eEND)) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (ENUM_TYPE), toVariantMapper, fromVariantMapper); } #if 0 template <typename T> inline ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Sequence<T>> () { return mkSerializerInfoFor_Sequence_<T> (); } #endif } } } #endif /*_Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_*/ <|endoftext|>
<commit_before>#include"all_defines.hpp" #include"symbols.hpp" #include"mutexes.hpp" #include<boost/noncopyable.hpp> #include<string> #include<map> void Symbol::copy_value_to(ValueHolderRef& p) { {AppLock l(m); /*Unfortunately the entire cloning has to be done while we have the lock. This is because a Symbol::set_value() might invalidate the pointer from under us if we didn't do the entire cloning locked. Other alternatives exist: we can use a locked reference counting scheme, or use some sort of deferred deallocation. */ value->clone(p); } } void Symbol::copy_value_to_and_add_notify(ValueHolderRef& p, Process* R) { {AppLock l(m); value->clone(p); /*check for dead processes in notification list*/ size_t j = 0; for(size_t i = 0; i < notification_list.size(); ++i) { if(!notification_list[i]->is_dead()) { if(i != j) { notification_list[j] = notification_list[i]; } ++j; } } notification_list.resize(j + 1); notification_list[j] = R; } } void Symbol::set_value(Object::ref o) { ValueHolderRef tmp; ValueHolder::copy_object(tmp, o); {AppLock l(m); value.swap(tmp); size_t j = 0; for(size_t i = 0; i < notification_list.size(); ++i) { if(!notification_list[i]->is_dead()) { if(i != j) { notification_list[j] = notification_list[i]; } ++j; notification_list[j]->notify_global_change(this); } } notification_list.resize(j); } } typedef std::map<std::string, Symbol*> maptype; Symbol* SymbolsTable::lookup(std::string x) { {AppLock l(m); Symbol*& s = tb[x]; if(s) return s; s = new Symbol(x); return s; } } void SymbolsTable::traverse_symbols(SymbolsTableTraverser* stt) const { for(maptype::const_iterator it = tb.begin(); it != tb.end(); ++it) { stt->traverse(it->second); } } class SymbolDeletor : public SymbolsTableTraverser { public: virtual void traverse(Symbol* s) { delete s; } }; SymbolsTable::~SymbolsTable() { /*go through the table and delete each symbol*/ SymbolDeletor sd; traverse_symbols(&sd); } <commit_msg>src/symbols.cpp: Added missing include for processes.hpp<commit_after>#include"all_defines.hpp" #include"symbols.hpp" #include"processes.hpp" #include"mutexes.hpp" #include<boost/noncopyable.hpp> #include<string> #include<map> void Symbol::copy_value_to(ValueHolderRef& p) { {AppLock l(m); /*Unfortunately the entire cloning has to be done while we have the lock. This is because a Symbol::set_value() might invalidate the pointer from under us if we didn't do the entire cloning locked. Other alternatives exist: we can use a locked reference counting scheme, or use some sort of deferred deallocation. */ value->clone(p); } } void Symbol::copy_value_to_and_add_notify(ValueHolderRef& p, Process* R) { {AppLock l(m); value->clone(p); /*check for dead processes in notification list*/ size_t j = 0; for(size_t i = 0; i < notification_list.size(); ++i) { if(!notification_list[i]->is_dead()) { if(i != j) { notification_list[j] = notification_list[i]; } ++j; } } notification_list.resize(j + 1); notification_list[j] = R; } } void Symbol::set_value(Object::ref o) { ValueHolderRef tmp; ValueHolder::copy_object(tmp, o); {AppLock l(m); value.swap(tmp); size_t j = 0; for(size_t i = 0; i < notification_list.size(); ++i) { if(!notification_list[i]->is_dead()) { if(i != j) { notification_list[j] = notification_list[i]; } ++j; notification_list[j]->notify_global_change(this); } } notification_list.resize(j); } } typedef std::map<std::string, Symbol*> maptype; Symbol* SymbolsTable::lookup(std::string x) { {AppLock l(m); Symbol*& s = tb[x]; if(s) return s; s = new Symbol(x); return s; } } void SymbolsTable::traverse_symbols(SymbolsTableTraverser* stt) const { for(maptype::const_iterator it = tb.begin(); it != tb.end(); ++it) { stt->traverse(it->second); } } class SymbolDeletor : public SymbolsTableTraverser { public: virtual void traverse(Symbol* s) { delete s; } }; SymbolsTable::~SymbolsTable() { /*go through the table and delete each symbol*/ SymbolDeletor sd; traverse_symbols(&sd); } <|endoftext|>
<commit_before>#include "cc_music_locate.hh" #include "cc_music_io.hh" #include "cc_music_edit.hh" #include <iostream> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; Vec4i locateSymbolsX(Mat, Vec4i); vector<Vec4i> locateSheetLines(Mat image){ vector<Vec4i> lines; Mat temp; Mat kernel = (Mat_<float>(3,3) << 0, -1, 0, 0, 3, 0, 0, -1, 0); filter2D(image, temp, image.depth(), kernel); image = temp; polarize(image, 128); int threshold = image.cols / 10; int minLen = image.cols / 2; int maxGap = 10; HoughLinesP(image, lines, 1, CV_PI/180, threshold, minLen, maxGap); auto cmp = [](const Vec4i& l, const Vec4i& r){ return l[1]<r[1]; }; sort(lines.begin(), lines.end(), cmp); return lines; } vector<Vec4i> locateFrames(vector<Vec4i> lines){ vector<Vec4i> mid, res; size_t i,j; int min_x, max_x, min_y, max_y; for(i = 0; i<lines.size(); i++){ if (i==0){ mid.push_back(lines[i]); } else { if (lines[i][1]!=lines[i-1][1]+1) mid.push_back(lines[i]); } } if (mid.size()%5!=0){ cout << "Number does not match." << endl; cout << "Found: " << mid.size() << endl; return vector<Vec4i>(); } for (i=0; i<mid.size(); i++) if (i%5 == 0){ min_x = mid[i][0]; min_y = mid[i][1]; max_x = mid[i][2]; max_y = mid[i][3]; } else { if (min_x > mid[i][0]) min_x = mid[i][0]; if (min_y > mid[i][1]) min_y = mid[i][1]; if (max_x < mid[i][2]) max_x = mid[i][2]; if (max_y < mid[i][3]) max_y = mid[i][3]; if (i%5 == 4){ int space = (max_y - min_y)/2; res.push_back(Vec4i(min_x, min_y - space, max_x + 1, max_y + space)); } } return res; } vector<Vec4i> locateSymbols(Mat image, Vec4i frame){ vector<Vec4i> res, resx; vector<int> weight; int i,j; int x1 = frame[0]; int y1 = frame[1]; int x2 = frame[2]; int y2 = frame[3]; weight.resize(x2 - x1 + 1, 0); for (i=y1; i<=y2; i++){ uchar* row = image.ptr<uchar>(i); for (j=x1; j<=x2; j++){ if (row[j] == 255) weight[j-x1]++; } } bool streak = false; int xa = 0; for (j=x1; j<=x2; j++){ int a = weight[j-x1]; if (a != 0 && !streak){ xa = j; streak = true; } if (a == 0 && streak){ streak = false; resx.push_back(Vec4i(xa, y1, j, y2)); } } for (Vec4i v : resx){ vector<Vec4i> r = locateSymbolsX(image, v); res.insert(res.end(), r.begin(), r.end()); } return res; } Vec4i locateSymbolsX(Mat image, Vec4i frame){ vector<Vec4i> res; vector<int> weight; int i,j; int x1 = frame[0]; int y1 = frame[1]; int x2 = frame[2]; int y2 = frame[3]; weight.resize(y2 - y1 + 1, 0); for (i=y1; i<=y2; i++){ uchar* row = image.ptr<uchar>(i); for (j=x1; j<=x2; j++){ if (row[j] == 255) weight[i-y1]++; } } bool streak = false; int ya = 0; for (j=y1; j<=y2; j++){ int a = weight[j-y1]; if (a != 0 && !streak){ ya = j; streak = true; } if (a == 0 && streak){ res.push_back(Vec4i(x1, ya, x2, j)); } } return res; } <commit_msg>Modify symbol locate<commit_after>#include "cc_music_locate.hh" #include "cc_music_io.hh" #include "cc_music_edit.hh" #include <iostream> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; vector<Vec4i> locateSymbolsX(Mat, Vec4i); vector<Vec4i> locateSheetLines(Mat image){ vector<Vec4i> lines; Mat temp; Mat kernel = (Mat_<float>(3,3) << 0, -1, 0, 0, 3, 0, 0, -1, 0); filter2D(image, temp, image.depth(), kernel); image = temp; polarize(image, 128); int threshold = image.cols / 10; int minLen = image.cols / 2; int maxGap = 10; HoughLinesP(image, lines, 1, CV_PI/180, threshold, minLen, maxGap); auto cmp = [](const Vec4i& l, const Vec4i& r){ return l[1]<r[1]; }; sort(lines.begin(), lines.end(), cmp); return lines; } vector<Vec4i> locateFrames(vector<Vec4i> lines){ vector<Vec4i> mid, res; size_t i,j; int min_x, max_x, min_y, max_y; for(i = 0; i<lines.size(); i++){ if (i==0){ mid.push_back(lines[i]); } else { if (lines[i][1]!=lines[i-1][1]+1) mid.push_back(lines[i]); } } if (mid.size()%5!=0){ cout << "Number does not match." << endl; cout << "Found: " << mid.size() << endl; return vector<Vec4i>(); } for (i=0; i<mid.size(); i++) if (i%5 == 0){ min_x = mid[i][0]; min_y = mid[i][1]; max_x = mid[i][2]; max_y = mid[i][3]; } else { if (min_x > mid[i][0]) min_x = mid[i][0]; if (min_y > mid[i][1]) min_y = mid[i][1]; if (max_x < mid[i][2]) max_x = mid[i][2]; if (max_y < mid[i][3]) max_y = mid[i][3]; if (i%5 == 4){ int space = (max_y - min_y)/2; res.push_back(Vec4i(min_x, min_y - space, max_x + 1, max_y + space)); } } return res; } vector<Vec4i> locateSymbols(Mat image, Vec4i frame){ vector<Vec4i> res, resx; vector<int> weight; int i,j; int x1 = frame[0]; int y1 = frame[1]; int x2 = frame[2]; int y2 = frame[3]; weight.resize(x2 - x1 + 1, 0); for (i=y1; i<=y2; i++){ uchar* row = image.ptr<uchar>(i); for (j=x1; j<=x2; j++){ if (row[j] == 255) weight[j-x1]++; } } bool streak = false; int xa = 0; for (j=x1; j<=x2; j++){ int a = weight[j-x1]; if (a != 0 && !streak){ xa = j; streak = true; } if (a == 0 && streak){ streak = false; resx.push_back(Vec4i(xa, y1, j, y2)); } } for (Vec4i v : resx){ vector<Vec4i> r = locateSymbolsX(image, v); res.insert(res.end(), r.begin(), r.end()); } return res; } vector<Vec4i> locateSymbolsX(Mat image, Vec4i frame){ vector<Vec4i> res; vector<int> weight; int i,j; int x1 = frame[0]; int y1 = frame[1]; int x2 = frame[2]; int y2 = frame[3]; weight.resize(y2 - y1 + 1, 0); for (i=y1; i<=y2; i++){ uchar* row = image.ptr<uchar>(i); for (j=x1; j<=x2; j++){ if (row[j] == 255) weight[i-y1]++; } } bool streak = false; int ya = 0; for (j=y1; j<=y2; j++){ int a = weight[j-y1]; if (a != 0 && !streak){ ya = j; streak = true; } if (a == 0 && streak){ streak = false; res.push_back(Vec4i(x1, ya, x2, j)); } } return res; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 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 <iostream> #include <sstream> #include <vector> #include <string> #include <mapnik/version.hpp> #include <mapnik/debug.hpp> #include <mapnik/marker.hpp> #include <mapnik/marker_cache.hpp> #include <mapnik/image_util.hpp> #include <mapnik/svg/svg_path_adapter.hpp> #include <mapnik/svg/svg_renderer_agg.hpp> #include <mapnik/svg/svg_path_attributes.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-local-typedef" #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #pragma GCC diagnostic pop #include "agg_rasterizer_scanline_aa.h" #include "agg_basics.h" #include "agg_rendering_buffer.h" #include "agg_renderer_base.h" #include "agg_pixfmt_rgba.h" #include "agg_scanline_u.h" #include <libxml/parser.h> // for xmlInitParser(), xmlCleanupParser() struct main_marker_visitor { main_marker_visitor(std::string & svg_name, int & return_value, bool verbose, bool auto_open) : svg_name_(svg_name), return_value_(return_value), verbose_(verbose), auto_open_(auto_open) {} void operator() (mapnik::marker_null const&) { std::clog << "svg2png error: '" << svg_name_ << "' is not a valid vector!\n"; return_value_ = -1; } void operator() (mapnik::marker_rgba8 const&) { std::clog << "svg2png error: '" << svg_name_ << "' is not a valid vector!\n"; return_value_ = -1; } void operator() (mapnik::marker_svg const& marker) { using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>; agg::rasterizer_scanline_aa<> ras_ptr; agg::scanline_u8 sl; double opacity = 1; int w = marker.width(); int h = marker.height(); if (verbose_) { std::clog << "found width of '" << w << "' and height of '" << h << "'\n"; } // 10 pixel buffer to avoid edge clipping of 100% svg's mapnik::image_rgba8 im(w+0,h+0); agg::rendering_buffer buf(im.bytes(), im.width(), im.height(), im.row_size()); pixfmt pixf(buf); renderer_base renb(pixf); mapnik::box2d<double> const& bbox = marker.get_data()->bounding_box(); mapnik::coord<double,2> c = bbox.center(); // center the svg marker on '0,0' agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y); // render the marker at the center of the marker box mtx.translate(0.5 * im.width(), 0.5 * im.height()); mapnik::svg::vertex_stl_adapter<mapnik::svg::svg_path_storage> stl_storage(marker.get_data()->source()); mapnik::svg::svg_path_adapter svg_path(stl_storage); mapnik::svg::svg_renderer_agg<mapnik::svg::svg_path_adapter, agg::pod_bvector<mapnik::svg::path_attributes>, renderer_solid, agg::pixfmt_rgba32_pre > svg_renderer_this(svg_path, marker.get_data()->attributes()); svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox); boost::algorithm::ireplace_last(svg_name_,".svg",".png"); demultiply_alpha(im); mapnik::save_to_file<mapnik::image_rgba8>(im,svg_name_,"png"); if (auto_open_) { std::ostringstream s; #ifdef DARWIN s << "open " << svg_name_; #else s << "xdg-open " << svg_name_; #endif int ret = system(s.str().c_str()); if (ret != 0) return_value_ = ret; } std::clog << "rendered to: " << svg_name_ << "\n"; } private: std::string & svg_name_; int & return_value_; bool verbose_; bool auto_open_; }; int main (int argc,char** argv) { namespace po = boost::program_options; bool verbose = false; bool auto_open = false; int return_value = 0; std::vector<std::string> svg_files; mapnik::logger::instance().set_severity(mapnik::logger::error); try { po::options_description desc("svg2png utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("open","automatically open the file after rendering (os x only)") ("svg",po::value<std::vector<std::string> >(),"svg file to read") ; po::positional_options_description p; p.add("svg",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { std::clog <<"version " << MAPNIK_VERSION_STRING << std::endl; return 1; } if (vm.count("help")) { std::clog << desc << std::endl; return 1; } if (vm.count("verbose")) { verbose = true; } if (vm.count("open")) { auto_open = true; } if (vm.count("svg")) { svg_files=vm["svg"].as< std::vector<std::string> >(); } else { std::clog << "please provide an svg file!" << std::endl; return -1; } std::vector<std::string>::const_iterator itr = svg_files.begin(); if (itr == svg_files.end()) { std::clog << "no svg files to render" << std::endl; return 0; } xmlInitParser(); while (itr != svg_files.end()) { std::string svg_name (*itr++); if (verbose) { std::clog << "found: " << svg_name << "\n"; } std::shared_ptr<mapnik::marker const> marker = mapnik::marker_cache::instance().find(svg_name, false); main_marker_visitor visitor(svg_name, return_value, verbose, auto_open); mapnik::util::apply_visitor(visitor, *marker); } } catch (...) { std::clog << "Exception of unknown type!" << std::endl; xmlCleanupParser(); return -1; } // only call this once, on exit // to make sure valgrind output is clean // http://xmlsoft.org/xmlmem.html xmlCleanupParser(); return return_value; } <commit_msg>make visitor return `status` + don't mutating `svg_name_`<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 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 <iostream> #include <sstream> #include <vector> #include <string> #include <mapnik/version.hpp> #include <mapnik/debug.hpp> #include <mapnik/marker.hpp> #include <mapnik/marker_cache.hpp> #include <mapnik/image_util.hpp> #include <mapnik/svg/svg_path_adapter.hpp> #include <mapnik/svg/svg_renderer_agg.hpp> #include <mapnik/svg/svg_path_attributes.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-local-typedef" #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #pragma GCC diagnostic pop #include "agg_rasterizer_scanline_aa.h" #include "agg_basics.h" #include "agg_rendering_buffer.h" #include "agg_renderer_base.h" #include "agg_pixfmt_rgba.h" #include "agg_scanline_u.h" #include <libxml/parser.h> // for xmlInitParser(), xmlCleanupParser() struct main_marker_visitor { main_marker_visitor(std::string const& svg_name, bool verbose, bool auto_open) : svg_name_(svg_name), verbose_(verbose), auto_open_(auto_open) {} int operator() (mapnik::marker_null const&) { std::clog << "svg2png error: '" << svg_name_ << "' is not a valid vector!\n"; return -1; } int operator() (mapnik::marker_rgba8 const&) { std::clog << "svg2png error: '" << svg_name_ << "' is not a valid vector!\n"; return -1; } int operator() (mapnik::marker_svg const& marker) { using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>; agg::rasterizer_scanline_aa<> ras_ptr; agg::scanline_u8 sl; double opacity = 1; int w = marker.width(); int h = marker.height(); if (verbose_) { std::clog << "found width of '" << w << "' and height of '" << h << "'\n"; } // 10 pixel buffer to avoid edge clipping of 100% svg's mapnik::image_rgba8 im(w+0,h+0); agg::rendering_buffer buf(im.bytes(), im.width(), im.height(), im.row_size()); pixfmt pixf(buf); renderer_base renb(pixf); mapnik::box2d<double> const& bbox = marker.get_data()->bounding_box(); mapnik::coord<double,2> c = bbox.center(); // center the svg marker on '0,0' agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y); // render the marker at the center of the marker box mtx.translate(0.5 * im.width(), 0.5 * im.height()); mapnik::svg::vertex_stl_adapter<mapnik::svg::svg_path_storage> stl_storage(marker.get_data()->source()); mapnik::svg::svg_path_adapter svg_path(stl_storage); mapnik::svg::svg_renderer_agg<mapnik::svg::svg_path_adapter, agg::pod_bvector<mapnik::svg::path_attributes>, renderer_solid, agg::pixfmt_rgba32_pre > svg_renderer_this(svg_path, marker.get_data()->attributes()); svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox); std::string png_name(svg_name_); boost::algorithm::ireplace_last(png_name,".svg",".png"); demultiply_alpha(im); mapnik::save_to_file<mapnik::image_rgba8>(im,png_name,"png"); int status = 0; if (auto_open_) { std::ostringstream s; #ifdef DARWIN s << "open " << png_name; #else s << "xdg-open " << png_name; #endif int ret = system(s.str().c_str()); if (ret != 0) status = ret; } std::clog << "rendered to: " << svg_name_ << "\n"; return status; } private: std::string const& svg_name_; bool verbose_; bool auto_open_; }; int main (int argc,char** argv) { namespace po = boost::program_options; bool verbose = false; bool auto_open = false; int status = 0; std::vector<std::string> svg_files; mapnik::logger::instance().set_severity(mapnik::logger::error); try { po::options_description desc("svg2png utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("open","automatically open the file after rendering (os x only)") ("svg",po::value<std::vector<std::string> >(),"svg file to read") ; po::positional_options_description p; p.add("svg",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { std::clog <<"version " << MAPNIK_VERSION_STRING << std::endl; return 1; } if (vm.count("help")) { std::clog << desc << std::endl; return 1; } if (vm.count("verbose")) { verbose = true; } if (vm.count("open")) { auto_open = true; } if (vm.count("svg")) { svg_files=vm["svg"].as< std::vector<std::string> >(); } else { std::clog << "please provide an svg file!" << std::endl; return -1; } std::vector<std::string>::const_iterator itr = svg_files.begin(); if (itr == svg_files.end()) { std::clog << "no svg files to render" << std::endl; return 0; } xmlInitParser(); while (itr != svg_files.end()) { std::string svg_name (*itr++); if (verbose) { std::clog << "found: " << svg_name << "\n"; } std::shared_ptr<mapnik::marker const> marker = mapnik::marker_cache::instance().find(svg_name, false); main_marker_visitor visitor(svg_name, verbose, auto_open); status = mapnik::util::apply_visitor(visitor, *marker); } } catch (...) { std::clog << "Exception of unknown type!" << std::endl; xmlCleanupParser(); return -1; } // only call this once, on exit // to make sure valgrind output is clean // http://xmlsoft.org/xmlmem.html xmlCleanupParser(); return status; } <|endoftext|>
<commit_before>#pragma once #include <memory> #include <iostream> #include <array> #include <mutex> #include <cassert> namespace petsc { class TimeStepper; namespace TimeStepper_private { // template< typename context > std::function<PetscErrorCode(TS, PetscReal, Vec, Mat*, Mat*, MatStructure*)> jacobian; PetscErrorCode jacobian_function_( TS ts, PetscReal t, Vec u, Mat* A, Mat* B, MatStructure* ms, void* cntx ); // template< typename context > std::function<PetscErrorCode( TS, PetscReal, Vec, Vec )> rhs; PetscErrorCode rhs_function_( TS ts, PetscReal t, Vec v, Vec f, void* cntx ); } class TimeStepper { public: typedef PetscErrorCode( jacobian_function_type )( TS, PetscReal, Vec, Mat*, Mat*, MatStructure* ); typedef PetscErrorCode( rhs_function_type )( TS, PetscReal, Vec, Vec ); // This won't immediately run, because that is impractical (a lot of // optional setup) TimeStepper( const MPI_Comm& comm, TSProblemType pt, TSType type, PetscReal t0, PetscReal dt, Vector& solution, PetscReal tf, PetscInt max_step, std::function<jacobian_function_type> jac, std::function<rhs_function_type> rhs, Matrix& rhs_mat_initial ) { TSCreate( comm, &ts_ ); TSSetProblemType( ts_, pt ); TSSetType( ts_, type ); TSSetInitialTimeStep( ts_, t0, dt ); TSSetSolution( ts_, solution.v_ ); if ( max_step > 0 ) TSSetDuration( ts_, static_cast<int>( ( tf - t0 ) / dt ), tf ); else TSSetDuration( ts_, max_step, tf ); TSSetFromOptions( ts_ ); TSSetRHSJacobian( ts_, rhs_mat_initial.m_, rhs_mat_initial.m_, TimeStepper_private::jacobian_function_, NULL ); TimeStepper_private::jacobian = jac; if ( pt == TS_LINEAR ) TSSetRHSFunction( ts_, NULL, TSComputeRHSFunctionLinear, NULL ); else { TSSetRHSFunction( ts_, NULL, TimeStepper_private::rhs_function_, NULL ); TimeStepper_private::rhs = rhs; } TSSolve( ts_, PETSC_NULL ); } explicit TimeStepper( TS& ts ) : ts_( ts ) {} TimeStepper( Vector& solution, PetscReal t0, PetscReal tf, PetscReal dt, std::function<jacobian_function_type> jac, Matrix& rhs_mat_initial, TSProblemType pt = TS_LINEAR, TSType type = TSCN ) : TimeStepper( solution.comm(), pt, type, t0, dt, solution, tf, -1, jac, nullptr, rhs_mat_initial ) {} TimeStepper( const TimeStepper& other ) = delete; TimeStepper( TimeStepper&& other ) : ts_( other.ts_ ) { other.ts_ = PETSC_NULL; } ~TimeStepper() { TSDestroy( &ts_ ); } // func (TS ts,PetscReal t,Vec u,Vec F,void *ctx); // void rhs_function( std::function<PetscErrorCode( // TimeStepper, PetscReal, Vector, Vector )> rhs_function_ ) //{ // TimeStepper_private::rhs = rhs_function_; //} //// func (TS ts,PetscReal t,Vec u,Mat *A,Mat *B,MatStructure *flag,void //// *ctx); // void rhs_jacobian( std::function<PetscErrorCode( // TS, PetscReal, Vec, Mat*, Mat*, MatStructure*)> // jac_function_ ) //{ // TimeStepper_private::jacobian = jac_function_; //} TS ts_; }; PetscErrorCode TimeStepper_private::jacobian_function_( TS ts, PetscReal t, Vec u, Mat* A, Mat* B, MatStructure* ms, void* cntx ) { return TimeStepper_private::jacobian( ts, t, u, A, B, ms ); } PetscErrorCode TimeStepper_private::rhs_function_( TS ts, PetscReal t, Vec v, Vec f, void* cntx ) { return TimeStepper_private::rhs( ts, t, v, f ); } } <commit_msg>TimeStepper initial commit.<commit_after>#pragma once #include <petsc.h> #ifdef SLEPC #include <slepc.h> #endif #include <petsc_cpp/Vector.hpp> #include <petsc_cpp/Matrix.hpp> namespace petsc { class TimeStepper { /* Interested in solving problems of the type: F(t, u, u') = G(t, u) Where the jacobian is F_u + (shift) F_u'. G_u is the RHS jacobian. For the most common case: u' = A(t) u: G = A(t) u G_u = A(t). F = u' F_u + (shift) F_u' = (shift) */ public: using RHSJacobian = PetscErrorCode ( * )( TS, PetscReal, Vec, Mat, Mat, void* ); using RHS = PetscErrorCode ( * )( TS, PetscReal, Vec, Vec, void* ); using LHSJacobian = PetscErrorCode ( * )( TS, PetscReal, Vec, Vec, PetscReal, Mat, Mat, void* ); using LHS = PetscErrorCode ( * )( TS, PetscReal, Vec, Vec, Vec, void* ); enum class problem_type { linear = TS_LINEAR, nonlinear = TS_NONLINEAR }; struct time { double t0, tf, dt; }; TimeStepper( problem_type type, TSType solver_type, const MPI_Comm& comm = PETSC_COMM_WORLD ) { TSCreate( comm, &ts ); TSSetProblemType( ts, static_cast<TSProblemType>( type ) ); TSSetType( ts, solver_type ); } /* For simple case u' = A(t) u */ // Jac has approximate type (Vector& u, Matrix& A, Matrix& B, TimeStepper& // ts, double time) template <typename Jac> TimeStepper( Jac G_u, Matrix& A, time t, TSType solver_type, const MPI_Comm& comm = PETSC_COMM_WORLD ) : TimeStepper( problem_type::linear, solver_type, comm ) { assert( A.comm() == comm ); TSSetInitialTimeStep( ts, t.t0, t.dt ); // TSSetSolution( ts, solution.v_ ); TSSetDuration( ts, static_cast<int>( ( t.tf - t.t0 ) / t.dt ) + 10, t.tf ); TSSetFromOptions( ts ); TSSetRHSFunction( ts, NULL, TSComputeRHSFunctionLinear, NULL ); TSSetRHSJacobian( ts, A.m_, A.m_, TimeStepper::RHSJacobian_function<Jac>, &G_u ); } template <typename Jac> static PetscErrorCode RHSJacobian_function( TS ts, double t_, Vec u, Mat A, Mat B, void* G_u ) { ( *(Jac*)G_u )( Vector( u, false ), Matrix( A, false ), Matrix( B, false ), TimeStepper( ts, false ), t_ ); return 0; } explicit TimeStepper( TS& ts, bool owned = false ) : ts( ts ), owned( owned ) { } /* rule of 4.5 */ TimeStepper( const TimeStepper& other ) = delete; TimeStepper( TimeStepper&& other ) : ts( other.ts ) { other.ts = PETSC_NULL; } ~TimeStepper() { if ( !owned ) TSDestroy( &ts ); } void solve( Vector& u_0 ) { TSSolve( ts, u_0.v_ ); } void print() const { TSView( ts, PETSC_VIEWER_STDOUT_WORLD ); } template <typename Mon> void set_monitor( Mon m ) { TSMonitorSet( ts, []( TS ts, int step, double t, Vec u, void* monitor ) { ( *(Mon*)monitor )( TimeStepper( ts, false ), step, t, Vector( u, false ) ); }, &m, PETSC_NULL ); } TS ts; bool owned{true}; }; } <|endoftext|>
<commit_before>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ******************************************************************************/ #ifndef NOMLIB_SYSTEM_SEARCH_PATH_HPP #define NOMLIB_SYSTEM_SEARCH_PATH_HPP #include <memory> #include <string> #include <vector> #include "nomlib/config.hpp" #include "nomlib/system/File.hpp" #include "nomlib/ptree.hpp" #include "nomlib/serializers.hpp" namespace nom { /// \brief Determine the directory location to use based on search prefixes /// /// \todo Add an interface for using this class without a file. class SearchPath { public: typedef SearchPath self_type; typedef self_type* raw_ptr; typedef std::unique_ptr<self_type> unique_ptr; typedef std::shared_ptr<self_type> shared_ptr; /// \brief Default constructor; initialize the parser to NULL. SearchPath(); /// \brief Destructor. ~SearchPath(); /// \brief Get the resolved path. const std::string& path(); /// \brief Set a custom parser. /// /// \remarks The default parser is JSON. void set_deserializer( std::unique_ptr<IValueDeserializer> fp ); /// \brief Parse a file into memory. /// /// \param filename The absolute file path. /// \param node The top-level object to use in formation of the path. /// /// \remarks The default parser is JSON, and can be changed using the /// ::set_deserializer method. bool load_file( const std::string& filename, const std::string& node ); private: /// \brief Parser object to use. /// /// \see nom::IValueDeserializer std::unique_ptr<IValueDeserializer> fp_; /// \brief List of path prefixes to scan through with the given path. std::vector<std::string> search_prefix_; /// \brief The resolved path. std::string path_; }; } // namespace nom #endif // include guard defined /// Usage example: /// /// nom::SearchPath resources; /// resources.load_file( "resources.json" ); /// /// ```resources.json``` /// (should generally be in the same directory as the executable) /// /// \code /// { /// // Top-level object 'node' /// "resources": /// { /// // List of paths to search /// "search_prefix": /// [ /// "./", /// "../../", /// "../../../" /// ], /// // The 'suffix' that is appended to each search prefix path during the /// // scan; the first full path that exists will be what is returned on a /// // call to ::path. /// "path": "Resources/tests/gui/librocket/nomlibTest/" /// } /// } /// \endcode <commit_msg>SearchPaths: Use arg default for 2nd param in ::load_file method<commit_after>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ******************************************************************************/ #ifndef NOMLIB_SYSTEM_SEARCH_PATH_HPP #define NOMLIB_SYSTEM_SEARCH_PATH_HPP #include <memory> #include <string> #include <vector> #include "nomlib/config.hpp" #include "nomlib/system/File.hpp" #include "nomlib/ptree.hpp" #include "nomlib/serializers.hpp" namespace nom { /// \brief Determine the directory location to use based on search prefixes /// /// \todo Add an interface for using this class without a file. class SearchPath { public: typedef SearchPath self_type; typedef self_type* raw_ptr; typedef std::unique_ptr<self_type> unique_ptr; typedef std::shared_ptr<self_type> shared_ptr; /// \brief Default constructor; initialize the parser to NULL. SearchPath(); /// \brief Destructor. ~SearchPath(); /// \brief Get the resolved path. const std::string& path(); /// \brief Set a custom parser. /// /// \remarks The default parser is JSON. void set_deserializer( std::unique_ptr<IValueDeserializer> fp ); /// \brief Parse a file into memory. /// /// \param filename The absolute file path. /// \param node The top-level object to use in formation of the path; /// defaults to an object member by name of "resources". /// /// \remarks The default parser is JSON, and can be changed using the /// ::set_deserializer method. bool load_file( const std::string& filename, const std::string& node = "resources" ); private: /// \brief Parser object to use. /// /// \see nom::IValueDeserializer std::unique_ptr<IValueDeserializer> fp_; /// \brief List of path prefixes to scan through with the given path. std::vector<std::string> search_prefix_; /// \brief The resolved path. std::string path_; }; } // namespace nom #endif // include guard defined /// Common usage: /// /// #include "nomlib/system.hpp" /// /// int main( int argc, char** argv ) /// { /// // Set the current working directory path to the path leading to this /// // executable file; used for unit tests that require file-system I/O. /// if( nom::init( argc, argv ) == false ) /// { /// nom::DialogMessageBox( "Critical Error", "Could not initialize nomlib.", nom::MessageBoxType::NOM_DIALOG_ERROR ); /// return NOM_EXIT_FAILURE; /// } /// atexit( nom::quit ); /// return NOM_EXIT_SUCCESS; /// } /// /// nom::SearchPath resources; /// resources.load_file( "resources.json" ); /// /// ```resources.json``` /// (should generally be in the same directory as the executable) /// /// \code /// { /// // Top-level object 'node' /// "resources": /// { /// // List of paths to search /// "search_prefix": /// [ /// "./", /// "../../", /// "../../../" /// ], /// // The 'suffix' that is appended to each search prefix path during the /// // scan; the first full path that exists will be what is returned on a /// // call to ::path. /// "path": "Resources/tests/gui/librocket/nomlibTest/" /// } /// } /// \endcode <|endoftext|>
<commit_before>/* -*- Mode:C++; c-file-style:"gnu" -*- */ /* * Copyright 2014 Waseda University, Sato Laboratory * Author: Zhu Li <phillipszhuli1990@gmail.com> * Jairo Eduardo Lopez <jairo@ruri.waseda.jp> * * nnn-face.cc is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nnn-face.cc 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 Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with nnn-face.cc. If not, see <http://www.gnu.org/licenses/>. */ #include <ns3-dev/ns3/assert.h> #include <ns3-dev/ns3/boolean.h> #include <ns3-dev/ns3/double.h> #include <ns3-dev/ns3/log.h> #include <ns3-dev/ns3/node.h> #include <ns3-dev/ns3/packet.h> #include <ns3-dev/ns3/uinteger.h> #include <ns3-dev/ns3/simulator.h> #include <ns3-dev/ns3/random-variable.h> #include <ns3-dev/ns3/pointer.h> #include "nnn-face.h" #include "../helper/nnn-header-helper.h" #include "wire/nnn-wire.h" #include <boost/ref.hpp> NS_LOG_COMPONENT_DEFINE ("nnn.Face"); namespace ns3 { namespace nnn { NS_OBJECT_ENSURE_REGISTERED (Face); TypeId Face::GetTypeId () { static TypeId tid = TypeId ("ns3::nnn::Face") .SetParent<Object> () .SetGroupName ("Nnn") .AddAttribute ("Id", "Face id (unique integer for the Nnn stack on this node)", TypeId::ATTR_GET, // allow only getting it. UintegerValue (0), MakeUintegerAccessor (&Face::m_id), MakeUintegerChecker<uint32_t> ()) ; return tid; } /** * By default, Nnn face are created in the "down" state * with no MAC addresses. Before becoming useable, the user must * invoke SetUp on them once an Nnn address and mask have been set. */ Face::Face (Ptr<Node> node) : m_node (node) , m_upstreamNULLpHandler (MakeNullCallback< void, Ptr<Face>, Ptr<NULLp> > ()) , m_upstreamSOHandler (MakeNullCallback< void, Ptr<Face>, Ptr<SO> > ()) , m_upstreamDOHandler (MakeNullCallback< void, Ptr<Face>, Ptr<DO> > ()) , m_ifup (false) , m_id ((uint32_t)-1) , m_metric (0) , m_flags (0) { NS_LOG_FUNCTION (this << node); NS_ASSERT_MSG (node != 0, "node cannot be NULL. Check the code"); } Face::~Face () { NS_LOG_FUNCTION_NOARGS (); } Face::Face (const Face &) { } Face& Face::operator= (const Face &) { return *this; } Ptr<Node> Face::GetNode () const { return m_node; } void Face::RegisterProtocolHandlers (const NULLpHandler &NULLpHandler, const SOHandler &SOHandler, const DOHandler &DOHandler, const ENHandler &ENHandler, const AENHandler &AENHandler, const RENHandler &RENHandler, const INFHandler &INFHandler) { NS_LOG_FUNCTION_NOARGS (); m_upstreamNULLpHandler = NULLpHandler; m_upstreamSOHandler = SOHandler; m_upstreamDOHandler = DOHandler; m_upstreamENHandler = ENHandler; m_upstreamAENHandler = AENHandler; m_upstreamRENHandler = RENHandler; m_upstreamINFHandler = INFHandler; } void Face::UnRegisterProtocolHandlers () { NS_LOG_FUNCTION_NOARGS (); m_upstreamNULLpHandler = MakeNullCallback< void, Ptr<Face>, Ptr<NULLp> > (); m_upstreamSOHandler = MakeNullCallback< void, Ptr<Face>, Ptr<SO> > (); m_upstreamDOHandler = MakeNullCallback< void, Ptr<Face>, Ptr<DO> > (); } bool Face::SendNULLp (Ptr<const NULLp> n_o) { NS_LOG_FUNCTION (this << n_o); if (!IsUp ()) { return false; } return Send (Wire::FromNULLp (n_o)); } bool Face::SendSO (Ptr<const SO> so_p) { NS_LOG_FUNCTION (this << boost::cref (*this) << so_p->GetName ()); if (!IsUp ()) { return false; } return Send (Wire::FromSO (so_p)); } bool Face::SendDO (Ptr<const DO> do_p) { NS_LOG_FUNCTION (this << boost::cref (*this) << do_p->GetName ()); if (!IsUp ()) { return false; } return Send (Wire::FromDO (do_p)); } bool Face::Send (Ptr<Packet> packet) { return true; } bool Face::Receive (Ptr<const Packet> p) { NS_LOG_FUNCTION (this << p << p->GetSize ()); if (!IsUp ()) { // no tracing here. If we were off while receiving, we shouldn't even know that something was there return false; } Ptr<Packet> packet = p->Copy (); // give upper layers a rw copy of the packet try { HeaderHelper::Type type = HeaderHelper::GetNnnHeaderType (packet); switch (type) { case HeaderHelper::NULL_NNN: return ReceiveNULLp (Wire::ToNULLp (packet, Wire::WIRE_FORMAT_NNNSIM)); case HeaderHelper::SO_NNN: return ReceiveSO (Wire::ToSO (packet, Wire::WIRE_FORMAT_NNNSIM)); case HeaderHelper::DO_NNN: return ReceiveDO (Wire::ToDO (packet, Wire::WIRE_FORMAT_NNNSIM)); default: NS_FATAL_ERROR ("Not supported NNN header"); return false; } // exception will be thrown if packet is not recognized } catch (UnknownHeaderException) { NS_FATAL_ERROR ("Unknown NNN header. Should not happen"); return false; } return false; } bool Face::ReceiveNULLp (Ptr<NULLp> n_o) { if (!IsUp ()) { // no tracing here. If we were off while receiving, we shouldn't even know that something was there return false; } m_upstreamNULLpHandler (this, n_o); return true; } bool Face::ReceiveSO (Ptr<SO> so_p) { if (!IsUp ()) { // no tracing here. If we were off while receiving, we shouldn't even know that something was there return false; } m_upstreamSOHandler (this, so_p); return true; } bool Face::ReceiveDO (Ptr<DO> do_p) { if (!IsUp ()) { // no tracing here. If we were off while receiving, we shouldn't even know that something was there return false; } m_upstreamDOHandler (this, do_p); return true; } void Face::SetMetric (uint16_t metric) { NS_LOG_FUNCTION (metric); m_metric = metric; } uint16_t Face::GetMetric (void) const { return m_metric; } void Face::SetFlags (uint32_t flags) { m_flags = flags; } bool Face::operator== (const Face &face) const { NS_ASSERT_MSG (m_node->GetId () == face.m_node->GetId (), "NN_Faces of different nodes should not be compared to each other: " << *this << " == " << face); return (m_id == face.m_id); } bool Face::operator< (const Face &face) const { NS_ASSERT_MSG (m_node->GetId () == face.m_node->GetId (), "NN_Faces of different nodes should not be compared to each other: " << *this << " == " << face); return (m_id < face.m_id); } std::ostream& Face::Print (std::ostream &os) const { os << "id=" << GetId (); return os; } std::ostream& operator<< (std::ostream& os, const Face &face) { face.Print (os); return os; } } // namespace nnn } // namespace ns3 <commit_msg>New headers for nnn-face.cc<commit_after>/* -*- Mode:C++; c-file-style:"gnu" -*- */ /* * Copyright 2014 Waseda University, Sato Laboratory * Author: Zhu Li <phillipszhuli1990@gmail.com> * Jairo Eduardo Lopez <jairo@ruri.waseda.jp> * * nnn-face.cc is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nnn-face.cc 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 Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with nnn-face.cc. If not, see <http://www.gnu.org/licenses/>. */ #include <ns3-dev/ns3/assert.h> #include <ns3-dev/ns3/boolean.h> #include <ns3-dev/ns3/double.h> #include <ns3-dev/ns3/log.h> #include <ns3-dev/ns3/node.h> #include <ns3-dev/ns3/packet.h> #include <ns3-dev/ns3/uinteger.h> #include <ns3-dev/ns3/simulator.h> #include <ns3-dev/ns3/random-variable.h> #include <ns3-dev/ns3/pointer.h> #include "nnn-face.h" #include "../helper/nnn-header-helper.h" #include "wire/nnn-nnnsim-wire.h" #include <boost/ref.hpp> NS_LOG_COMPONENT_DEFINE ("nnn.Face"); namespace ns3 { namespace nnn { NS_OBJECT_ENSURE_REGISTERED (Face); TypeId Face::GetTypeId () { static TypeId tid = TypeId ("ns3::nnn::Face") .SetParent<Object> () .SetGroupName ("Nnn") .AddAttribute ("Id", "Face id (unique integer for the Nnn stack on this node)", TypeId::ATTR_GET, // allow only getting it. UintegerValue (0), MakeUintegerAccessor (&Face::m_id), MakeUintegerChecker<uint32_t> ()) ; return tid; } /** * By default, Nnn face are created in the "down" state * with no MAC addresses. Before becoming useable, the user must * invoke SetUp on them once an Nnn address and mask have been set. */ Face::Face (Ptr<Node> node) : m_node (node) , m_upstreamNULLpHandler (MakeNullCallback< void, Ptr<Face>, Ptr<NULLp> > ()) , m_upstreamSOHandler (MakeNullCallback< void, Ptr<Face>, Ptr<SO> > ()) , m_upstreamDOHandler (MakeNullCallback< void, Ptr<Face>, Ptr<DO> > ()) , m_ifup (false) , m_id ((uint32_t)-1) , m_metric (0) , m_flags (0) { NS_LOG_FUNCTION (this << node); NS_ASSERT_MSG (node != 0, "node cannot be NULL. Check the code"); } Face::~Face () { NS_LOG_FUNCTION_NOARGS (); } Face::Face (const Face &) { } Face& Face::operator= (const Face &) { return *this; } Ptr<Node> Face::GetNode () const { return m_node; } void Face::RegisterProtocolHandlers (const NULLpHandler &NULLpHandler, const SOHandler &SOHandler, const DOHandler &DOHandler, const ENHandler &ENHandler, const AENHandler &AENHandler, const RENHandler &RENHandler, const INFHandler &INFHandler) { NS_LOG_FUNCTION_NOARGS (); m_upstreamNULLpHandler = NULLpHandler; m_upstreamSOHandler = SOHandler; m_upstreamDOHandler = DOHandler; m_upstreamENHandler = ENHandler; m_upstreamAENHandler = AENHandler; m_upstreamRENHandler = RENHandler; m_upstreamINFHandler = INFHandler; } void Face::UnRegisterProtocolHandlers () { NS_LOG_FUNCTION_NOARGS (); m_upstreamNULLpHandler = MakeNullCallback< void, Ptr<Face>, Ptr<NULLp> > (); m_upstreamSOHandler = MakeNullCallback< void, Ptr<Face>, Ptr<SO> > (); m_upstreamDOHandler = MakeNullCallback< void, Ptr<Face>, Ptr<DO> > (); } bool Face::SendNULLp (Ptr<const NULLp> n_o) { NS_LOG_FUNCTION (this << n_o); if (!IsUp ()) { return false; } return Send (Wire::FromNULLp (n_o)); } bool Face::SendSO (Ptr<const SO> so_p) { NS_LOG_FUNCTION (this << boost::cref (*this) << so_p->GetName ()); if (!IsUp ()) { return false; } return Send (Wire::FromSO (so_p)); } bool Face::SendDO (Ptr<const DO> do_p) { NS_LOG_FUNCTION (this << boost::cref (*this) << do_p->GetName ()); if (!IsUp ()) { return false; } return Send (Wire::FromDO (do_p)); } bool Face::Send (Ptr<Packet> packet) { return true; } bool Face::Receive (Ptr<const Packet> p) { NS_LOG_FUNCTION (this << p << p->GetSize ()); if (!IsUp ()) { // no tracing here. If we were off while receiving, we shouldn't even know that something was there return false; } Ptr<Packet> packet = p->Copy (); // give upper layers a rw copy of the packet try { HeaderHelper::Type type = HeaderHelper::GetNnnHeaderType (packet); switch (type) { case HeaderHelper::NULL_NNN: return ReceiveNULLp (Wire::ToNULLp (packet, Wire::WIRE_FORMAT_NNNSIM)); case HeaderHelper::SO_NNN: return ReceiveSO (Wire::ToSO (packet, Wire::WIRE_FORMAT_NNNSIM)); case HeaderHelper::DO_NNN: return ReceiveDO (Wire::ToDO (packet, Wire::WIRE_FORMAT_NNNSIM)); default: NS_FATAL_ERROR ("Not supported NNN header"); return false; } // exception will be thrown if packet is not recognized } catch (UnknownHeaderException) { NS_FATAL_ERROR ("Unknown NNN header. Should not happen"); return false; } return false; } bool Face::ReceiveNULLp (Ptr<NULLp> n_o) { if (!IsUp ()) { // no tracing here. If we were off while receiving, we shouldn't even know that something was there return false; } m_upstreamNULLpHandler (this, n_o); return true; } bool Face::ReceiveSO (Ptr<SO> so_p) { if (!IsUp ()) { // no tracing here. If we were off while receiving, we shouldn't even know that something was there return false; } m_upstreamSOHandler (this, so_p); return true; } bool Face::ReceiveDO (Ptr<DO> do_p) { if (!IsUp ()) { // no tracing here. If we were off while receiving, we shouldn't even know that something was there return false; } m_upstreamDOHandler (this, do_p); return true; } void Face::SetMetric (uint16_t metric) { NS_LOG_FUNCTION (metric); m_metric = metric; } uint16_t Face::GetMetric (void) const { return m_metric; } void Face::SetFlags (uint32_t flags) { m_flags = flags; } bool Face::operator== (const Face &face) const { NS_ASSERT_MSG (m_node->GetId () == face.m_node->GetId (), "NN_Faces of different nodes should not be compared to each other: " << *this << " == " << face); return (m_id == face.m_id); } bool Face::operator< (const Face &face) const { NS_ASSERT_MSG (m_node->GetId () == face.m_node->GetId (), "NN_Faces of different nodes should not be compared to each other: " << *this << " == " << face); return (m_id < face.m_id); } std::ostream& Face::Print (std::ostream &os) const { os << "id=" << GetId (); return os; } std::ostream& operator<< (std::ostream& os, const Face &face) { face.Print (os); return os; } } // namespace nnn } // namespace ns3 <|endoftext|>
<commit_before><commit_msg>Fix bad regex<commit_after><|endoftext|>
<commit_before>// ImageProcessor // Class to handle the processing of the image sequence #include "imageProcessor.h" ImageProcessor::ImageProcessor() { width = 480; height = 480; minVal = 0; maxVal = 255; bucketSize = 8; buckets = (maxVal + 1) / bucketSize; } ImageProcessor::~ImageProcessor() { if (bucketData) delete bucketData; } // Set input file sequence void ImageProcessor::setFiles(std::vector<std::string> fn) { fileNames = fn; inferParameters(); initializeData(); } // Infer processor parameters from the first file void ImageProcessor::inferParameters() { if (fileNames.size() <= 0) { std::cerr << "Image list empty. Exiting." << std::endl; exit(EXIT_FAILURE); } frames = fileNames.size(); cimg::CImg<unsigned char> inspectImage(fileNames[0].c_str()); width = inspectImage.width(); height = inspectImage.height(); channels = inspectImage.spectrum(); std::cout << "Image data" << std::endl; std::cout << "\tFrames:\t\t" << frames << std::endl; std::cout << "\tWidth:\t\t" << width << std::endl; std::cout << "\tHeight:\t\t" << height << std::endl; std::cout << "\tChannels:\t" << channels << std::endl; } // Set up the data structure to store bucket information void ImageProcessor::initializeData() { bucketData = new BucketData(width, height, buckets); } // Set the size of a bucket in terms of color intensity values void ImageProcessor::setBucketSize(int newSize) { bucketSize = newSize; buckets = (maxVal + 1) / bucketSize; } // Find the correspoding A Bucket for the color intensity value int ImageProcessor::getABucket(int value) { if (value < minVal) return 0; if (value > maxVal) return buckets - 1; return value / bucketSize; } // Find the corresponding B Bucket for the color intensity value int ImageProcessor::getBBucket(int value) { value += bucketSize / 2; if (value < minVal) return 0; if (value > maxVal - bucketSize / 2) return buckets - 1; return value / bucketSize; } // Process the image sequence and create final output void ImageProcessor::processSequence() { countBuckets(); findBiggestBucket(); refineSolution(); createFinal(); } // Read the image files and count the pixel values into buckets void ImageProcessor::countBuckets() { std::cout << std::endl << "Reading:\t"; // Read image frames and count the buckets for (auto &file : fileNames) { cimg::CImg<unsigned char> newImage(file.c_str()); std::cout << "|"; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int redPixel = newImage(i, j, 0, 0); int greenPixel = newImage(i, j, 0, 1); int bluePixel = newImage(i, j, 0, 2); int a_bucket = getABucket(redPixel); bucketData->redBucketA[i + j * width + a_bucket * (width * height)]++; int b_bucket = getBBucket(redPixel); bucketData->redBucketB[i + j * width + b_bucket * (width * height)]++; a_bucket = getABucket(greenPixel); bucketData->greenBucketA[i + j * width + a_bucket * (width * height)]++; b_bucket = getBBucket(greenPixel); bucketData->greenBucketB[i + j * width + b_bucket * (width * height)]++; a_bucket = getABucket(bluePixel); bucketData->blueBucketA[i + j * width + a_bucket * (width * height)]++; b_bucket = getBBucket(bluePixel); bucketData->blueBucketB[i + j * width + b_bucket * (width * height)]++; } } } } // Find the biggest bucket for each pixel void ImageProcessor::findBiggestBucket() { // Find the biggest bucket for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int idx = i + j * width; // Red channel { int redMaxCount = 0; int redMaxBucket = -1; bool redMaxTypeA = true; for (int bucket = 0; bucket < buckets; bucket++) { if (bucketData->redBucketA[i + j * width + bucket * (width * height)] > redMaxCount) { redMaxCount = bucketData->redBucketA[i + j * width + bucket * (width * height)]; redMaxBucket = bucket; redMaxTypeA = true; } if (bucketData->redBucketB[i + j * width + bucket * (width * height)] > redMaxCount) { redMaxCount = bucketData->redBucketB[i + j * width + bucket * (width * height)]; redMaxBucket = bucket; redMaxTypeA = false; } } bucketData->redFinalBucket[idx].id = redMaxBucket; bucketData->redFinalBucket[idx].isABucket = redMaxTypeA; bucketData->redFinalBucket[idx].diff = redMaxCount; } // Green channel { int greenMaxCount = 0; int greenMaxBucket = -1; bool greenMaxTypeA = true; for (int bucket = 0; bucket < buckets; bucket++) { if (bucketData->greenBucketA[i + j * width + bucket * (width * height)] > greenMaxCount) { greenMaxCount = bucketData->greenBucketA[i + j * width + bucket * (width * height)]; greenMaxBucket = bucket; greenMaxTypeA = true; } if (bucketData->redBucketB[i + j * width + bucket * (width * height)] > greenMaxCount) { greenMaxCount = bucketData->greenBucketB[i + j * width + bucket * (width * height)]; greenMaxBucket = bucket; greenMaxTypeA = false; } } bucketData->greenFinalBucket[idx].id = greenMaxBucket; bucketData->greenFinalBucket[idx].isABucket = greenMaxTypeA; bucketData->greenFinalBucket[idx].diff = greenMaxCount; } // Blue channel { int blueMaxCount = 0; int blueMaxBucket = -1; bool blueMaxTypeA = true; for (int bucket = 0; bucket < buckets; bucket++) { if (bucketData->redBucketA[i + j * width + bucket * (width * height)] > blueMaxCount) { blueMaxCount = bucketData->blueBucketA[i + j * width + bucket * (width * height)]; blueMaxBucket = bucket; blueMaxTypeA = true; } if (bucketData->redBucketB[i + j * width + bucket * (width * height)] > blueMaxCount) { blueMaxCount = bucketData->blueBucketB[i + j * width + bucket * (width * height)]; blueMaxBucket = bucket; blueMaxTypeA = false; } } bucketData->blueFinalBucket[idx].id = blueMaxBucket; bucketData->blueFinalBucket[idx].isABucket = blueMaxTypeA; bucketData->blueFinalBucket[idx].diff = blueMaxCount; } } } } // Optional step to let neighboring buckets with stronger confidence influence the bucket values of // weak confidence pixels void ImageProcessor::refineSolution() { short int confidenceLow = (short int)(0.5f * frames); short int confidenceHigh = (short int)(0.75f * frames); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int idx = i + j * width; // Check to see if the pixel has a low-confidence solution if (bucketData->greenFinalBucket[idx].diff < confidenceLow) { bool done = false; // Iterate through the pixel neighborhood for high confidence values for (int m = i - 1; m < i + 1 && !done; m++) { for (int n = j - 1; n < j + 1 && !done; n++) { if (m >= 0 && m < width && n >= 0 && n < height) { int neighIndex = m + n * width; if (bucketData->greenFinalBucket[neighIndex].diff > confidenceHigh) { // Replace the current pixel's bucket with the neighbor's bucketData->greenFinalBucket[idx] = bucketData->greenFinalBucket[neighIndex]; // Zero out the confidence bucketData->greenFinalBucket[idx].diff = 0; // Break out of the two innermost loops done = true; } } } } } } } } // Create final color image and a confidence mask, then display them void ImageProcessor::createFinal() { std::vector<float> accRed(width * height); std::vector<float> accGreen(width * height); std::vector<float> accBlue(width * height); std::vector<int> count(width * height); std::cout << std::endl << "Averaging:\t"; // Average out all the pixel values from the biggest bucket for (auto &file : fileNames) { cimg::CImg<unsigned char> newImage(file.c_str()); std::cout << "|"; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int idx = i + j * width; int pixelRed = newImage(i, j, 0, 0); int pixelGreen = newImage(i, j, 0, 1); int pixelBlue = newImage(i, j, 0, 2); // Test red // BucketEntry redEntry = bucketData->redFinalBucket[i + j * width]; // if (redEntry.isABucket && redEntry.id != getABucket(pixelRed)) // continue; // if (!redEntry.isABucket && redEntry.id != getBBucket(pixelRed)) // continue; // Test green BucketEntry greenEntry = bucketData->greenFinalBucket[idx]; if (greenEntry.isABucket && greenEntry.id != getABucket(pixelGreen)) continue; if (!greenEntry.isABucket && greenEntry.id != getBBucket(pixelGreen)) continue; // Test blue // BucketEntry blueEntry = bucketData->blueFinalBucket[i + j * width]; // if (blueEntry.isABucket && blueEntry.id != getABucket(pixelBlue)) // continue; // if (!blueEntry.isABucket && blueEntry.id != getBBucket(pixelBlue)) // continue; accRed[i + j * width] += pixelRed; accGreen[i + j * width] += pixelGreen; accBlue[i + j * width] += pixelBlue; count[i + j * width]++; // OLD CODE OLD CODE //if (bucketData->redFinalBucket[i + j * width].isABucket) //{ // int pixABucket = getABucket(pixelRed); // if (pixABucket == bucketData->redFinalBucket[i + j * width].id) // { // accRed[i + j * width] += pixelRed; // accGreen[i + j * width] += newImage(i, j, 0, 1); // accBlue[i + j * width] += newImage(i, j, 0, 2); // count[i + j * width]++; // } //} //else //{ // int pixBBucket = getBBucket(pixelRed); // if (pixBBucket == bucketData->redFinalBucket[i + j * width].id) // { // accRed[i + j * width] += pixelRed; // accGreen[i + j * width] += newImage(i, j, 0, 1); // accBlue[i + j * width] += newImage(i, j, 0, 2); // count[i + j * width]++; // } //} // OLD CODE OLD CODE } } } // Paint the final result in a window cimg::CImg<unsigned char> reconstructionImage(width, height, 1, 3, 0); cimg::CImgDisplay main_disp(width, height, "Reconstructed background"); // Paint the confidence mask cimg::CImg<unsigned char> confidenceImage(width, height, 1, 3, 0); cimg::CImgDisplay aux_disp(width, height, "Confidence mask"); // Paint the green buckets for debugging cimg::CImg<unsigned char> greenBucketImage(width, height, 1, 1, 0); cimg::CImgDisplay green_disp(width, height, "Green buckets"); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int idx = i + j * width; reconstructionImage(i, j, 0, 0) = (unsigned char) (accRed[i + j * width] / count[i + j * width]); reconstructionImage(i, j, 0, 1) = (unsigned char) (accGreen[i + j * width] / count[i + j * width]); reconstructionImage(i, j, 0, 2) = (unsigned char) (accBlue[i + j * width] / count[i + j * width]); int confidence = (int) (count[i + j * width] * ((float)256.0f / frames)); confidence = std::min(confidence, 255); confidenceImage(i, j, 0, 0) = (unsigned char) confidence; confidenceImage(i, j, 0, 1) = (unsigned char) confidence; confidenceImage(i, j, 0, 2) = (unsigned char) confidence; if(count[idx] < 1) { confidenceImage(i, j, 0, 0) = 255; confidenceImage(i, j, 0, 1) = 0; confidenceImage(i, j, 0, 2) = 0; } BucketEntry greenEntry = bucketData->greenFinalBucket[i + j * width]; unsigned char valueGreen = greenEntry.id * bucketSize; if(!greenEntry.isABucket) valueGreen -= bucketSize / 2; greenBucketImage(i, j, 0, 0) = valueGreen; } main_disp.render(reconstructionImage); main_disp.paint(); aux_disp.render(confidenceImage); aux_disp.paint(); green_disp.render(greenBucketImage); green_disp.paint(); } std::cout << std::endl; // Write the final color image to file std::remove("output.png"); reconstructionImage.save_png("output.png"); // Write out the confidence mask std::remove("confidence.png"); confidenceImage.save_png("confidence.png"); while (!main_disp.is_closed()) { main_disp.wait(); } } <commit_msg>Cleaned up index notation with precalculated variable<commit_after>// ImageProcessor // Class to handle the processing of the image sequence #include "imageProcessor.h" ImageProcessor::ImageProcessor() { width = 480; height = 480; minVal = 0; maxVal = 255; bucketSize = 8; buckets = (maxVal + 1) / bucketSize; } ImageProcessor::~ImageProcessor() { if (bucketData) delete bucketData; } // Set input file sequence void ImageProcessor::setFiles(std::vector<std::string> fn) { fileNames = fn; inferParameters(); initializeData(); } // Infer processor parameters from the first file void ImageProcessor::inferParameters() { if (fileNames.size() <= 0) { std::cerr << "Image list empty. Exiting." << std::endl; exit(EXIT_FAILURE); } frames = fileNames.size(); cimg::CImg<unsigned char> inspectImage(fileNames[0].c_str()); width = inspectImage.width(); height = inspectImage.height(); channels = inspectImage.spectrum(); std::cout << "Image data" << std::endl; std::cout << "\tFrames:\t\t" << frames << std::endl; std::cout << "\tWidth:\t\t" << width << std::endl; std::cout << "\tHeight:\t\t" << height << std::endl; std::cout << "\tChannels:\t" << channels << std::endl; } // Set up the data structure to store bucket information void ImageProcessor::initializeData() { bucketData = new BucketData(width, height, buckets); } // Set the size of a bucket in terms of color intensity values void ImageProcessor::setBucketSize(int newSize) { bucketSize = newSize; buckets = (maxVal + 1) / bucketSize; } // Find the correspoding A Bucket for the color intensity value int ImageProcessor::getABucket(int value) { if (value < minVal) return 0; if (value > maxVal) return buckets - 1; return value / bucketSize; } // Find the corresponding B Bucket for the color intensity value int ImageProcessor::getBBucket(int value) { value += bucketSize / 2; if (value < minVal) return 0; if (value > maxVal - bucketSize / 2) return buckets - 1; return value / bucketSize; } // Process the image sequence and create final output void ImageProcessor::processSequence() { countBuckets(); findBiggestBucket(); refineSolution(); createFinal(); } // Read the image files and count the pixel values into buckets void ImageProcessor::countBuckets() { std::cout << std::endl << "Reading:\t"; // Read image frames and count the buckets for (auto &file : fileNames) { cimg::CImg<unsigned char> newImage(file.c_str()); std::cout << "|"; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int redPixel = newImage(i, j, 0, 0); int greenPixel = newImage(i, j, 0, 1); int bluePixel = newImage(i, j, 0, 2); int a_bucket = getABucket(redPixel); bucketData->redBucketA[i + j * width + a_bucket * (width * height)]++; int b_bucket = getBBucket(redPixel); bucketData->redBucketB[i + j * width + b_bucket * (width * height)]++; a_bucket = getABucket(greenPixel); bucketData->greenBucketA[i + j * width + a_bucket * (width * height)]++; b_bucket = getBBucket(greenPixel); bucketData->greenBucketB[i + j * width + b_bucket * (width * height)]++; a_bucket = getABucket(bluePixel); bucketData->blueBucketA[i + j * width + a_bucket * (width * height)]++; b_bucket = getBBucket(bluePixel); bucketData->blueBucketB[i + j * width + b_bucket * (width * height)]++; } } } } // Find the biggest bucket for each pixel void ImageProcessor::findBiggestBucket() { // Find the biggest bucket for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int idx = i + j * width; // Red channel { int redMaxCount = 0; int redMaxBucket = -1; bool redMaxTypeA = true; for (int bucket = 0; bucket < buckets; bucket++) { if (bucketData->redBucketA[i + j * width + bucket * (width * height)] > redMaxCount) { redMaxCount = bucketData->redBucketA[i + j * width + bucket * (width * height)]; redMaxBucket = bucket; redMaxTypeA = true; } if (bucketData->redBucketB[i + j * width + bucket * (width * height)] > redMaxCount) { redMaxCount = bucketData->redBucketB[i + j * width + bucket * (width * height)]; redMaxBucket = bucket; redMaxTypeA = false; } } bucketData->redFinalBucket[idx].id = redMaxBucket; bucketData->redFinalBucket[idx].isABucket = redMaxTypeA; bucketData->redFinalBucket[idx].diff = redMaxCount; } // Green channel { int greenMaxCount = 0; int greenMaxBucket = -1; bool greenMaxTypeA = true; for (int bucket = 0; bucket < buckets; bucket++) { if (bucketData->greenBucketA[i + j * width + bucket * (width * height)] > greenMaxCount) { greenMaxCount = bucketData->greenBucketA[i + j * width + bucket * (width * height)]; greenMaxBucket = bucket; greenMaxTypeA = true; } if (bucketData->redBucketB[i + j * width + bucket * (width * height)] > greenMaxCount) { greenMaxCount = bucketData->greenBucketB[i + j * width + bucket * (width * height)]; greenMaxBucket = bucket; greenMaxTypeA = false; } } bucketData->greenFinalBucket[idx].id = greenMaxBucket; bucketData->greenFinalBucket[idx].isABucket = greenMaxTypeA; bucketData->greenFinalBucket[idx].diff = greenMaxCount; } // Blue channel { int blueMaxCount = 0; int blueMaxBucket = -1; bool blueMaxTypeA = true; for (int bucket = 0; bucket < buckets; bucket++) { if (bucketData->redBucketA[i + j * width + bucket * (width * height)] > blueMaxCount) { blueMaxCount = bucketData->blueBucketA[i + j * width + bucket * (width * height)]; blueMaxBucket = bucket; blueMaxTypeA = true; } if (bucketData->redBucketB[i + j * width + bucket * (width * height)] > blueMaxCount) { blueMaxCount = bucketData->blueBucketB[i + j * width + bucket * (width * height)]; blueMaxBucket = bucket; blueMaxTypeA = false; } } bucketData->blueFinalBucket[idx].id = blueMaxBucket; bucketData->blueFinalBucket[idx].isABucket = blueMaxTypeA; bucketData->blueFinalBucket[idx].diff = blueMaxCount; } } } } // Optional step to let neighboring buckets with stronger confidence influence the bucket values of // weak confidence pixels void ImageProcessor::refineSolution() { short int confidenceLow = (short int)(0.5f * frames); short int confidenceHigh = (short int)(0.75f * frames); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int idx = i + j * width; // Check to see if the pixel has a low-confidence solution if (bucketData->greenFinalBucket[idx].diff < confidenceLow) { bool done = false; // Iterate through the pixel neighborhood for high confidence values for (int m = i - 1; m < i + 1 && !done; m++) { for (int n = j - 1; n < j + 1 && !done; n++) { if (m >= 0 && m < width && n >= 0 && n < height) { int neighIndex = m + n * width; if (bucketData->greenFinalBucket[neighIndex].diff > confidenceHigh) { // Replace the current pixel's bucket with the neighbor's bucketData->greenFinalBucket[idx] = bucketData->greenFinalBucket[neighIndex]; // Zero out the confidence bucketData->greenFinalBucket[idx].diff = 0; // Break out of the two innermost loops done = true; } } } } } } } } // Create final color image and a confidence mask, then display them void ImageProcessor::createFinal() { std::vector<float> accRed(width * height); std::vector<float> accGreen(width * height); std::vector<float> accBlue(width * height); std::vector<int> count(width * height); std::cout << std::endl << "Averaging:\t"; // Average out all the pixel values from the biggest bucket for (auto &file : fileNames) { cimg::CImg<unsigned char> newImage(file.c_str()); std::cout << "|"; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int idx = i + j * width; int pixelRed = newImage(i, j, 0, 0); int pixelGreen = newImage(i, j, 0, 1); int pixelBlue = newImage(i, j, 0, 2); // Test red // BucketEntry redEntry = bucketData->redFinalBucket[i + j * width]; // if (redEntry.isABucket && redEntry.id != getABucket(pixelRed)) // continue; // if (!redEntry.isABucket && redEntry.id != getBBucket(pixelRed)) // continue; // Test green BucketEntry greenEntry = bucketData->greenFinalBucket[idx]; if (greenEntry.isABucket && greenEntry.id != getABucket(pixelGreen)) continue; if (!greenEntry.isABucket && greenEntry.id != getBBucket(pixelGreen)) continue; // Test blue // BucketEntry blueEntry = bucketData->blueFinalBucket[i + j * width]; // if (blueEntry.isABucket && blueEntry.id != getABucket(pixelBlue)) // continue; // if (!blueEntry.isABucket && blueEntry.id != getBBucket(pixelBlue)) // continue; accRed[idx] += pixelRed; accGreen[idx] += pixelGreen; accBlue[idx] += pixelBlue; count[idx]++; // OLD CODE OLD CODE //if (bucketData->redFinalBucket[i + j * width].isABucket) //{ // int pixABucket = getABucket(pixelRed); // if (pixABucket == bucketData->redFinalBucket[i + j * width].id) // { // accRed[i + j * width] += pixelRed; // accGreen[i + j * width] += newImage(i, j, 0, 1); // accBlue[i + j * width] += newImage(i, j, 0, 2); // count[i + j * width]++; // } //} //else //{ // int pixBBucket = getBBucket(pixelRed); // if (pixBBucket == bucketData->redFinalBucket[i + j * width].id) // { // accRed[i + j * width] += pixelRed; // accGreen[i + j * width] += newImage(i, j, 0, 1); // accBlue[i + j * width] += newImage(i, j, 0, 2); // count[i + j * width]++; // } //} // OLD CODE OLD CODE } } } // Paint the final result in a window cimg::CImg<unsigned char> reconstructionImage(width, height, 1, 3, 0); cimg::CImgDisplay main_disp(width, height, "Reconstructed background"); // Paint the confidence mask cimg::CImg<unsigned char> confidenceImage(width, height, 1, 3, 0); cimg::CImgDisplay aux_disp(width, height, "Confidence mask"); // Paint the green buckets for debugging cimg::CImg<unsigned char> greenBucketImage(width, height, 1, 1, 0); cimg::CImgDisplay green_disp(width, height, "Green buckets"); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int idx = i + j * width; reconstructionImage(i, j, 0, 0) = (unsigned char) (accRed[i + j * width] / count[i + j * width]); reconstructionImage(i, j, 0, 1) = (unsigned char) (accGreen[i + j * width] / count[i + j * width]); reconstructionImage(i, j, 0, 2) = (unsigned char) (accBlue[i + j * width] / count[i + j * width]); int confidence = (int) (count[i + j * width] * ((float)256.0f / frames)); confidence = std::min(confidence, 255); confidenceImage(i, j, 0, 0) = (unsigned char) confidence; confidenceImage(i, j, 0, 1) = (unsigned char) confidence; confidenceImage(i, j, 0, 2) = (unsigned char) confidence; if(count[idx] < 1) { confidenceImage(i, j, 0, 0) = 255; confidenceImage(i, j, 0, 1) = 0; confidenceImage(i, j, 0, 2) = 0; } BucketEntry greenEntry = bucketData->greenFinalBucket[i + j * width]; unsigned char valueGreen = greenEntry.id * bucketSize; if(!greenEntry.isABucket) valueGreen -= bucketSize / 2; greenBucketImage(i, j, 0, 0) = valueGreen; } main_disp.render(reconstructionImage); main_disp.paint(); aux_disp.render(confidenceImage); aux_disp.paint(); green_disp.render(greenBucketImage); green_disp.paint(); } std::cout << std::endl; // Write the final color image to file std::remove("output.png"); reconstructionImage.save_png("output.png"); // Write out the confidence mask std::remove("confidence.png"); confidenceImage.save_png("confidence.png"); while (!main_disp.is_closed()) { main_disp.wait(); } } <|endoftext|>
<commit_before>#include "BeaconTile.h" Tile* BeaconTile::beacon = NULL; BeaconTile::BeaconTile(int id) : Tile(id, &Material::metal) { tex = getTextureUVCoordinateSet("glass", 0); secondary_tex = getTextureUVCoordinateSet("obsidian", 0); terciary_tex = getTextureUVCoordinateSet("beacon", 0); //fourth_tex = getTextureUVCoordinateSet("beacon_beam", 0); //fifth_tex = getTextureUVCoordinateSet("beacon_beam", 1); beacon->renderPass = Tile::glass->renderPass; Tile::solid[id] = false; Tile::lightBlock[id] = 0; new TileItem(id - 256); } bool BeaconTile::isCubeShaped() { return false; } bool BeaconTile::isSolidRender() { return false; } const TextureUVCoordinateSet& BeaconTile::getTexture(signed char side, int data) { return side == 0 ? tex : (side == 1 ? secondary_tex : terciary_tex); } <commit_msg>Hopefully fix the beacon.<commit_after>#include "BeaconTile.h" Tile* BeaconTile::beacon = NULL; BeaconTile::BeaconTile(int id) : Tile(id, &Material::metal) { tex = getTextureUVCoordinateSet("glass", 0); secondary_tex = getTextureUVCoordinateSet("obsidian", 0); terciary_tex = getTextureUVCoordinateSet("diamond_block", 0); //fourth_tex = getTextureUVCoordinateSet("beacon_beam", 0); //fifth_tex = getTextureUVCoordinateSet("beacon_beam", 1); beacon->renderPass = Tile::glass->renderPass; Tile::solid[id] = false; Tile::lightBlock[id] = 0; new TileItem(id - 256); } bool BeaconTile::isCubeShaped() { return false; } bool BeaconTile::isSolidRender() { return false; } const TextureUVCoordinateSet& BeaconTile::getTexture(signed char side, int data) { return side == 0 ? tex : (side == 1 ? secondary_tex : terciary_tex); } <|endoftext|>
<commit_before>/* Copyright (c) 2006 - 2007 Volker Krause <vkrause@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "monitor.h" #include "monitor_p.h" #include "collectionlistjob.h" #include "collectionstatusjob.h" #include "itemfetchjob.h" #include "notificationmanagerinterface.h" #include "notificationmessage.h" #include "session.h" #include <kdebug.h> #include <QtDBus/QDBusInterface> #include <QtDBus/QDBusConnection> #include <QtCore/QDebug> #include <QtCore/QTimer> using namespace Akonadi; class Monitor::Private { public: Private( Monitor *parent ) : mParent( parent ), fetchCollection( false ), fetchCollectionStatus( false ), fetchAllParts( false ) { } Monitor *mParent; org::kde::Akonadi::NotificationManager *nm; Collection::List collections; QSet<QByteArray> resources; QSet<int> items; QSet<QString> mimetypes; bool monitorAll; QList<QByteArray> sessions; QStringList mFetchParts; QHash<KJob*,NotificationMessage> pendingJobs; bool isCollectionMonitored( int collection, const QByteArray &resource ) const { if ( monitorAll || isCollectionMonitored( collection ) || resources.contains( resource ) ) return true; return false; } bool isItemMonitored( uint item, int collection, int collectionDest, const QString &mimetype, const QByteArray &resource ) const { if ( monitorAll || isCollectionMonitored( collection ) || isCollectionMonitored( collectionDest ) ||items.contains( item ) || resources.contains( resource ) || mimetypes.contains( mimetype ) ) return true; return false; } bool isSessionIgnored( const QByteArray &sessionId ) const { return sessions.contains( sessionId ); } bool connectToNotificationManager(); // private slots void sessionDestroyed( QObject* ); void slotStatusChangedFinished( KJob* ); void slotFlushRecentlyChangedCollections(); void slotNotify( const NotificationMessage::List &msgs ); void slotItemJobFinished( KJob* job ); void slotCollectionJobFinished( KJob *job ); void emitItemNotification( const NotificationMessage &msg, const Item &item = Item(), const Collection &collection = Collection(), const Collection &collectionDest = Collection() ); void emitCollectionNotification( const NotificationMessage &msg, const Collection &col = Collection(), const Collection &par = Collection() ); bool fetchCollection; bool fetchCollectionStatus; bool fetchAllParts; private: // collections that need a status update QSet<int> recentlyChangedCollections; bool isCollectionMonitored( int collection ) const { if ( collections.contains( Collection( collection ) ) ) return true; if ( collections.contains( Collection::root() ) ) return true; return false; } void fetchStatus( int colId ) { CollectionStatusJob *job = new CollectionStatusJob( Collection( colId ), mParent ); connect( job, SIGNAL(result(KJob*)), mParent, SLOT(slotStatusChangedFinished(KJob*)) ); } void notifyCollectionStatusWatchers( int collection, const QByteArray &resource ) { if ( isCollectionMonitored( collection, resource ) ) { if (recentlyChangedCollections.empty() ) QTimer::singleShot( 500, mParent, SLOT(slotFlushRecentlyChangedCollections()) ); recentlyChangedCollections.insert( collection ); } } }; bool Monitor::Private::connectToNotificationManager() { NotificationMessage::registerDBusTypes(); if ( !nm ) nm = new org::kde::Akonadi::NotificationManager( QLatin1String( "org.kde.Akonadi" ), QLatin1String( "/notifications" ), QDBusConnection::sessionBus(), mParent ); else return true; if ( !nm ) { qWarning() << "Unable to connect to notification manager"; } else { connect( nm, SIGNAL(notify(Akonadi::NotificationMessage::List)), mParent, SLOT(slotNotify(Akonadi::NotificationMessage::List)) ); return true; } return false; } void Monitor::Private::sessionDestroyed( QObject * object ) { Session* session = qobject_cast<Session*>( object ); if ( session ) sessions.removeAll( session->sessionId() ); } void Monitor::Private::slotStatusChangedFinished( KJob* job ) { if ( job->error() ) { qWarning() << "Error on fetching collection status: " << job->errorText(); } else { CollectionStatusJob *statusJob = static_cast<CollectionStatusJob*>( job ); emit mParent->collectionStatusChanged( statusJob->collection().id(), statusJob->status() ); } } void Monitor::Private::slotFlushRecentlyChangedCollections() { foreach( int collection, recentlyChangedCollections ) { if ( fetchCollectionStatus ) { fetchStatus( collection ); } else { static const CollectionStatus dummyStatus; emit mParent->collectionStatusChanged( collection, dummyStatus ); } } recentlyChangedCollections.clear(); } void Monitor::Private::slotNotify( const NotificationMessage::List &msgs ) { foreach ( const NotificationMessage msg, msgs ) { if ( isSessionIgnored( msg.sessionId() ) ) continue; if ( msg.type() == NotificationMessage::Item ) { notifyCollectionStatusWatchers( msg.parentCollection(), msg.resource() ); if ( !isItemMonitored( msg.uid(), msg.parentCollection(), msg.parentDestCollection(), msg.mimeType(), msg.resource() ) ) continue; if ( !mFetchParts.isEmpty() && ( msg.operation() == NotificationMessage::Add || msg.operation() == NotificationMessage::Move )) { ItemCollectionFetchJob *job = new ItemCollectionFetchJob( DataReference( msg.uid(), msg.remoteId() ), msg.parentCollection(), mParent ); foreach( QString part, mFetchParts ) job->addFetchPart( part ); if ( fetchAllParts ) job->fetchAllParts(); pendingJobs.insert( job, msg ); connect( job, SIGNAL(result(KJob*)), mParent, SLOT(slotItemJobFinished(KJob*)) ); continue; } if ( !mFetchParts.isEmpty() && msg.operation() == NotificationMessage::Modify ) { ItemFetchJob *job = new ItemFetchJob( DataReference( msg.uid(), msg.remoteId() ), mParent ); foreach( QString part, mFetchParts ) job->addFetchPart( part ); if ( fetchAllParts ) job->fetchAllParts(); pendingJobs.insert( job, msg ); connect( job, SIGNAL(result(KJob*)), mParent, SLOT(slotItemJobFinished(KJob*)) ); continue; } emitItemNotification( msg ); } else if ( msg.type() == NotificationMessage::Collection ) { if ( msg.operation() != NotificationMessage::Remove && fetchCollection ) { Collection::List list; list << Collection( msg.uid() ); if ( msg.operation() == NotificationMessage::Add ) list << Collection( msg.parentCollection() ); CollectionListJob *job = new CollectionListJob( list, mParent ); pendingJobs.insert( job, msg ); connect( job, SIGNAL(result(KJob*)), mParent, SLOT(slotCollectionJobFinished(KJob*)) ); continue; } if ( msg.operation() == NotificationMessage::Remove ) { // no need for status updates anymore recentlyChangedCollections.remove( msg.uid() ); } emitCollectionNotification( msg ); } else { qWarning() << "Received unknown change notification!"; } } } void Monitor::Private::emitItemNotification( const NotificationMessage &msg, const Item &item, const Collection &collection, const Collection &collectionDest ) { Q_ASSERT( msg.type() == NotificationMessage::Item ); Collection col = collection; Collection colDest = collectionDest; if ( !col.isValid() ) { col = Collection( msg.parentCollection() ); col.setResource( QString::fromUtf8( msg.resource() ) ); } if ( !colDest.isValid() ) { colDest = Collection( msg.parentDestCollection() ); // FIXME setResource here required ? } Item it = item; if ( !it.isValid() ) { it = Item( DataReference( msg.uid(), msg.remoteId() ) ); it.setMimeType( msg.mimeType() ); } switch ( msg.operation() ) { case NotificationMessage::Add: emit mParent->itemAdded( it, col ); break; case NotificationMessage::Modify: emit mParent->itemChanged( it, msg.itemParts() ); break; case NotificationMessage::Move: emit mParent->itemMoved( it, col, colDest ); break; case NotificationMessage::Remove: emit mParent->itemRemoved( it.reference() ); break; default: Q_ASSERT_X( false, "Monitor::Private::emitItemNotification()", "Invalid enum value" ); } } void Monitor::Private::emitCollectionNotification( const NotificationMessage &msg, const Collection &col, const Collection &par ) { Q_ASSERT( msg.type() == NotificationMessage::Collection ); Collection collection = col; if ( !collection.isValid() ) { collection = Collection( msg.uid() ); collection.setParent( msg.parentCollection() ); collection.setResource( QString::fromUtf8( msg.resource() ) ); collection.setRemoteId( msg.remoteId() ); } Collection parent = par; if ( !parent.isValid() ) parent = Collection( msg.parentCollection() ); switch ( msg.operation() ) { case NotificationMessage::Add: emit mParent->collectionAdded( collection, parent ); break; case NotificationMessage::Modify: emit mParent->collectionChanged( collection ); break; case NotificationMessage::Remove: emit mParent->collectionRemoved( collection.id(), collection.remoteId() ); break; default: Q_ASSERT_X( false, "Monitor::Private::emitCollectionNotification", "Invalid enum value" ); } } void Monitor::Private::slotItemJobFinished( KJob* job ) { if ( !pendingJobs.contains( job ) ) { kWarning() <<"unknown job - wtf is going on here?"; return; } NotificationMessage msg = pendingJobs.take( job ); if ( job->error() ) { kWarning() <<"Error on fetching item:" << job->errorText(); } else { Item item; Collection col; ItemFetchJob *fetchJob = qobject_cast<ItemFetchJob*>( job ); if ( fetchJob && fetchJob->items().count() > 0 ) item = fetchJob->items().first(); ItemCollectionFetchJob *cfjob = qobject_cast<ItemCollectionFetchJob*>( job ); if ( cfjob ) { item = cfjob->item(); col = cfjob->collection(); } emitItemNotification( msg, item, col ); } } void Monitor::Private::slotCollectionJobFinished( KJob* job ) { if ( !pendingJobs.contains( job ) ) { kWarning() <<"unknown job - wtf is going on here?"; return; } NotificationMessage msg = pendingJobs.take( job ); if ( job->error() ) { kWarning() <<"Error on fetching collection:" << job->errorText(); } else { Collection col, parent; CollectionListJob *listJob = qobject_cast<CollectionListJob*>( job ); if ( listJob && listJob->collections().count() > 0 ) col = listJob->collections().first(); if ( listJob && listJob->collections().count() > 1 && msg.operation() == NotificationMessage::Add ) { parent = listJob->collections().at( 1 ); if ( col.id() != msg.uid() ) qSwap( col, parent ); } emitCollectionNotification( msg, col, parent ); } } Monitor::Monitor( QObject *parent ) : QObject( parent ), d( new Private( this ) ) { d->nm = 0; d->monitorAll = false; d->connectToNotificationManager(); } Monitor::~Monitor() { delete d; } void Monitor::monitorCollection( const Collection &collection ) { d->collections << collection; } void Monitor::monitorItem( const DataReference & ref ) { d->items.insert( ref.id() ); } void Monitor::monitorResource(const QByteArray & resource) { d->resources.insert( resource ); } void Monitor::monitorMimeType(const QString & mimetype) { d->mimetypes.insert( mimetype ); } void Akonadi::Monitor::monitorAll() { d->monitorAll = true; } void Monitor::ignoreSession(Session * session) { d->sessions << session->sessionId(); } void Monitor::fetchCollection(bool enable) { d->fetchCollection = enable; } void Monitor::addFetchPart( const QString &identifier ) { if ( !d->mFetchParts.contains( identifier ) ) d->mFetchParts.append( identifier ); } void Monitor::fetchCollectionStatus(bool enable) { d->fetchCollectionStatus = enable; } void Monitor::fetchAllParts() { d->fetchAllParts = true; } #include "monitor.moc" <commit_msg>If you just have fetchAllParts enabled, mFetchParts is empty... So without this patch, the monitor returns Items without payload, which leads to crashes in resources. Volker, is that ok?<commit_after>/* Copyright (c) 2006 - 2007 Volker Krause <vkrause@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "monitor.h" #include "monitor_p.h" #include "collectionlistjob.h" #include "collectionstatusjob.h" #include "itemfetchjob.h" #include "notificationmanagerinterface.h" #include "notificationmessage.h" #include "session.h" #include <kdebug.h> #include <QtDBus/QDBusInterface> #include <QtDBus/QDBusConnection> #include <QtCore/QDebug> #include <QtCore/QTimer> using namespace Akonadi; class Monitor::Private { public: Private( Monitor *parent ) : mParent( parent ), fetchCollection( false ), fetchCollectionStatus( false ), fetchAllParts( false ) { } Monitor *mParent; org::kde::Akonadi::NotificationManager *nm; Collection::List collections; QSet<QByteArray> resources; QSet<int> items; QSet<QString> mimetypes; bool monitorAll; QList<QByteArray> sessions; QStringList mFetchParts; QHash<KJob*,NotificationMessage> pendingJobs; bool isCollectionMonitored( int collection, const QByteArray &resource ) const { if ( monitorAll || isCollectionMonitored( collection ) || resources.contains( resource ) ) return true; return false; } bool isItemMonitored( uint item, int collection, int collectionDest, const QString &mimetype, const QByteArray &resource ) const { if ( monitorAll || isCollectionMonitored( collection ) || isCollectionMonitored( collectionDest ) ||items.contains( item ) || resources.contains( resource ) || mimetypes.contains( mimetype ) ) return true; return false; } bool isSessionIgnored( const QByteArray &sessionId ) const { return sessions.contains( sessionId ); } bool connectToNotificationManager(); // private slots void sessionDestroyed( QObject* ); void slotStatusChangedFinished( KJob* ); void slotFlushRecentlyChangedCollections(); void slotNotify( const NotificationMessage::List &msgs ); void slotItemJobFinished( KJob* job ); void slotCollectionJobFinished( KJob *job ); void emitItemNotification( const NotificationMessage &msg, const Item &item = Item(), const Collection &collection = Collection(), const Collection &collectionDest = Collection() ); void emitCollectionNotification( const NotificationMessage &msg, const Collection &col = Collection(), const Collection &par = Collection() ); bool fetchCollection; bool fetchCollectionStatus; bool fetchAllParts; private: // collections that need a status update QSet<int> recentlyChangedCollections; bool isCollectionMonitored( int collection ) const { if ( collections.contains( Collection( collection ) ) ) return true; if ( collections.contains( Collection::root() ) ) return true; return false; } void fetchStatus( int colId ) { CollectionStatusJob *job = new CollectionStatusJob( Collection( colId ), mParent ); connect( job, SIGNAL(result(KJob*)), mParent, SLOT(slotStatusChangedFinished(KJob*)) ); } void notifyCollectionStatusWatchers( int collection, const QByteArray &resource ) { if ( isCollectionMonitored( collection, resource ) ) { if (recentlyChangedCollections.empty() ) QTimer::singleShot( 500, mParent, SLOT(slotFlushRecentlyChangedCollections()) ); recentlyChangedCollections.insert( collection ); } } }; bool Monitor::Private::connectToNotificationManager() { NotificationMessage::registerDBusTypes(); if ( !nm ) nm = new org::kde::Akonadi::NotificationManager( QLatin1String( "org.kde.Akonadi" ), QLatin1String( "/notifications" ), QDBusConnection::sessionBus(), mParent ); else return true; if ( !nm ) { qWarning() << "Unable to connect to notification manager"; } else { connect( nm, SIGNAL(notify(Akonadi::NotificationMessage::List)), mParent, SLOT(slotNotify(Akonadi::NotificationMessage::List)) ); return true; } return false; } void Monitor::Private::sessionDestroyed( QObject * object ) { Session* session = qobject_cast<Session*>( object ); if ( session ) sessions.removeAll( session->sessionId() ); } void Monitor::Private::slotStatusChangedFinished( KJob* job ) { if ( job->error() ) { qWarning() << "Error on fetching collection status: " << job->errorText(); } else { CollectionStatusJob *statusJob = static_cast<CollectionStatusJob*>( job ); emit mParent->collectionStatusChanged( statusJob->collection().id(), statusJob->status() ); } } void Monitor::Private::slotFlushRecentlyChangedCollections() { foreach( int collection, recentlyChangedCollections ) { if ( fetchCollectionStatus ) { fetchStatus( collection ); } else { static const CollectionStatus dummyStatus; emit mParent->collectionStatusChanged( collection, dummyStatus ); } } recentlyChangedCollections.clear(); } void Monitor::Private::slotNotify( const NotificationMessage::List &msgs ) { foreach ( const NotificationMessage msg, msgs ) { if ( isSessionIgnored( msg.sessionId() ) ) continue; if ( msg.type() == NotificationMessage::Item ) { notifyCollectionStatusWatchers( msg.parentCollection(), msg.resource() ); if ( !isItemMonitored( msg.uid(), msg.parentCollection(), msg.parentDestCollection(), msg.mimeType(), msg.resource() ) ) continue; if ( !mFetchParts.isEmpty() && ( msg.operation() == NotificationMessage::Add || msg.operation() == NotificationMessage::Move ) || fetchAllParts ) { ItemCollectionFetchJob *job = new ItemCollectionFetchJob( DataReference( msg.uid(), msg.remoteId() ), msg.parentCollection(), mParent ); foreach( QString part, mFetchParts ) job->addFetchPart( part ); if ( fetchAllParts ) job->fetchAllParts(); pendingJobs.insert( job, msg ); connect( job, SIGNAL(result(KJob*)), mParent, SLOT(slotItemJobFinished(KJob*)) ); continue; } if ( !mFetchParts.isEmpty() && msg.operation() == NotificationMessage::Modify ) { ItemFetchJob *job = new ItemFetchJob( DataReference( msg.uid(), msg.remoteId() ), mParent ); foreach( QString part, mFetchParts ) job->addFetchPart( part ); if ( fetchAllParts ) job->fetchAllParts(); pendingJobs.insert( job, msg ); connect( job, SIGNAL(result(KJob*)), mParent, SLOT(slotItemJobFinished(KJob*)) ); continue; } emitItemNotification( msg ); } else if ( msg.type() == NotificationMessage::Collection ) { if ( msg.operation() != NotificationMessage::Remove && fetchCollection ) { Collection::List list; list << Collection( msg.uid() ); if ( msg.operation() == NotificationMessage::Add ) list << Collection( msg.parentCollection() ); CollectionListJob *job = new CollectionListJob( list, mParent ); pendingJobs.insert( job, msg ); connect( job, SIGNAL(result(KJob*)), mParent, SLOT(slotCollectionJobFinished(KJob*)) ); continue; } if ( msg.operation() == NotificationMessage::Remove ) { // no need for status updates anymore recentlyChangedCollections.remove( msg.uid() ); } emitCollectionNotification( msg ); } else { qWarning() << "Received unknown change notification!"; } } } void Monitor::Private::emitItemNotification( const NotificationMessage &msg, const Item &item, const Collection &collection, const Collection &collectionDest ) { Q_ASSERT( msg.type() == NotificationMessage::Item ); Collection col = collection; Collection colDest = collectionDest; if ( !col.isValid() ) { col = Collection( msg.parentCollection() ); col.setResource( QString::fromUtf8( msg.resource() ) ); } if ( !colDest.isValid() ) { colDest = Collection( msg.parentDestCollection() ); // FIXME setResource here required ? } Item it = item; if ( !it.isValid() ) { it = Item( DataReference( msg.uid(), msg.remoteId() ) ); it.setMimeType( msg.mimeType() ); } switch ( msg.operation() ) { case NotificationMessage::Add: emit mParent->itemAdded( it, col ); break; case NotificationMessage::Modify: emit mParent->itemChanged( it, msg.itemParts() ); break; case NotificationMessage::Move: emit mParent->itemMoved( it, col, colDest ); break; case NotificationMessage::Remove: emit mParent->itemRemoved( it.reference() ); break; default: Q_ASSERT_X( false, "Monitor::Private::emitItemNotification()", "Invalid enum value" ); } } void Monitor::Private::emitCollectionNotification( const NotificationMessage &msg, const Collection &col, const Collection &par ) { Q_ASSERT( msg.type() == NotificationMessage::Collection ); Collection collection = col; if ( !collection.isValid() ) { collection = Collection( msg.uid() ); collection.setParent( msg.parentCollection() ); collection.setResource( QString::fromUtf8( msg.resource() ) ); collection.setRemoteId( msg.remoteId() ); } Collection parent = par; if ( !parent.isValid() ) parent = Collection( msg.parentCollection() ); switch ( msg.operation() ) { case NotificationMessage::Add: emit mParent->collectionAdded( collection, parent ); break; case NotificationMessage::Modify: emit mParent->collectionChanged( collection ); break; case NotificationMessage::Remove: emit mParent->collectionRemoved( collection.id(), collection.remoteId() ); break; default: Q_ASSERT_X( false, "Monitor::Private::emitCollectionNotification", "Invalid enum value" ); } } void Monitor::Private::slotItemJobFinished( KJob* job ) { if ( !pendingJobs.contains( job ) ) { kWarning() <<"unknown job - wtf is going on here?"; return; } NotificationMessage msg = pendingJobs.take( job ); if ( job->error() ) { kWarning() <<"Error on fetching item:" << job->errorText(); } else { Item item; Collection col; ItemFetchJob *fetchJob = qobject_cast<ItemFetchJob*>( job ); if ( fetchJob && fetchJob->items().count() > 0 ) item = fetchJob->items().first(); ItemCollectionFetchJob *cfjob = qobject_cast<ItemCollectionFetchJob*>( job ); if ( cfjob ) { item = cfjob->item(); col = cfjob->collection(); } emitItemNotification( msg, item, col ); } } void Monitor::Private::slotCollectionJobFinished( KJob* job ) { if ( !pendingJobs.contains( job ) ) { kWarning() <<"unknown job - wtf is going on here?"; return; } NotificationMessage msg = pendingJobs.take( job ); if ( job->error() ) { kWarning() <<"Error on fetching collection:" << job->errorText(); } else { Collection col, parent; CollectionListJob *listJob = qobject_cast<CollectionListJob*>( job ); if ( listJob && listJob->collections().count() > 0 ) col = listJob->collections().first(); if ( listJob && listJob->collections().count() > 1 && msg.operation() == NotificationMessage::Add ) { parent = listJob->collections().at( 1 ); if ( col.id() != msg.uid() ) qSwap( col, parent ); } emitCollectionNotification( msg, col, parent ); } } Monitor::Monitor( QObject *parent ) : QObject( parent ), d( new Private( this ) ) { d->nm = 0; d->monitorAll = false; d->connectToNotificationManager(); } Monitor::~Monitor() { delete d; } void Monitor::monitorCollection( const Collection &collection ) { d->collections << collection; } void Monitor::monitorItem( const DataReference & ref ) { d->items.insert( ref.id() ); } void Monitor::monitorResource(const QByteArray & resource) { d->resources.insert( resource ); } void Monitor::monitorMimeType(const QString & mimetype) { d->mimetypes.insert( mimetype ); } void Akonadi::Monitor::monitorAll() { d->monitorAll = true; } void Monitor::ignoreSession(Session * session) { d->sessions << session->sessionId(); } void Monitor::fetchCollection(bool enable) { d->fetchCollection = enable; } void Monitor::addFetchPart( const QString &identifier ) { if ( !d->mFetchParts.contains( identifier ) ) d->mFetchParts.append( identifier ); } void Monitor::fetchCollectionStatus(bool enable) { d->fetchCollectionStatus = enable; } void Monitor::fetchAllParts() { d->fetchAllParts = true; } #include "monitor.moc" <|endoftext|>
<commit_before>#ifndef VENTURA_REACTIVE_LINUX_INOTIFY_HPP #define VENTURA_REACTIVE_LINUX_INOTIFY_HPP #include <silicium/observable/observer.hpp> #include <silicium/error_or.hpp> #include <silicium/exchange.hpp> #include <silicium/throw_last_error.hpp> #include <ventura/linux/inotify_watch_descriptor.hpp> #include <ventura/absolute_path.hpp> #include <ventura/path_segment.hpp> #include <boost/asio/posix/stream_descriptor.hpp> #include <boost/swap.hpp> #include <boost/optional.hpp> #include <boost/ref.hpp> #include <dirent.h> #define VENTURA_HAS_INOTIFY_OBSERVABLE SILICIUM_HAS_EXCEPTIONS namespace ventura { namespace linux { #if VENTURA_HAS_INOTIFY_OBSERVABLE struct file_notification { boost::uint32_t mask; path_segment name; int watch_descriptor; file_notification() BOOST_NOEXCEPT : mask(0), watch_descriptor(-1) { } explicit file_notification(boost::uint32_t mask, path_segment name, int watch_descriptor) BOOST_NOEXCEPT : mask(mask), name(std::move(name)), watch_descriptor(watch_descriptor) { } }; struct inotify_observable { typedef std::vector<file_notification> element_type; inotify_observable() BOOST_NOEXCEPT { } explicit inotify_observable(boost::asio::io_service &io) : notifier(Si::make_unique<boost::asio::posix::stream_descriptor>(boost::ref(io))) { int fd = inotify_init(); if (fd < 0) { Si::throw_last_error(); } try { notifier->assign(fd); } catch (...) { close(fd); throw; } } Si::error_or<watch_descriptor> watch(absolute_path const &target, boost::uint32_t mask) BOOST_NOEXCEPT { assert(notifier); int const wd = inotify_add_watch(notifier->native_handle(), target.c_str(), mask); if (wd < 0) { return Si::get_last_error(); } return watch_descriptor(notifier->native_handle(), wd); } template <class Observer> void async_get_one(Observer &&receiver) { std::size_t const min_buffer_size = sizeof(inotify_event) + NAME_MAX + 1; std::size_t const additional_buffer = 8192; read_buffer.resize(min_buffer_size + additional_buffer); assert(notifier); notifier->async_read_some( boost::asio::buffer(read_buffer), [ this, SILICIUM_CAPTURE_EXPRESSION(receiver, std::forward<Observer>(receiver)) ]( boost::system::error_code error, std::size_t bytes_read) mutable { if (error) { if (error == boost::asio::error::operation_aborted) { return; } throw std::logic_error("not implemented"); } else { std::vector<file_notification> changes; for (std::size_t i = 0; i < bytes_read;) { inotify_event const &event = *reinterpret_cast<inotify_event const *>(read_buffer.data() + i); Si::optional<path_segment> segment = path_segment::create(boost::filesystem::path( event.name + 0, std::find(event.name + 0, event.name + event.len, '\0'))); assert(segment); changes.emplace_back(file_notification{event.mask, std::move(*segment), event.wd}); i += sizeof(inotify_event); i += event.len; } std::forward<Observer>(receiver).got_element(std::move(changes)); } }); } private: std::unique_ptr<boost::asio::posix::stream_descriptor> notifier; std::vector<char> read_buffer; }; #endif } } #endif <commit_msg>fix for Linux<commit_after>#ifndef VENTURA_REACTIVE_LINUX_INOTIFY_HPP #define VENTURA_REACTIVE_LINUX_INOTIFY_HPP #include <silicium/observable/observer.hpp> #include <silicium/error_or.hpp> #include <silicium/exchange.hpp> #include <silicium/throw_last_error.hpp> #include <ventura/linux/inotify_watch_descriptor.hpp> #include <ventura/absolute_path.hpp> #include <ventura/path_segment.hpp> #include <boost/asio/posix/stream_descriptor.hpp> #include <boost/swap.hpp> #include <boost/optional.hpp> #include <boost/ref.hpp> #include <dirent.h> #define VENTURA_HAS_INOTIFY_OBSERVABLE SILICIUM_HAS_EXCEPTIONS namespace ventura { namespace linux { #if VENTURA_HAS_INOTIFY_OBSERVABLE struct file_notification { boost::uint32_t mask; path_segment name; int watch_descriptor; file_notification() BOOST_NOEXCEPT : mask(0), watch_descriptor(-1) { } explicit file_notification(boost::uint32_t mask, path_segment name, int watch_descriptor) BOOST_NOEXCEPT : mask(mask), name(std::move(name)), watch_descriptor(watch_descriptor) { } }; struct inotify_observable { typedef std::vector<file_notification> element_type; inotify_observable() BOOST_NOEXCEPT { } explicit inotify_observable(boost::asio::io_service &io) : notifier(Si::make_unique<boost::asio::posix::stream_descriptor>(boost::ref(io))) { int fd = inotify_init(); if (fd < 0) { Si::throw_last_error(); } try { notifier->assign(fd); } catch (...) { close(fd); throw; } } Si::error_or<watch_descriptor> watch(absolute_path const &target, boost::uint32_t mask) BOOST_NOEXCEPT { assert(notifier); int const wd = inotify_add_watch(notifier->native_handle(), target.c_str(), mask); if (wd < 0) { return Si::get_last_error(); } return watch_descriptor(notifier->native_handle(), wd); } template <class Observer> void async_get_one(Observer &&receiver) { std::size_t const min_buffer_size = sizeof(inotify_event) + NAME_MAX + 1; std::size_t const additional_buffer = 8192; read_buffer.resize(min_buffer_size + additional_buffer); assert(notifier); notifier->async_read_some( boost::asio::buffer(read_buffer), [ this, SILICIUM_CAPTURE_EXPRESSION(receiver, std::forward<Observer>(receiver)) ]( boost::system::error_code error, std::size_t bytes_read) mutable { if (error) { if (error == boost::asio::error::operation_aborted) { return; } throw std::logic_error("not implemented"); } else { std::vector<file_notification> changes; for (std::size_t i = 0; i < bytes_read;) { inotify_event const &event = *reinterpret_cast<inotify_event const *>(read_buffer.data() + i); Si::optional<path_segment> segment = path_segment::create(path( event.name + 0, std::find(event.name + 0, event.name + event.len, '\0'))); assert(segment); changes.emplace_back(file_notification{event.mask, std::move(*segment), event.wd}); i += sizeof(inotify_event); i += event.len; } std::forward<Observer>(receiver).got_element(std::move(changes)); } }); } private: std::unique_ptr<boost::asio::posix::stream_descriptor> notifier; std::vector<char> read_buffer; }; #endif } } #endif <|endoftext|>
<commit_before>/* Copyright 2016 Mitchell Young 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. */ #pragma once #include <string> const std::string complex_xml = "<mesh id=\"1\" type=\"cyl\" pitch=\"1.26\">" " <radii>0.54 0.62</radii>" " <sub_radii>5 2</sub_radii>" " <sub_azi>8</sub_azi>" "</mesh>" "<mesh id=\"2\" type=\"rect\" pitch=\"1.26\">" " <sub_x>3</sub_x>" " <sub_y>3</sub_y>" "</mesh>" "" "<material_lib path=\"../c5g7.xsl\">" " <material id=\"1\" name=\"UO2-3.3\" />" " <material id=\"2\" name=\"MOX-4.3\" />" " <material id=\"6\" name=\"Moderator\" />" " <material id=\"7\" name=\"GuideTube\" />" " <material id=\"8\" name=\"CRod\" />" "</material_lib>" "" "<!-- UO2 pin -->" "<pin id=\"1\" mesh=\"1\">" " 1 6 6" "</pin>" "<!-- MOx-4.3 pin -->" "<pin id=\"2\" mesh=\"1\">" " 2 6 6" "</pin>" "<!-- MOx-7.0 pin -->" "<pin id=\"3\" mesh=\"1\">" " 3 6 6" "</pin>" "<!-- MOx-8.7 pin -->" "<pin id=\"4\" mesh=\"1\">" " 4 6 6" "</pin>" "<!-- Fission Chamber -->" "<pin id=\"5\" mesh=\"1\">" " 5 6 6" "</pin>" "<!-- Moderator -->" "<pin id=\"6\" mesh=\"2\">" " 6 6 6" " 6 6 6" " 6 6 6" "</pin>" "" "<!-- Guide Tube -->" "<pin id=\"7\" mesh=\"1\">" " 7 6 6" "</pin>" "" "<!-- Control Rod -->" "<pin id=\"8\" mesh=\"1\">" " 8 6 6" "</pin>" "" "" "<!-- Unrodded UO2 -->" "<lattice id=\"1\" nx=\"3\" ny=\"3\">" " 1 1 1" " 1 7 1" " 1 1 1" "</lattice>" "<!-- Rodded UO2 -->" "<lattice id=\"11\" nx=\"3\" ny=\"3\">" " 1 8 1" " 1 8 1" " 1 1 1" "</lattice>" "<!-- Unrodded MOx -->" "<lattice id=\"2\" nx=\"3\" ny=\"3\">" " 2 2 2" " 2 7 2" " 2 2 2" "</lattice>" "<!-- Rodded MOx -->" "<lattice id=\"22\" nx=\"3\" ny=\"3\">" " 2 2 2" " 2 8 2" " 2 2 2" "</lattice>" "" "<!-- Reflector, rodded -->" "<lattice id=\"33\" nx=\"3\" ny=\"3\">" " 6 6 6" " 6 8 6" " 6 6 6" "</lattice>" "" "<assembly id=\"1\" np=\"45\" hz=\"1.428\">" " <lattices>" " {33 33 33 33 33}" " {33 33 33 33 33}" " {33 33 33 33 33}" " {11 11 11 11 11}" " {11 11 11 11 11}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " </lattices>" "</assembly>" "<assembly id=\"2\" np=\"45\" hz=\"1.428\">" " <lattices>" " {33 33 33 33 33}" " {33 33 33 33 33}" " {33 33 33 33 33}" " { 2 2 2 2 2}" " { 2 2 2 2 2}" " { 2 2 2 2 2}" " { 2 2 2 2 2}" " { 2 2 2 2 2}" " { 2 2 2 2 2}" " </lattices>" "</assembly>" "<assembly id=\"3\" np=\"45\" hz=\"1.428\">" " <lattices>" " {33 33 33 33 33}" " {33 33 33 33 33}" " {33 33 33 33 33}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " </lattices>" "</assembly>" "" "<core nx=\"2\" ny=\"2\"" " north=\"reflect\"" " south=\"reflect\"" " east=\"reflect\"" " west=\"reflect\"" " top=\"vacuum\"" " bottom=\"reflect\">" " 1 2" " 2 3" "</core>"; <commit_msg>Split up portions of inputs.hpp<commit_after>/* Copyright 2016 Mitchell Young 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. */ #pragma once #include <string> /* This is a sufficiently complicated example that it should exercise most of the features and variability of the CoreMesh class and its various clients. There are square and non-square lattices, macroplanes of various sizes, non-uniform plane heights. */ const std::string pinmesh_xml = "<mesh id=\"1\" type=\"cyl\" pitch=\"1.26\">" " <radii>0.54 0.62</radii>" " <sub_radii>5 2</sub_radii>" " <sub_azi>8</sub_azi>" "</mesh>" "<mesh id=\"2\" type=\"rect\" pitch=\"1.26\">" " <sub_x>3</sub_x>" " <sub_y>3</sub_y>" "</mesh>"; const std::string material_xml = "<material_lib path=\"c5g7.xsl\">" " <material id=\"1\" name=\"UO2-3.3\" />" " <material id=\"2\" name=\"MOX-4.3\" />" " <material id=\"6\" name=\"Moderator\" />" " <material id=\"7\" name=\"GuideTube\" />" " <material id=\"8\" name=\"CRod\" />" "</material_lib>"; const std::string pin_xml = "<!-- UO2 pin -->" "<pin id=\"1\" mesh=\"1\">" " 1 6 6" "</pin>" "<!-- MOx-4.3 pin -->" "<pin id=\"2\" mesh=\"1\">" " 2 6 6" "</pin>" "<!-- Moderator -->" "<pin id=\"6\" mesh=\"2\">" " 6 6 6" " 6 6 6" " 6 6 6" "</pin>" "" "<!-- Guide Tube -->" "<pin id=\"7\" mesh=\"1\">" " 7 6 6" "</pin>" "" "<!-- Control Rod -->" "<pin id=\"8\" mesh=\"1\">" " 8 6 6" "</pin>"; const std::string lattice_xml = "<!-- Unrodded UO2 -->" "<lattice id=\"1\" nx=\"3\" ny=\"3\">" " 1 1 1" " 1 7 1" " 1 1 1" "</lattice>" "<!-- Rodded UO2 -->" "<lattice id=\"11\" nx=\"3\" ny=\"3\">" " 1 8 1" " 1 8 1" " 1 1 1" "</lattice>" "<!-- Unrodded MOx -->" "<lattice id=\"2\" nx=\"3\" ny=\"3\">" " 2 2 2" " 2 7 2" " 2 2 2" "</lattice>" "<!-- Rodded MOx -->" "<lattice id=\"22\" nx=\"3\" ny=\"3\">" " 2 2 2" " 2 8 2" " 2 2 2" "</lattice>" "" "<!-- Reflector, rodded -->" "<lattice id=\"33\" nx=\"3\" ny=\"3\">" " 6 6 6" " 6 8 6" " 6 6 6" "</lattice>" "<!-- South boundary lattice -->" "<lattice id=\"101\" nx=\"3\" ny=\"2\">" " 1 1 1" " 2 2 2" "</lattice>" "<!-- East boundary lattice -->" "<lattice id=\"102\" nx=\"2\" ny=\"3\">" " 1 2" " 1 2" " 1 2" "</lattice>" "<!-- South boundary lattice -->" "<lattice id=\"103\" nx=\"2\" ny=\"2\">" " 1 2" " 2 2" "</lattice>" "<!-- South boundary reflector -->" "<lattice id=\"201\" nx=\"3\" ny=\"2\">" " 6 6 6" " 6 6 6" "</lattice>" "<!-- East boundary reflector -->" "<lattice id=\"202\" nx=\"2\" ny=\"3\">" " 6 6" " 6 6" " 6 6" "</lattice>" "<!-- South boundary reflector -->" "<lattice id=\"203\" nx=\"2\" ny=\"2\">" " 6 6" " 6 6" "</lattice>"; const std::string assembly_xml = "<assembly id=\"1\" np=\"45\" hz=\"1.428\">" " <lattices>" " {33 33 33 33 33}" " {33 33 33 33 33}" " 33 33 33 33 33" " 11 11 {11 11 11}" " {11 11 11 11 11}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " </lattices>" "</assembly>" "<assembly id=\"2\" np=\"45\" hz=\"1.428\">" " <lattices>" " {33 33 33 33 33}" " {33 33 33 33 33}" " 33 33 33 33 33" " 2 2 {2 2 2}" " { 2 2 2 2 2}" " { 2 2 2 2 2}" " { 2 2 2 2 2}" " { 2 2 2 2 2}" " { 2 2 2 2 2}" " </lattices>" "</assembly>" "<assembly id=\"3\" np=\"45\" hz=\"1.428\">" " <lattices>" " {33 33 33 33 33}" " {33 33 33 33 33}" " 33 33 33 33 33" " 1 1 {1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " { 1 1 1 1 1}" " </lattices>" "</assembly>" "<assembly id=\"11\" np=\"45\" hz=\"1.428\">" " <lattices>" " {201 201 201 201 201}" " {201 201 201 201 201}" " 201 201 201 201 201" " 101 101 {101 101 101}" " {101 101 101 101 101}" " {101 101 101 101 101}" " {101 101 101 101 101}" " {101 101 101 101 101}" " {101 101 101 101 101}" " </lattices>" "</assembly>" "<assembly id=\"12\" np=\"45\" hz=\"1.428\">" " <lattices>" " {202 202 202 202 202}" " {202 202 202 202 202}" " 202 202 202 202 202" " 102 102 {102 102 102}" " {102 102 102 102 102}" " {102 102 102 102 102}" " {102 102 102 102 102}" " {102 102 102 102 102}" " {102 102 102 102 102}" " </lattices>" "</assembly>" "<assembly id=\"13\" np=\"45\" hz=\"1.428\">" " <lattices>" " {203 203 203 203 203}" " {203 203 203 203 203}" " 203 203 203 203 203" " 103 103 {103 103 103}" " {103 103 103 103 103}" " {103 103 103 103 103}" " {103 103 103 103 103}" " {103 103 103 103 103}" " {103 103 103 103 103}" " </lattices>" "</assembly>" "<assembly id=\"100\" np=\"45\" hz=\"1.428\">" " <lattices>" " {203 203 203 203 203}" " {203 203 203 203 203}" " 203 203 203 203 203" " {103 103 103 103 103}" " {103 103 103 103 103}" " {103 103 103 103 103}" " {103 103 103 103 103}" " {103 103 103 103 103}" " {103 103 103 103 103}" " </lattices>" "</assembly>"; const std::string complex_xml = pinmesh_xml + material_xml + pin_xml + lattice_xml + assembly_xml + "<core nx=\"3\" ny=\"3\"" " north=\"reflect\"" " south=\"reflect\"" " east=\"reflect\"" " west=\"reflect\"" " top=\"vacuum\"" " bottom=\"reflect\">" " 1 2 12" " 2 3 12" " 11 11 13" "</core>"; <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth 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. * * VapourSynth 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 VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "vscore.h" #ifdef VS_TARGET_CPU_X86 #include "x86utils.h" #endif VSThread::VSThread(VSThreadPool *owner) : owner(owner), stop(false) { } void VSThread::stopThread() { stop = true; } void VSThread::run() { #ifdef VS_TARGET_OS_WINDOWS if (!vs_isMMXStateOk()) qFatal("Bad MMX state detected after creating new thread"); if (!vs_isFPUStateOk()) qFatal("Bad FPU state detected after creating new thread"); if (!vs_isSSEStateOk()) qFatal("Bad SSE state detected after creating new thread"); #endif owner->lock.lock(); owner->activeThreads.ref(); while (true) { bool ranTask = false; for (int i = 0; i < owner->tasks.count(); i++) { PFrameContext rCtx = owner->tasks[i]; if (rCtx->frameDone && rCtx->returnedFrame) { owner->tasks.removeAt(i--); owner->returnFrame(rCtx, rCtx->returnedFrame); ranTask = true; break; } else if (rCtx->frameDone && rCtx->hasError()) { owner->tasks.removeAt(i--); owner->returnFrame(rCtx, rCtx->getErrorMessage()); ranTask = true; break; } else { PFrameContext pCtx = rCtx; if (rCtx->returnedFrame || rCtx->hasError()) rCtx = rCtx->upstreamContext; Q_ASSERT(rCtx); Q_ASSERT(pCtx); // if an error has already been flagged upstream simply drop this task so a filter won't get multiple arError calls for the same frame if (rCtx->hasError()) { owner->tasks.removeAt(i--); continue; } bool isSingleInstance = (rCtx->clip->filterMode == fmParallelRequests && pCtx->returnedFrame && rCtx->numFrameRequests == 1 && pCtx != rCtx) || rCtx->clip->filterMode == fmSerial; // this check is common for both filter modes, it makes sure that multiple calls won't be made in parallel to a single filter to produce the same frame // special casing so serial unordered doesn't need yet another list if (owner->runningTasks.contains(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n))) continue; if (isSingleInstance) { // this is the complicated case, a new frame may not be started until all calls are completed for the current one if (owner->framesInProgress.contains(rCtx->clip) && owner->framesInProgress[rCtx->clip] != rCtx->n) continue; } // mark task as active owner->tasks.removeAt(i--); owner->runningTasks.insert(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n), rCtx); if (isSingleInstance) owner->framesInProgress.insert(rCtx->clip, rCtx->n); VSActivationReason ar = arInitial; if (pCtx->hasError()) { ar = arError; rCtx->setError(pCtx->getErrorMessage()); } else if (pCtx != rCtx && pCtx->returnedFrame) { if (--rCtx->numFrameRequests) ar = arFrameReady; else ar = arAllFramesReady; Q_ASSERT(rCtx->numFrameRequests >= 0); rCtx->availableFrames.insert(NodeOutputKey(pCtx->clip, pCtx->n, pCtx->index), pCtx->returnedFrame); rCtx->lastCompletedN = pCtx->n; rCtx->lastCompletedNode = pCtx->node; } owner->lock.unlock(); // run task PVideoFrame f = rCtx->clip->getFrameInternal(rCtx->n, ar, rCtx); ranTask = true; owner->lock.lock(); if (f && rCtx->numFrameRequests > 0) qFatal("Frame returned but there are still pending frame requests, filter: %s", rCtx->clip->name.constData()); owner->runningTasks.remove(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n)); if (f || ar == arError || rCtx->hasError()) { // free all input frames quickly since the frame processing is done rCtx->availableFrames.clear(); if (isSingleInstance) { if (owner->framesInProgress[rCtx->clip] != rCtx->n && !rCtx->hasError()) qWarning("Releasing unobtained frame lock"); owner->framesInProgress.remove(rCtx->clip); } owner->allContexts.remove(NodeOutputKey(rCtx->clip, rCtx->n, rCtx->index)); } if (rCtx->hasError()) { PFrameContext n; do { n = rCtx->notificationChain; if (n) { rCtx->notificationChain.clear(); n->setError(rCtx->getErrorMessage()); } if (rCtx->upstreamContext) { owner->startInternal(rCtx); } if (rCtx->frameDone) { owner->returnFrame(rCtx, rCtx->getErrorMessage()); } } while ((rCtx = n)); } else if (f) { Q_ASSERT(rCtx->numFrameRequests == 0); PFrameContext n; do { n = rCtx->notificationChain; if (n) rCtx->notificationChain.clear(); if (rCtx->upstreamContext) { rCtx->returnedFrame = f; owner->startInternal(rCtx); } if (rCtx->frameDone) owner->returnFrame(rCtx, f); } while ((rCtx = n)); } else if (rCtx->numFrameRequests > 0 || rCtx->n < 0) { // already scheduled or in the case of negative n it is simply a cache notify message } else { qFatal("No frame returned at the end of processing by %s", rCtx->clip->name.constData()); } break; } } if ((!ranTask && !stop) || (owner->activeThreadCount() > owner->threadCount())) { owner->activeThreads.deref(); owner->idleThreads++; owner->newWork.wait(&owner->lock); owner->idleThreads--; owner->activeThreads.ref(); } if (stop) { owner->idleThreads--; owner->activeThreads.deref(); owner->lock.unlock(); return; } } } VSThreadPool::VSThreadPool(VSCore *core, int threads) : core(core), activeThreads(0), idleThreads(0) { maxThreads = threads > 0 ? threads : QThread::idealThreadCount(); QMutexLocker m(&lock); } int VSThreadPool::activeThreadCount() const { return activeThreads; } int VSThreadPool::threadCount() const { return maxThreads; } void VSThreadPool::spawnThread() { VSThread *vst = new VSThread(this); allThreads.insert(vst); vst->start(); } void VSThreadPool::setThreadCount(int threads) { maxThreads = threads; } void VSThreadPool::wakeThread() { if (activeThreads < maxThreads && idleThreads == 0) spawnThread(); if (activeThreads < maxThreads) newWork.wakeOne(); } void VSThreadPool::releaseThread() { activeThreads.deref(); } void VSThreadPool::reserveThread() { activeThreads.ref(); } void VSThreadPool::notifyCaches(CacheActivation reason) { QMutexLocker lock(&core->cacheLock); for (int i = 0; i < core->caches.count(); i++) tasks.insert(0, PFrameContext(new FrameContext(reason, 0, core->caches[i], PFrameContext()))); } void VSThreadPool::start(const PFrameContext &context) { Q_ASSERT(context); QMutexLocker m(&lock); startInternal(context); } void VSThreadPool::returnFrame(const PFrameContext &rCtx, const PVideoFrame &f) { Q_ASSERT(rCtx->frameDone); // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others lock.unlock(); VSFrameRef *ref = new VSFrameRef(f); callbackLock.lock(); rCtx->frameDone(rCtx->userData, ref, rCtx->n, rCtx->node, NULL); callbackLock.unlock(); lock.lock(); } void VSThreadPool::returnFrame(const PFrameContext &rCtx, const QByteArray &errMsg) { Q_ASSERT(rCtx->frameDone); // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others lock.unlock(); callbackLock.lock(); rCtx->frameDone(rCtx->userData, NULL, rCtx->n, rCtx->node, errMsg.constData()); callbackLock.unlock(); lock.lock(); } void VSThreadPool::startInternal(const PFrameContext &context) { //technically this could be done by walking up the context chain and add a new notification to the correct one //unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it if (context->n < 0) qFatal("Negative frame request by: %s", context->clip->getName().constData()); // check to see if it's time to reevaluate cache sizes if (core->memory->isOverLimit()) { ticks = 0; notifyCaches(cNeedMemory); } // a normal tick for caches to adjust their sizes based on recent history if (!context->upstreamContext && ticks.fetchAndAddAcquire(1) == 99) { ticks = 0; notifyCaches(cCacheTick); } // add it immediately if the task is to return a completed frame and put it at the front of the line since it has no dependencies if (context->returnedFrame || context->hasError()) { tasks.prepend(context); wakeThread(); return; } else { if (context->upstreamContext) context->upstreamContext->numFrameRequests++; //////////////////////// // see if the task is a duplicate foreach(const PFrameContext &ctx, tasks) { if (context->clip == ctx->clip && context->n == ctx->n && context->index == ctx->index) { if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.append(context); wakeThread(); return; } else { PFrameContext rCtx = ctx; if (rCtx->returnedFrame) rCtx = rCtx->upstreamContext; if (context->clip == rCtx->clip && context->n == rCtx->n && context->index == ctx->index) { PFrameContext t = rCtx; while (t && t->notificationChain) t = t->notificationChain; t->notificationChain = context; return; } } } } NodeOutputKey p(context->clip, context->n, context->index); if (allContexts.contains(p)) { PFrameContext ctx = allContexts[p]; Q_ASSERT(ctx); Q_ASSERT(context->clip == ctx->clip && context->n == ctx->n); if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.append(context); wakeThread(); return; } else { while (ctx->notificationChain) ctx = ctx->notificationChain; ctx->notificationChain = context; return; } } else { allContexts[p] = context; } tasks.append(context); wakeThread(); return; } } bool VSThreadPool::isWorkerThread() { QMutexLocker m(&lock); return allThreads.contains((VSThread *)QThread::currentThread()); } void VSThreadPool::waitForDone() { // todo } VSThreadPool::~VSThreadPool() { QMutexLocker m(&lock); // fixme, hangs on free while (allThreads.count()) { VSThread *t = *allThreads.begin(); t->stopThread(); newWork.wakeAll(); m.unlock(); t->wait(); m.relock(); allThreads.remove(t); delete t; newWork.wakeAll(); } }; <commit_msg>Undo a part of the previous commit since it's broken<commit_after>/* * Copyright (c) 2012 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth 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. * * VapourSynth 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 VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "vscore.h" #ifdef VS_TARGET_CPU_X86 #include "x86utils.h" #endif VSThread::VSThread(VSThreadPool *owner) : owner(owner), stop(false) { } void VSThread::stopThread() { stop = true; } void VSThread::run() { #ifdef VS_TARGET_OS_WINDOWS if (!vs_isMMXStateOk()) qFatal("Bad MMX state detected after creating new thread"); if (!vs_isFPUStateOk()) qFatal("Bad FPU state detected after creating new thread"); if (!vs_isSSEStateOk()) qFatal("Bad SSE state detected after creating new thread"); #endif owner->lock.lock(); owner->activeThreads.ref(); while (true) { bool ranTask = false; for (int i = 0; i < owner->tasks.count(); i++) { PFrameContext rCtx = owner->tasks[i]; if (rCtx->frameDone && rCtx->returnedFrame) { owner->tasks.removeAt(i--); owner->returnFrame(rCtx, rCtx->returnedFrame); ranTask = true; break; } else if (rCtx->frameDone && rCtx->hasError()) { owner->tasks.removeAt(i--); owner->returnFrame(rCtx, rCtx->getErrorMessage()); ranTask = true; break; } else { PFrameContext pCtx = rCtx; if (rCtx->returnedFrame || rCtx->hasError()) rCtx = rCtx->upstreamContext; Q_ASSERT(rCtx); Q_ASSERT(pCtx); // if an error has already been flagged upstream simply drop this task so a filter won't get multiple arError calls for the same frame if (rCtx->hasError()) { owner->tasks.removeAt(i--); continue; } bool isSingleInstance = (rCtx->clip->filterMode == fmParallelRequests && pCtx->returnedFrame && rCtx->numFrameRequests == 1 && pCtx != rCtx) || rCtx->clip->filterMode == fmSerial; // this check is common for both filter modes, it makes sure that multiple calls won't be made in parallel to a single filter to produce the same frame // special casing so serial unordered doesn't need yet another list if (owner->runningTasks.contains(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n))) continue; if (isSingleInstance) { // this is the complicated case, a new frame may not be started until all calls are completed for the current one if (owner->framesInProgress.contains(rCtx->clip) && owner->framesInProgress[rCtx->clip] != rCtx->n) continue; } // mark task as active owner->tasks.removeAt(i--); owner->runningTasks.insert(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n), rCtx); if (isSingleInstance) owner->framesInProgress.insert(rCtx->clip, rCtx->n); VSActivationReason ar = arInitial; if (pCtx->hasError()) { ar = arError; rCtx->setError(pCtx->getErrorMessage()); } else if (pCtx != rCtx && pCtx->returnedFrame) { if (--rCtx->numFrameRequests) ar = arFrameReady; else ar = arAllFramesReady; Q_ASSERT(rCtx->numFrameRequests >= 0); rCtx->availableFrames.insert(NodeOutputKey(pCtx->clip, pCtx->n, pCtx->index), pCtx->returnedFrame); rCtx->lastCompletedN = pCtx->n; rCtx->lastCompletedNode = pCtx->node; } owner->lock.unlock(); // run task PVideoFrame f = rCtx->clip->getFrameInternal(rCtx->n, ar, rCtx); ranTask = true; owner->lock.lock(); if (f && rCtx->numFrameRequests > 0) qFatal("Frame returned but there are still pending frame requests, filter: %s", rCtx->clip->name.constData()); owner->runningTasks.remove(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n)); if (f || ar == arError || rCtx->hasError()) { // free all input frames quickly since the frame processing is done rCtx->availableFrames.clear(); if (isSingleInstance) { if (owner->framesInProgress[rCtx->clip] != rCtx->n && !rCtx->hasError()) qWarning("Releasing unobtained frame lock"); owner->framesInProgress.remove(rCtx->clip); } owner->allContexts.remove(NodeOutputKey(rCtx->clip, rCtx->n, rCtx->index)); } if (rCtx->hasError()) { PFrameContext n; do { n = rCtx->notificationChain; if (n) { rCtx->notificationChain.clear(); n->setError(rCtx->getErrorMessage()); } if (rCtx->upstreamContext) { owner->startInternal(rCtx); } if (rCtx->frameDone) { owner->returnFrame(rCtx, rCtx->getErrorMessage()); } } while ((rCtx = n)); } else if (f) { Q_ASSERT(rCtx->numFrameRequests == 0); PFrameContext n; do { n = rCtx->notificationChain; if (n) rCtx->notificationChain.clear(); if (rCtx->upstreamContext) { rCtx->returnedFrame = f; owner->startInternal(rCtx); } if (rCtx->frameDone) owner->returnFrame(rCtx, f); } while ((rCtx = n)); } else if (rCtx->numFrameRequests > 0 || rCtx->n < 0) { // already scheduled or in the case of negative n it is simply a cache notify message } else { qFatal("No frame returned at the end of processing by %s", rCtx->clip->name.constData()); } break; } } if ((!ranTask && !stop) || (owner->activeThreadCount() > owner->threadCount())) { owner->activeThreads.deref(); owner->idleThreads++; owner->newWork.wait(&owner->lock); owner->idleThreads--; owner->activeThreads.ref(); } if (stop) { owner->idleThreads--; owner->activeThreads.deref(); owner->lock.unlock(); return; } } } VSThreadPool::VSThreadPool(VSCore *core, int threads) : core(core), activeThreads(0), idleThreads(0) { maxThreads = threads > 0 ? threads : QThread::idealThreadCount(); QMutexLocker m(&lock); } int VSThreadPool::activeThreadCount() const { return activeThreads; } int VSThreadPool::threadCount() const { return maxThreads; } void VSThreadPool::spawnThread() { VSThread *vst = new VSThread(this); allThreads.insert(vst); vst->start(); } void VSThreadPool::setThreadCount(int threads) { maxThreads = threads; } void VSThreadPool::wakeThread() { if (activeThreads < maxThreads && idleThreads == 0) spawnThread(); if (activeThreads < maxThreads) newWork.wakeOne(); } void VSThreadPool::releaseThread() { activeThreads.deref(); } void VSThreadPool::reserveThread() { activeThreads.ref(); } void VSThreadPool::notifyCaches(CacheActivation reason) { QMutexLocker lock(&core->cacheLock); for (int i = 0; i < core->caches.count(); i++) tasks.insert(0, PFrameContext(new FrameContext(reason, 0, core->caches[i], PFrameContext()))); } void VSThreadPool::start(const PFrameContext &context) { Q_ASSERT(context); QMutexLocker m(&lock); startInternal(context); } void VSThreadPool::returnFrame(const PFrameContext &rCtx, const PVideoFrame &f) { Q_ASSERT(rCtx->frameDone); // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others lock.unlock(); VSFrameRef *ref = new VSFrameRef(f); callbackLock.lock(); rCtx->frameDone(rCtx->userData, ref, rCtx->n, rCtx->node, NULL); callbackLock.unlock(); lock.lock(); } void VSThreadPool::returnFrame(const PFrameContext &rCtx, const QByteArray &errMsg) { Q_ASSERT(rCtx->frameDone); // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others lock.unlock(); callbackLock.lock(); rCtx->frameDone(rCtx->userData, NULL, rCtx->n, rCtx->node, errMsg.constData()); callbackLock.unlock(); lock.lock(); } void VSThreadPool::startInternal(const PFrameContext &context) { //technically this could be done by walking up the context chain and add a new notification to the correct one //unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it if (context->n < 0) qFatal("Negative frame request by: %s", context->clip->getName().constData()); // check to see if it's time to reevaluate cache sizes if (core->memory->isOverLimit()) { ticks = 0; notifyCaches(cNeedMemory); } // a normal tick for caches to adjust their sizes based on recent history if (!context->upstreamContext && ticks.fetchAndAddAcquire(1) == 99) { ticks = 0; notifyCaches(cCacheTick); } // add it immediately if the task is to return a completed frame and put it at the front of the line since it has no dependencies if (context->returnedFrame || context->hasError()) { tasks.append(context); wakeThread(); return; } else { if (context->upstreamContext) context->upstreamContext->numFrameRequests++; //////////////////////// // see if the task is a duplicate foreach(const PFrameContext &ctx, tasks) { if (context->clip == ctx->clip && context->n == ctx->n && context->index == ctx->index) { if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.append(context); wakeThread(); return; } else { PFrameContext rCtx = ctx; if (rCtx->returnedFrame) rCtx = rCtx->upstreamContext; if (context->clip == rCtx->clip && context->n == rCtx->n && context->index == ctx->index) { PFrameContext t = rCtx; while (t && t->notificationChain) t = t->notificationChain; t->notificationChain = context; return; } } } } NodeOutputKey p(context->clip, context->n, context->index); if (allContexts.contains(p)) { PFrameContext ctx = allContexts[p]; Q_ASSERT(ctx); Q_ASSERT(context->clip == ctx->clip && context->n == ctx->n); if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.append(context); wakeThread(); return; } else { while (ctx->notificationChain) ctx = ctx->notificationChain; ctx->notificationChain = context; return; } } else { allContexts[p] = context; } tasks.append(context); wakeThread(); return; } } bool VSThreadPool::isWorkerThread() { QMutexLocker m(&lock); return allThreads.contains((VSThread *)QThread::currentThread()); } void VSThreadPool::waitForDone() { // todo } VSThreadPool::~VSThreadPool() { QMutexLocker m(&lock); // fixme, hangs on free while (allThreads.count()) { VSThread *t = *allThreads.begin(); t->stopThread(); newWork.wakeAll(); m.unlock(); t->wait(); m.relock(); allThreads.remove(t); delete t; newWork.wakeAll(); } }; <|endoftext|>
<commit_before>// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "trace.h" #include "utils.h" #include "pal.h" #include "fx_ver.h" #include "error_codes.h" #if FEATURE_APPHOST #define CURHOST_TYPE _X("apphost") #define CUREXE_PKG_VER APPHOST_PKG_VER #else // !FEATURE_APPHOST #define CURHOST_TYPE _X("dotnet") #define CUREXE_PKG_VER HOST_PKG_VER #endif // !FEATURE_APPHOST typedef int(*hostfxr_main_fn) (const int argc, const pal::char_t* argv[]); #if FEATURE_APPHOST /** * Detect if the apphost executable is allowed to load and execute a managed assembly. * * - The exe is built with a known hash string at some offset in the image * - The exe is useless as is with the built-in hash value, and will fail with an error message * - The hash value should be replaced with the managed DLL filename using "NUL terminated UTF-8" by "dotnet build" * - The exe may be signed at this point by the app publisher * - When the exe runs, the managed DLL name is validated against the executable's own name * - If validation passes, the embedded managed DLL name will be loaded by the exe * - Note: the maximum size of the managed DLL file name can be 1024 bytes in UTF-8 (not including NUL) * o https://en.wikipedia.org/wiki/Comparison_of_file_systems * has more details on maximum file name sizes. */ #define EMBED_HASH_HI_PART_UTF8 "c3ab8ff13720e8ad9047dd39466b3c89" // SHA-256 of "foobar" in UTF-8 #define EMBED_HASH_LO_PART_UTF8 "74e592c2fa383d4a3960714caef0c4f2" #define EMBED_HASH_FULL_UTF8 (EMBED_HASH_HI_PART_UTF8 EMBED_HASH_LO_PART_UTF8) // NUL terminated bool is_exe_enabled_for_execution(const pal::string_t& own_path) { constexpr int EMBED_SZ = sizeof(EMBED_HASH_FULL_UTF8) / sizeof(EMBED_HASH_FULL_UTF8[0]); constexpr int EMBED_MAX = (EMBED_SZ > 1025 ? EMBED_SZ : 1025); // 1024 DLL name length, 1 NUL static const char embed[EMBED_MAX] = EMBED_HASH_FULL_UTF8; // series of NULs followed by embed hash string static const char hi_part[] = EMBED_HASH_HI_PART_UTF8; static const char lo_part[] = EMBED_HASH_LO_PART_UTF8; // At this point the "embed" variable may contain the embed hash value specified above at compile time // or the managed DLL name replaced by "dotnet build". std::string binding(&embed[0]); pal::string_t pal_binding; if (!pal::utf8_palstring(binding, &pal_binding)) { trace::error(_X("The managed DLL bound to this executable could not be retrieved from the executable image.")); return false; } // Since the single static string is replaced by editing the executable, a reference string is needed to do the compare. // So use two parts of the string that will be unaffected by the edit. size_t hi_len = (sizeof(hi_part) / sizeof(hi_part[0])) - 1; size_t lo_len = (sizeof(lo_part) / sizeof(lo_part[0])) - 1; if ((binding.size() >= (hi_len + lo_len)) && binding.compare(0, hi_len, &hi_part[0]) == 0 && binding.compare(hi_len, lo_len, &lo_part[0]) == 0) { trace::error(_X("This executable is not bound to a managed DLL to execute. The binding value is: '%s'"), pal_binding.c_str()); return false; } pal::string_t own_name = get_filename(own_path); pal::string_t own_dll_filename = get_executable(own_name) + _X(".dll"); if (pal::strcasecmp(own_dll_filename.c_str(), pal_binding.c_str()) != 0) { trace::error(_X("The managed DLL bound to this executable: '%s', did not match own name '%s'."), pal_binding.c_str(), own_dll_filename.c_str()); return false; } trace::info(_X("The managed DLL bound to this executable is: '%s'"), pal_binding.c_str()); return true; } #endif // FEATURE_APPHOST pal::string_t resolve_fxr_path(const pal::string_t& own_dir) { #if FEATURE_APPHOST pal::string_t fxr_path; if (library_exists_in_dir(own_dir, LIBFXR_NAME, &fxr_path)) { trace::info(_X("Resolved fxr [%s]..."), fxr_path.c_str()); return fxr_path; } trace::error(_X("A fatal error occurred, the required library %s could not be found at [%s]"), LIBFXR_NAME, own_dir.c_str()); return pal::string_t(); #else pal::string_t fxr_dir = own_dir; append_path(&fxr_dir, _X("host")); append_path(&fxr_dir, _X("fxr")); if (!pal::directory_exists(fxr_dir)) { trace::error(_X("A fatal error occurred, the folder [%s] does not exist"), fxr_dir.c_str()); return pal::string_t(); } trace::info(_X("Reading fx resolver directory=[%s]"), fxr_dir.c_str()); std::vector<pal::string_t> list; pal::readdir_onlydirectories(fxr_dir, &list); fx_ver_t max_ver(-1, -1, -1); for (const auto& dir : list) { trace::info(_X("Considering fxr version=[%s]..."), dir.c_str()); pal::string_t ver = get_filename(dir); fx_ver_t fx_ver(-1, -1, -1); if (fx_ver_t::parse(ver, &fx_ver, false)) { max_ver = std::max(max_ver, fx_ver); } } if (max_ver == fx_ver_t(-1, -1, -1)) { trace::error(_X("A fatal error occurred, the folder [%s] does not contain any version-numbered child folders"), fxr_dir.c_str()); return pal::string_t(); } pal::string_t max_ver_str = max_ver.as_str(); append_path(&fxr_dir, max_ver_str.c_str()); trace::info(_X("Detected latest fxr version=[%s]..."), fxr_dir.c_str()); pal::string_t ret_path; if (library_exists_in_dir(fxr_dir, LIBFXR_NAME, &ret_path)) { trace::info(_X("Resolved fxr [%s]..."), ret_path.c_str()); return ret_path; } trace::error(_X("A fatal error occurred, the required library %s could not be found in [%s]"), LIBFXR_NAME, fxr_dir.c_str()); return pal::string_t(); #endif } int run(const int argc, const pal::char_t* argv[]) { pal::string_t own_path; if (!pal::get_own_executable_path(&own_path) || !pal::realpath(&own_path)) { trace::error(_X("Failed to resolve full path of the current executable [%s]"), own_path.c_str()); return StatusCode::CoreHostCurExeFindFailure; } #ifdef FEATURE_APPHOST if (!is_exe_enabled_for_execution(own_path)) { trace::error(_X("A fatal error was encountered. This executable was not bound to load a managed DLL.")); return StatusCode::AppHostExeNotBoundFailure; } #else pal::string_t own_name = get_executable(get_filename(own_path)); if (pal::strcasecmp(own_name.c_str(), CURHOST_TYPE) != 0) { trace::error(_X("A fatal error was encountered. Cannot execute %s when renamed to %s."), CURHOST_TYPE,own_name.c_str()); return StatusCode::CoreHostEntryPointFailure; } if (argc <= 1) { trace::println(); trace::println(_X("Usage: dotnet [options]")); trace::println(_X("Usage: dotnet [path-to-application]")); trace::println(); trace::println(_X("Options:")); trace::println(_X(" -h|--help Display help.")); trace::println(_X(" --version Display the current SDK version.")); trace::println(_X(" --list-sdks Display the installed SDKs.")); trace::println(_X(" --list-runtimes Display the installed runtimes.")); trace::println(); trace::println(_X("path-to-application:")); trace::println(_X(" The path to an application .dll file to execute.")); return StatusCode::InvalidArgFailure; } #endif pal::dll_t fxr; pal::string_t own_dir = get_directory(own_path); // Load library pal::string_t fxr_path = resolve_fxr_path(own_dir); if (fxr_path.empty()) { return StatusCode::CoreHostLibMissingFailure; } if (!pal::load_library(&fxr_path, &fxr)) { trace::error(_X("The library %s was found, but loading it from %s failed"), LIBFXR_NAME, fxr_path.c_str()); trace::error(_X(" - Installing .NET Core prerequisites might help resolve this problem.")); trace::error(_X(" %s"), DOTNET_CORE_URL); return StatusCode::CoreHostLibLoadFailure; } // Previous corehost trace messages must be printed before calling trace::setup in hostfxr trace::flush(); // Obtain the entrypoints. hostfxr_main_fn main_fn = (hostfxr_main_fn) pal::get_symbol(fxr, "hostfxr_main"); int code = main_fn(argc, argv); pal::unload_library(fxr); return code; } #if defined(_WIN32) int __cdecl wmain(const int argc, const pal::char_t* argv[]) #else int main(const int argc, const pal::char_t* argv[]) #endif { trace::setup(); if (trace::is_enabled()) { trace::info(_X("--- Invoked %s [version: %s, commit hash: %s] main = {"), CURHOST_TYPE, _STRINGIFY(CUREXE_PKG_VER), _STRINGIFY(REPO_COMMIT_HASH)); for (int i = 0; i < argc; ++i) { trace::info(_X("%s"), argv[i]); } trace::info(_X("}")); } return run(argc, argv); } <commit_msg>Fix issue with standalone exe name length >64 (#3659)<commit_after>// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "trace.h" #include "utils.h" #include "pal.h" #include "fx_ver.h" #include "error_codes.h" #if FEATURE_APPHOST #define CURHOST_TYPE _X("apphost") #define CUREXE_PKG_VER APPHOST_PKG_VER #else // !FEATURE_APPHOST #define CURHOST_TYPE _X("dotnet") #define CUREXE_PKG_VER HOST_PKG_VER #endif // !FEATURE_APPHOST typedef int(*hostfxr_main_fn) (const int argc, const pal::char_t* argv[]); #if FEATURE_APPHOST /** * Detect if the apphost executable is allowed to load and execute a managed assembly. * * - The exe is built with a known hash string at some offset in the image * - The exe is useless as is with the built-in hash value, and will fail with an error message * - The hash value should be replaced with the managed DLL filename using "NUL terminated UTF-8" by "dotnet build" * - The exe may be signed at this point by the app publisher * - When the exe runs, the managed DLL name is validated against the executable's own name * - If validation passes, the embedded managed DLL name will be loaded by the exe * - Note: the maximum size of the managed DLL file name can be 1024 bytes in UTF-8 (not including NUL) * o https://en.wikipedia.org/wiki/Comparison_of_file_systems * has more details on maximum file name sizes. */ #define EMBED_HASH_HI_PART_UTF8 "c3ab8ff13720e8ad9047dd39466b3c89" // SHA-256 of "foobar" in UTF-8 #define EMBED_HASH_LO_PART_UTF8 "74e592c2fa383d4a3960714caef0c4f2" #define EMBED_HASH_FULL_UTF8 (EMBED_HASH_HI_PART_UTF8 EMBED_HASH_LO_PART_UTF8) // NUL terminated bool is_exe_enabled_for_execution(const pal::string_t& own_path) { constexpr int EMBED_SZ = sizeof(EMBED_HASH_FULL_UTF8) / sizeof(EMBED_HASH_FULL_UTF8[0]); constexpr int EMBED_MAX = (EMBED_SZ > 1025 ? EMBED_SZ : 1025); // 1024 DLL name length, 1 NUL // Contains the embed hash value at compile time or the managed DLL name replaced by "dotnet build". // Must not be 'const' because std::string(&embed[0]) below would bind to a const string ctor plus length // where length is determined at compile time (=64) instead of the actual length of the string at runtime. static char embed[EMBED_MAX] = EMBED_HASH_FULL_UTF8; // series of NULs followed by embed hash string static const char hi_part[] = EMBED_HASH_HI_PART_UTF8; static const char lo_part[] = EMBED_HASH_LO_PART_UTF8; std::string binding(&embed[0]); pal::string_t pal_binding; if (!pal::utf8_palstring(binding, &pal_binding)) { trace::error(_X("The managed DLL bound to this executable could not be retrieved from the executable image.")); return false; } // Since the single static string is replaced by editing the executable, a reference string is needed to do the compare. // So use two parts of the string that will be unaffected by the edit. size_t hi_len = (sizeof(hi_part) / sizeof(hi_part[0])) - 1; size_t lo_len = (sizeof(lo_part) / sizeof(lo_part[0])) - 1; if ((binding.size() >= (hi_len + lo_len)) && binding.compare(0, hi_len, &hi_part[0]) == 0 && binding.compare(hi_len, lo_len, &lo_part[0]) == 0) { trace::error(_X("This executable is not bound to a managed DLL to execute. The binding value is: '%s'"), pal_binding.c_str()); return false; } pal::string_t own_name = get_filename(own_path); pal::string_t own_dll_filename = get_executable(own_name) + _X(".dll"); if (pal::strcasecmp(own_dll_filename.c_str(), pal_binding.c_str()) != 0) { trace::error(_X("The managed DLL bound to this executable: '%s', did not match own name '%s'."), pal_binding.c_str(), own_dll_filename.c_str()); return false; } trace::info(_X("The managed DLL bound to this executable is: '%s'"), pal_binding.c_str()); return true; } #endif // FEATURE_APPHOST pal::string_t resolve_fxr_path(const pal::string_t& own_dir) { #if FEATURE_APPHOST pal::string_t fxr_path; if (library_exists_in_dir(own_dir, LIBFXR_NAME, &fxr_path)) { trace::info(_X("Resolved fxr [%s]..."), fxr_path.c_str()); return fxr_path; } trace::error(_X("A fatal error occurred, the required library %s could not be found at [%s]"), LIBFXR_NAME, own_dir.c_str()); return pal::string_t(); #else pal::string_t fxr_dir = own_dir; append_path(&fxr_dir, _X("host")); append_path(&fxr_dir, _X("fxr")); if (!pal::directory_exists(fxr_dir)) { trace::error(_X("A fatal error occurred, the folder [%s] does not exist"), fxr_dir.c_str()); return pal::string_t(); } trace::info(_X("Reading fx resolver directory=[%s]"), fxr_dir.c_str()); std::vector<pal::string_t> list; pal::readdir_onlydirectories(fxr_dir, &list); fx_ver_t max_ver(-1, -1, -1); for (const auto& dir : list) { trace::info(_X("Considering fxr version=[%s]..."), dir.c_str()); pal::string_t ver = get_filename(dir); fx_ver_t fx_ver(-1, -1, -1); if (fx_ver_t::parse(ver, &fx_ver, false)) { max_ver = std::max(max_ver, fx_ver); } } if (max_ver == fx_ver_t(-1, -1, -1)) { trace::error(_X("A fatal error occurred, the folder [%s] does not contain any version-numbered child folders"), fxr_dir.c_str()); return pal::string_t(); } pal::string_t max_ver_str = max_ver.as_str(); append_path(&fxr_dir, max_ver_str.c_str()); trace::info(_X("Detected latest fxr version=[%s]..."), fxr_dir.c_str()); pal::string_t ret_path; if (library_exists_in_dir(fxr_dir, LIBFXR_NAME, &ret_path)) { trace::info(_X("Resolved fxr [%s]..."), ret_path.c_str()); return ret_path; } trace::error(_X("A fatal error occurred, the required library %s could not be found in [%s]"), LIBFXR_NAME, fxr_dir.c_str()); return pal::string_t(); #endif } int run(const int argc, const pal::char_t* argv[]) { pal::string_t own_path; if (!pal::get_own_executable_path(&own_path) || !pal::realpath(&own_path)) { trace::error(_X("Failed to resolve full path of the current executable [%s]"), own_path.c_str()); return StatusCode::CoreHostCurExeFindFailure; } #ifdef FEATURE_APPHOST if (!is_exe_enabled_for_execution(own_path)) { trace::error(_X("A fatal error was encountered. This executable was not bound to load a managed DLL.")); return StatusCode::AppHostExeNotBoundFailure; } #else pal::string_t own_name = get_executable(get_filename(own_path)); if (pal::strcasecmp(own_name.c_str(), CURHOST_TYPE) != 0) { trace::error(_X("A fatal error was encountered. Cannot execute %s when renamed to %s."), CURHOST_TYPE,own_name.c_str()); return StatusCode::CoreHostEntryPointFailure; } if (argc <= 1) { trace::println(); trace::println(_X("Usage: dotnet [options]")); trace::println(_X("Usage: dotnet [path-to-application]")); trace::println(); trace::println(_X("Options:")); trace::println(_X(" -h|--help Display help.")); trace::println(_X(" --version Display the current SDK version.")); trace::println(_X(" --list-sdks Display the installed SDKs.")); trace::println(_X(" --list-runtimes Display the installed runtimes.")); trace::println(); trace::println(_X("path-to-application:")); trace::println(_X(" The path to an application .dll file to execute.")); return StatusCode::InvalidArgFailure; } #endif pal::dll_t fxr; pal::string_t own_dir = get_directory(own_path); // Load library pal::string_t fxr_path = resolve_fxr_path(own_dir); if (fxr_path.empty()) { return StatusCode::CoreHostLibMissingFailure; } if (!pal::load_library(&fxr_path, &fxr)) { trace::error(_X("The library %s was found, but loading it from %s failed"), LIBFXR_NAME, fxr_path.c_str()); trace::error(_X(" - Installing .NET Core prerequisites might help resolve this problem.")); trace::error(_X(" %s"), DOTNET_CORE_URL); return StatusCode::CoreHostLibLoadFailure; } // Previous corehost trace messages must be printed before calling trace::setup in hostfxr trace::flush(); // Obtain the entrypoints. hostfxr_main_fn main_fn = (hostfxr_main_fn) pal::get_symbol(fxr, "hostfxr_main"); int code = main_fn(argc, argv); pal::unload_library(fxr); return code; } #if defined(_WIN32) int __cdecl wmain(const int argc, const pal::char_t* argv[]) #else int main(const int argc, const pal::char_t* argv[]) #endif { trace::setup(); if (trace::is_enabled()) { trace::info(_X("--- Invoked %s [version: %s, commit hash: %s] main = {"), CURHOST_TYPE, _STRINGIFY(CUREXE_PKG_VER), _STRINGIFY(REPO_COMMIT_HASH)); for (int i = 0; i < argc; ++i) { trace::info(_X("%s"), argv[i]); } trace::info(_X("}")); } return run(argc, argv); } <|endoftext|>
<commit_before>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ #if 0 sink_ = new SinkNode(); constant_ = new ConstantNode(1.0); sink_ << constant_; #endif } //-------------------------------------------------------------- void testApp::update(){ } //-------------------------------------------------------------- void testApp::draw(){ plot(std::vector<double>(256, 5.0)); } void testApp::plot(const std::vector<double>& data) { static float radius = 2.0f; float x = 0.0f; float max = *std::max_element(data.begin(), data.end()); for (double y : data) { ofCircle(x, -y / max * ofGetHeight() / 2 + (ofGetHeight() / 2), radius); x += ofGetWidth() / data.size(); } } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>データの最大値を1.0と仮定<commit_after>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ #if 0 sink_ = new SinkNode(); constant_ = new ConstantNode(1.0); sink_ << constant_; #endif } //-------------------------------------------------------------- void testApp::update(){ } //-------------------------------------------------------------- void testApp::draw(){ plot(std::vector<double>(256, -1.0)); } // f[^̍ől1.0Ɖ肵ĕ` void testApp::plot(const std::vector<double>& data) { static float radius = 2.0f; float x = 0.0f; for (double y : data) { ofCircle(x, -y * ofGetHeight() / 2 + (ofGetHeight() / 2), radius); x += ofGetWidth() / data.size(); } } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Project OSRM contributors 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. 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. */ #ifndef TINY_COMPONENTS_HPP #define TINY_COMPONENTS_HPP #include "../typedefs.h" #include "../data_structures/deallocating_vector.hpp" #include "../data_structures/import_edge.hpp" #include "../data_structures/query_node.hpp" #include "../data_structures/percent.hpp" #include "../data_structures/restriction.hpp" #include "../data_structures/restriction_map.hpp" #include "../data_structures/turn_instructions.hpp" #include "../util/integer_range.hpp" #include "../util/simple_logger.hpp" #include "../util/std_hash.hpp" #include "../util/timing_util.hpp" #include <osrm/coordinate.hpp> #include <boost/assert.hpp> #include <tbb/parallel_sort.h> #include <cstdint> #include <memory> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> template <typename GraphT> class TarjanSCC { struct TarjanStackFrame { explicit TarjanStackFrame(NodeID v, NodeID parent) : v(v), parent(parent) {} NodeID v; NodeID parent; }; struct TarjanNode { TarjanNode() : index(SPECIAL_NODEID), low_link(SPECIAL_NODEID), on_stack(false) {} unsigned index; unsigned low_link; bool on_stack; }; std::vector<unsigned> components_index; std::vector<NodeID> component_size_vector; std::shared_ptr<GraphT> m_node_based_graph; std::unordered_set<NodeID> barrier_node_set; RestrictionMap m_restriction_map; std::size_t size_one_counter; public: template <class ContainerT> TarjanSCC(std::shared_ptr<GraphT> graph, const RestrictionMap &restrictions, const ContainerT &barrier_node_list) : components_index(graph->GetNumberOfNodes(), SPECIAL_NODEID), m_node_based_graph(graph), m_restriction_map(restrictions), size_one_counter(0) { barrier_node_set.insert(std::begin(barrier_node_list), std::end(barrier_node_list)); BOOST_ASSERT(m_node_based_graph->GetNumberOfNodes() > 0); } void run() { TIMER_START(SCC_RUN); // The following is a hack to distinguish between stuff that happens // before the recursive call and stuff that happens after std::stack<TarjanStackFrame> recursion_stack; // true = stuff before, false = stuff after call std::stack<NodeID> tarjan_stack; std::vector<TarjanNode> tarjan_node_list(m_node_based_graph->GetNumberOfNodes()); unsigned component_index = 0, size_of_current_component = 0; unsigned index = 0; const NodeID last_node = m_node_based_graph->GetNumberOfNodes(); std::vector<bool> processing_node_before_recursion(m_node_based_graph->GetNumberOfNodes(), true); for (const NodeID node : osrm::irange(0u, last_node)) { if (SPECIAL_NODEID == components_index[node]) { recursion_stack.emplace(TarjanStackFrame(node, node)); } while (!recursion_stack.empty()) { TarjanStackFrame currentFrame = recursion_stack.top(); const NodeID u = currentFrame.parent; const NodeID v = currentFrame.v; recursion_stack.pop(); const bool before_recursion = processing_node_before_recursion[v]; if (before_recursion && tarjan_node_list[v].index != UINT_MAX) { continue; } if (before_recursion) { // Mark frame to handle tail of recursion recursion_stack.emplace(currentFrame); processing_node_before_recursion[v] = false; // Mark essential information for SCC tarjan_node_list[v].index = index; tarjan_node_list[v].low_link = index; tarjan_stack.push(v); tarjan_node_list[v].on_stack = true; ++index; const NodeID to_node_of_only_restriction = m_restriction_map.CheckForEmanatingIsOnlyTurn(u, v); for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(v)) { const auto vprime = m_node_based_graph->GetTarget(current_edge); // Traverse outgoing edges if (barrier_node_set.find(v) != barrier_node_set.end() && u != vprime) { // continue; } if (to_node_of_only_restriction != std::numeric_limits<unsigned>::max() && vprime == to_node_of_only_restriction) { // At an only_-restriction but not at the right turn // continue; } if (m_restriction_map.CheckIfTurnIsRestricted(u, v, vprime)) { // continue; } if (SPECIAL_NODEID == tarjan_node_list[vprime].index) { recursion_stack.emplace(TarjanStackFrame(vprime, v)); } else { if (tarjan_node_list[vprime].on_stack && tarjan_node_list[vprime].index < tarjan_node_list[v].low_link) { tarjan_node_list[v].low_link = tarjan_node_list[vprime].index; } } } } else { processing_node_before_recursion[v] = true; tarjan_node_list[currentFrame.parent].low_link = std::min(tarjan_node_list[currentFrame.parent].low_link, tarjan_node_list[v].low_link); // after recursion, lets do cycle checking // Check if we found a cycle. This is the bottom part of the recursion if (tarjan_node_list[v].low_link == tarjan_node_list[v].index) { NodeID vprime; do { vprime = tarjan_stack.top(); tarjan_stack.pop(); tarjan_node_list[vprime].on_stack = false; components_index[vprime] = component_index; ++size_of_current_component; } while (v != vprime); component_size_vector.emplace_back(size_of_current_component); if (size_of_current_component > 1000) { SimpleLogger().Write() << "large component [" << component_index << "]=" << size_of_current_component; } ++component_index; size_of_current_component = 0; } } } } TIMER_STOP(SCC_RUN); SimpleLogger().Write() << "SCC run took: " << TIMER_MSEC(SCC_RUN) / 1000. << "s"; size_one_counter = std::count_if(component_size_vector.begin(), component_size_vector.end(), [](unsigned value) { return 1 == value; }); } std::size_t get_number_of_components() const { return component_size_vector.size(); } std::size_t get_size_one_count() const { return size_one_counter; } unsigned get_component_size(const NodeID node) const { return component_size_vector[components_index[node]]; } unsigned get_component_id(const NodeID node) const { return components_index[node]; } }; #endif /* TINY_COMPONENTS_HPP */ <commit_msg>make sure GetNumberOfNodes() is only called once<commit_after>/* Copyright (c) 2015, Project OSRM contributors 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. 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. */ #ifndef TINY_COMPONENTS_HPP #define TINY_COMPONENTS_HPP #include "../typedefs.h" #include "../data_structures/deallocating_vector.hpp" #include "../data_structures/import_edge.hpp" #include "../data_structures/query_node.hpp" #include "../data_structures/percent.hpp" #include "../data_structures/restriction.hpp" #include "../data_structures/restriction_map.hpp" #include "../data_structures/turn_instructions.hpp" #include "../util/integer_range.hpp" #include "../util/simple_logger.hpp" #include "../util/std_hash.hpp" #include "../util/timing_util.hpp" #include <osrm/coordinate.hpp> #include <boost/assert.hpp> #include <tbb/parallel_sort.h> #include <cstdint> #include <memory> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> template <typename GraphT> class TarjanSCC { struct TarjanStackFrame { explicit TarjanStackFrame(NodeID v, NodeID parent) : v(v), parent(parent) {} NodeID v; NodeID parent; }; struct TarjanNode { TarjanNode() : index(SPECIAL_NODEID), low_link(SPECIAL_NODEID), on_stack(false) {} unsigned index; unsigned low_link; bool on_stack; }; std::vector<unsigned> components_index; std::vector<NodeID> component_size_vector; std::shared_ptr<GraphT> m_node_based_graph; std::unordered_set<NodeID> barrier_node_set; RestrictionMap m_restriction_map; std::size_t size_one_counter; public: template <class ContainerT> TarjanSCC(std::shared_ptr<GraphT> graph, const RestrictionMap &restrictions, const ContainerT &barrier_node_list) : components_index(graph->GetNumberOfNodes(), SPECIAL_NODEID), m_node_based_graph(graph), m_restriction_map(restrictions), size_one_counter(0) { barrier_node_set.insert(std::begin(barrier_node_list), std::end(barrier_node_list)); BOOST_ASSERT(m_node_based_graph->GetNumberOfNodes() > 0); } void run() { TIMER_START(SCC_RUN); const NodeID max_node_id = m_node_based_graph->GetNumberOfNodes(); // The following is a hack to distinguish between stuff that happens // before the recursive call and stuff that happens after std::stack<TarjanStackFrame> recursion_stack; // true = stuff before, false = stuff after call std::stack<NodeID> tarjan_stack; std::vector<TarjanNode> tarjan_node_list(max_node_id); unsigned component_index = 0, size_of_current_component = 0; unsigned index = 0; std::vector<bool> processing_node_before_recursion(max_node_id, true); for (const NodeID node : osrm::irange(0u, max_node_id)) { if (SPECIAL_NODEID == components_index[node]) { recursion_stack.emplace(TarjanStackFrame(node, node)); } while (!recursion_stack.empty()) { TarjanStackFrame currentFrame = recursion_stack.top(); const NodeID u = currentFrame.parent; const NodeID v = currentFrame.v; recursion_stack.pop(); const bool before_recursion = processing_node_before_recursion[v]; if (before_recursion && tarjan_node_list[v].index != UINT_MAX) { continue; } if (before_recursion) { // Mark frame to handle tail of recursion recursion_stack.emplace(currentFrame); processing_node_before_recursion[v] = false; // Mark essential information for SCC tarjan_node_list[v].index = index; tarjan_node_list[v].low_link = index; tarjan_stack.push(v); tarjan_node_list[v].on_stack = true; ++index; const NodeID to_node_of_only_restriction = m_restriction_map.CheckForEmanatingIsOnlyTurn(u, v); for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(v)) { const auto vprime = m_node_based_graph->GetTarget(current_edge); // Traverse outgoing edges if (barrier_node_set.find(v) != barrier_node_set.end() && u != vprime) { // continue; } if (to_node_of_only_restriction != std::numeric_limits<unsigned>::max() && vprime == to_node_of_only_restriction) { // At an only_-restriction but not at the right turn // continue; } if (m_restriction_map.CheckIfTurnIsRestricted(u, v, vprime)) { // continue; } if (SPECIAL_NODEID == tarjan_node_list[vprime].index) { recursion_stack.emplace(TarjanStackFrame(vprime, v)); } else { if (tarjan_node_list[vprime].on_stack && tarjan_node_list[vprime].index < tarjan_node_list[v].low_link) { tarjan_node_list[v].low_link = tarjan_node_list[vprime].index; } } } } else { processing_node_before_recursion[v] = true; tarjan_node_list[currentFrame.parent].low_link = std::min(tarjan_node_list[currentFrame.parent].low_link, tarjan_node_list[v].low_link); // after recursion, lets do cycle checking // Check if we found a cycle. This is the bottom part of the recursion if (tarjan_node_list[v].low_link == tarjan_node_list[v].index) { NodeID vprime; do { vprime = tarjan_stack.top(); tarjan_stack.pop(); tarjan_node_list[vprime].on_stack = false; components_index[vprime] = component_index; ++size_of_current_component; } while (v != vprime); component_size_vector.emplace_back(size_of_current_component); if (size_of_current_component > 1000) { SimpleLogger().Write() << "large component [" << component_index << "]=" << size_of_current_component; } ++component_index; size_of_current_component = 0; } } } } TIMER_STOP(SCC_RUN); SimpleLogger().Write() << "SCC run took: " << TIMER_MSEC(SCC_RUN) / 1000. << "s"; size_one_counter = std::count_if(component_size_vector.begin(), component_size_vector.end(), [](unsigned value) { return 1 == value; }); } std::size_t get_number_of_components() const { return component_size_vector.size(); } std::size_t get_size_one_count() const { return size_one_counter; } unsigned get_component_size(const NodeID node) const { return component_size_vector[components_index[node]]; } unsigned get_component_id(const NodeID node) const { return components_index[node]; } }; #endif /* TINY_COMPONENTS_HPP */ <|endoftext|>
<commit_before>/// HEADER #include <csapex.h> /// PROJECT #include <csapex/core/csapex_core.h> #include <csapex/core/drag_io.h> #include <csapex/core/graphio.h> #include <csapex/core/settings.h> #include <csapex/scheduling/thread_pool.h> #include <csapex/model/graph.h> #include <csapex/model/graph_worker.h> #include <csapex/model/node_factory.h> #include <csapex/model/node_factory.h> #include <csapex/model/node_worker.h> #include <csapex/plugin/plugin_locator.h> #include <csapex/utility/error_handling.h> #include <csapex/utility/thread.h> #include <csapex/view/activity_legend.h> #include <csapex/view/activity_timeline.h> #include <csapex/view/box.h> #include <csapex/view/csapex_window.h> #include <csapex/view/designer.h> #include <csapex/view/designer_scene.h> #include <csapex/view/designer_view.h> #include <csapex/view/minimap_widget.h> #include <csapex/view/node_adapter_factory.h> #include <csapex/view/widget_controller.h> #include <utils_param/parameter_factory.h> /// SYSTEM #include <boost/program_options.hpp> #include <QtGui> #include <execinfo.h> #include <stdlib.h> #include <console_bridge/console.h> namespace po = boost::program_options; using namespace csapex; CsApexApp::CsApexApp(int& argc, char** argv, bool fatal_exceptions) : QApplication(argc, argv), fatal_exceptions_(fatal_exceptions) {} CsApexCoreApp::CsApexCoreApp(int& argc, char** argv, bool fatal_exceptions) : QCoreApplication(argc, argv), fatal_exceptions_(fatal_exceptions) {} bool CsApexApp::notify(QObject* receiver, QEvent* event) { try { return QApplication::notify(receiver, event); } catch(const std::exception& e) { ErrorState* er = dynamic_cast<ErrorState*> (receiver); NodeWorker* bw = dynamic_cast<NodeWorker*> (receiver); if(fatal_exceptions_) { std::cerr << "caught an exception in --fatal-exceptions mode: Abort!" << std::endl; std::abort(); } std::cerr << "exception: " << e.what() << std::endl; if(er) { er->setError(true, e.what()); } else if(bw) { bw->triggerError(true, e.what()); } else { std::cerr << "Uncatched exception:" << e.what() << std::endl; } return false; } catch(const std::string& s) { std::cerr << "Uncatched exception (string) exception: " << s << std::endl; } catch(...) { std::cerr << "Uncatched exception of unknown type and origin!" << std::endl; std::abort(); } return true; } bool CsApexCoreApp::notify(QObject* receiver, QEvent* event) { try { return QCoreApplication::notify(receiver, event); } catch(const std::exception& e) { ErrorState* er = dynamic_cast<ErrorState*> (receiver); NodeWorker* bw = dynamic_cast<NodeWorker*> (receiver); if(fatal_exceptions_) { std::cerr << "caught an exception in --fatal-exceptions mode: Abort!" << std::endl; std::abort(); } std::cerr << "exception: " << e.what() << std::endl; if(er) { er->setError(true, e.what()); } else if(bw) { bw->triggerError(true, e.what()); } else { std::cerr << "Uncatched exception:" << e.what() << std::endl; } return false; } catch(const std::string& s) { std::cerr << "Uncatched exception (string) exception: " << s << std::endl; } catch(...) { std::cerr << "Uncatched exception of unknown type and origin!" << std::endl; std::abort(); } return true; } Main::Main(std::unique_ptr<QCoreApplication> &&a) : app(std::move(a)), splash(nullptr) { csapex::thread::set_name("cs::APEX main"); } Main::~Main() { delete splash; } int Main::run() { csapex::error_handling::init(); int result = app->exec(); return result; } int Main::main(bool headless, bool threadless, bool paused, bool thread_grouping, const std::string& config, const std::string& path_to_bin, const std::vector<std::string>& additional_args) { // console_bridge::setLogLevel(console_bridge::CONSOLE_BRIDGE_LOG_DEBUG); if(!headless) { QPixmap pm(":/apex_splash.png"); splash = new QSplashScreen (pm); splash->show(); showMessage("loading libraries"); } Settings settings; settings.set("config", config); if(!settings.knows("path_to_bin")) { settings.add(param::ParameterFactory::declareFileInputPath("path_to_bin", path_to_bin)); } else { settings.set("path_to_bin", path_to_bin); } if(!settings.knows("headless")) { settings.add(param::ParameterFactory::declareBool("headless", headless)); } else { settings.set("headless", headless); } if(!settings.knows("threadless")) { settings.add(param::ParameterFactory::declareBool("threadless", threadless)); } else { settings.set("threadless", threadless); } if(!settings.knows("thread_grouping")) { settings.add(param::ParameterFactory::declareBool("thread_grouping", thread_grouping)); } else { settings.set("thread_grouping", thread_grouping); } if(!settings.knows("additional_args")) { settings.add(param::ParameterFactory::declareValue< std::vector<std::string> >("additional_args", additional_args)); } else { settings.set("additional_args", additional_args); } PluginLocatorPtr plugin_locator =std::make_shared<PluginLocator>(settings); GraphPtr graph = std::make_shared<Graph>(); ThreadPool thread_pool(!threadless, thread_grouping, paused); GraphWorkerPtr graph_worker = std::make_shared<GraphWorker>(thread_pool, graph.get()); graph_worker->generatorAdded.connect([&thread_pool](TaskGeneratorPtr tg) { thread_pool.add(tg.get()); }); graph_worker->generatorRemoved.connect([&thread_pool](TaskGeneratorPtr tg) { thread_pool.remove(tg.get()); }); graph_worker->paused.connect([&thread_pool](bool pause) { thread_pool.setPause(pause); }); graph_worker->stopped.connect([&thread_pool]() { thread_pool.stop(); }); NodeFactoryPtr node_factory = std::make_shared<NodeFactory>(settings, plugin_locator.get()); NodeAdapterFactoryPtr node_adapter_factory = std::make_shared<NodeAdapterFactory>(settings, plugin_locator.get()); CommandDispatcher dispatcher(settings, graph_worker, graph, &thread_pool, node_factory.get()); // TODO: core must be destroyed AFTER the factories -> refactor it CsApexCorePtr core = std::make_shared<CsApexCore>(settings, plugin_locator, graph_worker, graph, thread_pool, node_factory.get(), node_adapter_factory.get(), &dispatcher); core->saveSettingsRequest.connect([&thread_pool](YAML::Node& n){ thread_pool.saveSettings(n); }); core->loadSettingsRequest.connect([&thread_pool](YAML::Node& n){ thread_pool.loadSettings(n); }); int res; if(!headless) { app->processEvents(); app->connect(app.get(), SIGNAL(lastWindowClosed()), app.get(), SLOT(quit())); WidgetControllerPtr widget_control = std::make_shared<WidgetController>(settings, dispatcher, graph_worker, node_factory.get(), node_adapter_factory.get()); DragIO drag_io(graph.get(), &dispatcher, widget_control); DesignerStyleable style; DesignerScene* scene = new DesignerScene(graph, &dispatcher, widget_control, &style); DesignerView* view = new DesignerView(scene, graph, settings, thread_pool, &dispatcher, widget_control, drag_io, &style); MinimapWidget* minimap = new MinimapWidget(view, scene); Designer* designer = new Designer(settings, graph, &dispatcher, widget_control, view, scene, minimap); ActivityLegend* legend = new ActivityLegend; ActivityTimeline* timeline = new ActivityTimeline; QObject::connect(legend, SIGNAL(nodeSelectionChanged(QList<NodeWorker*>)), timeline, SLOT(setSelection(QList<NodeWorker*>))); graph->nodeAdded.connect([legend](NodeWorkerPtr n) { legend->startTrackingNode(n); }); graph->nodeRemoved.connect([legend](NodeWorkerPtr n) { legend->stopTrackingNode(n); }); QObject::connect(legend, SIGNAL(nodeAdded(NodeWorker*)), timeline, SLOT(addNode(NodeWorker*))); QObject::connect(legend, SIGNAL(nodeRemoved(NodeWorker*)), timeline, SLOT(removeNode(NodeWorker*))); widget_control->setDesigner(designer); CsApexWindow w(*core, &dispatcher, widget_control, graph_worker, graph, thread_pool, designer, minimap, legend, timeline, plugin_locator.get()); QObject::connect(&w, SIGNAL(statusChanged(QString)), this, SLOT(showMessage(QString))); csapex::error_handling::stop_request().connect(std::bind(&CsApexWindow::close, &w)); core->init(&drag_io); w.start(); core->startup(); w.show(); splash->finish(&w); res = run(); delete designer; } else { core->init(nullptr); csapex::error_handling::stop_request().connect(std::bind(&csapex::error_handling::kill)); core->startup(); res = run(); } node_factory.reset(); node_adapter_factory.reset(); return res; } void Main::showMessage(const QString& msg) { if(splash->isVisible()) { splash->showMessage(msg, Qt::AlignTop | Qt::AlignRight, Qt::black); } app->processEvents(); } int main(int argc, char** argv) { // console_bridge::setLogLevel(console_bridge::CONSOLE_BRIDGE_LOG_DEBUG); std::string path_to_bin(argv[0]); po::options_description desc("Allowed options"); desc.add_options() ("help", "show help message") ("dump", "show variables") ("paused", "start paused") ("headless", "run without gui") ("threadless", "run without threading") ("fatal_exceptions", "abort execution on exception") ("thread_grouping", "create one thread per graph component") ("input", "config file to load") ; po::positional_options_description p; p.add("input", 1); // first check for --headless or --fatal_exceptions parameter // this has to be done before the qapp can be created, which // has to be done before parameters can be read. bool headless = false; bool fatal_exceptions = false; for(int i = 1; i < argc; ++i) { std::string arg(argv[i]); if(arg == "--headless") { headless = true; } else if(arg == "--fatal_exceptions") { fatal_exceptions = true; } } if(!headless) { // if headless not requested, check if there is a display // if not, we enforce headless mode if(!getenv("DISPLAY")) { headless = true; std::cout << "warning: enforcing headless mode because there is no display detected" << std::endl; } } // filters all qt parameters from argv std::unique_ptr<QCoreApplication> app; if(headless) { app.reset(new CsApexCoreApp(argc, argv, fatal_exceptions)); } else { app.reset(new CsApexApp(argc, argv, fatal_exceptions)); } // filters ros remappings std::vector<std::string> remapping_args; std::vector<std::string> rest_args; for(int i = 1; i < argc; ++i) { std::string arg(argv[i]); if(arg.find(":=") != std::string::npos) { remapping_args.push_back(arg); } else { rest_args.push_back(arg); } } // now check for remaining parameters po::variables_map vm; std::vector<std::string> additional_args; try { po::parsed_options parsed = po::command_line_parser(rest_args).options(desc).positional(p).run(); po::store(parsed, vm); po::notify(vm); additional_args = po::collect_unrecognized(parsed.options, po::include_positional); } catch(const std::exception& e) { std::cerr << "cannot parse parameters: " << e.what() << std::endl; return 4; } // add ros remappings additional_args.insert(additional_args.end(), remapping_args.begin(), remapping_args.end()); // display help? if(vm.count("help")) { std::cerr << desc << std::endl; return 1; } if(vm.count("dump")) { std::cout << "to be passed on:\n"; for(std::size_t i = 0; i < additional_args.size(); ++i) { std::cout << additional_args[i] << "\n"; } std::cout << std::flush; return 0; } // which file to use? std::string input; if (vm.count("input")) { input = vm["input"].as<std::string>(); } else { input = Settings::default_config; } bool threadless = vm.count("threadless"); bool thread_grouping = vm.count("thread_grouping"); bool paused = vm.count("paused"); // start the app Main m(std::move(app)); return m.main(headless, threadless, paused, thread_grouping, input, path_to_bin, additional_args); } /// MOC #include "moc_csapex.cpp" <commit_msg>quick fix<commit_after>/// HEADER #include <csapex.h> /// PROJECT #include <csapex/core/csapex_core.h> #include <csapex/core/drag_io.h> #include <csapex/core/graphio.h> #include <csapex/core/settings.h> #include <csapex/scheduling/thread_pool.h> #include <csapex/model/graph.h> #include <csapex/model/graph_worker.h> #include <csapex/model/node_factory.h> #include <csapex/model/node_factory.h> #include <csapex/model/node_worker.h> #include <csapex/plugin/plugin_locator.h> #include <csapex/utility/error_handling.h> #include <csapex/utility/thread.h> #include <csapex/view/activity_legend.h> #include <csapex/view/activity_timeline.h> #include <csapex/view/box.h> #include <csapex/view/csapex_window.h> #include <csapex/view/designer.h> #include <csapex/view/designer_scene.h> #include <csapex/view/designer_view.h> #include <csapex/view/minimap_widget.h> #include <csapex/view/node_adapter_factory.h> #include <csapex/view/widget_controller.h> #include <utils_param/parameter_factory.h> /// SYSTEM #include <boost/program_options.hpp> #include <QtGui> #include <execinfo.h> #include <stdlib.h> #include <console_bridge/console.h> namespace po = boost::program_options; using namespace csapex; CsApexApp::CsApexApp(int& argc, char** argv, bool fatal_exceptions) : QApplication(argc, argv), fatal_exceptions_(fatal_exceptions) {} CsApexCoreApp::CsApexCoreApp(int& argc, char** argv, bool fatal_exceptions) : QCoreApplication(argc, argv), fatal_exceptions_(fatal_exceptions) {} bool CsApexApp::notify(QObject* receiver, QEvent* event) { try { return QApplication::notify(receiver, event); } catch(const std::exception& e) { ErrorState* er = dynamic_cast<ErrorState*> (receiver); NodeWorker* bw = dynamic_cast<NodeWorker*> (receiver); if(fatal_exceptions_) { std::cerr << "caught an exception in --fatal-exceptions mode: Abort!" << std::endl; std::abort(); } std::cerr << "exception: " << e.what() << std::endl; if(er) { er->setError(true, e.what()); } else if(bw) { bw->triggerError(true, e.what()); } else { std::cerr << "Uncatched exception:" << e.what() << std::endl; } return false; } catch(const std::string& s) { std::cerr << "Uncatched exception (string) exception: " << s << std::endl; } catch(...) { std::cerr << "Uncatched exception of unknown type and origin!" << std::endl; std::abort(); } return true; } bool CsApexCoreApp::notify(QObject* receiver, QEvent* event) { try { return QCoreApplication::notify(receiver, event); } catch(const std::exception& e) { ErrorState* er = dynamic_cast<ErrorState*> (receiver); NodeWorker* bw = dynamic_cast<NodeWorker*> (receiver); if(fatal_exceptions_) { std::cerr << "caught an exception in --fatal-exceptions mode: Abort!" << std::endl; std::abort(); } std::cerr << "exception: " << e.what() << std::endl; if(er) { er->setError(true, e.what()); } else if(bw) { bw->triggerError(true, e.what()); } else { std::cerr << "Uncatched exception:" << e.what() << std::endl; } return false; } catch(const std::string& s) { std::cerr << "Uncatched exception (string) exception: " << s << std::endl; } catch(...) { std::cerr << "Uncatched exception of unknown type and origin!" << std::endl; std::abort(); } return true; } Main::Main(std::unique_ptr<QCoreApplication> &&a) : app(std::move(a)), splash(nullptr) { csapex::thread::set_name("cs::APEX main"); } Main::~Main() { delete splash; } int Main::run() { csapex::error_handling::init(); int result = app->exec(); return result; } int Main::main(bool headless, bool threadless, bool paused, bool thread_grouping, const std::string& config, const std::string& path_to_bin, const std::vector<std::string>& additional_args) { // console_bridge::setLogLevel(console_bridge::CONSOLE_BRIDGE_LOG_DEBUG); if(!headless) { QPixmap pm(":/apex_splash.png"); splash = new QSplashScreen (pm); splash->show(); showMessage("loading libraries"); } Settings settings; settings.set("config", config); if(!settings.knows("path_to_bin")) { settings.add(param::ParameterFactory::declareFileInputPath("path_to_bin", path_to_bin)); } else { settings.set("path_to_bin", path_to_bin); } if(!settings.knows("headless")) { settings.add(param::ParameterFactory::declareBool("headless", headless)); } else { settings.set("headless", headless); } if(!settings.knows("threadless")) { settings.add(param::ParameterFactory::declareBool("threadless", threadless)); } else { settings.set("threadless", threadless); } if(!settings.knows("thread_grouping")) { settings.add(param::ParameterFactory::declareBool("thread_grouping", thread_grouping)); } else { settings.set("thread_grouping", thread_grouping); } if(!settings.knows("additional_args")) { settings.add(param::ParameterFactory::declareValue< std::vector<std::string> >("additional_args", additional_args)); } else { settings.set("additional_args", additional_args); } PluginLocatorPtr plugin_locator =std::make_shared<PluginLocator>(settings); GraphPtr graph = std::make_shared<Graph>(); ThreadPool thread_pool(!threadless, thread_grouping, paused); GraphWorkerPtr graph_worker = std::make_shared<GraphWorker>(thread_pool, graph.get()); graph_worker->generatorAdded.connect([&thread_pool](TaskGeneratorPtr tg) { thread_pool.add(tg.get()); }); graph_worker->generatorRemoved.connect([&thread_pool](TaskGeneratorPtr tg) { thread_pool.remove(tg.get()); }); graph_worker->paused.connect([&thread_pool](bool pause) { thread_pool.setPause(pause); }); graph_worker->stopped.connect([&thread_pool]() { thread_pool.stop(); }); NodeFactoryPtr node_factory = std::make_shared<NodeFactory>(settings, plugin_locator.get()); NodeAdapterFactoryPtr node_adapter_factory = std::make_shared<NodeAdapterFactory>(settings, plugin_locator.get()); CommandDispatcher dispatcher(settings, graph_worker, graph, &thread_pool, node_factory.get()); // TODO: core must be destroyed AFTER the factories -> refactor it CsApexCorePtr core = std::make_shared<CsApexCore>(settings, plugin_locator, graph_worker, graph, thread_pool, node_factory.get(), node_adapter_factory.get(), &dispatcher); core->saveSettingsRequest.connect([&thread_pool](YAML::Node& n){ thread_pool.saveSettings(n); }); core->loadSettingsRequest.connect([&thread_pool](YAML::Node& n){ thread_pool.loadSettings(n); }); int res; if(!headless) { app->processEvents(); app->connect(app.get(), SIGNAL(lastWindowClosed()), app.get(), SLOT(quit())); WidgetControllerPtr widget_control = std::make_shared<WidgetController>(settings, dispatcher, graph_worker, node_factory.get(), node_adapter_factory.get()); DragIO drag_io(graph.get(), &dispatcher, widget_control); DesignerStyleable style; DesignerScene* scene = new DesignerScene(graph, &dispatcher, widget_control, &style); DesignerView* view = new DesignerView(scene, graph, settings, thread_pool, &dispatcher, widget_control, drag_io, &style); MinimapWidget* minimap = new MinimapWidget(view, scene); Designer* designer = new Designer(settings, graph, &dispatcher, widget_control, view, scene, minimap); ActivityLegend* legend = new ActivityLegend; ActivityTimeline* timeline = new ActivityTimeline; QObject::connect(legend, SIGNAL(nodeSelectionChanged(QList<NodeWorker*>)), timeline, SLOT(setSelection(QList<NodeWorker*>))); graph->nodeAdded.connect([legend](NodeWorkerPtr n) { legend->startTrackingNode(n); }); graph->nodeRemoved.connect([legend](NodeWorkerPtr n) { legend->stopTrackingNode(n); }); QObject::connect(legend, SIGNAL(nodeAdded(NodeWorker*)), timeline, SLOT(addNode(NodeWorker*))); QObject::connect(legend, SIGNAL(nodeRemoved(NodeWorker*)), timeline, SLOT(removeNode(NodeWorker*))); widget_control->setDesigner(designer); CsApexWindow w(*core, &dispatcher, widget_control, graph_worker, graph, thread_pool, designer, minimap, legend, timeline, plugin_locator.get()); QObject::connect(&w, SIGNAL(statusChanged(QString)), this, SLOT(showMessage(QString))); csapex::error_handling::stop_request().connect(std::bind(&CsApexWindow::close, &w)); core->init(&drag_io); w.start(); core->startup(); w.show(); splash->finish(&w); res = run(); // FIXME: this is necessary for some adapted nodes. graph->reset(); delete designer; } else { core->init(nullptr); csapex::error_handling::stop_request().connect(std::bind(&csapex::error_handling::kill)); core->startup(); res = run(); } node_factory.reset(); node_adapter_factory.reset(); return res; } void Main::showMessage(const QString& msg) { if(splash->isVisible()) { splash->showMessage(msg, Qt::AlignTop | Qt::AlignRight, Qt::black); } app->processEvents(); } int main(int argc, char** argv) { // console_bridge::setLogLevel(console_bridge::CONSOLE_BRIDGE_LOG_DEBUG); std::string path_to_bin(argv[0]); po::options_description desc("Allowed options"); desc.add_options() ("help", "show help message") ("dump", "show variables") ("paused", "start paused") ("headless", "run without gui") ("threadless", "run without threading") ("fatal_exceptions", "abort execution on exception") ("thread_grouping", "create one thread per graph component") ("input", "config file to load") ; po::positional_options_description p; p.add("input", 1); // first check for --headless or --fatal_exceptions parameter // this has to be done before the qapp can be created, which // has to be done before parameters can be read. bool headless = false; bool fatal_exceptions = false; for(int i = 1; i < argc; ++i) { std::string arg(argv[i]); if(arg == "--headless") { headless = true; } else if(arg == "--fatal_exceptions") { fatal_exceptions = true; } } if(!headless) { // if headless not requested, check if there is a display // if not, we enforce headless mode if(!getenv("DISPLAY")) { headless = true; std::cout << "warning: enforcing headless mode because there is no display detected" << std::endl; } } // filters all qt parameters from argv std::unique_ptr<QCoreApplication> app; if(headless) { app.reset(new CsApexCoreApp(argc, argv, fatal_exceptions)); } else { app.reset(new CsApexApp(argc, argv, fatal_exceptions)); } // filters ros remappings std::vector<std::string> remapping_args; std::vector<std::string> rest_args; for(int i = 1; i < argc; ++i) { std::string arg(argv[i]); if(arg.find(":=") != std::string::npos) { remapping_args.push_back(arg); } else { rest_args.push_back(arg); } } // now check for remaining parameters po::variables_map vm; std::vector<std::string> additional_args; try { po::parsed_options parsed = po::command_line_parser(rest_args).options(desc).positional(p).run(); po::store(parsed, vm); po::notify(vm); additional_args = po::collect_unrecognized(parsed.options, po::include_positional); } catch(const std::exception& e) { std::cerr << "cannot parse parameters: " << e.what() << std::endl; return 4; } // add ros remappings additional_args.insert(additional_args.end(), remapping_args.begin(), remapping_args.end()); // display help? if(vm.count("help")) { std::cerr << desc << std::endl; return 1; } if(vm.count("dump")) { std::cout << "to be passed on:\n"; for(std::size_t i = 0; i < additional_args.size(); ++i) { std::cout << additional_args[i] << "\n"; } std::cout << std::flush; return 0; } // which file to use? std::string input; if (vm.count("input")) { input = vm["input"].as<std::string>(); } else { input = Settings::default_config; } bool threadless = vm.count("threadless"); bool thread_grouping = vm.count("thread_grouping"); bool paused = vm.count("paused"); // start the app Main m(std::move(app)); return m.main(headless, threadless, paused, thread_grouping, input, path_to_bin, additional_args); } /// MOC #include "moc_csapex.cpp" <|endoftext|>
<commit_before>/* * ===================================================================================== * * Filename: main.cc * * Description: * * Version: 1.0 * Created: 03/20/2008 12:34:14 AM EDT * Revision: none * Compiler: gcc * * Author: Nikolaos Vasiloglou (NV), nvasil@ieee.org * Company: Georgia Tech Fastlab-ESP Lab * * ===================================================================================== */ #include <string> #include "fastlib/fastlib.h" #include "mvu_objectives.h" #include "../l_bfgs/l_bfgs.h" int main(int argc, char *argv[]){ fx_module *fx_root=fx_init(argc, argv, NULL); std::string optimized_function=fx_param_str(NULL, "opts/optfun", "mvu"); std::string data_file=fx_param_str_req(NULL, "opts/data_file"); Matrix data_mat; if (data::Load(data_file.c_str(), &data_mat)==SUCCESS_FAIL) { FATAL("Didn't manage to load %s", data_file.c_str()); } NOTIFY("Removing the mean., centering data..."); OptUtils::RemoveMean(&data_mat); fx_module *optfun_node; fx_module *l_bfgs_node; l_bfgs_node=fx_submodule(fx_root, "opts/l_bfgs"); optfun_node=fx_submodule(fx_root, "opts/optfun"); bool pca_preprocess=fx_param_bool(fx_root, "opts/pca_pre", false); index_t pca_dimension=fx_param_int(fx_root, "opts/pca_dim", 5); bool pca_init=fx_param_bool(fx_root, "opts/pca_init", false); Matrix *initial_data; if (pca_preprocess==true) { NOTIFY("Preprocessing with pca"); Matrix temp; OptUtils::SVDTransform(data_mat, &temp, pca_dimension); data_mat.Destruct(); data_mat.Own(&temp); } if (pca_init==true) { NOTIFY("Preprocessing with pca"); initial_data = new Matrix(); index_t new_dimension=fx_param_int(l_bfgs_node, "new_dimension", 2); OptUtils::SVDTransform(data_mat, initial_data, new_dimension); } //we need to insert the number of points fx_set_param_int(l_bfgs_node, "num_of_points", data_mat.n_cols()); std::string result_file=fx_param_str(NULL, "opts/result_file", "result.csv"); bool done=false; if (optimized_function == "mvu") { MaxVariance opt_function; opt_function.Init(optfun_node, data_mat); LBfgs<MaxVariance> engine; engine.Init(&opt_function, l_bfgs_node); if (pca_init==true) { engine.set_coordinates(*initial_data); } engine.ComputeLocalOptimumBFGS(); Matrix result; engine.GetResults(&result); if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) { FATAL("Didn't manage to save %s", result_file.c_str()); } engine.Destruct(); done=true; } if (optimized_function=="mvuineq") { MaxVarianceInequalityOnFurthest opt_function; opt_function.Init(optfun_node, data_mat); LBfgs<MaxVarianceInequalityOnFurthest> engine; engine.Init(&opt_function, l_bfgs_node); if (pca_init==true) { engine.set_coordinates(*initial_data); } engine.ComputeLocalOptimumBFGS(); Matrix result; engine.GetResults(&result); if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) { FATAL("Didn't manage to save %s", result_file.c_str()); } engine.Destruct(); done=true; } if (optimized_function == "mvfu"){ MaxFurthestNeighbors opt_function; opt_function.Init(optfun_node, data_mat); //opt_function.set_lagrange_mult(0.0); LBfgs<MaxFurthestNeighbors> engine; engine.Init(&opt_function, l_bfgs_node); if (pca_init==true) { la::Scale(1e-1, initial_data); engine.set_coordinates(*initial_data); } engine.ComputeLocalOptimumBFGS(); Matrix result; engine.GetResults(&result); if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) { FATAL("Didn't manage to save %s", result_file.c_str()); } engine.Destruct(); done=true; } if (done==false) { FATAL("The method you provided %s is not supported", optimized_function.c_str()); } if (pca_init==true) { delete initial_data; } fx_done(fx_root); } <commit_msg>Fixed a minor warning<commit_after>/* * ===================================================================================== * * Filename: main.cc * * Description: * * Version: 1.0 * Created: 03/20/2008 12:34:14 AM EDT * Revision: none * Compiler: gcc * * Author: Nikolaos Vasiloglou (NV), nvasil@ieee.org * Company: Georgia Tech Fastlab-ESP Lab * * ===================================================================================== */ #include <string> #include "fastlib/fastlib.h" #include "mvu_objectives.h" #include "../l_bfgs/l_bfgs.h" int main(int argc, char *argv[]){ fx_module *fx_root=fx_init(argc, argv, NULL); std::string optimized_function=fx_param_str(NULL, "opts/optfun", "mvu"); std::string data_file=fx_param_str_req(NULL, "opts/data_file"); Matrix data_mat; if (data::Load(data_file.c_str(), &data_mat)==SUCCESS_FAIL) { FATAL("Didn't manage to load %s", data_file.c_str()); } NOTIFY("Removing the mean., centering data..."); OptUtils::RemoveMean(&data_mat); fx_module *optfun_node; fx_module *l_bfgs_node; l_bfgs_node=fx_submodule(fx_root, "opts/l_bfgs"); optfun_node=fx_submodule(fx_root, "opts/optfun"); bool pca_preprocess=fx_param_bool(fx_root, "opts/pca_pre", false); index_t pca_dimension=fx_param_int(fx_root, "opts/pca_dim", 5); bool pca_init=fx_param_bool(fx_root, "opts/pca_init", false); Matrix *initial_data=NULL; if (pca_preprocess==true) { NOTIFY("Preprocessing with pca"); Matrix temp; OptUtils::SVDTransform(data_mat, &temp, pca_dimension); data_mat.Destruct(); data_mat.Own(&temp); } if (pca_init==true) { NOTIFY("Preprocessing with pca"); initial_data = new Matrix(); index_t new_dimension=fx_param_int(l_bfgs_node, "new_dimension", 2); OptUtils::SVDTransform(data_mat, initial_data, new_dimension); } //we need to insert the number of points fx_set_param_int(l_bfgs_node, "num_of_points", data_mat.n_cols()); std::string result_file=fx_param_str(NULL, "opts/result_file", "result.csv"); bool done=false; if (optimized_function == "mvu") { MaxVariance opt_function; opt_function.Init(optfun_node, data_mat); LBfgs<MaxVariance> engine; engine.Init(&opt_function, l_bfgs_node); if (pca_init==true) { engine.set_coordinates(*initial_data); } engine.ComputeLocalOptimumBFGS(); Matrix result; engine.GetResults(&result); if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) { FATAL("Didn't manage to save %s", result_file.c_str()); } engine.Destruct(); done=true; } if (optimized_function=="mvuineq") { MaxVarianceInequalityOnFurthest opt_function; opt_function.Init(optfun_node, data_mat); LBfgs<MaxVarianceInequalityOnFurthest> engine; engine.Init(&opt_function, l_bfgs_node); if (pca_init==true) { engine.set_coordinates(*initial_data); } engine.ComputeLocalOptimumBFGS(); Matrix result; engine.GetResults(&result); if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) { FATAL("Didn't manage to save %s", result_file.c_str()); } engine.Destruct(); done=true; } if (optimized_function == "mvfu"){ MaxFurthestNeighbors opt_function; opt_function.Init(optfun_node, data_mat); //opt_function.set_lagrange_mult(0.0); LBfgs<MaxFurthestNeighbors> engine; engine.Init(&opt_function, l_bfgs_node); if (pca_init==true) { la::Scale(1e-1, initial_data); engine.set_coordinates(*initial_data); } engine.ComputeLocalOptimumBFGS(); Matrix result; engine.GetResults(&result); if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) { FATAL("Didn't manage to save %s", result_file.c_str()); } engine.Destruct(); done=true; } if (done==false) { FATAL("The method you provided %s is not supported", optimized_function.c_str()); } if (pca_init==true) { delete initial_data; } fx_done(fx_root); } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbConcatenateImages.h" #include <iostream> #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbObjectList.h" #include "otbImageList.h" #include "otbImageListToVectorImageFilter.h" #include "otbStreamingImageFileWriter.h" #include "otbStandardFilterWatcher.h" namespace otb { template<typename PixelType> int generic_main_concatenate(otb::ApplicationOptionsResult* parseResult) { const unsigned int NbImages = parseResult->GetNumberOfParameters("InputImagesList"); std::ofstream textFile; if (parseResult->IsOptionPresent("OutputNameList")) { std::string textName = parseResult->GetParameterString("OutputNameList"); textFile.open(textName.c_str()); } std::cout << "Concat of " << NbImages << " images into a multi-band image " << std::endl; const unsigned int Dimension = 2; typedef otb::Image<PixelType, Dimension> InputImageType; typedef otb::ImageFileReader<InputImageType> ImageReaderType; typedef otb::ObjectList<ImageReaderType> ReaderListType; typename ReaderListType::Pointer readerList = ReaderListType::New(); typedef otb::ImageList<InputImageType> ImageListType; typename ImageListType::Pointer imageList = ImageListType::New(); for (unsigned int i = 0; i < NbImages; i++) { typename ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName(parseResult->GetParameterString("InputImagesList", i).c_str()); std::cout << "Adding image " << parseResult->GetParameterString("InputImagesList", i).c_str() << std::endl; textFile << parseResult->GetParameterString("InputImagesList", i) << "\n"; imageReader->UpdateOutputInformation(); imageList->PushBack(imageReader->GetOutput()); readerList->PushBack(imageReader); } textFile.close(); typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::ImageListToVectorImageFilter<ImageListType, VectorImageType> ImageListToVectorImageFilterType; typename ImageListToVectorImageFilterType::Pointer iL2VI = ImageListToVectorImageFilterType::New(); iL2VI->SetInput(imageList); typedef otb::StreamingImageFileWriter<VectorImageType> ImageWriterType; typename ImageWriterType::Pointer imageWriter = ImageWriterType::New(); imageWriter->SetFileName(parseResult->GetOutputImage().c_str()); unsigned long size = (10000 * 10000 * sizeof(PixelType)) / NbImages; std::cout << "Streaming size: " << size << std::endl; imageWriter->SetBufferMemorySize(size); imageWriter->SetInput(iL2VI->GetOutput()); otb::StandardFilterWatcher watcher(imageWriter, "Writing"); imageWriter->Update(); return EXIT_SUCCESS; } int ConcatenateImages::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("ConcatenateImages"); descriptor->SetDescription("Concatenate n images in a multiband image"); descriptor->AddOptionNParams("InputImagesList", "Images list to concatenate", "il", true,ApplicationDescriptor::InputImage); descriptor->AddOutputImage(); descriptor->AddOption("OutputPixelType", "OutputPixelType: unsigned char (1), short int (2), int (3), float (4)," " double (5), unsigned short int (12), unsigned int (13); default 2", "t", 1, false, ApplicationDescriptor::Integer); descriptor->AddOption("OutputNameList", "Text file containing the name of the images used to generate the output in the same order", "ot", 1, false,ApplicationDescriptor::String); return EXIT_SUCCESS; } int ConcatenateImages::Execute(otb::ApplicationOptionsResult* parseResult) { unsigned int type = 2; //default to short int as the original //program if (parseResult->IsOptionPresent("OutputPixelType")) { type = parseResult->GetParameterUInt("OutputPixelType"); } switch (type) { case 1: generic_main_concatenate<unsigned char> (parseResult); break; case 2: generic_main_concatenate<short int> (parseResult); break; case 3: generic_main_concatenate<int> (parseResult); break; case 4: generic_main_concatenate<float> (parseResult); break; case 5: generic_main_concatenate<double> (parseResult); break; case 12: generic_main_concatenate<unsigned short int> (parseResult); break; case 13: generic_main_concatenate<unsigned int> (parseResult); break; default: generic_main_concatenate<unsigned char> (parseResult); break; } return EXIT_SUCCESS; } } <commit_msg>STYLE<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbConcatenateImages.h" #include <iostream> #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbObjectList.h" #include "otbImageList.h" #include "otbImageListToVectorImageFilter.h" #include "otbStreamingImageFileWriter.h" #include "otbStandardFilterWatcher.h" namespace otb { template<typename PixelType> int generic_main_concatenate(otb::ApplicationOptionsResult* parseResult) { const unsigned int NbImages = parseResult->GetNumberOfParameters("InputImagesList"); std::ofstream textFile; if (parseResult->IsOptionPresent("OutputNameList")) { std::string textName = parseResult->GetParameterString("OutputNameList"); textFile.open(textName.c_str()); } std::cout << "Concat of " << NbImages << " images into a multi-band image " << std::endl; const unsigned int Dimension = 2; typedef otb::Image<PixelType, Dimension> InputImageType; typedef otb::ImageFileReader<InputImageType> ImageReaderType; typedef otb::ObjectList<ImageReaderType> ReaderListType; typename ReaderListType::Pointer readerList = ReaderListType::New(); typedef otb::ImageList<InputImageType> ImageListType; typename ImageListType::Pointer imageList = ImageListType::New(); for (unsigned int i = 0; i < NbImages; i++) { typename ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName(parseResult->GetParameterString("InputImagesList", i).c_str()); std::cout << "Adding image " << parseResult->GetParameterString("InputImagesList", i).c_str() << std::endl; textFile << parseResult->GetParameterString("InputImagesList", i) << "\n"; imageReader->UpdateOutputInformation(); imageList->PushBack(imageReader->GetOutput()); readerList->PushBack(imageReader); } textFile.close(); typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::ImageListToVectorImageFilter<ImageListType, VectorImageType> ImageListToVectorImageFilterType; typename ImageListToVectorImageFilterType::Pointer iL2VI = ImageListToVectorImageFilterType::New(); iL2VI->SetInput(imageList); typedef otb::StreamingImageFileWriter<VectorImageType> ImageWriterType; typename ImageWriterType::Pointer imageWriter = ImageWriterType::New(); imageWriter->SetFileName(parseResult->GetOutputImage().c_str()); unsigned long size = (10000 * 10000 * sizeof(PixelType)) / NbImages; std::cout << "Streaming size: " << size << std::endl; imageWriter->SetBufferMemorySize(size); imageWriter->SetInput(iL2VI->GetOutput()); otb::StandardFilterWatcher watcher(imageWriter, "Writing"); imageWriter->Update(); return EXIT_SUCCESS; } int ConcatenateImages::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("ConcatenateImages"); descriptor->SetDescription("Concatenate n images in a multiband image"); descriptor->AddOptionNParams("InputImagesList", "Images list to concatenate", "il", true, ApplicationDescriptor::InputImage); descriptor->AddOutputImage(); descriptor->AddOption("OutputPixelType", "OutputPixelType: unsigned char (1), short int (2), int (3), float (4)," " double (5), unsigned short int (12), unsigned int (13); default 2", "t", 1, false, ApplicationDescriptor::Integer); descriptor->AddOption("OutputNameList", "Text file containing the name of the images used to generate the output in the same order", "ot", 1, false, ApplicationDescriptor::String); return EXIT_SUCCESS; } int ConcatenateImages::Execute(otb::ApplicationOptionsResult* parseResult) { unsigned int type = 2; //default to short int as the original //program if (parseResult->IsOptionPresent("OutputPixelType")) { type = parseResult->GetParameterUInt("OutputPixelType"); } switch (type) { case 1: generic_main_concatenate<unsigned char> (parseResult); break; case 2: generic_main_concatenate<short int> (parseResult); break; case 3: generic_main_concatenate<int> (parseResult); break; case 4: generic_main_concatenate<float> (parseResult); break; case 5: generic_main_concatenate<double> (parseResult); break; case 12: generic_main_concatenate<unsigned short int> (parseResult); break; case 13: generic_main_concatenate<unsigned int> (parseResult); break; default: generic_main_concatenate<unsigned char> (parseResult); break; } return EXIT_SUCCESS; } } <|endoftext|>
<commit_before>/* * derived from: https://github.com/sabas1080/FXAS21002C_Arduino_Library * * modified by Francesco Ferraro 01/2016 * francesco.ferrarogm@gmail.com * */ #include <Wire.h> #include <math.h> #include "FXAS21002C.h" // Public Methods ////////////////////////////////////////////////////////////// FXAS21002C::FXAS21002C(byte addr) { address = addr; gyroODR = GODR_200HZ; // gyroFSR = GFS_1000DPS; } void FXAS21002C::writeReg(byte reg, byte value) { Wire1.beginTransmission(address); Wire1.write(reg); Wire1.write(value); Wire1.endTransmission(); } // Reads a register byte FXAS21002C::readReg(byte reg) { byte value; Wire1.beginTransmission(address); Wire1.write(reg); Wire1.endTransmission(); Wire1.requestFrom(address, (uint8_t)1); value = Wire1.read(); Wire1.endTransmission(); return value; } void FXAS21002C::readRegs(byte reg, uint8_t count, byte dest[]) { uint8_t i = 0; Wire1.beginTransmission(address); // Initialize the Tx buffer Wire1.write(reg); // Put slave register address in Tx buffer Wire1.endTransmission(false); // Send the Tx buffer, but send a restart to keep connection alive Wire1.requestFrom(address, count); // Read bytes from slave register address while (Wire1.available()) { dest[i++] = Wire1.read(); // Put read results in the Rx buffer } } // Read the temperature data void FXAS21002C::readTempData() { tempData = readReg(FXAS21002C_H_TEMP); } // Put the FXAS21002C into standby mode. // It must be in standby for modifying most registers void FXAS21002C::standby() { byte c = readReg(FXAS21002C_H_CTRL_REG1); writeReg(FXAS21002C_H_CTRL_REG1, c & ~(0x03));// Clear bits 0 and 1; standby mode } // Sets the FXAS21000 to active mode. // Needs to be in this mode to output data void FXAS21002C::ready() { byte c = readReg(FXAS21002C_H_CTRL_REG1); writeReg(FXAS21002C_H_CTRL_REG1, c & ~(0x03)); // Clear bits 0 and 1; standby mode writeReg(FXAS21002C_H_CTRL_REG1, c | 0x01); // Set bit 0 to 1, ready mode; no data acquisition yet } // Put the FXAS21002C into active mode. // Needs to be in this mode to output data. void FXAS21002C::active() { byte c = readReg(FXAS21002C_H_CTRL_REG1); writeReg(FXAS21002C_H_CTRL_REG1, c & ~(0x03)); // Clear bits 0 and 1; standby mode writeReg(FXAS21002C_H_CTRL_REG1, c | 0x02); // Set bit 1 to 1, active mode; data acquisition enabled } void FXAS21002C::init() { /* standby(); // Must be in standby to change registers // Set up the full scale range to 250, 500, 1000, or 2000 deg/s. writeReg(FXAS21002C_H_CTRL_REG0, gyroFSR); // Setup the 3 data rate bits, 4:2 if (gyroODR < 8) writeReg(FXAS21002C_H_CTRL_REG1, gyroODR << 2); // Disable FIFO, route FIFO and rate threshold interrupts to INT2, enable data ready interrupt, route to INT1 // Active HIGH, push-pull output driver on interrupts writeReg(FXAS21002C_H_CTRL_REG2, 0x0E); // Set up rate threshold detection; at max rate threshold = FSR; rate threshold = THS*FSR/128 writeReg(FXAS21002C_H_RT_CFG, 0x07); // enable rate threshold detection on all axes writeReg(FXAS21002C_H_RT_THS, 0x00 | 0x0D); // unsigned 7-bit THS, set to one-tenth FSR; set clearing debounce counter writeReg(FXAS21002C_H_RT_COUNT, 0x04); // set to 4 (can set up to 255) // Configure interrupts 1 and 2 //writeReg(CTRL_REG3, readReg(CTRL_REG3) & ~(0x02)); // clear bits 0, 1 //writeReg(CTRL_REG3, readReg(CTRL_REG3) | (0x02)); // select ACTIVE HIGH, push-pull interrupts //writeReg(CTRL_REG4, readReg(CTRL_REG4) & ~(0x1D)); // clear bits 0, 3, and 4 //writeReg(CTRL_REG4, readReg(CTRL_REG4) | (0x1D)); // DRDY, Freefall/Motion, P/L and tap ints enabled //writeReg(CTRL_REG5, 0x01); // DRDY on INT1, P/L and taps on INT2 active(); // Set to active to start reading */ // write 0000 0000 = 0x00 to CTRL_REG1 to place FXOS21002 in Standby // [7]: ZR_cond=0 // [6]: RST=0 // [5]: ST=0 self test disabled // [4-2]: DR[2-0]=000 for 800Hz // [1-0]: Active=0, Ready=0 for Standby mode writeReg(FXAS21002_CTRL_REG1, 0x00); // write 0000 0000 = 0x00 to CTRL_REG0 to configure range and filters // [7-6]: BW[1-0]=00, LPF disabled // [5]: SPIW=0 4 wire SPI (irrelevant) // [4-3]: SEL[1-0]=00 for 10Hz HPF at 200Hz ODR // [2]: HPF_EN=0 disable HPF // [1-0]: FS[1-0]=00 for 1600dps (TBD CHANGE TO 2000dps when final trimmed parts available) writeReg(FXAS21002_CTRL_REG0, 0b00000001); // [7-4]: BW[1-0]=00, LPF disabled // [3]: Auto-increment read address pointer roll-over behavior: // [2]: External power mode control input // [1] disabled // [0]: Full-scale range expansion enable writeReg(FXAS21002_CTRL_REG3, 0b00000000); // write 0000 1010 = 0x0A to CTRL_REG1 to configure 200Hz ODR and enter Active mode // [7]: ZR_cond=0 // [6]: RST=0 // [5]: ST=0 self test disabled // [4-2]: DR[2-0]=010 for 200Hz ODR // [1-0]: Active=1, Ready=0 for Active mode writeReg(FXAS21002_CTRL_REG1, 0x0A); } // Read the gyroscope data void FXAS21002C::readGyroData() { uint8_t rawData[6]; // x/y/z gyro register data stored here readRegs(FXAS21002C_H_OUT_X_MSB, 6, &rawData[0]); // Read the six raw data registers into data array gyroData.x = ((int16_t)( rawData[0] << 8 | rawData[1])) - gBias[0];// >> 2; gyroData.y = ((int16_t)( rawData[2] << 8 | rawData[3])) - gBias[1];// >> 2; gyroData.z = ((int16_t)( rawData[4] << 8 | rawData[5])) - gBias[2];// >> 2; } // Get accelerometer resolution float FXAS21002C::getGres(void) { switch (gyroFSR) { // Possible gyro scales (and their register bit settings) are: // 250 DPS (11), 500 DPS (10), 1000 DPS (01), and 2000 DPS (00). case GFS_2000DPS: gRes = 1600.0/8192.0; break; case GFS_1000DPS: gRes = 0.03125; break; case GFS_500DPS: gRes = 400.0/8192.0; break; case GFS_250DPS: gRes = 200.0/8192.0; } } void FXAS21002C::calibrate() { int32_t gyro_bias[3] = {0, 0, 0}; uint16_t ii = 0, fcount = 200; int16_t temp[3]; // Clear all interrupts by reading the data output and STATUS registers //readGyroData(temp); readReg(FXAS21002C_H_STATUS); uint8_t rawData[6]; // x/y/z FIFO accel data stored here uint32_t lastRead = micros(); for(ii = 0; ii < fcount; ii++) // construct count sums for each axis { readRegs(FXAS21002C_H_OUT_X_MSB, 6, &rawData[0]); // Read the FIFO data registers into data array temp[0] = ((int16_t)( rawData[0] << 8 | rawData[1])); temp[1] = ((int16_t)( rawData[2] << 8 | rawData[3])); temp[2] = ((int16_t)( rawData[4] << 8 | rawData[5])); gyro_bias[0] += (int32_t) temp[0]; gyro_bias[1] += (int32_t) temp[1]; gyro_bias[2] += (int32_t) temp[2]; delayMicroseconds(5000-(micros()-lastRead)); // wait for next data sample at 200 Hz rate lastRead = micros(); } gBias[0] = gyro_bias[0] / (int32_t) fcount; // get average values gBias[1] = gyro_bias[1] / (int32_t) fcount; gBias[2] = gyro_bias[2] / (int32_t) fcount; //Serial.print("Calibration complete"); Serial.println(gBias[0]); Serial.println(gBias[1]); Serial.println(gBias[2]); } void FXAS21002C::reset() { writeReg(FXAS21002C_H_CTRL_REG1, 0x20); // set reset bit to 1 to assert software reset to zero at end of boot process delay(100); while(!(readReg(FXAS21002C_H_INT_SRC_FLAG) & 0x08)) { // wait for boot end flag to be set } } // Private Methods ////////////////////////////////////////////////////////////// <commit_msg>Delete FXAS21002C.cpp<commit_after><|endoftext|>
<commit_before>/* Copyright (C) 2002 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdarg.h> #include "cssysdef.h" #include "iengine/engine.h" #include "iutil/objreg.h" #include "iutil/vfs.h" #include "cstool/initapp.h" #include "iutil/eventq.h" #include "csutil/cseventq.h" #include "cssys/sysfunc.h" //------------------------------------------------- We need the 3D engine ----- CS_IMPLEMENT_APPLICATION //----------------------------------------------------------------------------- bool run_pool_tests(iObjectRegistry* object_reg) { csTicks begin, end; csRef<iEvent> ten[10], hundred[100], thousand[1000], lots[100000]; csRef<iEventQueue> q (CS_QUERY_REGISTRY(object_reg, iEventQueue)); if (!q) { printf ("EventQueue not loaded, Zoinks!\n"); return false; } csEventQueue *eq = STATIC_CAST(csEventQueue *, (iEventQueue *)q); fprintf (stdout, "Event Pool count: %d\n", eq->CountPool()); fprintf (stdout, "Allocating 10 events... "); begin = csGetTicks(); int i; for (i = 0; i < 10; i++) { ten[i] = q->CreateEvent(1); } end = csGetTicks(); fprintf (stdout, "%d ms\n\n", end - begin); fprintf (stdout, "Event Pool count: %d\n", eq->CountPool()); fprintf (stdout, "Allocating 100 events... "); begin = csGetTicks(); for (i = 0; i < 100; i++) { hundred[i] = q->CreateEvent(1); } end = csGetTicks(); fprintf (stdout, "%d ms\n\n", end - begin); fprintf (stdout, "Event Pool count: %d\n", eq->CountPool()); fprintf (stdout, "Allocating 1000 events... "); begin = csGetTicks(); for (i = 0; i < 1000; i += 10) { thousand[i] = q->CreateEvent(1); thousand[i+1] = q->CreateEvent(1); thousand[i+2] = q->CreateEvent(1); thousand[i+3] = q->CreateEvent(1); thousand[i+4] = q->CreateEvent(1); thousand[i+5] = q->CreateEvent(1); thousand[i+6] = q->CreateEvent(1); thousand[i+7] = q->CreateEvent(1); thousand[i+8] = q->CreateEvent(1); thousand[i+9] = q->CreateEvent(1); } end = csGetTicks(); fprintf (stdout, "%d ms\n\n", end - begin); fprintf (stdout, "Event Pool count: %d\n", eq->CountPool()); fprintf (stdout, "Allocating 10000 events... "); begin = csGetTicks(); // On my machine, this unrolled loop is 10x faster then doing one at a time for (i = 0; i < 10000; i += 10) { lots[i] = q->CreateEvent(1); lots[i+1] = q->CreateEvent(1); lots[i+2] = q->CreateEvent(1); lots[i+3] = q->CreateEvent(1); lots[i+4] = q->CreateEvent(1); lots[i+5] = q->CreateEvent(1); lots[i+6] = q->CreateEvent(1); lots[i+7] = q->CreateEvent(1); lots[i+8] = q->CreateEvent(1); lots[i+9] = q->CreateEvent(1); } end = csGetTicks(); fprintf (stdout, "%d ms\n\n", end - begin); return true; } bool compare_buffers(char *b1, char *b2, uint32 length) { for (uint32 i = 0; i < length; i++) { if (b1[i] != b2[i]) return false; } return true; } bool run_event_tests(iObjectRegistry* object_reg) { csRef<iEventQueue> q (CS_QUERY_REGISTRY(object_reg, iEventQueue)); if (!q) { fprintf (stdout, "EventQueue not loaded, Zoinks!\n"); return false; } csRef<iEvent> e = q->CreateEvent(1); fprintf (stdout, "Ok, now it's time to test the events themselves:\n"); fprintf (stdout, "Adding an my_int8... %s\n", e->Add("my_int8", (int8)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_uint8... %s\n", e->Add("my_uint8", (uint8)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_int16... %s\n", e->Add("my_int16", (int16)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_uint16... %s\n", e->Add("my_uint16", (uint16)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_int32... %s\n", e->Add("my_int32", (int32)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_uint32... %s\n", e->Add("my_uint32", (uint32)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_int64... %s\n", e->Add("my_int64", (int64)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_uint64... %s\n", e->Add("my_uint64", (uint64)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_float... %s\n", e->Add("my_float", (float)1.0) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_double... %s\n", e->Add("my_double", (double)1.0) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_bool... %s\n", e->Add("my_bool", (bool)true) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_string... %s\n", e->Add("my_string", "Hello World!") ? "Sucess!" : "Failure!"); int8 my_int8 = 0; fprintf (stdout, "Searching for my_int8...%s", e->Find("my_int8", my_int8) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %d)\n", my_int8); uint8 my_uint8 = 0; fprintf (stdout, "Searching for my_uint8...%s", e->Find("my_uint8", my_uint8) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %d)\n", my_uint8); int16 my_int16 = 0; fprintf (stdout, "Searching for my_int16...%s", e->Find("my_int16", my_int16) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %d)\n", my_int16); uint16 my_uint16 = 0; fprintf (stdout, "Searching for my_uint16...%s", e->Find("my_uint16", my_uint16) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %d)\n", my_uint16); int32 my_int32 = 0; fprintf (stdout, "Searching for my_int32...%s", e->Find("my_int32", my_int32) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %d)\n", my_int32); uint32 my_uint32 = 0; fprintf (stdout, "Searching for my_uint32...%s", e->Find("my_uint32", my_uint32) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %u)\n", my_uint32); int64 my_int64 = 0; fprintf (stdout, "Searching for my_int64...%s", e->Find("my_int64", my_int64) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %lld)\n", my_int64); uint64 my_uint64 = 0; fprintf (stdout, "Searching for my_uint64...%s", e->Find("my_uint64", my_uint64) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %llu)\n", my_uint64); float my_float= 0; fprintf (stdout, "Searching for my_float...%s", e->Find("my_float", my_float) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %f)\n", my_float); double my_double = 0; fprintf (stdout, "Searching for my_double...%s", e->Find("my_double", my_double) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %f)\n", my_double); bool my_bool = false; fprintf (stdout, "Searching for my_bool...%s", e->Find("my_bool", my_bool) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %s)\n", my_bool ? "true" : "false"); char *my_string = NULL; fprintf (stdout, "Searching for my_string...%s", e->Find("my_string", &my_string) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %s)\n", my_string); char buffer[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; fprintf (stdout, "Adding a databuffer 32 in length called my_databuffer... %s\n", e->Add("my_databuffer", (void*)buffer, 32) ? "Sucess!" : "Failure!"); my_string = NULL; uint32 l; bool found = false; fprintf (stdout, "Searching for my_databuffer...%s\n", (found = e->Find("my_databuffer", (void**)&my_string, (uint32&)l, 0)) ? "Success!" : "Failure!"); if (found) fprintf (stdout, " Comparing buffers...%s\n", compare_buffers(my_string, (char*)buffer, 32) ? "Perfect!" : "Not the same!"); fprintf (stdout, "Adding an this event to itself... %s\n", e->Add("my_event", e) ? "Sucess!" : "Failure!"); fprintf (stdout, " That should have failed.\n"); csRef<iEvent> f = q->CreateEvent(1); fprintf (stdout, "Adding a new event as my_event... %s\n", e->Add("my_event", f) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding the parent event to the child event... %s\n", f->Add("my_event", e) ? "Sucess!" : "Failure!"); fprintf (stdout, " That should have failed.\n"); uint32 size = e->FlattenSize(); char *serialized_buffer = new char[size]; fprintf (stdout, "Serializing the event to a buffer...%s\n", e->Flatten(serialized_buffer) ? "Sucess!" : "Failure"); FILE *log = fopen("test.bin", "wb"); fwrite(serialized_buffer,size, 1, log); fclose(log); csRef<iEvent> a = q->CreateEvent(1); fprintf (stdout, "Recreating event from the buffer...%s\n", a->Unflatten(serialized_buffer, size) ? "Sucess!" : "Failure"); fprintf (stdout, "Printing the contents of the new event out:\n"); a->Print(); return true; } bool DoStuff (iObjectRegistry* object_reg) { csRef<iEventQueue> q (CS_QUERY_REGISTRY(object_reg, iEventQueue)); if (!q) { fprintf (stdout, "EventQueue not loaded, Zoinks!\n"); return false; } fprintf (stdout, "\nEvent Pool test v0.96\nby Jonathan Tarbox\n\n"); fprintf (stdout, "This will allocate 10, 100, and then 1000 events.\n"); fprintf (stdout, "As these are the initial allocations, they will be\n"); fprintf (stdout, "allocating memory each time, thus a little slow.\n\n"); if (!run_pool_tests(object_reg)) return false; fprintf (stdout, "\nOk, now that we've left the scope of the last test\n"); fprintf (stdout, "all the events should have DecRef'd and should be sitting\n"); fprintf (stdout, "in the pool. Let's try the same test again and see how\n"); fprintf (stdout, "much faster this is.\n\n"); if (!run_pool_tests(object_reg)) return false; if (!run_event_tests(object_reg)) return false; fprintf (stdout, "\n\nTests complete.. if it hasn't crashed yet, that's a good thing!\n"); return true; } /*---------------------------------------------------------------------* * Main function *---------------------------------------------------------------------*/ int main (int argc, char* argv[]) { // Initialize the random number generator srand (time (NULL)); iObjectRegistry* object_reg = csInitializer::CreateEnvironment (argc, argv); if (!object_reg) return -1; if (!csInitializer::RequestPlugins (object_reg, CS_REQUEST_VFS, CS_REQUEST_END)) { csInitializer::DestroyApplication (object_reg); return -1; } DoStuff (object_reg); csInitializer::DestroyApplication (object_reg); return 0; } <commit_msg>Eric Sunshine eliminated numerous compilation warnings throughout the project.<commit_after>/* Copyright (C) 2002 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdarg.h> #include "cssysdef.h" #include "iengine/engine.h" #include "iutil/objreg.h" #include "iutil/vfs.h" #include "cstool/initapp.h" #include "iutil/eventq.h" #include "csutil/cseventq.h" #include "cssys/sysfunc.h" //------------------------------------------------- We need the 3D engine ----- CS_IMPLEMENT_APPLICATION //----------------------------------------------------------------------------- bool run_pool_tests(iObjectRegistry* object_reg) { csTicks begin, end; csRef<iEvent> ten[10], hundred[100], thousand[1000], lots[100000]; csRef<iEventQueue> q (CS_QUERY_REGISTRY(object_reg, iEventQueue)); if (!q) { printf ("EventQueue not loaded, Zoinks!\n"); return false; } csEventQueue *eq = STATIC_CAST(csEventQueue *, (iEventQueue *)q); fprintf (stdout, "Event Pool count: %d\n", eq->CountPool()); fprintf (stdout, "Allocating 10 events... "); begin = csGetTicks(); int i; for (i = 0; i < 10; i++) { ten[i] = q->CreateEvent(1); } end = csGetTicks(); fprintf (stdout, "%d ms\n\n", end - begin); fprintf (stdout, "Event Pool count: %d\n", eq->CountPool()); fprintf (stdout, "Allocating 100 events... "); begin = csGetTicks(); for (i = 0; i < 100; i++) { hundred[i] = q->CreateEvent(1); } end = csGetTicks(); fprintf (stdout, "%d ms\n\n", end - begin); fprintf (stdout, "Event Pool count: %d\n", eq->CountPool()); fprintf (stdout, "Allocating 1000 events... "); begin = csGetTicks(); for (i = 0; i < 1000; i += 10) { thousand[i] = q->CreateEvent(1); thousand[i+1] = q->CreateEvent(1); thousand[i+2] = q->CreateEvent(1); thousand[i+3] = q->CreateEvent(1); thousand[i+4] = q->CreateEvent(1); thousand[i+5] = q->CreateEvent(1); thousand[i+6] = q->CreateEvent(1); thousand[i+7] = q->CreateEvent(1); thousand[i+8] = q->CreateEvent(1); thousand[i+9] = q->CreateEvent(1); } end = csGetTicks(); fprintf (stdout, "%d ms\n\n", end - begin); fprintf (stdout, "Event Pool count: %d\n", eq->CountPool()); fprintf (stdout, "Allocating 10000 events... "); begin = csGetTicks(); // On my machine, this unrolled loop is 10x faster then doing one at a time for (i = 0; i < 10000; i += 10) { lots[i] = q->CreateEvent(1); lots[i+1] = q->CreateEvent(1); lots[i+2] = q->CreateEvent(1); lots[i+3] = q->CreateEvent(1); lots[i+4] = q->CreateEvent(1); lots[i+5] = q->CreateEvent(1); lots[i+6] = q->CreateEvent(1); lots[i+7] = q->CreateEvent(1); lots[i+8] = q->CreateEvent(1); lots[i+9] = q->CreateEvent(1); } end = csGetTicks(); fprintf (stdout, "%d ms\n\n", end - begin); return true; } bool compare_buffers(char *b1, char *b2, uint32 length) { for (uint32 i = 0; i < length; i++) { if (b1[i] != b2[i]) return false; } return true; } bool run_event_tests(iObjectRegistry* object_reg) { csRef<iEventQueue> q (CS_QUERY_REGISTRY(object_reg, iEventQueue)); if (!q) { fprintf (stdout, "EventQueue not loaded, Zoinks!\n"); return false; } csRef<iEvent> e = q->CreateEvent(1); fprintf (stdout, "Ok, now it's time to test the events themselves:\n"); fprintf (stdout, "Adding an my_int8... %s\n", e->Add("my_int8", (int8)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_uint8... %s\n", e->Add("my_uint8", (uint8)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_int16... %s\n", e->Add("my_int16", (int16)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_uint16... %s\n", e->Add("my_uint16", (uint16)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_int32... %s\n", e->Add("my_int32", (int32)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_uint32... %s\n", e->Add("my_uint32", (uint32)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_int64... %s\n", e->Add("my_int64", (int64)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_uint64... %s\n", e->Add("my_uint64", (uint64)1) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_float... %s\n", e->Add("my_float", (float)1.0) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_double... %s\n", e->Add("my_double", (double)1.0) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_bool... %s\n", e->Add("my_bool", (bool)true) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding an my_string... %s\n", e->Add("my_string", "Hello World!") ? "Sucess!" : "Failure!"); int8 my_int8 = 0; fprintf (stdout, "Searching for my_int8...%s", e->Find("my_int8", my_int8) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %d)\n", my_int8); uint8 my_uint8 = 0; fprintf (stdout, "Searching for my_uint8...%s", e->Find("my_uint8", my_uint8) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %d)\n", my_uint8); int16 my_int16 = 0; fprintf (stdout, "Searching for my_int16...%s", e->Find("my_int16", my_int16) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %d)\n", my_int16); uint16 my_uint16 = 0; fprintf (stdout, "Searching for my_uint16...%s", e->Find("my_uint16", my_uint16) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %d)\n", my_uint16); int32 my_int32 = 0; fprintf (stdout, "Searching for my_int32...%s", e->Find("my_int32", my_int32) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %d)\n", my_int32); uint32 my_uint32 = 0; fprintf (stdout, "Searching for my_uint32...%s", e->Find("my_uint32", my_uint32) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %u)\n", my_uint32); int64 my_int64 = 0; fprintf (stdout, "Searching for my_int64...%s", e->Find("my_int64", my_int64) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %lld)\n", (long long)my_int64); uint64 my_uint64 = 0; fprintf (stdout, "Searching for my_uint64...%s", e->Find("my_uint64", my_uint64) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %llu)\n", (unsigned long long)my_uint64); float my_float= 0; fprintf (stdout, "Searching for my_float...%s", e->Find("my_float", my_float) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %f)\n", my_float); double my_double = 0; fprintf (stdout, "Searching for my_double...%s", e->Find("my_double", my_double) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %f)\n", my_double); bool my_bool = false; fprintf (stdout, "Searching for my_bool...%s", e->Find("my_bool", my_bool) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %s)\n", my_bool ? "true" : "false"); char *my_string = NULL; fprintf (stdout, "Searching for my_string...%s", e->Find("my_string", &my_string) ? "Success!" : "Failure!"); fprintf (stdout, " (value: %s)\n", my_string); char buffer[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; fprintf (stdout, "Adding a databuffer 32 in length called my_databuffer... %s\n", e->Add("my_databuffer", (void*)buffer, 32) ? "Sucess!" : "Failure!"); my_string = NULL; uint32 l; bool found = false; fprintf (stdout, "Searching for my_databuffer...%s\n", (found = e->Find("my_databuffer", (void**)&my_string, (uint32&)l, 0)) ? "Success!" : "Failure!"); if (found) fprintf (stdout, " Comparing buffers...%s\n", compare_buffers(my_string, (char*)buffer, 32) ? "Perfect!" : "Not the same!"); fprintf (stdout, "Adding an this event to itself... %s\n", e->Add("my_event", e) ? "Sucess!" : "Failure!"); fprintf (stdout, " That should have failed.\n"); csRef<iEvent> f = q->CreateEvent(1); fprintf (stdout, "Adding a new event as my_event... %s\n", e->Add("my_event", f) ? "Sucess!" : "Failure!"); fprintf (stdout, "Adding the parent event to the child event... %s\n", f->Add("my_event", e) ? "Sucess!" : "Failure!"); fprintf (stdout, " That should have failed.\n"); uint32 size = e->FlattenSize(); char *serialized_buffer = new char[size]; fprintf (stdout, "Serializing the event to a buffer...%s\n", e->Flatten(serialized_buffer) ? "Sucess!" : "Failure"); FILE *log = fopen("test.bin", "wb"); fwrite(serialized_buffer,size, 1, log); fclose(log); csRef<iEvent> a = q->CreateEvent(1); fprintf (stdout, "Recreating event from the buffer...%s\n", a->Unflatten(serialized_buffer, size) ? "Sucess!" : "Failure"); fprintf (stdout, "Printing the contents of the new event out:\n"); a->Print(); return true; } bool DoStuff (iObjectRegistry* object_reg) { csRef<iEventQueue> q (CS_QUERY_REGISTRY(object_reg, iEventQueue)); if (!q) { fprintf (stdout, "EventQueue not loaded, Zoinks!\n"); return false; } fprintf (stdout, "\nEvent Pool test v0.96\nby Jonathan Tarbox\n\n"); fprintf (stdout, "This will allocate 10, 100, and then 1000 events.\n"); fprintf (stdout, "As these are the initial allocations, they will be\n"); fprintf (stdout, "allocating memory each time, thus a little slow.\n\n"); if (!run_pool_tests(object_reg)) return false; fprintf (stdout, "\nOk, now that we've left the scope of the last test\n"); fprintf (stdout, "all the events should have DecRef'd and should be sitting\n"); fprintf (stdout, "in the pool. Let's try the same test again and see how\n"); fprintf (stdout, "much faster this is.\n\n"); if (!run_pool_tests(object_reg)) return false; if (!run_event_tests(object_reg)) return false; fprintf (stdout, "\n\nTests complete.. if it hasn't crashed yet, that's a good thing!\n"); return true; } /*---------------------------------------------------------------------* * Main function *---------------------------------------------------------------------*/ int main (int argc, char* argv[]) { // Initialize the random number generator srand (time (NULL)); iObjectRegistry* object_reg = csInitializer::CreateEnvironment (argc, argv); if (!object_reg) return -1; if (!csInitializer::RequestPlugins (object_reg, CS_REQUEST_VFS, CS_REQUEST_END)) { csInitializer::DestroyApplication (object_reg); return -1; } DoStuff (object_reg); csInitializer::DestroyApplication (object_reg); return 0; } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2003-2012 \file app/rdo_studio_mfc/src/edit/view_base.cpp \author (rdo@rk9.bmstu.ru) \date 20.02.2003 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "app/rdo_studio_mfc/pch/stdpch.h" // ----------------------------------------------------------------------- INCLUDES #include <QtCore/qtimer.h> #include <QtCore/qcoreevent.h> #include <boost/foreach.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "app/rdo_studio_mfc/src/edit/view_base.h" #include "app/rdo_studio_mfc/src/application.h" #include "app/rdo_studio_mfc/src/main_windows_base.h" #include "app/rdo_studio_mfc/rdo_edit/rdoeditoredit.h" // -------------------------------------------------------------------------------- #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif using namespace rdoEditor; // -------------------------------------------------------------------------------- // -------------------- RDOStudioEditBaseView // -------------------------------------------------------------------------------- RDOStudioEditBaseView::Buffer::Buffer(QTimer* pTimer) : value ("" ) , reset (false ) , pTimer(pTimer) {} RDOStudioEditBaseView::RDOStudioEditBaseView(QWidget* pParent) : QWidget(pParent) , m_currentBuffer(0) { m_thisCWnd.Attach(winId()); m_bufferList.insert(BufferList::value_type(0, Buffer(new QTimer(this)))); m_bufferList.insert(BufferList::value_type(1, Buffer(new QTimer(this)))); m_bufferList.insert(BufferList::value_type(2, Buffer(new QTimer(this)))); m_bufferList.insert(BufferList::value_type(3, Buffer(new QTimer(this)))); BOOST_FOREACH(BufferList::value_type& buffer, m_bufferList) { connect(buffer.second.pTimer, SIGNAL(timeout()), this, SLOT(timerEvent(QTimerEvent*))); } //! todo qt //popupMenu.CreatePopupMenu(); //CMenu* mainMenu = AfxGetMainWnd()->GetMenu(); //rbool maximized = studioApp.getIMainWnd()->isMDIMaximazed(); //int delta = maximized ? 1 : 0; //appendMenu( mainMenu, 4 + delta, &popupMenu ); //popupMenu.AppendMenu( MF_SEPARATOR ); //appendMenu( mainMenu->GetSubMenu( 1 + delta ), 3, &popupMenu ); //appendMenu( mainMenu->GetSubMenu( 1 + delta ), 4, &popupMenu ); //appendMenu( mainMenu->GetSubMenu( 1 + delta ), 5, &popupMenu ); //popupMenu.AppendMenu( MF_SEPARATOR ); //appendMenu( mainMenu->GetSubMenu( 1 + delta ), 10, &popupMenu ); //popupMenu.AppendMenu( MF_SEPARATOR ); //appendMenu( mainMenu->GetSubMenu( 2 + delta ), 0, &popupMenu ); //appendMenu( mainMenu->GetSubMenu( 2 + delta ), 3, &popupMenu ); //appendMenu( mainMenu->GetSubMenu( 2 + delta ), 1, &popupMenu ); } RDOStudioEditBaseView::~RDOStudioEditBaseView() { m_thisCWnd.Detach(); //! todo qt // eraseMenu(&m_popupMenu); } void RDOStudioEditBaseView::restartBufTimer(ruint bufferID) { BufferList::iterator it = m_bufferList.find(bufferID); if (it == m_bufferList.end()) return; stopTimer(it->second.pTimer); if (studioApp.getStyle()->style_editor.buffer->canClearBuffer) { int delay = studioApp.getStyle()->style_editor.buffer->clearBufferDelay * 1000; if (delay < 0) { delay = 0; } it->second.pTimer->start(delay); } } void RDOStudioEditBaseView::stopTimer(QTimer* pTimer) { ASSERT(pTimer); if (pTimer->isActive()) { pTimer->stop(); } } void RDOStudioEditBaseView::timerEvent(QTimerEvent* event) { BOOST_FOREACH(BufferList::value_type& buffer, m_bufferList) { if (buffer.second.pTimer->timerId() == event->timerId()) { buffer.second.reset = true; stopTimer(buffer.second.pTimer); break; } } } <commit_msg> - удалено лишнее<commit_after>/*! \copyright (c) RDO-Team, 2003-2012 \file app/rdo_studio_mfc/src/edit/view_base.cpp \author (rdo@rk9.bmstu.ru) \date 20.02.2003 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "app/rdo_studio_mfc/pch/stdpch.h" // ----------------------------------------------------------------------- INCLUDES #include <QtCore/qtimer.h> #include <QtCore/qcoreevent.h> #include <boost/foreach.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "app/rdo_studio_mfc/src/edit/view_base.h" #include "app/rdo_studio_mfc/src/application.h" #include "app/rdo_studio_mfc/src/main_windows_base.h" #include "app/rdo_studio_mfc/rdo_edit/rdoeditoredit.h" // -------------------------------------------------------------------------------- #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif using namespace rdoEditor; // -------------------------------------------------------------------------------- // -------------------- RDOStudioEditBaseView // -------------------------------------------------------------------------------- RDOStudioEditBaseView::Buffer::Buffer(QTimer* pTimer) : value ("" ) , reset (false ) , pTimer(pTimer) {} RDOStudioEditBaseView::RDOStudioEditBaseView(QWidget* pParent) : QWidget(pParent) , m_currentBuffer(0) { m_thisCWnd.Attach(winId()); m_bufferList.insert(BufferList::value_type(0, Buffer(new QTimer(this)))); m_bufferList.insert(BufferList::value_type(1, Buffer(new QTimer(this)))); m_bufferList.insert(BufferList::value_type(2, Buffer(new QTimer(this)))); m_bufferList.insert(BufferList::value_type(3, Buffer(new QTimer(this)))); //! todo qt //popupMenu.CreatePopupMenu(); //CMenu* mainMenu = AfxGetMainWnd()->GetMenu(); //rbool maximized = studioApp.getIMainWnd()->isMDIMaximazed(); //int delta = maximized ? 1 : 0; //appendMenu( mainMenu, 4 + delta, &popupMenu ); //popupMenu.AppendMenu( MF_SEPARATOR ); //appendMenu( mainMenu->GetSubMenu( 1 + delta ), 3, &popupMenu ); //appendMenu( mainMenu->GetSubMenu( 1 + delta ), 4, &popupMenu ); //appendMenu( mainMenu->GetSubMenu( 1 + delta ), 5, &popupMenu ); //popupMenu.AppendMenu( MF_SEPARATOR ); //appendMenu( mainMenu->GetSubMenu( 1 + delta ), 10, &popupMenu ); //popupMenu.AppendMenu( MF_SEPARATOR ); //appendMenu( mainMenu->GetSubMenu( 2 + delta ), 0, &popupMenu ); //appendMenu( mainMenu->GetSubMenu( 2 + delta ), 3, &popupMenu ); //appendMenu( mainMenu->GetSubMenu( 2 + delta ), 1, &popupMenu ); } RDOStudioEditBaseView::~RDOStudioEditBaseView() { m_thisCWnd.Detach(); //! todo qt // eraseMenu(&m_popupMenu); } void RDOStudioEditBaseView::restartBufTimer(ruint bufferID) { BufferList::iterator it = m_bufferList.find(bufferID); if (it == m_bufferList.end()) return; stopTimer(it->second.pTimer); if (studioApp.getStyle()->style_editor.buffer->canClearBuffer) { int delay = studioApp.getStyle()->style_editor.buffer->clearBufferDelay * 1000; if (delay < 0) { delay = 0; } it->second.pTimer->start(delay); } } void RDOStudioEditBaseView::stopTimer(QTimer* pTimer) { ASSERT(pTimer); if (pTimer->isActive()) { pTimer->stop(); } } void RDOStudioEditBaseView::timerEvent(QTimerEvent* event) { BOOST_FOREACH(BufferList::value_type& buffer, m_bufferList) { if (buffer.second.pTimer->timerId() == event->timerId()) { buffer.second.reset = true; stopTimer(buffer.second.pTimer); break; } } } <|endoftext|>
<commit_before>/* **************************************************************************** * * FILE diskManagerTest.cpp * * AUTHOR Javier Lois * * DATE December 2011 * * DESCRIPTION * * unit testing of the engine library * */ #include <sys/time.h> #include "gtest/gtest.h" #include "engine/DiskManager.h" #include "au/ProcessStats.h" #include "xmlparser/xmlParser.h" // Test DiskManager's instantiation TEST(diskManagerTest, instantiationTest) { ProcessStats pstats; unsigned long threadsBefore = pstats.get_nthreads(); //access instance without initialise. Should return NULL. EXPECT_EQ(engine::DiskManager::shared(), static_cast<engine::DiskManager*>(NULL)) << "Uninitialized DiskManager should be null"; //using just NULL produces compilation error //call init() and then shared(). Should return a valid one. engine::DiskManager::init(3); ASSERT_TRUE(engine::DiskManager::shared() != static_cast<engine::DiskManager*>(NULL)) << "DiskManager instance should not be null after instantiation"; //check that new threads have been created pstats.refresh(); unsigned long threadsAfter = pstats.get_nthreads(); EXPECT_TRUE(threadsAfter > threadsBefore); } //test void getInfo( std::ostringstream& output); TEST(diskManagerTest, getInfoTest) { engine::Engine::init(); engine::DiskManager::init(3); char buffer[1024*1024]; engine::DiskOperation* operation = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation); std::ostringstream info; engine::DiskManager::shared()->getInfo( info ); //XML parsing XMLNode xMainNode=XMLNode::parseString(info.str().c_str(),"disk_manager"); EXPECT_EQ(std::string(xMainNode.getChildNode("num_pending_operations").getClear().lpszValue), "1") << "Error writing pending operations tag"; EXPECT_EQ(std::string(xMainNode.getChildNode("num_running_operations").getClear().lpszValue), "1") << "Error writing running operations tag"; XMLNode queuedNode = xMainNode.getChildNode("queued"); XMLNode diskOperationNode = queuedNode.getChildNode("disk_operation"); EXPECT_EQ(std::string(diskOperationNode.getChildNode("type").getText()), "read") << "Error writing type tag"; EXPECT_EQ(std::string(diskOperationNode.getChildNode("file_name").getText()), "test_filename.txt") << "Error writing file_name tag"; EXPECT_EQ(std::string(diskOperationNode.getChildNode("size").getText()), "1") << "Error writing size tag"; EXPECT_EQ(std::string(diskOperationNode.getChildNode("offset").getText()), "0") << "Error writing offset tag"; XMLNode statisticsNode = xMainNode.getChildNode("statistics"); XMLNode readNode = statisticsNode.getChildNode("read"); EXPECT_TRUE(std::string(readNode.getChildNode("description").getText()).find("Currently 0 hits/s 0 B/s")) << "Error writing read statistics tag"; EXPECT_EQ(std::string(readNode.getChildNode("rate").getClear().lpszValue), "0") << "Error writing read rate tag"; XMLNode writeNode = statisticsNode.getChildNode("read"); EXPECT_TRUE(std::string(writeNode.getChildNode("description").getText()).find("Currently 0 hits/s 0 B/s")) << "Error writing write statistics tag"; EXPECT_EQ(std::string(writeNode.getChildNode("rate").getClear().lpszValue), "0") << "Error writing write rate tag"; XMLNode totalNode = statisticsNode.getChildNode("read"); EXPECT_TRUE(std::string(totalNode.getChildNode("description").getText()).find("Currently 0 hits/s 0 B/s")) << "Error writing total statistics tag"; EXPECT_EQ(std::string(totalNode.getChildNode("rate").getClear().lpszValue), "0") << "Error writing total rate tag"; /* CMarkup xmlData( info.str() ); xmlData.FindElem("disk_manager"); xmlData.IntoElem(); xmlData.FindElem("num_pending_operations"); EXPECT_EQ(xmlData.GetData(), "1") << "Error writing pending operations tag"; xmlData.FindElem("num_running_operations"); EXPECT_EQ(xmlData.GetData(), "1") << "Error writing running operations tag"; //xmlData.OutOfElem(); xmlData.FindElem("queued"); xmlData.IntoElem(); xmlData.FindElem("disk_operation"); xmlData.IntoElem(); xmlData.FindElem("type"); EXPECT_EQ(xmlData.GetData(), "read") << "Error writing type tag"; xmlData.FindElem("file_name"); EXPECT_EQ(xmlData.GetData(), "test_filename.txt") << "Error writing file_name tag"; xmlData.FindElem("size"); EXPECT_EQ(xmlData.GetData(), "1") << "Error writing size tag"; xmlData.FindElem("offset"); if(xmlData.GetData()!="0") std::cout << info.str() << std::endl; EXPECT_EQ(xmlData.GetData(), "0") << "Error writing offset tag"; xmlData.OutOfElem();//disk_element xmlData.OutOfElem();//queued xmlData.FindElem("statistics"); xmlData.IntoElem(); xmlData.FindElem("read"); xmlData.IntoElem(); xmlData.FindElem("description"); EXPECT_TRUE(xmlData.GetData().find("Currently 0 hits/s 0 B/s")) << "Error writing read statistics tag"; xmlData.OutOfElem();//read xmlData.FindElem("write"); xmlData.IntoElem(); xmlData.FindElem("description"); EXPECT_TRUE(xmlData.GetData().find("Currently 0 hits/s 0 B/s")) << "Error writing write statistics tag"; xmlData.OutOfElem();//write xmlData.FindElem("total"); xmlData.IntoElem(); xmlData.FindElem("description"); EXPECT_TRUE(xmlData.GetData().find("Currently 0 hits/s 0 B/s")) << "Error writing total statistics tag"; xmlData.OutOfElem();//total */ } //test void add( DiskOperation *operation ) TEST(diskManagerTest, addTest) { engine::Engine::init(); engine::DiskManager::init(3); char buffer[1024*1024]; engine::DiskOperation* operation = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation); std::ostringstream info; EXPECT_EQ(engine::DiskManager::shared()->getNumOperations(), 1) << "Wrong number of disk operations"; } //test void cancel( DiskOperation *operation ); TEST(diskManagerTest, cancelTest) { engine::Engine::init(); engine::DiskManager::init(3); char buffer[1024*1024]; engine::DiskOperation* operation = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation); EXPECT_EQ(engine::DiskManager::shared()->getNumOperations(), 1) << "Error adding operation"; engine::DiskManager::shared()->cancel(operation); usleep(50000); EXPECT_EQ(engine::DiskManager::shared()->getNumOperations(), 0) << "Operation was not cancelled"; } //test void run_worker(); (TODO: How??) //test int getNumOperations(); TEST(diskManagerTest, getNumOperationsTest) { //add two operations and check that it returns 2 engine::Engine::init(); engine::DiskManager::init(3); char buffer[1024*1024]; engine::DiskOperation* operation = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation); engine::DiskOperation* operation2 = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation2); EXPECT_EQ(engine::DiskManager::shared()->getNumOperations(), 2) << "Error in getNumOperations()"; } //test void setNumOperations( int _num_disk_operations ); TEST(diskManagerTest, setNumOperationsTest) { engine::Engine::init(); engine::DiskManager::init(3); ProcessStats pstats; long threadsBefore = pstats.get_nthreads(); engine::DiskManager::shared()->setNumOperations(6); pstats.refresh(); long threadsAfter = pstats.get_nthreads(); //should be threadsBefore+3, since we extended the number of operations from 3 to 6 EXPECT_EQ(threadsAfter - threadsBefore, 3) << "Error in setNumOperations()"; } //test void quitEngineService(); TEST(diskManagerTest, quitEngineServiceTest) { engine::Engine::init(); engine::DiskManager::init(3); char buffer[1024*1024]; engine::DiskOperation* operation = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation); ProcessStats pstats; unsigned long threadsBefore = pstats.get_nthreads(); engine::DiskManager::shared()->quitEngineService(); pstats.refresh(); unsigned long threadsAfter = pstats.get_nthreads(); //Now the number of threads should have been reduced EXPECT_TRUE(threadsAfter < threadsBefore); } <commit_msg>More unit testing fixes<commit_after>/* **************************************************************************** * * FILE diskManagerTest.cpp * * AUTHOR Javier Lois * * DATE December 2011 * * DESCRIPTION * * unit testing of the engine library * */ #include <sys/time.h> #include "gtest/gtest.h" #include "engine/DiskManager.h" #include "au/ProcessStats.h" #include "xmlparser/xmlParser.h" // Test DiskManager's instantiation TEST(diskManagerTest, instantiationTest) { ProcessStats pstats; unsigned long threadsBefore = pstats.get_nthreads(); //access instance without initialise. Should return NULL. EXPECT_EQ(engine::DiskManager::shared(), static_cast<engine::DiskManager*>(NULL)) << "Uninitialized DiskManager should be null"; //using just NULL produces compilation error //call init() and then shared(). Should return a valid one. engine::DiskManager::init(10); ASSERT_TRUE(engine::DiskManager::shared() != static_cast<engine::DiskManager*>(NULL)) << "DiskManager instance should not be null after instantiation"; //check that new threads have been created pstats.refresh(); unsigned long threadsAfter = pstats.get_nthreads(); EXPECT_TRUE(threadsAfter > threadsBefore); } //test void getInfo( std::ostringstream& output); TEST(diskManagerTest, getInfoTest) { engine::Engine::init(); engine::DiskManager::init(10); char buffer[1024*1024]; engine::DiskOperation* operation = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation); std::ostringstream info; engine::DiskManager::shared()->getInfo( info ); //std::cout << std::endl << info.str() << std::endl; //XML parsing XMLNode xMainNode=XMLNode::parseString(info.str().c_str(),"disk_manager"); EXPECT_EQ(std::string(xMainNode.getChildNode("num_pending_operations").getClear().lpszValue), "1") << "Error writing pending operations tag"; EXPECT_EQ(std::string(xMainNode.getChildNode("num_running_operations").getClear().lpszValue), "1") << "Error writing running operations tag"; XMLNode queuedNode = xMainNode.getChildNode("queued"); ASSERT_TRUE(!queuedNode.isEmpty()); XMLNode diskOperationNode = queuedNode.getChildNode("disk_operation"); ASSERT_TRUE(!diskOperationNode.isEmpty()); EXPECT_EQ(std::string(diskOperationNode.getChildNode("type").getText()), "read") << "Error writing type tag"; EXPECT_EQ(std::string(diskOperationNode.getChildNode("file_name").getText()), "test_filename.txt") << "Error writing file_name tag"; EXPECT_EQ(std::string(diskOperationNode.getChildNode("size").getText()), "1") << "Error writing size tag"; EXPECT_EQ(std::string(diskOperationNode.getChildNode("offset").getText()), "0") << "Error writing offset tag"; XMLNode statisticsNode = xMainNode.getChildNode("statistics"); XMLNode readNode = statisticsNode.getChildNode("read"); EXPECT_TRUE(std::string(readNode.getChildNode("description").getText()).find("Currently 0 hits/s 0 B/s")) << "Error writing read statistics tag"; EXPECT_EQ(std::string(readNode.getChildNode("rate").getClear().lpszValue), "0") << "Error writing read rate tag"; XMLNode writeNode = statisticsNode.getChildNode("read"); EXPECT_TRUE(std::string(writeNode.getChildNode("description").getText()).find("Currently 0 hits/s 0 B/s")) << "Error writing write statistics tag"; EXPECT_EQ(std::string(writeNode.getChildNode("rate").getClear().lpszValue), "0") << "Error writing write rate tag"; XMLNode totalNode = statisticsNode.getChildNode("read"); EXPECT_TRUE(std::string(totalNode.getChildNode("description").getText()).find("Currently 0 hits/s 0 B/s")) << "Error writing total statistics tag"; EXPECT_EQ(std::string(totalNode.getChildNode("rate").getClear().lpszValue), "0") << "Error writing total rate tag"; } //test void add( DiskOperation *operation ) TEST(diskManagerTest, addTest) { engine::Engine::init(); engine::DiskManager::init(10); char buffer[1024*1024]; engine::DiskOperation* operation = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation); std::ostringstream info; EXPECT_EQ(engine::DiskManager::shared()->getNumOperations(), 1) << "Wrong number of disk operations"; } //test void cancel( DiskOperation *operation ); TEST(diskManagerTest, cancelTest) { engine::Engine::init(); engine::DiskManager::init(10); char buffer[1024*1024]; engine::DiskOperation* operation = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation); EXPECT_EQ(engine::DiskManager::shared()->getNumOperations(), 1) << "Error adding operation"; engine::DiskManager::shared()->cancel(operation); usleep(50000); EXPECT_EQ(engine::DiskManager::shared()->getNumOperations(), 0) << "Operation was not cancelled"; } //test void run_worker(); (TODO: How??) //test int getNumOperations(); TEST(diskManagerTest, getNumOperationsTest) { //add two operations and check that it returns 2 engine::Engine::init(); engine::DiskManager::init(10); char buffer[1024*1024]; engine::DiskOperation* operation = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation); engine::DiskOperation* operation2 = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation2); EXPECT_EQ(engine::DiskManager::shared()->getNumOperations(), 2) << "Error in getNumOperations()"; } //test void setNumOperations( int _num_disk_operations ); TEST(diskManagerTest, setNumOperationsTest) { engine::Engine::init(); engine::DiskManager::init(10); ProcessStats pstats; long threadsBefore = pstats.get_nthreads(); engine::DiskManager::shared()->setNumOperations(14); pstats.refresh(); long threadsAfter = pstats.get_nthreads(); //should be threadsBefore+4, since we extended the number of operations from 10 to 14 EXPECT_EQ(threadsAfter - threadsBefore, 4) << "Error in setNumOperations()"; } //test void quitEngineService(); TEST(diskManagerTest, quitEngineServiceTest) { engine::Engine::init(); engine::DiskManager::init(10); char buffer[1024*1024]; engine::DiskOperation* operation = engine::DiskOperation::newReadOperation( buffer , "test_filename.txt" , 0 , 1, 0 ); engine::DiskManager::shared()->add(operation); ProcessStats pstats; unsigned long threadsBefore = pstats.get_nthreads(); engine::DiskManager::shared()->quitEngineService(); pstats.refresh(); unsigned long threadsAfter = pstats.get_nthreads(); //Now the number of threads should have been reduced EXPECT_TRUE(threadsAfter < threadsBefore); } <|endoftext|>
<commit_before>#ifndef __AXIS_HPP #define __AXIS_HPP #ifndef __ODRIVE_MAIN_H #error "This file should not be included directly. Include odrive_main.h instead." #endif enum HomingState_t { HOMING_STATE_IDLE, HOMING_STATE_HOMING, HOMING_STATE_MOVE_TO_ZERO }; class Axis { public: enum Error_t { ERROR_NONE = 0x00, ERROR_INVALID_STATE = 0x01, //<! an invalid state was requested ERROR_DC_BUS_UNDER_VOLTAGE = 0x02, ERROR_DC_BUS_OVER_VOLTAGE = 0x04, ERROR_CURRENT_MEASUREMENT_TIMEOUT = 0x08, ERROR_BRAKE_RESISTOR_DISARMED = 0x10, //<! the brake resistor was unexpectedly disarmed ERROR_MOTOR_DISARMED = 0x20, //<! the motor was unexpectedly disarmed ERROR_MOTOR_FAILED = 0x40, // Go to motor.hpp for information, check odrvX.axisX.motor.error for error value ERROR_SENSORLESS_ESTIMATOR_FAILED = 0x80, ERROR_ENCODER_FAILED = 0x100, // Go to encoder.hpp for information, check odrvX.axisX.encoder.error for error value ERROR_CONTROLLER_FAILED = 0x200, ERROR_POS_CTRL_DURING_SENSORLESS = 0x400, ERROR_WATCHDOG_TIMER_EXPIRED = 0x800, ERROR_MIN_ENDSTOP_PRESSED = 0x800, ERROR_MAX_ENDSTOP_PRESSED = 0x1000 }; enum State_t { AXIS_STATE_UNDEFINED = 0, //<! will fall through to idle AXIS_STATE_IDLE = 1, //<! disable PWM and do nothing AXIS_STATE_STARTUP_SEQUENCE = 2, //<! the actual sequence is defined by the config.startup_... flags AXIS_STATE_FULL_CALIBRATION_SEQUENCE = 3, //<! run all calibration procedures, then idle AXIS_STATE_MOTOR_CALIBRATION = 4, //<! run motor calibration AXIS_STATE_SENSORLESS_CONTROL = 5, //<! run sensorless control AXIS_STATE_ENCODER_INDEX_SEARCH = 6, //<! run encoder index search AXIS_STATE_ENCODER_OFFSET_CALIBRATION = 7, //<! run encoder offset calibration AXIS_STATE_CLOSED_LOOP_CONTROL = 8, //<! run closed loop control AXIS_STATE_LOCKIN_SPIN = 9, //<! run lockin spin AXIS_STATE_ENCODER_DIR_FIND = 10, AXIS_STATE_HOMING = 9 //<! run axis homing function struct LockinConfig_t { float current = 10.0f; // [A] float ramp_time = 0.4f; // [s] float ramp_distance = 1 * M_PI; // [rad] float accel = 20.0f; // [rad/s^2] float vel = 40.0f; // [rad/s] float finish_distance = 100.0f; // [rad] bool finish_on_vel = false; bool finish_on_distance = false; bool finish_on_enc_idx = false; }; struct Config_t { bool startup_motor_calibration = false; //<! run motor calibration at startup, skip otherwise bool startup_encoder_index_search = false; //<! run encoder index search after startup, skip otherwise // this only has an effect if encoder.config.use_index is also true bool startup_encoder_offset_calibration = false; //<! run encoder offset calibration after startup, skip otherwise bool startup_closed_loop_control = false; //<! enable closed loop control after calibration/startup bool startup_sensorless_control = false; //<! enable sensorless control after calibration/startup bool startup_homing = false; //<! enable homing after calibration/startup bool enable_step_dir = false; //<! enable step/dir input after calibration // For M0 this has no effect if enable_uart is true float counts_per_step = 2.0f; float watchdog_timeout = 0.0f; // [s] (0 disables watchdog) // Defaults loaded from hw_config in load_configuration in main.cpp uint16_t step_gpio_pin = 0; uint16_t dir_gpio_pin = 0; LockinConfig_t lockin; }; enum thread_signals { M_SIGNAL_PH_CURRENT_MEAS = 1u << 0 }; enum LockinState_t { LOCKIN_STATE_INACTIVE, LOCKIN_STATE_RAMP, LOCKIN_STATE_ACCELERATE, LOCKIN_STATE_CONST_VEL, }; Axis(const AxisHardwareConfig_t& hw_config, Config_t& config, Encoder& encoder, SensorlessEstimator& sensorless_estimator, Controller& controller, Motor& motor, TrapezoidalTrajectory& trap, Endstop& min_endstop, Endstop& max_endstop); void setup(); void start_thread(); void signal_current_meas(); bool wait_for_current_meas(); void step_cb(); void set_step_dir_active(bool enable); void decode_step_dir_pins(); void update_watchdog_settings(); static void load_default_step_dir_pin_config( const AxisHardwareConfig_t& hw_config, Config_t* config); bool check_DRV_fault(); bool check_PSU_brownout(); bool do_checks(); bool do_updates(); void watchdog_feed(); bool watchdog_check(); // True if there are no errors bool inline check_for_errors() { return error_ == ERROR_NONE; } // @brief Runs the specified update handler at the frequency of the current measurements. // // The loop runs until one of the following conditions: // - update_handler returns false // - the current measurement times out // - the health checks fail (brownout, driver fault line) // - update_handler doesn't update the modulation timings in time // This criterion is ignored if current_state is AXIS_STATE_IDLE // // If update_handler is going to update the motor timings, you must call motor.arm() // shortly before this function. // // If the function returns, it is guaranteed that error is non-zero, except if the cause // for the exit was a negative return value of update_handler or an external // state change request (requested_state != AXIS_STATE_DONT_CARE). // Under all exit conditions the motor is disarmed and the brake current set to zero. // Furthermore, if the update_handler does not set the phase voltages in time, they will // go to zero. // // @tparam T Must be a callable type that takes no arguments and returns a bool template<typename T> void run_control_loop(const T& update_handler) { while (requested_state_ == AXIS_STATE_UNDEFINED) { // look for errors at axis level and also all subcomponents bool checks_ok = do_checks(); // Update all estimators // Note: updates run even if checks fail bool updates_ok = do_updates(); // make sure the watchdog is being fed. bool watchdog_ok = watchdog_check(); if (!checks_ok || !updates_ok || !watchdog_ok) { // It's not useful to quit idle since that is the safe action // Also leaving idle would rearm the motors if (current_state_ != AXIS_STATE_IDLE) break; } // Run main loop function, defer quitting for after wait // TODO: change arming logic to arm after waiting bool main_continue = update_handler(); // Check we meet deadlines after queueing ++loop_counter_; // Wait until the current measurement interrupt fires if (!wait_for_current_meas()) { // maybe the interrupt handler is dead, let's be // safe and float the phases safety_critical_disarm_motor_pwm(motor_); update_brake_current(); error_ |= ERROR_CURRENT_MEASUREMENT_TIMEOUT; break; } if (!main_continue) break; } } bool run_lockin_spin(); bool run_sensorless_control_loop(); bool run_closed_loop_control_loop(); bool run_idle_loop(); void run_state_machine_loop(); const AxisHardwareConfig_t& hw_config_; Config_t& config_; Encoder& encoder_; SensorlessEstimator& sensorless_estimator_; Controller& controller_; Motor& motor_; TrapezoidalTrajectory& trap_; Endstop& min_endstop_; Endstop& max_endstop_; osThreadId thread_id_; volatile bool thread_id_valid_ = false; // variables exposed on protocol Error_t error_ = ERROR_NONE; bool step_dir_active_ = false; // auto enabled after calibration, based on config.enable_step_dir // updated from config in constructor, and on protocol hook GPIO_TypeDef* step_port_; uint16_t step_pin_; GPIO_TypeDef* dir_port_; uint16_t dir_pin_; State_t requested_state_ = AXIS_STATE_STARTUP_SEQUENCE; State_t task_chain_[10] = { AXIS_STATE_UNDEFINED }; State_t& current_state_ = task_chain_[0]; uint32_t loop_counter_ = 0; LockinState_t lockin_state_ = LOCKIN_STATE_INACTIVE; HomingState_t homing_state_ = HOMING_STATE_IDLE; // watchdog uint32_t watchdog_reset_value_ = 0; //computed from config_.watchdog_timeout in update_watchdog_settings() uint32_t watchdog_current_value_= 0; // Communication protocol definitions auto make_protocol_definitions() { return make_protocol_member_list( make_protocol_property("error", &error_), make_protocol_ro_property("step_dir_active", &step_dir_active_), make_protocol_ro_property("current_state", &current_state_), make_protocol_property("requested_state", &requested_state_), make_protocol_ro_property("loop_counter", &loop_counter_), make_protocol_ro_property("lockin_state", &lockin_state_), make_protocol_ro_property("homing_state", &homing_state_), make_protocol_object("config", make_protocol_property("startup_motor_calibration", &config_.startup_motor_calibration), make_protocol_property("startup_encoder_index_search", &config_.startup_encoder_index_search), make_protocol_property("startup_encoder_offset_calibration", &config_.startup_encoder_offset_calibration), make_protocol_property("startup_closed_loop_control", &config_.startup_closed_loop_control), make_protocol_property("startup_sensorless_control", &config_.startup_sensorless_control), make_protocol_property("startup_homing", &config_.startup_homing), make_protocol_property("enable_step_dir", &config_.enable_step_dir), make_protocol_property("counts_per_step", &config_.counts_per_step), make_protocol_property("watchdog_timeout", &config_.watchdog_timeout, [](void* ctx) { static_cast<Axis*>(ctx)->update_watchdog_settings(); }, this), make_protocol_property("step_gpio_pin", &config_.step_gpio_pin, [](void* ctx) { static_cast<Axis*>(ctx)->decode_step_dir_pins(); }, this), make_protocol_property("dir_gpio_pin", &config_.dir_gpio_pin, [](void* ctx) { static_cast<Axis*>(ctx)->decode_step_dir_pins(); }, this), make_protocol_object("lockin", make_protocol_property("current", &config_.lockin.current), make_protocol_property("ramp_time", &config_.lockin.ramp_time), make_protocol_property("ramp_distance", &config_.lockin.ramp_distance), make_protocol_property("accel", &config_.lockin.accel), make_protocol_property("vel", &config_.lockin.vel), make_protocol_property("finish_distance", &config_.lockin.finish_distance), make_protocol_property("finish_on_vel", &config_.lockin.finish_on_vel), make_protocol_property("finish_on_distance", &config_.lockin.finish_on_distance), make_protocol_property("finish_on_enc_idx", &config_.lockin.finish_on_enc_idx) ) ), make_protocol_object("motor", motor_.make_protocol_definitions()), make_protocol_object("controller", controller_.make_protocol_definitions()), make_protocol_object("encoder", encoder_.make_protocol_definitions()), make_protocol_object("sensorless_estimator", sensorless_estimator_.make_protocol_definitions()), make_protocol_object("trap_traj", trap_.make_protocol_definitions()), make_protocol_object("min_endstop", min_endstop_.make_protocol_definitions()), make_protocol_object("max_endstop", max_endstop_.make_protocol_definitions()), make_protocol_function("watchdog_feed", *this, &Axis::watchdog_feed) ); } }; DEFINE_ENUM_FLAG_OPERATORS(Axis::Error_t) #endif /* __AXIS_HPP */ <commit_msg>Fix bad struct and enums<commit_after>#ifndef __AXIS_HPP #define __AXIS_HPP #ifndef __ODRIVE_MAIN_H #error "This file should not be included directly. Include odrive_main.h instead." #endif enum HomingState_t { HOMING_STATE_IDLE, HOMING_STATE_HOMING, HOMING_STATE_MOVE_TO_ZERO }; class Axis { public: enum Error_t { ERROR_NONE = 0x00, ERROR_INVALID_STATE = 0x01, //<! an invalid state was requested ERROR_DC_BUS_UNDER_VOLTAGE = 0x02, ERROR_DC_BUS_OVER_VOLTAGE = 0x04, ERROR_CURRENT_MEASUREMENT_TIMEOUT = 0x08, ERROR_BRAKE_RESISTOR_DISARMED = 0x10, //<! the brake resistor was unexpectedly disarmed ERROR_MOTOR_DISARMED = 0x20, //<! the motor was unexpectedly disarmed ERROR_MOTOR_FAILED = 0x40, // Go to motor.hpp for information, check odrvX.axisX.motor.error for error value ERROR_SENSORLESS_ESTIMATOR_FAILED = 0x80, ERROR_ENCODER_FAILED = 0x100, // Go to encoder.hpp for information, check odrvX.axisX.encoder.error for error value ERROR_CONTROLLER_FAILED = 0x200, ERROR_POS_CTRL_DURING_SENSORLESS = 0x400, ERROR_WATCHDOG_TIMER_EXPIRED = 0x800, ERROR_MIN_ENDSTOP_PRESSED = 0x1000, ERROR_MAX_ENDSTOP_PRESSED = 0x2000 }; enum State_t { AXIS_STATE_UNDEFINED = 0, //<! will fall through to idle AXIS_STATE_IDLE = 1, //<! disable PWM and do nothing AXIS_STATE_STARTUP_SEQUENCE = 2, //<! the actual sequence is defined by the config.startup_... flags AXIS_STATE_FULL_CALIBRATION_SEQUENCE = 3, //<! run all calibration procedures, then idle AXIS_STATE_MOTOR_CALIBRATION = 4, //<! run motor calibration AXIS_STATE_SENSORLESS_CONTROL = 5, //<! run sensorless control AXIS_STATE_ENCODER_INDEX_SEARCH = 6, //<! run encoder index search AXIS_STATE_ENCODER_OFFSET_CALIBRATION = 7, //<! run encoder offset calibration AXIS_STATE_CLOSED_LOOP_CONTROL = 8, //<! run closed loop control AXIS_STATE_LOCKIN_SPIN = 9, //<! run lockin spin AXIS_STATE_ENCODER_DIR_FIND = 10, AXIS_STATE_HOMING = 11, //<! run axis homing function }; struct LockinConfig_t { float current = 10.0f; // [A] float ramp_time = 0.4f; // [s] float ramp_distance = 1 * M_PI; // [rad] float accel = 20.0f; // [rad/s^2] float vel = 40.0f; // [rad/s] float finish_distance = 100.0f; // [rad] bool finish_on_vel = false; bool finish_on_distance = false; bool finish_on_enc_idx = false; }; struct Config_t { bool startup_motor_calibration = false; //<! run motor calibration at startup, skip otherwise bool startup_encoder_index_search = false; //<! run encoder index search after startup, skip otherwise // this only has an effect if encoder.config.use_index is also true bool startup_encoder_offset_calibration = false; //<! run encoder offset calibration after startup, skip otherwise bool startup_closed_loop_control = false; //<! enable closed loop control after calibration/startup bool startup_sensorless_control = false; //<! enable sensorless control after calibration/startup bool startup_homing = false; //<! enable homing after calibration/startup bool enable_step_dir = false; //<! enable step/dir input after calibration // For M0 this has no effect if enable_uart is true float counts_per_step = 2.0f; float watchdog_timeout = 0.0f; // [s] (0 disables watchdog) // Defaults loaded from hw_config in load_configuration in main.cpp uint16_t step_gpio_pin = 0; uint16_t dir_gpio_pin = 0; LockinConfig_t lockin; }; enum thread_signals { M_SIGNAL_PH_CURRENT_MEAS = 1u << 0 }; enum LockinState_t { LOCKIN_STATE_INACTIVE, LOCKIN_STATE_RAMP, LOCKIN_STATE_ACCELERATE, LOCKIN_STATE_CONST_VEL, }; Axis(const AxisHardwareConfig_t& hw_config, Config_t& config, Encoder& encoder, SensorlessEstimator& sensorless_estimator, Controller& controller, Motor& motor, TrapezoidalTrajectory& trap, Endstop& min_endstop, Endstop& max_endstop); void setup(); void start_thread(); void signal_current_meas(); bool wait_for_current_meas(); void step_cb(); void set_step_dir_active(bool enable); void decode_step_dir_pins(); void update_watchdog_settings(); static void load_default_step_dir_pin_config( const AxisHardwareConfig_t& hw_config, Config_t* config); bool check_DRV_fault(); bool check_PSU_brownout(); bool do_checks(); bool do_updates(); void watchdog_feed(); bool watchdog_check(); // True if there are no errors bool inline check_for_errors() { return error_ == ERROR_NONE; } // @brief Runs the specified update handler at the frequency of the current measurements. // // The loop runs until one of the following conditions: // - update_handler returns false // - the current measurement times out // - the health checks fail (brownout, driver fault line) // - update_handler doesn't update the modulation timings in time // This criterion is ignored if current_state is AXIS_STATE_IDLE // // If update_handler is going to update the motor timings, you must call motor.arm() // shortly before this function. // // If the function returns, it is guaranteed that error is non-zero, except if the cause // for the exit was a negative return value of update_handler or an external // state change request (requested_state != AXIS_STATE_DONT_CARE). // Under all exit conditions the motor is disarmed and the brake current set to zero. // Furthermore, if the update_handler does not set the phase voltages in time, they will // go to zero. // // @tparam T Must be a callable type that takes no arguments and returns a bool template<typename T> void run_control_loop(const T& update_handler) { while (requested_state_ == AXIS_STATE_UNDEFINED) { // look for errors at axis level and also all subcomponents bool checks_ok = do_checks(); // Update all estimators // Note: updates run even if checks fail bool updates_ok = do_updates(); // make sure the watchdog is being fed. bool watchdog_ok = watchdog_check(); if (!checks_ok || !updates_ok || !watchdog_ok) { // It's not useful to quit idle since that is the safe action // Also leaving idle would rearm the motors if (current_state_ != AXIS_STATE_IDLE) break; } // Run main loop function, defer quitting for after wait // TODO: change arming logic to arm after waiting bool main_continue = update_handler(); // Check we meet deadlines after queueing ++loop_counter_; // Wait until the current measurement interrupt fires if (!wait_for_current_meas()) { // maybe the interrupt handler is dead, let's be // safe and float the phases safety_critical_disarm_motor_pwm(motor_); update_brake_current(); error_ |= ERROR_CURRENT_MEASUREMENT_TIMEOUT; break; } if (!main_continue) break; } } bool run_lockin_spin(); bool run_sensorless_control_loop(); bool run_closed_loop_control_loop(); bool run_idle_loop(); void run_state_machine_loop(); const AxisHardwareConfig_t& hw_config_; Config_t& config_; Encoder& encoder_; SensorlessEstimator& sensorless_estimator_; Controller& controller_; Motor& motor_; TrapezoidalTrajectory& trap_; Endstop& min_endstop_; Endstop& max_endstop_; osThreadId thread_id_; volatile bool thread_id_valid_ = false; // variables exposed on protocol Error_t error_ = ERROR_NONE; bool step_dir_active_ = false; // auto enabled after calibration, based on config.enable_step_dir // updated from config in constructor, and on protocol hook GPIO_TypeDef* step_port_; uint16_t step_pin_; GPIO_TypeDef* dir_port_; uint16_t dir_pin_; State_t requested_state_ = AXIS_STATE_STARTUP_SEQUENCE; State_t task_chain_[10] = { AXIS_STATE_UNDEFINED }; State_t& current_state_ = task_chain_[0]; uint32_t loop_counter_ = 0; LockinState_t lockin_state_ = LOCKIN_STATE_INACTIVE; HomingState_t homing_state_ = HOMING_STATE_IDLE; // watchdog uint32_t watchdog_reset_value_ = 0; //computed from config_.watchdog_timeout in update_watchdog_settings() uint32_t watchdog_current_value_= 0; // Communication protocol definitions auto make_protocol_definitions() { return make_protocol_member_list( make_protocol_property("error", &error_), make_protocol_ro_property("step_dir_active", &step_dir_active_), make_protocol_ro_property("current_state", &current_state_), make_protocol_property("requested_state", &requested_state_), make_protocol_ro_property("loop_counter", &loop_counter_), make_protocol_ro_property("lockin_state", &lockin_state_), make_protocol_ro_property("homing_state", &homing_state_), make_protocol_object("config", make_protocol_property("startup_motor_calibration", &config_.startup_motor_calibration), make_protocol_property("startup_encoder_index_search", &config_.startup_encoder_index_search), make_protocol_property("startup_encoder_offset_calibration", &config_.startup_encoder_offset_calibration), make_protocol_property("startup_closed_loop_control", &config_.startup_closed_loop_control), make_protocol_property("startup_sensorless_control", &config_.startup_sensorless_control), make_protocol_property("startup_homing", &config_.startup_homing), make_protocol_property("enable_step_dir", &config_.enable_step_dir), make_protocol_property("counts_per_step", &config_.counts_per_step), make_protocol_property("watchdog_timeout", &config_.watchdog_timeout, [](void* ctx) { static_cast<Axis*>(ctx)->update_watchdog_settings(); }, this), make_protocol_property("step_gpio_pin", &config_.step_gpio_pin, [](void* ctx) { static_cast<Axis*>(ctx)->decode_step_dir_pins(); }, this), make_protocol_property("dir_gpio_pin", &config_.dir_gpio_pin, [](void* ctx) { static_cast<Axis*>(ctx)->decode_step_dir_pins(); }, this), make_protocol_object("lockin", make_protocol_property("current", &config_.lockin.current), make_protocol_property("ramp_time", &config_.lockin.ramp_time), make_protocol_property("ramp_distance", &config_.lockin.ramp_distance), make_protocol_property("accel", &config_.lockin.accel), make_protocol_property("vel", &config_.lockin.vel), make_protocol_property("finish_distance", &config_.lockin.finish_distance), make_protocol_property("finish_on_vel", &config_.lockin.finish_on_vel), make_protocol_property("finish_on_distance", &config_.lockin.finish_on_distance), make_protocol_property("finish_on_enc_idx", &config_.lockin.finish_on_enc_idx) ) ), make_protocol_object("motor", motor_.make_protocol_definitions()), make_protocol_object("controller", controller_.make_protocol_definitions()), make_protocol_object("encoder", encoder_.make_protocol_definitions()), make_protocol_object("sensorless_estimator", sensorless_estimator_.make_protocol_definitions()), make_protocol_object("trap_traj", trap_.make_protocol_definitions()), make_protocol_object("min_endstop", min_endstop_.make_protocol_definitions()), make_protocol_object("max_endstop", max_endstop_.make_protocol_definitions()), make_protocol_function("watchdog_feed", *this, &Axis::watchdog_feed) ); } }; DEFINE_ENUM_FLAG_OPERATORS(Axis::Error_t) #endif /* __AXIS_HPP */ <|endoftext|>
<commit_before>/* * MolecularBezierData.cpp * * Copyright (C) 2013 by TU Dresden * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "MolecularBezierData.h" #include "vislib/BezierCurve.h" #include "vislib/RawStorage.h" #include "vislib/RawStorageWriter.h" #include "vislib/Point.h" #include <list> #include "Color.h" #include "vislib/NamedColours.h" using namespace megamol; using namespace megamol::protein; /* * MolecularBezierData::MolecularBezierData */ MolecularBezierData::MolecularBezierData(void) : Module(), outDataSlot("outData", "presents data as BezierCurvesListDataCall"), inDataSlot("inData", "fetches data either as ExtBezierDataCall or v1.BezierDataCall"), hash(0), timeCode(0) { this->outDataSlot.SetCallback(core::misc::BezierCurvesListDataCall::ClassName(), "GetData", &MolecularBezierData::getDataCallback); this->outDataSlot.SetCallback(core::misc::BezierCurvesListDataCall::ClassName(), "GetExtent", &MolecularBezierData::getExtentCallback); this->MakeSlotAvailable(&this->outDataSlot); this->inDataSlot.SetCompatibleCall<MolecularDataCallDescription>(); this->MakeSlotAvailable(&this->inDataSlot); } /* * MolecularBezierData::~MolecularBezierData */ MolecularBezierData::~MolecularBezierData(void) { this->Release(); } /* * MolecularBezierData::create */ bool MolecularBezierData::create(void) { Color::ReadColorTableFromFile(nullptr, this->colorLookupTable); Color::MakeRainbowColorTable(100, this->rainbowColors); return true; } /* * MolecularBezierData::release */ void MolecularBezierData::release(void) { // intentionally empty } /* * MolecularBezierData::getDataCallback */ bool MolecularBezierData::getDataCallback(core::Call& caller) { core::misc::BezierCurvesListDataCall *bcldc = dynamic_cast<core::misc::BezierCurvesListDataCall *>(&caller); if (bcldc == nullptr) return false; core::AbstractGetData3DCall *agd3dc = this->inDataSlot.CallAs<core::AbstractGetData3DCall>(); if (agd3dc == nullptr) return false; // check hash via cheap ext test agd3dc->SetFrameID(bcldc->FrameID(), bcldc->IsFrameForced()); if (!(*agd3dc)(1u)) return false; agd3dc->Unlock(); if ((bcldc->FrameID() != this->timeCode) || (this->hash == 0) || (this->hash != agd3dc->DataHash())) { agd3dc->SetFrameID(bcldc->FrameID(), bcldc->IsFrameForced()); // fetch actual data if (!(*agd3dc)(0u)) return false; if ((this->hash != agd3dc->DataHash()) || (this->timeCode != agd3dc->FrameID())) { // new data: recompute bezier data this->hash = agd3dc->DataHash(); this->timeCode = agd3dc->FrameID(); MolecularDataCall *mdc = dynamic_cast<MolecularDataCall*>(agd3dc); if (mdc != nullptr) { this->update(*mdc); } else { this->data.Clear(); this->data.SetGlobalColour(127, 127, 127); this->data.SetGlobalRadius(0.1f); } } } bcldc->SetDataHash(this->hash); bcldc->SetFrameID(this->timeCode); bcldc->SetUnlocker(nullptr); // HAZARD bcldc->SetData(&this->data, 1); return true; } /* * MolecularBezierData::getExtentCallback */ bool MolecularBezierData::getExtentCallback(core::Call& caller) { core::misc::BezierCurvesListDataCall *bcldc = dynamic_cast<core::misc::BezierCurvesListDataCall *>(&caller); if (bcldc == nullptr) return false; core::AbstractGetData3DCall *agd3dc = this->inDataSlot.CallAs<core::AbstractGetData3DCall>(); if (agd3dc == nullptr) return false; agd3dc->SetFrameID(bcldc->FrameID(), bcldc->IsFrameForced()); if (!(*agd3dc)(1u)) return false; bcldc->AccessBoundingBoxes() = agd3dc->AccessBoundingBoxes(); bcldc->SetFrameID(agd3dc->FrameID(), agd3dc->IsFrameForced()); bcldc->SetFrameCount(agd3dc->FrameCount()); bcldc->SetDataHash(agd3dc->DataHash()); bcldc->SetUnlocker(nullptr); agd3dc->Unlock(); return true; } /* * MolecularBezierData::update */ void MolecularBezierData::update(MolecularDataCall& dat) { this->data.Clear(); vislib::RawStorage pt_blob; vislib::RawStorageWriter pt(pt_blob); vislib::RawStorage idx_blob; vislib::RawStorageWriter idx(idx_blob); size_t cnt = 0; const float col_mix = 1.0f; Color::MakeColorTable(&dat, Color::STRUCTURE, Color::BFACTOR, col_mix, // blending factor between both color maps 1.0 - col_mix, // this->atomColorTable, this->colorLookupTable, this->rainbowColors, _T("blue"), _T("white"), _T("red"), true); for (unsigned int mi = 0; mi < dat.MoleculeCount(); mi++) { std::list<vislib::math::Point<float, 3> > poss; std::list<float> rads; std::list<vislib::math::Vector<float, 3> > cols; unsigned ssi = dat.Molecules()[mi].FirstSecStructIndex(); for (unsigned int ssit = 0; ssit < dat.Molecules()[mi].SecStructCount(); ssi++, ssit++) { unsigned int aai = dat.SecondaryStructures()[ssi].FirstAminoAcidIndex(); for (unsigned int aait = 0; aait < dat.SecondaryStructures()[ssi].AminoAcidCount(); aait++, aai++) { if (dat.Residues()[aai]->Identifier() != MolecularDataCall::Residue::AMINOACID) continue; unsigned int ca = static_cast<const MolecularDataCall::AminoAcid*>(dat.Residues()[aai])->CAlphaIndex(); vislib::math::Point<float, 3> pos(dat.AtomPositions() + (ca * 3)); float rad = 0.3f; vislib::math::Vector<float, 3> col(atomColorTable.PeekElements() + (ca * 3)); switch (dat.SecondaryStructures()[ssi].Type()) { case MolecularDataCall::SecStructure::TYPE_HELIX: rad = 0.4f; // ngstrm break; case MolecularDataCall::SecStructure::TYPE_SHEET: rad = 0.4f; // ngstrm break; case MolecularDataCall::SecStructure::TYPE_TURN: rad = 0.2f; // ngstrm break; case MolecularDataCall::SecStructure::TYPE_COIL: // fall through default: rad = 0.3f; // ngstrm } poss.push_back(pos); rads.push_back(rad); cols.push_back(col); } } // TODO: Fix me auto possE = poss.end(); auto posI = poss.begin(); auto radI = rads.begin(); auto colI = cols.begin(); for (; posI != possE; posI++, radI++, colI++) { pt.Write(posI->X()); pt.Write(posI->Y()); pt.Write(posI->Z()); pt.Write(*radI); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(colI->X() * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(colI->Y() * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(colI->Z() * 255.0f), 0, 255))); if (cnt > 1) { idx.Write(static_cast<unsigned int>(cnt - 1)); idx.Write(static_cast<unsigned int>(cnt - 1)); idx.Write(static_cast<unsigned int>(cnt)); idx.Write(static_cast<unsigned int>(cnt)); } cnt++; } } if (pt.Position() > 0) { unsigned char *pt_dat = new unsigned char[pt.Position()]; ::memcpy(pt_dat, pt_blob, pt.Position()); unsigned int *idx_dat = new unsigned int[idx.Position() / sizeof(unsigned int)]; ::memcpy(idx_dat, idx_blob, idx.Position()); this->data.Set(core::misc::BezierCurvesListDataCall::DATALAYOUT_XYZR_F_RGB_B, pt_dat, cnt, true, idx_dat, idx.Position() / sizeof(unsigned int), true, 0.5f, 127, 127, 127); } else { this->data.Set(core::misc::BezierCurvesListDataCall::DATALAYOUT_NONE, nullptr, 0, nullptr, 0); } } <commit_msg>Spline interpolation copied from SiffCSplineFitter<commit_after>/* * MolecularBezierData.cpp * * Copyright (C) 2013 by TU Dresden * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "MolecularBezierData.h" #include "vislib/BezierCurve.h" #include "vislib/RawStorage.h" #include "vislib/RawStorageWriter.h" #include "vislib/Point.h" #include <vector> #include "Color.h" #include "vislib/NamedColours.h" using namespace megamol; using namespace megamol::protein; /* * MolecularBezierData::MolecularBezierData */ MolecularBezierData::MolecularBezierData(void) : Module(), outDataSlot("outData", "presents data as BezierCurvesListDataCall"), inDataSlot("inData", "fetches data either as ExtBezierDataCall or v1.BezierDataCall"), hash(0), timeCode(0) { this->outDataSlot.SetCallback(core::misc::BezierCurvesListDataCall::ClassName(), "GetData", &MolecularBezierData::getDataCallback); this->outDataSlot.SetCallback(core::misc::BezierCurvesListDataCall::ClassName(), "GetExtent", &MolecularBezierData::getExtentCallback); this->MakeSlotAvailable(&this->outDataSlot); this->inDataSlot.SetCompatibleCall<MolecularDataCallDescription>(); this->MakeSlotAvailable(&this->inDataSlot); } /* * MolecularBezierData::~MolecularBezierData */ MolecularBezierData::~MolecularBezierData(void) { this->Release(); } /* * MolecularBezierData::create */ bool MolecularBezierData::create(void) { Color::ReadColorTableFromFile(nullptr, this->colorLookupTable); Color::MakeRainbowColorTable(100, this->rainbowColors); return true; } /* * MolecularBezierData::release */ void MolecularBezierData::release(void) { // intentionally empty } /* * MolecularBezierData::getDataCallback */ bool MolecularBezierData::getDataCallback(core::Call& caller) { core::misc::BezierCurvesListDataCall *bcldc = dynamic_cast<core::misc::BezierCurvesListDataCall *>(&caller); if (bcldc == nullptr) return false; core::AbstractGetData3DCall *agd3dc = this->inDataSlot.CallAs<core::AbstractGetData3DCall>(); if (agd3dc == nullptr) return false; // check hash via cheap ext test agd3dc->SetFrameID(bcldc->FrameID(), bcldc->IsFrameForced()); if (!(*agd3dc)(1u)) return false; agd3dc->Unlock(); if ((bcldc->FrameID() != this->timeCode) || (this->hash == 0) || (this->hash != agd3dc->DataHash())) { agd3dc->SetFrameID(bcldc->FrameID(), bcldc->IsFrameForced()); // fetch actual data if (!(*agd3dc)(0u)) return false; if ((this->hash != agd3dc->DataHash()) || (this->timeCode != agd3dc->FrameID())) { // new data: recompute bezier data this->hash = agd3dc->DataHash(); this->timeCode = agd3dc->FrameID(); MolecularDataCall *mdc = dynamic_cast<MolecularDataCall*>(agd3dc); if (mdc != nullptr) { this->update(*mdc); } else { this->data.Clear(); this->data.SetGlobalColour(127, 127, 127); this->data.SetGlobalRadius(0.1f); } } } bcldc->SetDataHash(this->hash); bcldc->SetFrameID(this->timeCode); bcldc->SetUnlocker(nullptr); // HAZARD bcldc->SetData(&this->data, 1); return true; } /* * MolecularBezierData::getExtentCallback */ bool MolecularBezierData::getExtentCallback(core::Call& caller) { core::misc::BezierCurvesListDataCall *bcldc = dynamic_cast<core::misc::BezierCurvesListDataCall *>(&caller); if (bcldc == nullptr) return false; core::AbstractGetData3DCall *agd3dc = this->inDataSlot.CallAs<core::AbstractGetData3DCall>(); if (agd3dc == nullptr) return false; agd3dc->SetFrameID(bcldc->FrameID(), bcldc->IsFrameForced()); if (!(*agd3dc)(1u)) return false; bcldc->AccessBoundingBoxes() = agd3dc->AccessBoundingBoxes(); bcldc->SetFrameID(agd3dc->FrameID(), agd3dc->IsFrameForced()); bcldc->SetFrameCount(agd3dc->FrameCount()); bcldc->SetDataHash(agd3dc->DataHash()); bcldc->SetUnlocker(nullptr); agd3dc->Unlock(); return true; } /** * local utility function for linear interpolation * * @param v1 Value 1 * @param v2 Value 2 * @param a Interpolation value * * @return The interpolated value */ static float interpolate(float v1, float v2, float a) { if (a < 0.0f) a = 0.0f; if (a > 1.0f) a = 1.0f; return v1 * (1.0f - a) + v2 * a; } /* * MolecularBezierData::update */ void MolecularBezierData::update(MolecularDataCall& dat) { this->data.Clear(); vislib::RawStorage pt_blob; vislib::RawStorageWriter pt(pt_blob); vislib::RawStorage idx_blob; vislib::RawStorageWriter idx(idx_blob); size_t cnt = 0; const float col_mix = 0.5f; Color::MakeColorTable(&dat, Color::STRUCTURE, Color::BFACTOR, col_mix, // blending factor between both color maps 1.0 - col_mix, // this->atomColorTable, this->colorLookupTable, this->rainbowColors, _T("blue"), _T("white"), _T("red"), true); for (unsigned int mi = 0; mi < dat.MoleculeCount(); mi++) { std::vector<const float* > poss; std::vector<float> rads; std::vector<const float* > cols; unsigned ssi = dat.Molecules()[mi].FirstSecStructIndex(); for (unsigned int ssit = 0; ssit < dat.Molecules()[mi].SecStructCount(); ssi++, ssit++) { unsigned int aai = dat.SecondaryStructures()[ssi].FirstAminoAcidIndex(); for (unsigned int aait = 0; aait < dat.SecondaryStructures()[ssi].AminoAcidCount(); aait++, aai++) { if (dat.Residues()[aai]->Identifier() != MolecularDataCall::Residue::AMINOACID) continue; unsigned int ca = static_cast<const MolecularDataCall::AminoAcid*>(dat.Residues()[aai])->CAlphaIndex(); float rad = 0.3f; // ngstrm switch (dat.SecondaryStructures()[ssi].Type()) { case MolecularDataCall::SecStructure::TYPE_HELIX: rad = 0.4f; // ngstrm break; case MolecularDataCall::SecStructure::TYPE_SHEET: rad = 0.4f; // ngstrm break; case MolecularDataCall::SecStructure::TYPE_TURN: rad = 0.2f; // ngstrm break; case MolecularDataCall::SecStructure::TYPE_COIL: // fall through default: rad = 0.3f; // ngstrm } poss.push_back(dat.AtomPositions() + (ca * 3)); rads.push_back(rad); cols.push_back(atomColorTable.PeekElements() + (ca * 3)); } } ASSERT(poss.size() == rads.size()); ASSERT(poss.size() == cols.size()); if (poss.size() < 2) { continue; // skip this empty data } else if (poss.size() == 2) { // simple line: pt.Write(poss[0][0]); pt.Write(poss[0][1]); pt.Write(poss[0][2]); pt.Write(rads[0]); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[0][0] * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[0][1] * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[0][2] * 255.0f), 0, 255))); cnt++; pt.Write(poss[1][0]); pt.Write(poss[1][1]); pt.Write(poss[1][2]); pt.Write(rads[1]); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[1][0] * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[1][1] * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[1][2] * 255.0f), 0, 255))); cnt++; idx.Write(static_cast<unsigned int>(cnt - 2)); idx.Write(static_cast<unsigned int>(cnt - 2)); idx.Write(static_cast<unsigned int>(cnt - 1)); idx.Write(static_cast<unsigned int>(cnt - 1)); } else { // more than three points (spline-siff-code from old core module) // first curve pt.Write(poss[0][0]); pt.Write(poss[0][1]); pt.Write(poss[0][2]); pt.Write(rads[0]); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[0][0] * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[0][1] * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[0][2] * 255.0f), 0, 255))); idx.Write(static_cast<unsigned int>(cnt)); cnt++; pt.Write(interpolate(poss[0][0], poss[1][0], 0.75f)); pt.Write(interpolate(poss[0][1], poss[1][1], 0.75f)); pt.Write(interpolate(poss[0][2], poss[1][2], 0.75f)); pt.Write(interpolate(rads[0], rads[1], 0.75f)); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[0][0], cols[1][0], 0.75f) * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[0][1], cols[1][1], 0.75f) * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[0][2], cols[1][2], 0.75f) * 255.0f), 0, 255))); idx.Write(static_cast<unsigned int>(cnt)); cnt++; // inner curves for (unsigned int i = 1; i < poss.size() - 1; i++) { pt.Write(interpolate(poss[i][0], poss[i + 1][0], 0.25f)); pt.Write(interpolate(poss[i][1], poss[i + 1][1], 0.25f)); pt.Write(interpolate(poss[i][2], poss[i + 1][2], 0.25f)); pt.Write(interpolate(rads[i], rads[i + 1], 0.25f)); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[i][0], cols[i + 1][0], 0.25f) * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[i][1], cols[i + 1][1], 0.25f) * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[i][2], cols[i + 1][2], 0.25f) * 255.0f), 0, 255))); idx.Write(static_cast<unsigned int>(cnt)); cnt++; pt.Write(interpolate(poss[i][0], poss[i + 1][0], 0.5f)); pt.Write(interpolate(poss[i][1], poss[i + 1][1], 0.5f)); pt.Write(interpolate(poss[i][2], poss[i + 1][2], 0.5f)); pt.Write(interpolate(rads[i], rads[i + 1], 0.5f)); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[i][0], cols[i + 1][0], 0.5f) * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[i][1], cols[i + 1][1], 0.5f) * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[i][2], cols[i + 1][2], 0.5f) * 255.0f), 0, 255))); idx.Write(static_cast<unsigned int>(cnt)); idx.Write(static_cast<unsigned int>(cnt)); // use this point twice cnt++; pt.Write(interpolate(poss[i][0], poss[i + 1][0], 0.75f)); pt.Write(interpolate(poss[i][1], poss[i + 1][1], 0.75f)); pt.Write(interpolate(poss[i][2], poss[i + 1][2], 0.75f)); pt.Write(interpolate(rads[i], rads[i + 1], 0.75f)); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[i][0], cols[i + 1][0], 0.75f) * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[i][1], cols[i + 1][1], 0.75f) * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[i][2], cols[i + 1][2], 0.75f) * 255.0f), 0, 255))); idx.Write(static_cast<unsigned int>(cnt)); cnt++; } // last curve pt.Write(interpolate(poss[poss.size() - 2][0], poss[poss.size() - 1][0], 0.25f)); pt.Write(interpolate(poss[poss.size() - 2][1], poss[poss.size() - 1][1], 0.25f)); pt.Write(interpolate(poss[poss.size() - 2][2], poss[poss.size() - 1][2], 0.25f)); pt.Write(interpolate(rads[poss.size() - 2], rads[poss.size() - 1], 0.25f)); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[poss.size() - 2][0], cols[poss.size() - 1][0], 0.25f) * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[poss.size() - 2][1], cols[poss.size() - 1][1], 0.25f) * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(interpolate(cols[poss.size() - 2][2], cols[poss.size() - 1][2], 0.25f) * 255.0f), 0, 255))); idx.Write(static_cast<unsigned int>(cnt)); cnt++; pt.Write(poss[poss.size() - 1][0]); pt.Write(poss[poss.size() - 1][1]); pt.Write(poss[poss.size() - 1][2]); pt.Write(rads[poss.size() - 1]); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[poss.size() - 1][0] * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[poss.size() - 1][1] * 255.0f), 0, 255))); pt.Write(static_cast<unsigned char>(vislib::math::Clamp(static_cast<int>(cols[poss.size() - 1][2] * 255.0f), 0, 255))); idx.Write(static_cast<unsigned int>(cnt)); cnt++; } } if (pt.Position() > 0) { unsigned char *pt_dat = new unsigned char[pt.Position()]; ::memcpy(pt_dat, pt_blob, pt.Position()); unsigned int *idx_dat = new unsigned int[idx.Position() / sizeof(unsigned int)]; ::memcpy(idx_dat, idx_blob, idx.Position()); this->data.Set(core::misc::BezierCurvesListDataCall::DATALAYOUT_XYZR_F_RGB_B, pt_dat, cnt, true, idx_dat, idx.Position() / sizeof(unsigned int), true, 0.5f, 127, 127, 127); } else { this->data.Set(core::misc::BezierCurvesListDataCall::DATALAYOUT_NONE, nullptr, 0, nullptr, 0); } } <|endoftext|>