static bool distanceFromAncestor(const Location & self,
                                 const Location & other, Point3D & c)
{
    if (&self == &other) {
        return true;
    }

    if (other.m_loc == NULL) {
        return false;
    }

    if (other.orientation().isValid()) {
        c = c.toParentCoords(other.m_pos, other.orientation());
    } else {
        static const Quaternion identity(1, 0, 0, 0);
        c = c.toParentCoords(other.m_pos, identity);
    }

    return distanceFromAncestor(self, other.m_loc->m_location, c);
}
void SimpleCameraObjectScript::stableRotateAction(float dir, float amount)
{
    // Get the updated position
    Time now = context()->simTime();
    Location loc = mSelfProxy->extrapolateLocation(now);
    const Quaternion &orient = loc.getOrientation();

    double p, r, y;
    quat2Euler(orient, p, r, y);
    Vector3f raxis;
    raxis.x = 0;
    raxis.y = std::cos(p*DEG2RAD);
    raxis.z = -std::sin(p*DEG2RAD);

    // Request updates from spcae
    TimedMotionQuaternion neworient(now, MotionQuaternion(loc.getOrientation(), Quaternion(raxis, dir*amount)));
    mParent->requestOrientationUpdate(mID.space(), mID.object(), neworient);
    // And update our local Proxy's information, assuming the move will be successful
    mSelfProxy->setOrientation(neworient, 0, true);
}
Example #3
0
// --------- begin of function BulletHoming::init --------//
void BulletHoming::init(char parentType, short parentRecno, short targetXLoc, short targetYLoc, char targetMobileType)
{
	Bullet::init(parentType, parentRecno, targetXLoc, targetYLoc, targetMobileType);

	// ------- find the maximum range --------//

	BaseObj *baseObjPtr = base_obj_array[parent_base_obj_recno];
	if( baseObjPtr->cast_to_Unit() )
	{
		Unit *parentUnit = base_obj_array[parent_base_obj_recno]->cast_to_Unit();
		AttackInfo* attackInfo = parentUnit->attack_info_array+parentUnit->cur_attack;
		speed = attackInfo->bullet_speed;
		max_step = char((attackInfo->attack_range * LOCATE_WIDTH + speed-1)/ speed);
	}
	else if( baseObjPtr->cast_to_Firm() && baseObjPtr->cast_to_Firm()->cast_to_FirmFort() )
	{
		FirmFort *firmFort = baseObjPtr->cast_to_Firm()->cast_to_FirmFort();
		speed = firmFort->bullet_speed();
		max_step = 100;		// unlimited range
	}
	else
	{
		err_here();
	}

	//--------- keep backup of centre of the bullet ---------//
	SpriteFrame *spriteFrame = cur_sprite_frame();

	// origin_x/y and origin2_x/y are pointing at the centre of the bullet bitmap //
	origin_x += spriteFrame->offset_x + spriteFrame->width/2;
	origin_y += spriteFrame->offset_y + spriteFrame->height/2;
	origin2_x = origin_x; 
	origin2_y = origin_y;
	go_x += spriteFrame->offset_x + spriteFrame->width/2;
	go_y += spriteFrame->offset_y + spriteFrame->height/2;

	// ------- find the target_type and target_recno ------//

	Location *locPtr = world.get_loc(targetXLoc, targetYLoc);
	target_base_obj_recno = locPtr->base_obj_recno(targetMobileType);
}
Example #4
0
QT_BEGIN_NAMESPACE

void executeCommand( const Location& location, const QString& format,
		     const QStringList& args )
{
    QString actualCommand;
    for ( int i = 0; i < (int) format.length(); i++ ) {
	int ch = format[i].unicode();
	if ( ch > 0 && ch < 8 ) {
	    actualCommand += args[ch - 1];
	} else {
	    actualCommand += format[i];
	}
    }

    QString toolName = actualCommand;
    int space = toolName.indexOf( QLatin1Char(' ') );
    if ( space != -1 )
	toolName.truncate( space );

    QProcess process;
    process.start(QLatin1String("sh"),
        QStringList() << QLatin1String("-c") << actualCommand );
    process.waitForFinished();

    if (process.exitCode() == 127)
	location.fatal( tr("Couldn't launch the '%1' tool")
			.arg(toolName),
			tr("Make sure the tool is installed and in the"
			   " path.") );

    QString errors = QString::fromLocal8Bit(process.readAllStandardError());
    while ( errors.endsWith(QLatin1Char('\n')) )
        errors.truncate( errors.length() - 1 );
    if ( !errors.isEmpty() )
	location.fatal( tr("The '%1' tool encountered some problems")
			.arg(toolName),
			tr("The tool was invoked like this:\n%1\n"
			   "It emitted these errors:\n%2")
			.arg(actualCommand).arg(errors) );
}
Example #5
0
void BlockSummary::ComputeAssertNames()
{
  BlockCFG *cfg = GetBlockCFG(m_id);
  Assert(cfg);

  // the assertion names need the filename of the containing function.
  Location *loc = cfg->GetPointLocation(cfg->GetEntryPoint());

  // keep track of the last kind/index to be generated for an assertion.
  // the index space should be different for each assertion kind so that
  // different assertions do not interfere with one another. we can get this
  // with a simple counter because the assertions are sorted by kind.
  AssertKind last_kind = ASK_None;
  size_t last_index = 0;

  for (size_t ind = 0; m_assert_list && ind < m_assert_list->Size(); ind++) {
    AssertInfo &info = m_assert_list->At(ind);
    Assert(!info.name_buf);

    // only compute indexes for assertions which need to be checked.
    if (info.cls != ASC_Check) continue;

    // reset the index if this is a new kind of assertion.
    if (info.kind != last_kind) {
      last_kind = info.kind;
      last_index = 0;
    }
    last_index++;

    info.name_buf = new Buffer(256);
    BufferOutStream out(info.name_buf);

    out << AssertKindString(last_kind) << "$"
        << loc->FileName()->Value() << "$"
        << m_id->Function()->Value() << "$"
        << (m_id->Kind() == B_Loop ? m_id->Loop()->Value() : "func") << "$"
        << last_index << '\0';
  }

  cfg->DecRef();
}
Example #6
0
// @author Andre Allan Ponce
// checks the four cardinal spaces directly around player for an item (which was supposed to be symbols)
int Game::detectItemID(){
	int currPlayerX = player->getRoomLocX();
	int currPlayerY = player->getRoomLocY();
	bool noItem = true;
	Location* currRoom = world[currX][currY];
	for(int i = 1; i < 5; i++){
		cout << "in here" << i << "\n";
		switch(i){
		case MOVE_LEFT:{
			int finding = findItemID(currRoom->getSpaceAt(currPlayerX,currPlayerY-1));
			if(finding >= 0){
				return finding;
			}
			break;
		}
		case MOVE_UP:{
			int finding = findItemID(currRoom->getSpaceAt(currPlayerX-1,currPlayerY));
			cout << finding;
			if(finding >= 0){
				return finding;
			}
			break;
		}
		case MOVE_RIGHT:{
			int finding = findItemID(currRoom->getSpaceAt(currPlayerX,currPlayerY+1));
			if(finding >= 0){
				return finding;
			}
			break;
		}
		case MOVE_DOWN:{
			int finding = findItemID(currRoom->getSpaceAt(currPlayerX+1,currPlayerY));
			if(finding >= 0){
				return finding;
			}
			break;
		}
		}
	}
	return -1;
}
Example #7
0
int FindSymbolsJob::execute()
{
    int ret = 2;
    if (std::shared_ptr<Project> proj = project()) {
        Set<Symbol> symbols;
        Location filter;
        const uint32_t filteredFile = fileFilter();
        if (filteredFile)
            filter = Location(filteredFile, 0, 0);
        auto inserter = [proj, this, &symbols, &filter, filteredFile](Project::SymbolMatchType type,
                                                                      const String &symbolName,
                                                                      const Set<Location> &locations) {
            if (filter.fileId()) {
                auto it = locations.lower_bound(filter);
                if (it == locations.end() || it->fileId() != filteredFile)
                    return;
            }
            if (type == Project::StartsWith) {
                const size_t paren = symbolName.indexOf('(');
                if (paren == String::npos || paren != string.size() || RTags::isFunctionVariable(symbolName))
                    return;
            }
            for (const auto &it : locations) {
                const Symbol sym = proj->findSymbol(it);
                if (!sym.isNull())
                    symbols.insert(sym);
            }
        };
        proj->findSymbols(string, inserter, queryFlags());
        if (!symbols.isEmpty()) {
            const List<RTags::SortedSymbol> sorted = proj->sort(symbols, queryFlags());
            const Flags<WriteFlag> writeFlags = fileFilter() ? Unfiltered : NoWriteFlags;
            const int count = sorted.size();
            ret = count ? 0 : 1;
            for (int i=0; i<count; ++i) {
                write(sorted.at(i).location, writeFlags);
            }
        }
    }
    return ret;
}
Example #8
0
void FollowLocationJob::execute()
{
    Scope<const SymbolMap&> scope = project()->lockSymbolsForRead();
    if (scope.isNull())
        return;

    const SymbolMap &map = scope.data();
    const SymbolMap::const_iterator it = RTags::findCursorInfo(map, location);
    if (it == map.end())
        return;

    const CursorInfo &cursorInfo = it->second;
    if (cursorInfo.isClass() && cursorInfo.isDefinition())
        return;

    Location loc;
    CursorInfo target = cursorInfo.bestTarget(map, &loc);
    if (!loc.isNull()) {
        if (cursorInfo.kind != target.kind) {
            if (!target.isDefinition() && !target.targets.isEmpty()) {
                switch (target.kind) {
                case CXCursor_ClassDecl:
                case CXCursor_ClassTemplate:
                case CXCursor_StructDecl:
                case CXCursor_FunctionDecl:
                case CXCursor_CXXMethod:
                case CXCursor_Destructor:
                case CXCursor_Constructor:
                case CXCursor_FunctionTemplate:
                    target = target.bestTarget(map, &loc);
                    break;
                default:
                    break;
                }
            }
        }
        if (!loc.isNull()) {
            write(loc);
        }
    }
}
Example #9
0
File: ow_plant.cpp Project: 7k2/7k2
//------------ begin of function World::plant_grow ------------//
//
// pGrow = prabability of grow, range from 0 to 100
// scanDensity = scan one square per scanDensity^2
//
void World::plant_grow(int pGrow, int scanDensity)
{
    // scan part of the map for plant
    int yBase = misc.random(scanDensity);
    int xBase = misc.random(scanDensity);
    for( int y = yBase; y < max_y_loc; y += scanDensity)
        for( int x = xBase; x < max_x_loc; x += scanDensity)
        {
            Location *l = get_loc(x,y);
            short bitmapId, basePlantId;

            // is a plant and is not at maximum grade
            if( l->is_plant() && misc.random(100) < pGrow &&
                    (basePlantId = plant_res.plant_recno(bitmapId = l->plant_id())) != 0 &&
                    bitmapId - plant_res[basePlantId]->first_bitmap < plant_res[basePlantId]->bitmap_count -1)
            {
                // increase the grade of plant
                l->grow_plant();
            }
        }
}
Example #10
0
bool TranslationUnit::LocationIsInSystemHeader( const Location &location ) {
  unique_lock< mutex > lock( clang_access_mutex_ );

  if ( !clang_translation_unit_ || !location.IsValid() ) {
    return false;
  }

  return clang_Location_isInSystemHeader(
    GetSourceLocation( location.filename_,
                       location.line_number_,
                       location.column_number_ ) );
}
Example #11
0
// return best RTL location from current position
Location AP_Rally::calc_best_rally_or_home_location(const Location &current_loc, float rtl_home_alt) const
{
    RallyLocation ral_loc = {};
    Location return_loc = {};
    const struct Location &home_loc = AP::ahrs().get_home();
    
    // no valid rally point, return home position
    return_loc = home_loc;
    return_loc.alt = rtl_home_alt;
    return_loc.relative_alt = false; // read_alt_to_hold returns an absolute altitude

    if (find_nearest_rally_point(current_loc, ral_loc)) {
        Location loc = rally_location_to_location(ral_loc);
        // use the rally point if it's closer then home, or we aren't generally considering home as acceptable
        if (!_rally_incl_home  || (current_loc.get_distance(loc) < current_loc.get_distance(return_loc))) {
            return_loc = rally_location_to_location(ral_loc);
        }
    }

    return return_loc;
}
Example #12
0
/*!
  Creates the file named \a fileName in the output directory.
  Attaches a QTextStream to the created file, which is written
  to all over the place using out().
 */
void PageGenerator::beginSubPage(const Location& location,
                                 const QString& fileName)
{
    QFile* outFile = new QFile(outputDir() + "/" + fileName);
    if (!outFile->open(QFile::WriteOnly))
	location.fatal(tr("Cannot open output file '%1'").arg(outFile->fileName()));
    QTextStream* out = new QTextStream(outFile);

    if (outputCodec)
        out->setCodec(outputCodec);
    outStreamStack.push(out);
}
Example #13
0
// Find the first Assignment with loc on the LHS
Assignment* StatementList::findOnLeft(Exp* loc)
{
    if (slist.size() == 0)
        return NULL;
    for (iterator it = slist.begin(); it != slist.end(); it++)
        {
            Exp *left = ((Assignment*)*it)->getLeft();
            if (*left == *loc)
                return (Assignment*)*it;
            if (left->isLocal())
                {
                    Location *l = (Location*)left;
                    Exp *e = l->getProc()->expFromSymbol(((Const*)l->getSubExp1())->getStr());
                    if (e && ((*e == *loc) || (e->isSubscript() && *e->getSubExp1() == *loc)))
                        {
                            return (Assignment*)*it;
                        }
                }
        }
    return NULL;
}
Example #14
0
//------- Begin of function WallRes::disp_info -------//
//
void WallRes::disp_info(int refreshFlag)
{
	if( selected_x_loc < 0 )
		return;

	if( refreshFlag == INFO_REPAINT )
	{
		font_san.d3_put( INFO_X1, INFO_Y1, INFO_X2, INFO_Y1+17, "Defense Wall" );
		vga_front.d3_panel_up( INFO_X1, INFO_Y1+20, INFO_X2, INFO_Y1+40, 1 );
	}

	int x=INFO_X1+3, y=INFO_Y1+23;
	Location* locPtr = world.get_loc( selected_x_loc, selected_y_loc );

	String str;

	str  = locPtr->wall_abs_hit_point();
	str += " / 100";

	font_san.field( x, y, "Hit Points",  x+80, str, INFO_X2-4, refreshFlag );
}
Example #15
0
void Entity::move(Entity_List entities) {
  Location diff = Location::subtract(this->destination, this->location);
  Location direction = diff.get_direction_to(); 

  Location next_step(
      this->location.x + direction.x * this->speed,
      this->location.y + direction.y * this->speed);

  Entity_Iterator entity;
  Entity_Iterator end = entities.end();
  for (entity = entities.begin(); entity != end; ++entity) {
    if (next_step.collides_with(entity->location)
        && !entity->is_equal(*this)) {
      return;
    }
  }

  this->location = next_step;
  this->state = get_state(direction);
  this->idle = false;
}
Example #16
0
bool SMEntity::teleport(const Location &location, PlayerTeleportEvent::TeleportCause cause)
{
	if(!isDead())
		return false;

	if(entity->isRiding())
		entity->stopRiding(true);

	entity->setPos(location.getPos());

	return true;
}
Example #17
0
//------- Begin of function Tornado::hit_building -----//
//	building means firm or town
//
void Tornado::hit_building()
{
	short damageXLoc = damage_x_loc();
	short damageYLoc = damage_y_loc();
	if( damageXLoc < 0 || damageXLoc >= world.max_x_loc ||
		damageYLoc < 0 || damageYLoc >= world.max_y_loc)
		return;

	Location* locPtr = world.get_loc(damageXLoc, damageYLoc);

	// ##### begin Gilbert 30/10 #####//
	if(locPtr->is_firm() )
//		&& firm_res[(firmPtr=firm_array[locPtr->firm_recno()])->firm_id]->buildable )
	{
		Firm *firmPtr = firm_array[locPtr->firm_recno()];
		firmPtr->hit_points -= attack_damage*2;
		if( firmPtr->hit_points <= 0)
		{
			firmPtr->hit_points = (float) 0;

			se_res.sound(firmPtr->center_x, firmPtr->center_y, 1,
				'F', firmPtr->firm_id, "DIE" );

			firm_array.del_firm(locPtr->firm_recno());
		}
	}

	if( locPtr->is_town() )
	{
		Town *townPtr = town_array[locPtr->town_recno()];
		if( (life_time % 30) == 0 ) 
			townPtr->kill_town_people(0);
	}
	// ##### end Gilbert 30/10 #####//
}
Example #18
0
Location TranslationUnit::GetDefinitionOrDeclarationLocation(
  const std::string &filename,
  int line,
  int column,
  const std::vector< UnsavedFile > &unsaved_files,
  bool reparse ) {
  if ( reparse ) {
    Reparse( unsaved_files );
  }

  unique_lock< mutex > lock( clang_access_mutex_ );

  if ( !clang_translation_unit_ ) {
    return Location();
  }

  CXCursor cursor = GetCursor( filename, line, column );

  if ( !CursorIsValid( cursor ) ) {
    return Location();
  }

  // Return the definition or the declaration of a symbol under the cursor
  // according to the following logic:
  //  - if the cursor is already on the definition, return the location of the
  //    declaration;
  //  - otherwise, search for the definition and return its location;
  //  - if no definition is found, return the location of the declaration.
  if ( clang_isCursorDefinition( cursor ) ) {
    return GetDeclarationLocationForCursor( cursor );
  }

  Location location = GetDefinitionLocationForCursor( cursor );

  if ( location.IsValid() ) {
    return location;
  }

  return GetDeclarationLocationForCursor( cursor );
}
Example #19
0
    Datum getWciLocation( PG_FUNCTION_ARGS )
    {
		// Function is Strict, so no need to check for NULLs
        const text * location = PG_GETARG_TEXT_P( 0 );
        boost::scoped_array<char> p( new char[ VARSIZE( location ) + 1 ] );
        std::copy( VARDATA( location ), ( char* ) location + VARSIZE( location ), p.get() );
        p[ VARSIZE( location ) - VARHDRSZ ] = '\0';

        try
        {
            const Location loc( p.get() );

            Datum d = packWciLocation(
            		loc.interpolation().c_str(),
            		loc.hasGeometry() ? loc.geometry().c_str() : loc.placeName().c_str(),
            				loc.hasGeometry(),
            				fcinfo );
            return d;
        }
        catch ( std::logic_error & e )
        {
            ereport( ERROR,
                     ( errcode( ERRCODE_INVALID_TEXT_REPRESENTATION ),
                       errmsg( e.what() ) ) );
        }
        catch ( std::runtime_error & e )
        {
            ereport( ERROR,
                     ( errcode( ERRCODE_INVALID_TEXT_REPRESENTATION ),
                       errmsg( e.what() ) ) );
        }
        PG_RETURN_NULL();
    }
Example #20
0
bool QueryJob::locationToString(Location location,
                                const std::function<void(LocationPiece, const String &)> &cb,
                                Flags<WriteFlag> writeFlags)
{
    if (location.isNull())
        return false;
    Flags<Location::ToStringFlag> kf = locationToStringFlags();
    kf &= ~Location::ShowContext;
    cb(Piece_Location, location.toString(kf, &mContextCache));
    if (!(writeFlags & NoContext) && !(queryFlags() & QueryMessage::NoContext))
        cb(Piece_Context, location.context(kf, &mContextCache));

    const bool containingFunction = queryFlags() & QueryMessage::ContainingFunction;
    const bool containingFunctionLocation = queryFlags() & QueryMessage::ContainingFunctionLocation;
    const bool cursorKind = queryFlags() & QueryMessage::CursorKind;
    const bool displayName = queryFlags() & QueryMessage::DisplayName;
    if (containingFunction || containingFunctionLocation || cursorKind || displayName || !mKindFilters.isEmpty()) {
        int idx;
        Symbol symbol = project()->findSymbol(location, &idx);
        if (symbol.isNull()) {
            error() << "Somehow can't find" << location << "in symbols";
        } else {
            if (!mKindFilters.filter(symbol))
                return false;
            if (displayName)
                cb(Piece_SymbolName, symbol.displayName());
            if (cursorKind)
                cb(Piece_Kind, symbol.kindSpelling());
            if (containingFunction || containingFunctionLocation) {
                const uint32_t fileId = location.fileId();
                const unsigned int line = location.line();
                const unsigned int column = location.column();
                auto fileMap = project()->openSymbols(location.fileId());
                if (fileMap) {
                    while (idx > 0) {
                        symbol = fileMap->valueAt(--idx);
                        if (symbol.location.fileId() != fileId)
                            break;
                        if (symbol.isDefinition()
                            && RTags::isContainer(symbol.kind)
                            && comparePosition(line, column, symbol.startLine, symbol.startColumn) >= 0
                            && comparePosition(line, column, symbol.endLine, symbol.endColumn) <= 0) {
                            if (containingFunction)
                                cb(Piece_ContainingFunctionName, symbol.symbolName);
                            if (containingFunctionLocation)
                                cb(Piece_ContainingFunctionLocation, symbol.location.toString(locationToStringFlags() & ~Location::ShowContext));
                            break;
                        }
                    }
                }
            }
        }
    }
    return true;
}
Example #21
0
//------- Begin of function Bullet::hit_wall -----//
// ###### begin Gilbert 14/5 #########//
void Bullet::hit_wall(short x, short y)
{
	Location* locPtr = world.get_loc(x, y);

	if(!locPtr->is_wall())
		return;

	float attackDamage = attenuated_damage(x * ZOOM_LOC_WIDTH, y * ZOOM_LOC_HEIGHT );
	if( attackDamage == 0)
		return;
// ###### end Gilbert 14/5 #########//

	Unit *virtualUnit, *parentUnit;
	if(unit_array.is_deleted(parent_recno))
	{
		parentUnit = NULL;
		//### begin alex 26/9 ###//
		if(nation_array.is_deleted(nation_recno))
			return;
		//#### end alex 26/9 ####//

		for(int i=unit_array.size(); i>0; i--)
		{
			if(unit_array.is_deleted(i))
				continue;

			virtualUnit = unit_array[i];
			break;
		}

		if(!virtualUnit)
			return; //**** BUGHERE
	}
	else
		virtualUnit = parentUnit = unit_array[parent_recno];

	// ###### begin Gilbert 14/5 #########//
	virtualUnit->hit_wall(parentUnit, target_x_loc, target_y_loc, attackDamage);
	// ###### end Gilbert 14/5 ########//
}
Example #22
0
void Piece::addMoves(
		Location current,
		Board& board,
		set<Location>& moves,
		int rowDiff,
		int colDiff) const
{
	Location next = Location(current.row() + rowDiff, current.column() + colDiff);
	while(true)
	{
		if (!next.isValid())
			break;
		if (board.at(next) != NULL)
		{
			if (board.at(next)->color() != this->color())
			{
				moves.insert(next);
			}
			break;
		}
		else
		{
			moves.insert(next);
		}
		next = Location(next.row() + rowDiff, next.column() + colDiff);
	}
}
Example #23
0
int PID::goToDestination(Location& _currentLocation) {
    if (!updateLocation()) {
        for(int i = 0 ; i <= 1000 ; i++) {
  	    usleep(1000);
	    if (updateLocation()) {
	        break;
	    }
	    else {
	        if(i == 1000) {
		    tx->halt();
		    return 0;
		} 
	    }
	}
    }
    
    updateRatios();
    
    int controlIndices[] = {2, 3, 0};
    int index;

    control_vals[2] = ratios.X * trim[2];
    control_vals[3] = ratios.Y * trim[3];
    control_vals[0] = ratios.Z * STARTPOW;
	
    for (int i = 0 ; i < 3 ; i++) {
        index = controlIndices[i];
	if (control_vals[index] > 250)
	    control_vals[index] = 250;
	if (control_vals[index] <= 5)
	    control_vals[index] = 5;
    }
 

    if(control_vals[THROTTLE - 1] > MAXTHROTTLE) {
      std::cout << "Throttle: " << control_vals[THROTTLE] << std::endl; 
      control_vals[THROTTLE - 1] = MAXTHROTTLE;
    }

    std::cout << time_diff << "ms :: " 
	      << "[" << control_vals[AILERON - 1] << ", " 
	      << control_vals[ELEVATOR - 1] << ", " 
	      << control_vals[THROTTLE - 1] << "] :: (" 
	      << location.X << ", " 
	      << location.Y << ", " 
	      << location.Z << ")" << std::endl;

    tx->setValues(control_vals);
    _currentLocation.setValues(location.X, location.Y, location.Z);
  
    return 1;
}
/*
 * s_j + r CT + 2*|R| CT (3-c_{i,j}^{k1,k2,r}-m_i^k1-m_j^k2) \geq s_i + d_i (16)
 * s_i + 2*|R| CT (2+c_{i,j}^{k1,k2,r}-m_i^k1-m_j^k2) \geq s_j + d_j + r CT (17)
 */
void ConstraintsGenerator::addCollisions(const map1to1& s, const map1to1& d, const map2to1& x, const map2to1& y, const map4toN& c)	{
	assert(mRobots.size() > 1 && mLine != nullptr && "More than one robot expected!");
	for (const pair<ActivityMode*, ActivityMode*>& col : mLine->collisions())	{
		int32_t numberOfRobots = mRobots.size();
		for (int32_t r = -numberOfRobots; r <= numberOfRobots; ++r)	{
			Operator op = GREATER_EQUAL;
			SparseMatrix<double>::Row row;
			double constVal = 2.0*numberOfRobots*mCycleTime;
			double b1 = -3.0*constVal-r*mCycleTime, b2 = -2.0*constVal+r*mCycleTime;

			uint32_t a[2], m[2], i = 0;
			for (ActivityMode* mode : {col.first, col.second})	{
				Movement *mv = dynamic_cast<Movement*>(mode);
				if (mv != nullptr)	{
					DynamicActivity *da = mv->parent();
					a[i] = da->aid(); m[i] = mv->mid();
					row.emplace_back(getValue(y, {a[i], m[i]}, caller()), -constVal);
				}

				Location *loc = dynamic_cast<Location*>(mode);
				if (loc != nullptr)	{
					StaticActivity *sa = loc->parent();
					a[i] = sa->aid(); m[i] = loc->lid();
					row.emplace_back(getValue(x, {a[i], loc->point()}, caller()), -constVal);
				}

				++i;
			}

			SparseMatrix<double>::Row row1 = row, row2 = row;
			const vector<uint32_t>& v = getValue(c, {pack(a[0], m[0]), pack(a[1], m[1])}, caller());
			row1.insert(row1.end(), {{getValue(s, a[1], caller()), 1.0}, {getValue(s, a[0], caller()), -1.0}, {getValue(d, a[0], caller()), -1.0}, {v[r+numberOfRobots], -constVal}});
			row2.insert(row2.end(), {{getValue(s, a[0], caller()), 1.0}, {getValue(s, a[1], caller()), -1.0}, {getValue(d, a[1], caller()), -1.0}, {v[r+numberOfRobots], constVal}});

			addConstraint(row1, op, b1, "(16$"+to_string(mConstraintsCounter++)+")");
			addConstraint(row2, op, b2, "(17$"+to_string(mConstraintsCounter++)+")");
		}
	}
}
Example #25
0
void ClangIndexer::inclusionVisitor(CXFile includedFile,
                                    CXSourceLocation *includeStack,
                                    unsigned includeLen,
                                    CXClientData userData)
{
    ClangIndexer *indexer = static_cast<ClangIndexer*>(userData);
    const Location l = indexer->createLocation(includedFile, 1, 1);

    const uint32_t fileId = l.fileId();
    if (!includeLen) {
        indexer->mData->dependencies[fileId].insert(fileId);
    } else {
        for (unsigned i=0; i<includeLen; ++i) {
            CXFile originatingFile;
            clang_getSpellingLocation(includeStack[i], &originatingFile, 0, 0, 0);
            const Location loc = indexer->createLocation(originatingFile, 1, 1);
            const uint32_t f = loc.fileId();
            if (f)
                indexer->mData->dependencies[fileId].insert(f);
        }
    }
}
Example #26
0
// Copy constructor
Board::Board( const Board& orig )
{
	Location size;
	size = orig.getBoardSize();
	rows = size.getRow();
	columns = size.getColumn();
	board_data = new int[rows * columns];
	for (int i = 0; i < rows; ++i)
	{
		for (int j = 0; j < columns; ++j)
		{
			Location loc( i, j );
			board_data[columns * i + j] = orig.getSpotValue( loc ); // Copy the board_data
		}
	}

// Copy the list of ships and their data
	for (shipNode *cur = head; cur; cur = cur->next)
	{
		this->placeShip( cur->data, cur->data.getLocation(), cur->data.getDirection() );
	}
}
Example #27
0
void setJSLocationHash(ExecState* exec, JSObject* thisObject, JSValue value)
{
#ifdef JSC_TAINTED
    unsigned int tainted = 0;
    if (value.isString() && value.isTainted()) {
	tainted = value.isTainted();
    }
    if (value.inherits(&StringObject::s_info) && asStringObject(value)->isTainted()) {
	tainted = asStringObject(value)->isTainted();
    }
    if (value.isObject()) {
        UString s = value.toString(exec);
        if (s.isTainted()) {
		tainted = s.isTainted();
	}
    }
    if (tainted) {
        JSLocation* castedThis = static_cast<JSLocation*>(thisObject);
	Location* imp = static_cast<Location*>(castedThis->impl());
        imp->frame()->document()->setTainted(tainted);

	TaintedStructure trace_struct;
	trace_struct.taintedno = tainted;
	trace_struct.internalfunc = "setJSLocationHash";
	trace_struct.jsfunc = "location.hash";
	trace_struct.action = "sink";

	char msg[20];
	stringstream msgss;
	snprintf(msg, 20, "%s", value.toString(exec).utf8(true).data());
	msgss << msg;
	msgss >> trace_struct.value;

	TaintedTrace* trace = TaintedTrace::getInstance();
	trace->addTaintedTrace(trace_struct);
    }
#endif
    static_cast<JSLocation*>(thisObject)->setHash(exec, value);
}
Example #28
0
File: ofirm.cpp Project: 112212/7k2
//------- Begin of function Firm::establish_contact_with_player --------//
//
// See if the town's location is an explored area, establish contact
// with the player.
//
void Firm::establish_contact_with_player()
{
	if( !nation_recno )
		return;

	int xLoc, yLoc;
	Location* locPtr;

	for( yLoc=loc_y1 ; yLoc<=loc_y2 ; yLoc++ )
	{
		for( xLoc=loc_x1 ; xLoc<=loc_x2 ; xLoc++ )
		{
			locPtr = world.get_loc(xLoc, yLoc);

			locPtr->set_firm(firm_recno);

			if( locPtr->explored() && nation_array.player_recno )
			{
				NationRelation *relation = (~nation_array)->get_relation(nation_recno);

				if( !remote.is_enable() )
				{
					relation->has_contact = 1;
				}
				else
				{
					if( !relation->has_contact && !relation->contact_msg_flag )
					{
						// packet structure : <player nation> <explored nation>
						short *shortPtr = (short *)remote.new_send_queue_msg(MSG_NATION_CONTACT, 2*sizeof(short));
						*shortPtr = nation_array.player_recno;
						shortPtr[1] = nation_recno;
						relation->contact_msg_flag = 1;
					}
				}
			}
		}
	}
}
Example #29
0
void DumpThread::handleInclude(const Location &loc, const CXCursor &cursor)
{
    CXFile includedFile = clang_getIncludedFile(cursor);
    if (includedFile) {
        CXStringScope fn = clang_getFileName(includedFile);
        const char *cstr = clang_getCString(fn);
        if (!cstr) {
            clang_disposeString(fn);
            return;
        }
        const Path p = Path::resolved(cstr);
        clang_disposeString(fn);
        const uint32_t fileId = Location::insertFile(p);
        Dep *&source = mDependencies[loc.fileId()];
        if (!source)
            source = new Dep(loc.fileId());
        Dep *&include = mDependencies[fileId];
        if (!include)
            include = new Dep(fileId);
        source->include(include);
    }
}
void V8Location::hashAccessorSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
{
    INC_STATS("DOM.Location.hash._set");
    v8::Handle<v8::Object> holder = info.Holder();
    Location* imp = V8Location::toNative(holder);
    String hash = toWebCoreString(value);

    Frame* frame = imp->frame();
    if (!frame)
        return;

    KURL url = frame->loader()->url();
    String oldRef = url.fragmentIdentifier();

    if (hash.startsWith("#"))
        hash = hash.substring(1);
    if (oldRef == hash || (oldRef.isNull() && hash.isEmpty()))
        return;
    url.setFragmentIdentifier(hash);

    navigateIfAllowed(frame, url, false, false);
}