bool bSkeleton::relierVille(float gamma)
{
    routes.clear();
    if(gamma > 0)
        routes.reserve(villes.size()/gamma);

    //#pragma omp parallel for schedule(dynamic,1)
    for(unsigned int i=0; i<villes.size(); i++){
        const Vector3D& a = villes[i]->getPosition();

        for(unsigned int j=i+1; j<villes.size(); j++){
            const Vector3D& b = villes[j]->getPosition();
            float distAB = powf(distance(a, b), gamma);

            unsigned int k;
            for(k = 0; k<villes.size(); k++){
                if(k!=i && k!=j){
                    const Vector3D& p = villes[k]->getPosition();
                    float distAP = powf(distance(a, p), gamma);
                    if(distAB < distAP) //si la distance de AB* est déjà plus grande que la distance AP*,
                        continue;       // pas besoin de calculer la distance BP* qui peut être lourd en temps de calcul selon la méthode utilisé.
                    else if(distAB > distAP + powf(distance(b, p), gamma))  //si la distance AB* est supérieur à la somme des deux autres
                        break;          //la route n'ai pas insérer dans le B-squelette.
                }
            }
            if(k == villes.size())  //si aucun somme de routes n'a une plus petit distance* que celle de AB
                routes.push_back(Route(villes[i], villes[j]));
        }
    }
    return true;
}
bool bSkeleton::relierVilleHauteur2(float gamma, const Terrain& terrain){
    routes.clear();

    for(unsigned int i=0; i<villes.size(); i++){
        const Vector3D& a = villes[i]->getPosition();

        for(unsigned int j=i+1; j<villes.size(); j++){
            const Vector3D& b = villes[j]->getPosition();
            double distAB = pow(coutConstruction(a, b, terrain), gamma);

            unsigned int k;
            for(k=0; k<villes.size(); k++){
                if(k!=i && k!=j){
                    const Vector3D& p = villes[k]->getPosition();
                    double distAP = pow(coutConstruction(a, p, terrain), gamma);
                    if(distAB < distAP)
                        continue;
                    else if(distAB > distAP + pow(coutConstruction(b, p, terrain), gamma))
                        break;
                }
            }
            if(k == villes.size())
                routes.push_back(Route(villes[i], villes[j]));
        }
    }
    return true;
}
Exemple #3
0
Route RailSystem::getCheapestRoute(const string &from, const string &to) {
    assert(is_valid_city(from));
    assert(is_valid_city(to));
    reset();
    pair<int, int> p = calc_route(from, to);
    return Route(from, to, p.first, p.second);
}
bool bSkeleton::relierVille(const Terrain& terrain, float gamma)
{
    routes.clear();
    if(gamma > 0)
        routes.reserve(villes.size()/gamma);

    //#pragma omp parallel for schedule(dynamic,1)
    for(unsigned int i=0; i<villes.size(); i++){
        const Vector3D& a = villes[i]->getPosition();

        for(unsigned int j=i+1; j<villes.size(); j++){
            const Vector3D& b = villes[j]->getPosition();
            double distAB = pow(terrain.distance(a, b), gamma);

            unsigned int k;
            for(k = 0; k<villes.size(); k++){
                if(k!=i && k!=j){
                    const Vector3D& p = villes[k]->getPosition();
                    double distAP = pow(terrain.distance(a, p), gamma);
                    if(distAB < distAP)
                        continue;
                    else if(distAB > distAP + pow(terrain.distance(b, p), gamma))
                        break;

                }
            }
            if(k == villes.size())
                routes.push_back(Route(villes[i], villes[j]));
        }
    }
    return true;
}
Exemple #5
0
void RoutingModel::clear()
{
    d->m_route = Route();
    beginResetModel();
    endResetModel();
    emit currentRouteChanged();
}
void Individual::splitExtractWithoutVehicleLimit(vector<int>& P) {

    int n = this->getGene().size();

    int p = 0, t = 0, j = n, i, k, id = 0;

    // Depot
    //--trip.push_back(ROUTE_DELIM);
    p++;

    // Repeat
    do {

        t++;
        i = P.at(j);

        Route route = Route(this->getProblem(), this->getConfig(), this->getDepot(), id);
        id++;

        for (k = i; k < j; ++k) {
            //--trip.push_back(route.at(k));
            route.getTour().push_back(this->getGene().at(k));
        }

        route.calculateCost();
        this->getRoutes().push_back(route);

        // Depot
        //--trip.push_back(ROUTE_DELIM);
        j = i;

    } while (i > 0);

}
Exemple #7
0
int main(int argc, const char * argv[])
{
    List *cmnds = NULL;
    char *string = NULL;
    int quit = 0;
    
    ErrorCode errorCode = ERRORCODE_NO_ERROR, endOfFile = ERRORCODE_NO_ERROR;
    
    CATCH_ERROR(InitInput(&string), errHandler); // allocating input string
    MEM(string, initialError); // checking if allocation was successful, otherwise quiting
    
    while (endOfFile == ERRORCODE_NO_ERROR && quit != 1) // ends on <quit> command
    {
        ReleaseList(&cmnds); // releasing list of tokens
        endOfFile = ReadStringFromStream(stdin, &string); // reading string of unknown length
        CATCH_ERROR(Tokenize(string, &cmnds), errHandler); // creating a list of tokens from input string
        CATCH_ERROR(Route(cmnds, &quit), errHandler); // trying to find a matching method
        
        errHandler:
            PrintErrorFeedback(errorCode); // on error printing feedback info and continuing main loop
    }
    
    ReleaseList(&cmnds); // after escaping while
    ReleaseInput(string);
    
    return 0;
    
    initialError:
        return 1;
}
Exemple #8
0
/**
 * Apply the routing and send out the packet.
*/
int RouteAndSend(int PacketSlot)
{
	PacketRec*	p;

	DEBUGPATH;

#ifdef DEBUG
	printf("Routing the packet\n");
#endif

	p=&Globals.Packets[PacketSlot];

	/*No routing Protocols*/
	if (Globals.NumRoutes==0)
		return TRUE;

	/*dropped by rules*/
	if (!p->PassRawPacket){
		ReturnEmptyPacket(PacketSlot);
		return TRUE;
	}

	p->TargetInterface=-1;

#ifdef DEBUG1
	if (p->InterfaceNum==2)
	printf("Routing %02X:%02X:%02X:%02X:%02X:%02X->%02X:%02X:%02X:%02X:%02X:%02X\n",
		p->RawPacket[6],
		p->RawPacket[7],
		p->RawPacket[8],
		p->RawPacket[9],
		p->RawPacket[10],
		p->RawPacket[11],
		p->RawPacket[0],
		p->RawPacket[1],
		p->RawPacket[2],
		p->RawPacket[3],
		p->RawPacket[4],
		p->RawPacket[5]);
#endif

	if (!Route(PacketSlot)){
#ifdef DEBUG
		printf("Routing rules dropped the packet\n");
#endif
		ReturnEmptyPacket(PacketSlot);
		return FALSE;
	}

	if (p->TargetInterface==-1){
#ifdef DEBUG
		printf("No Packet Handler set a route. Dropping.\n");
#endif
		ReturnEmptyPacket(PacketSlot);
		return FALSE;
	}

	return SchedulePacket(PacketSlot);
}
Exemple #9
0
FceApplication::FceApplication() {
	m_port = 2000;
	m_socket = 0;
	decisionTaken = false;
	notificationSent = false;
	isCheater = false;
	flow = 1250;
	isVanet = IS_VANET;
	strategy = HYBRID_ROUTING;
	cheatersRatio = 0.05;

//	scenario.setDecisionEdges(CommonHelper::split("main_1b"));
//	scenario.setNotificationEdges(CommonHelper::split("main_2d bypass_2b"));
//	map<string, Route> alternativeRoutes = map<string, Route>();
//	alternativeRoutes["main"] = Route("main", "main_1 main_1b main_2 main_2a main_2b main_2c main_2d");
//	alternativeRoutes["main"].setCapacity(900);
//	alternativeRoutes["bypass"] = Route("bypass", "main_1 main_1b bypass_1 bypass_2 bypass_2b");
//	alternativeRoutes["bypass"].setCapacity(1500);
//	scenario.setAlternativeRoutes(alternativeRoutes);

	scenario.setDecisionEdges(CommonHelper::split("pre_2"));
	scenario.setNotificationEdges(CommonHelper::split("main_6 bypass_3"));
	map<string, Route> alternativeRoutes = map<string, Route>();
//	alternativeRoutes["main"] = Route("main", "pre_1 pre_2 main_1 main_2 main_3 main_4 main_5 main_6");
	alternativeRoutes["main"] = Route("main", "pre_1 pre_2 main_1 main_2a main_2b main_3a main_3b main_4a main_4b main_5a main_5b main_6");
	alternativeRoutes["main"].setCapacity(900);
	alternativeRoutes["bypass"] = Route("bypass", "pre_1 pre_2 bypass_1 bypass_2 bypass_3");
	alternativeRoutes["bypass"].setCapacity(1500);
	scenario.setAlternativeRoutes(alternativeRoutes);

//	scenario.setDecisionEdges(CommonHelper::split("56640729#5"));
//	scenario.setNotificationEdges(CommonHelper::split("53349130#1"));
//	map<string, Route> alternativeRoutes = map<string, Route>();
//	alternativeRoutes["kennedy"] = Route("kennedy", "56640729#0 56640729#1 56640729#2 56640729#3 56640729#4 56640729#5 56640728#0 56640728#1 56640728#2 56640728#3 56640728#4 56640728#5 56640728#6 56640728#7 56640728#8 55444662 23595095#0 23595095#1 53349130#0 53349130#1");
//	alternativeRoutes["kennedy"].setCapacity(1300);
//	alternativeRoutes["adenauer"] = Route("adenauer", "56640729#0 56640729#1 56640729#2 56640729#3 56640729#4 56640729#5 56640724#0 56640724#1 56640724#2 56640724#3 56640724#4 48977754#0 48977754#1 48977754#2 48977754#3 48977754#4 48977754#5 95511865#0 95511865#1 126603964 -149693909#2 -149693909#1 -149693909#0 -149693907 49248917#0 49248917#1 149693908 126603969 53349130#0 53349130#1");
//	alternativeRoutes["adenauer"].setCapacity(600);
//	alternativeRoutes["thuengen"] = Route("thuengen", "56640729#0 56640729#1 56640729#2 56640729#3 56640729#5 95511899 95511885#0 95511885#1 95511885#2 95511885#3 95511885#4 95511885#5 -50649897 -37847306#1 56640728#8 55444662 23595095#0 23595095#1 53349130#0 53349130#1");
//	alternativeRoutes["thuengen"].setCapacity(800);
//	scenario.setAlternativeRoutes(alternativeRoutes);
}
Exemple #10
0
bool RoutingModel::setCurrentRoute( GeoDataDocument* document )
{
    d->m_route = Route();
    QVector<RouteSegment> segments;
    RouteSegment outline;

    QVector<GeoDataFolder*> folders = document->folderList();
    foreach( const GeoDataFolder *folder, folders ) {
        foreach( const GeoDataPlacemark *placemark, folder->placemarkList() ) {
            d->importPlacemark( outline, segments, placemark );
        }
    }
			static Route find_route(int** map, int sx, int sy, int ex, int ey) {
				if (sx > ex || sy > ey)
					return Route();

				if (map[sx][sy] == 1) // blocked.
					return Route();	// cannot enter here.

				if ((sx == ex && sy + 1 == ex) ||
					(sx + 1 == ex && sy == ex)) {
					Route ret;
					ret.emplace_back(std::make_pair(ex, ey));
					return ret;
				}

				auto route = find_route(map, sx + 1, sy, ex, ey);
				if (route.size() > 0) {
					return route;
				} else {
					auto route2 = find_route(map, sx, sy + 1, ex, ey);
					return route;
				}
			}
Exemple #12
0
std::shared_ptr<T> DNP3Channel::AddStack(const LinkConfig& link, const std::shared_ptr<T>& stack)
{

	auto create = [stack, route = Route(link.RemoteAddr, link.LocalAddr), self = this->shared_from_this()]()
	{

		auto add = [stack, route, self]() -> bool
		{
			return self->iohandler->AddContext(stack, route);
		};

		return self->executor->ReturnFrom<bool>(add) ? stack : nullptr;
	};

	return this->resources->Bind<T>(create);
}
void Individual::splitExtractVehicleLimited(vector<int>& P) {

    int n = this->getGene().size();

    int p = 0, t = 0, j = n, i, k, id = 0;

    // Depot
    //--trip.push_back(ROUTE_DELIM);
    p++;

    // Repeat
    do {

        t++;
        i = P.at(j);

        // If the number of routes is less than the number of vehicles
        if (id < this->getProblem()->getVehicles()) {

            Route route = Route(this->getProblem(), this->getConfig(), this->getDepot(), id);
            id++;

            for (k = i; k < j; ++k) {
                //--trip.push_back(route.at(k));
                route.getTour().push_back(this->getGene().at(k));
            }

            route.calculateCost();
            this->getRoutes().push_back(route);

        } else {
            // Put in the last route
            for (k = i; k < j; ++k)
                this->getRoutes().at(this->getProblem()->getVehicles() - 1).addAtBack(this->getGene().at(k));
        }

        // Depot
        //--trip.push_back(ROUTE_DELIM);
        j = i;

    } while (i > 0);
}
Exemple #14
0
void
RibEntry::wireDecode(const Block& wire)
{
  m_prefix.clear();
  m_routes.clear();

  m_wire = wire;

  if (m_wire.type() != tlv::nfd::RibEntry) {
    std::stringstream error;
    error << "Expected RibEntry Block, but Block is of a different type: #"
          << m_wire.type();
    throw Error(error.str());
  }

  m_wire.parse();

  Block::element_const_iterator val = m_wire.elements_begin();

  if (val != m_wire.elements_end() && val->type() == tlv::Name) {
    m_prefix.wireDecode(*val);
    ++val;
  }
  else {
    throw Error("Missing required Name field");
  }

  for (; val != m_wire.elements_end(); ++val) {

    if (val->type() == tlv::nfd::Route) {
      m_routes.push_back(Route(*val));
    }
    else {
      std::stringstream error;
      error << "Expected Route Block, but Block is of a different type: #"
            << m_wire.type();
      throw Error(error.str());
    }
  }
}
Exemple #15
0
		void calcRoutes_4(int lookAheadCount)
		{
			//route, length
			std::queue<std::tuple<Route, int>> que;
			que.emplace(Route(), 0);

			for (int i = 0; i < LookAheadMax; i++)
			{
				_routes[i].clear();
			}

			//bfsでルートを全列挙
			while (!que.empty())
			{
				auto tup = que.front(); que.pop();
				int length = std::get<1>(tup);
				Route route = std::get<0>(tup);

				_routes[length].push_back(route);

				//debug(route);

				if (length == lookAheadCount)
				{
					continue;
				}

				int pre = route.top();
				for (int i = 0; i < 4; i++)
				{
					if ((i + 2) % 4 == pre) continue;//行って戻るのは禁止

					Route nextRoute = route;
					nextRoute.push_back(i);
					que.emplace(nextRoute, length + 1);

				}
			}
		}
Exemple #16
0
void AudioPortConfig::routingChanged()
{
    //---------------------------------------------------
    //  populate lists
    //---------------------------------------------------

    routeList->clear();
    newSrcList->clear();
    newDstList->clear();
    tracksList->clear();
    btnConnectOut->setEnabled(false);
    connectButton->setEnabled(false);
    removeButton->setEnabled(false);

    TrackList* tl = song->tracks();
    for (ciTrack i = tl->begin(); i != tl->end(); ++i)
    {
        if ((*i)->isMidiTrack())
            continue;
        AudioTrack* track = (AudioTrack*) (*i);
        if (track->type() == Track::WAVE_OUTPUT_HELPER || track->type() == Track::WAVE_INPUT_HELPER)
        {
            for (int channel = 0; channel < track->channels(); ++channel)
            {
                Route r(track, channel);
                tracksList->addItem(r.name());
            }
        }
        else
            tracksList->addItem(Route(track, -1).name());
    }
    if(selectedIndex < tracksList->count())
        tracksList->setCurrentRow(selectedIndex, QItemSelectionModel::ClearAndSelect);
    //if(_selected)
    //	setSelected(_selected->name());
}
Exemple #17
0
Route
RouteParser::createRoute(stringref str)
{
    Route ret;
    for (size_t from = 0, at = 0, depth = 0; at <= str.size(); ++at) {
        if (at == str.size() || (depth == 0 && isWhitespace(str[at]))) {
            if (from < at - 1) {
                Hop hop = createHop(str.substr(from, at - from));
                if (hop.hasDirectives() &&
                    hop.getDirective(0)->getType() == IHopDirective::TYPE_ERROR)
                {
                    return std::move(Route().addHop(std::move(hop)));
                }
                ret.addHop(std::move(hop));
            }
            from = at + 1;
        } else if (str[at] == '[') {
            ++depth;
        } else if (str[at] == ']') {
            --depth;
        }
    }
    return ret;
}
void AIRayPathFinderStrategy::Step(unsigned timeMs)
{
	//if (!Inited)
	//	Init();	
	//Ogre::SceneNode *Node = Parent->GetNode();
	// определить вектор на цель и двигаться по нему с

	ClosestObj = NULL;
	
    // заданной скоростью.

    IPhysical *phys = Parent->GetPhysical();
    assert(phys);

	//if (phys->IsCollided())
	//{		
 //       //int diff=timeMs-StartFreeFlyingTime;
 //       StartFreeFlyingTime+=timeMs;
 //       if (StartFreeFlyingTime>FREE_FLY_TOUT || phys->GetRotVelocity().isZeroLength()) 
 //       {
 //           StartFreeFlyingTime=0;
 //           phys->SetCollided(false);                
 //       }
	//}

	/* 
	если преграда - статический объект, то облетаем и движемся по ВП
	если преграда - целевой объект, то его не облетаем
	если преграда - динамический объект, то облетаем, но не дожидаемся достижения ВП
	*/
	Vector3 point;
	static Vector3 prev_forward_direction(0,0,0);

    AIPathFinderStrategy::Step(timeMs);

	if (TargetType != TT_NONE) 
	{	
		if (HaveCashedTarget)
		{
			point = CashedTargetPoint;
			Vector3 dist = point-Parent->GetScenable()->GetPosition();
			//if (dist.squaredLength()>100.f*100.f)
            if (!IsTargetReached(CashedTargetPoint))
			{                
                LastChangingDirectionTime+=timeMs;
				if (ClosestObj && ClosestObj->GetScenable()->GetType()==PT_DYNAMIC && LastChangingDirectionTime>CHANGE_DIRECTION_TOUT) 
				{   
                    LastChangingDirectionTime = 0;
					HaveCashedTarget = false;
					point = RouteToTarget();					
				} else
					Route(point);
			}
			else
			{
				HaveCashedTarget = false;
				point = RouteToTarget();
			}
		} else
		{
			point = RouteToTarget();
		}
		if (LastTargetPoint!=point)
		{
			LastChangingDirectionTime = 0;
			LastTargetPoint = point;
		}
	}	
}
Vector3 AIRayPathFinderStrategy::RouteToTarget()
{
    Ogre::Vector3 point;
	//if (TargetType == TT_OBJECT) {
	//	//assert(TargetID);
	//	Ogre::Vector3 parent_pos = Parent->GetPosition();

	//	if (TargetID<0)
	//	{
	//		assert(false);
	//		TargetPoint = parent_pos;
	//	}
	//	
	//	if (TargetID==0)
	//	{
	//		if (Owner)
	//		{
	//			TargetID = Owner->SelectTargetID();			
	//		}
	//		if (TargetID<=0)
	//		{
	//			//assert(false);
	//			TargetPoint = parent_pos;
	//		}
	//	}
 //       
	//	IAAObject *obj = CommonDeclarations::GetIDObject(TargetID);
	//	//assert(obj);
	//	if (obj)
	//	{
	//		Ogre::Vector3 target_pos = obj->GetPosition();
	//		if (DistanceToTarget>0)
	//			TargetPoint = target_pos + (parent_pos-target_pos).normalisedCopy()*DistanceToTarget;
	//		else
	//			TargetPoint=target_pos;
	//	} else
	//	{
	//		//if (--WaitTargetTimeout<0)
	//		//	CommonDeclarations::DeleteObjectRequest(Parent);
	//		TargetPoint = parent_pos;
	//		//CommonDeclarations::DeleteObjectRequest(Parent);
	//	}
	//}/* else
	//if (TargetType == TT_OBJECT)
	//{
	//	point = TargetPoint;
	//}*/
    
	point = TargetPoint;
	Vector3 dist = point-Parent->GetPosition();
	if (dist.squaredLength()>10.f*10.f)
		Route(point);
	else
	{
		if (TargetType==TT_POINT)
		{
			TargetType = TT_NONE;	
			State = FST_POINTREACHED;
		}		
		Parent->GetPhysical()->SetThrottle(Vector3(0,0,0));		
		Parent->GetPhysical()->SetForces(Ogre::Vector3::ZERO);
		//Parent->SetVelocityVector(Vector3(0,0,0));
	}
	return point;
}
Exemple #20
0
int main (void)
{
  xmlTextReaderPtr xml = xmlReaderForFd (STDIN_FILENO, "", NULL, 0);
  FILE *file = fopen ("gosmore.pak", "r");
  if (!xml || !file || fseek (file, 0, SEEK_END) != 0 ||
        !GosmInit (mmap (NULL, ftell (file), PROT_READ, MAP_SHARED,
                              fileno (file), 0), ftell (file))) {
    fprintf (stderr, "Unable to open gosmore.pak\n");
    return 1;
  }
                              
  
  int ptCnt = 0;
  printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  "<gpx\n"
  " version=\"1.0\"\n"
  " creator=\"osmunda\"\n"
  " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  " xmlns=\"http://www.topografix.com/GPX/1/0\"\n"
  " xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/\">\n");
  while (xmlTextReaderRead (xml)) {
    char *name = (char *) BAD_CAST xmlTextReaderName (xml);
    if (xmlTextReaderNodeType (xml) == XML_READER_TYPE_ELEMENT) {
      while (stricmp (name, "trkpt") == 0 &&
             xmlTextReaderMoveToNextAttribute (xml)) {
        char *aname = (char *) BAD_CAST xmlTextReaderName (xml);
        char *avalue = (char *) BAD_CAST xmlTextReaderValue (xml);
        if (stricmp (aname, "lat") == 0) tlat = Latitude (atof (avalue));
        if (stricmp (aname, "lon") == 0) tlon = Longitude (atof (avalue));
        xmlFree (aname);
        xmlFree (avalue);
      }
    }
    if (xmlTextReaderNodeType (xml) == XML_READER_TYPE_END_ELEMENT) {
      if (stricmp (name, "trkpt") == 0) {
        if (ptCnt++ > 0) {
          int vehicle[] = { bicycleR, motorcarR, footR }, i;
          for (i = 0; i < sizeof (vehicle) / sizeof (vehicle[0]); i++) {
            Route (TRUE, 0, 0, /*tlon - flon, tlat - flat,*/ bicycleR, 0);
            //routeNode *itr;
            //for (itr = shortest; itr->shortest; itr = itr->shortest) {}
            if (routeHeapSize > 0 && (!shortest || !shortest->shortest ||
                !shortest->shortest->shortest)) break;
          }
          if (i == sizeof (vehicle) / sizeof (vehicle[0])) {
//                fprintf (stderr, "%d\n", shortest->best);
            printf ("<trk>\n<trkseg>\n<trkpt lat=\"%.5lf\" "
              "lon=\"%.5lf\"/>\n<trkpt lat=\"%.5lf\" lon=\"%.5lf\"/>\n"
              "</trkseg>\n</trk>\n", LatInverse (flat), LonInverse (flon),
              LatInverse (tlat), LonInverse (tlon));
          }
        }
        flat = tlat;
        flon = tlon;
      }
      if (stricmp (name, "trk") == 0) ptCnt = 0; // Gap in track
    }
    xmlFree (name);
  }
  printf ("</gpx>\n");
  return 0;
}
bool LocalSearch::operateMoveDepotRouteM9(Route& ru, Route& rv, bool equal) {

    bool result = false;
    bool process = false;
    bool stop = false;

    if (equal)
        return result;

    if (ru.getTour().size() < 2)
        return result;

    if (rv.getTour().size() < 2)
        return result;

    for (auto iterRU = ru.getTour().begin(); iterRU != ru.getTour().end(); ++iterRU) {

        auto iterRX = next(iterRU);

        if (iterRX == ru.getTour().end())
            break;

        for (auto iterRV = rv.getTour().begin(); iterRV != rv.getTour().end(); ++iterRV) {

            auto iterRY = next(iterRV);

            if (iterRY == rv.getTour().end())
                break;

            Route newRU = Route(ru.getProblem(), ru.getConfig(), ru.getDepot(), ru.getId());
            Route newRV = Route(rv.getProblem(), rv.getConfig(), rv.getDepot(), rv.getId());

            // Stop at first penalty -----
            stop = false;

            //U: From D->U
            for (auto ite = ru.getTour().begin(); ite != iterRX; ++ite) {
                newRU.addAtBack((*ite));

                if (newRU.isPenalized()) {
                    stop = true;
                    break;
                }

            }

            if (stop)
                continue;

            //U: From Y->D
            for (auto ite = iterRY; ite != rv.getTour().end(); ++ite) {
                newRU.addAtBack((*ite));

                if (newRU.isPenalized()) {
                    stop = true;
                    break;
                }

            }

            if (stop)
                continue;

            //OLD: V: From D->X
            //for (auto ite = prev(ru.getTour().end()); ite != iterRU; --ite) {

            //V: From X->D
            for (auto ite = iterRX; ite != ru.getTour().end(); ++ite) {
                newRV.addAtBack((*ite));

                if (newRV.isPenalized()) {
                    stop = true;
                    break;
                }

            }

            if (stop)
                continue;

            //V: From V->D
            auto ite = iterRV;
            process = true;

            while (process) {

                if (ite == rv.getTour().begin())
                    process = false;

                newRV.addAtBack((*ite));

                if (newRV.isPenalized()) {
                    stop = true;
                    break;
                }

                if (ite != rv.getTour().begin())
                    --ite;
            }

            if (stop)
                continue;

            //cout << "U = " << (*iterRU) << " - X = " << (*iterRX);
            //cout << " / V = " << (*iterRV) << " - Y = " << (*iterRY);
            //cout << endl;

            //newRU.printSolution();
            //newRV.printSolution();

            if (Util::isBetterSolution(newRU.getTotalCost() + newRV.getTotalCost(), ru.getTotalCost() + rv.getTotalCost())) {
                ru = newRU;
                rv = newRV;
                result = true;
                break;
            }

            if (ru.getProblem()->getMonitor().isTerminated())
                break;

        }

        if (result)
            break;

        if (ru.getProblem()->getMonitor().isTerminated())
            break;

    }

    return result;
}
void MessageSwitch::AddRoute(unsigned int begin, unsigned int end, BufferedTransformation &destination, const std::string &channel)
{
	RangeRoute route(begin, end, Route(&destination, channel));
	RouteList::iterator it = upper_bound(m_routes.begin(), m_routes.end(), route);
	m_routes.insert(it, route);
}
Exemple #23
0
QString MidiJackDevice::open()
{
    _openFlags &= _rwFlags; // restrict to available bits

#ifdef JACK_MIDI_DEBUG
    printf("MidiJackDevice::open %s\n", name().toLatin1().constData());
#endif

    QString s;
    if (_openFlags & 1)
    {
        if (!_out_client_jackport)
        {
            if(audioDevice)
            {
                if (audioDevice->deviceType() == AudioDevice::JACK_AUDIO)
                {
                    s = name() + QString(JACK_MIDI_OUT_PORT_SUFFIX);
                    _out_client_jackport = (jack_port_t*) audioDevice->registerOutPort(s.toLatin1().constData());
                    if (!_out_client_jackport)
                    {
                        fprintf(stderr, "LOS: MidiJackDevice::open failed creating output port name %s\n", s.toLatin1().constData());
                        _openFlags &= ~1; // Remove the flag, but continue on...
                    }
                }
            }
        }
    }
    else
    {
        if (_out_client_jackport)
        {
            audio->msgRemoveRoutes(Route(this, 0), Route()); // New function msgRemoveRoutes simply uses Routes, for their pointers.
            audioDevice->unregisterPort(_out_client_jackport);
        }
        _out_client_jackport = NULL;
    }

    if (_openFlags & 2)
    {
        if (!_in_client_jackport)
        {
            if (audioDevice->deviceType() == AudioDevice::JACK_AUDIO)
            {
                s = name() + QString(JACK_MIDI_IN_PORT_SUFFIX);
                _in_client_jackport = (jack_port_t*) audioDevice->registerInPort(s.toLatin1().constData());
                if (!_in_client_jackport)
                {
                    fprintf(stderr, "LOS: MidiJackDevice::open failed creating input port name %s\n", s.toLatin1().constData());
                    _openFlags &= ~2; // Remove the flag, but continue on...
                }
            }
        }
    }
    else
    {
        if (_in_client_jackport)
        {
            audio->msgRemoveRoutes(Route(), Route(this, 0));
            audioDevice->unregisterPort(_in_client_jackport);
        }
        _in_client_jackport = NULL;
    }

    _writeEnable = bool(_openFlags & 1);
    _readEnable = bool(_openFlags & 2);

    return QString("OK");
}
	//---------
	Route RouteFind::solve(const Problem & problem) {
		this->bestSolution.cost = std::numeric_limits<float>::infinity();
		this->step(problem, Route(vector<int>(1, this->start), 0.0f) );
		return bestSolution;
	}
Exemple #25
0
Route name2route(const QString& rn, bool /*dst*/, int rtype)/*{{{*/
{
	// printf("name2route %s\n", rn.toLatin1().constData());
	int channel = -1;
	QString s(rn);
	// Support old route style in oom files. Obsolete.
	if (rn.size() >= 2 && rn[0].isNumber() && rn[1] == ':')
	{
		channel = rn[0].toAscii() - int('1');
		s = rn.mid(2);
	}

	if (rtype == -1)
	{
		if (checkAudioDevice())
		{
			void* p = audioDevice->findPort(s.toLatin1().constData());
			if (p)
				return Route(p, channel);
		}

		TrackList* tl = song->tracks();
		for (iTrack i = tl->begin(); i != tl->end(); ++i)
		{
			if ((*i)->isMidiTrack())
			{
				MidiTrack* track = (MidiTrack*) * i;
				if (track->name() == s)
					return Route(track, channel);
			}
			else
			{
				AudioTrack* track = (AudioTrack*) * i;
				if (track->name() == s)
					return Route(track, channel);
			}
		}

		for (iMidiDevice i = midiDevices.begin(); i != midiDevices.end(); ++i)
		{
			if ((*i)->name() == s)
				return Route(*i, channel);
		}

		// p3.3.49
		if (s.left(ROUTE_MIDIPORT_NAME_PREFIX.length()) == ROUTE_MIDIPORT_NAME_PREFIX)
		{
			bool ok = false;
			int port = s.mid(ROUTE_MIDIPORT_NAME_PREFIX.length()).toInt(&ok);
			if (ok)
				return Route(port, channel);
		}
	}
	else
	{
		if (rtype == Route::TRACK_ROUTE)
		{
			TrackList* tl = song->tracks();
			for (iTrack i = tl->begin(); i != tl->end(); ++i)
			{
				if ((*i)->isMidiTrack())
				{
					MidiTrack* track = (MidiTrack*) * i;
					if (track->name() == s)
						return Route(track, channel);
				}
				else
				{
					AudioTrack* track = (AudioTrack*) * i;
					if (track->name() == s)
						return Route(track, channel);
				}
			}
		}// TODO Distinguish the device types
		else if (rtype == Route::MIDI_DEVICE_ROUTE)
		{
			for (iMidiDevice i = midiDevices.begin(); i != midiDevices.end(); ++i)
			{
				if ((*i)->name() == s)
					return Route(*i, channel);
			}
		}
		else if (rtype == Route::JACK_ROUTE)
		{
			if (checkAudioDevice())
			{
				void* p = audioDevice->findPort(s.toLatin1().constData());
				if (p)
					return Route(p, channel);
			}
		}
		else if (rtype == Route::MIDI_PORT_ROUTE) // p3.3.49
		{
			if (s.left(ROUTE_MIDIPORT_NAME_PREFIX.length()) == ROUTE_MIDIPORT_NAME_PREFIX)
			{
				bool ok = false;
				int port = s.mid(ROUTE_MIDIPORT_NAME_PREFIX.length()).toInt(&ok);
				if (ok)
					return Route(port, channel);
			}
		}
	}

	printf("  name2route: <%s> not found\n", rn.toLatin1().constData());
	return Route((Track*) 0, channel);
}/*}}}*/
Exemple #26
0
void RouteMsg(tHostMsg** ppMsg)
{
  Route(*ppMsg,Normal); 
}
void MessageSwitch::AddDefaultRoute(BufferedTransformation &destination, const std::string &channel)
{
	m_defaultRoutes.push_back(Route(&destination, channel));
}
Exemple #28
0
void RouteMsgBlocking(tHostMsg** ppMsg)
{
  Route(*ppMsg,NormalWait); 
}
void ChannelSwitch::AddRoute(const std::string &inChannel, BufferedTransformation &destination, const std::string &outChannel)
{
	m_routeMap.insert(RouteMap::value_type(inChannel, Route(&destination, outChannel)));
}
Exemple #30
0
void RouteMsgFromIsr(tHostMsg** ppMsg)
{
  Route(*ppMsg,FromIsr);
}