Esempio n. 1
0
    // sets the value of the cell to [v]
    // the function also propagates constraints to other cells and deduce new values where possible
    bool set(int i, int j, int v)
    { 
        // updating state of the cell
        cell& c = cells[i][j];
        if (c.value == v)
            return true;
        if (c.constraints[v])
            return false;
        c.constraints = bitset<10>(0x3FE); // all 1s
        c.constraints.reset(v);
        c.numPossibilities = 1;
        c.value = v;

        // propagating constraints
        for (int k = 0; k<9; k++) {
            // to the row: 
            if (i != k && !updateConstraints(k, j, v))
                return false;
            // to the column:
            if (j != k && !updateConstraints(i, k, v))
                return false;
            // to the 3x3 square:
            int ix = (i / 3) * 3 + k / 3;
            int jx = (j / 3) * 3 + k % 3;
            if (ix != i && jx != j && !updateConstraints(ix, jx, v))
                return false;
        }
        return true;
    }
Esempio n. 2
0
void InfoApplet::dataUpdated( const QString& name, const Plasma::DataEngine::Data& data )
{
    Q_UNUSED( name );

    if( data.isEmpty() )
        return;

    if( m_initialized )
    {
        QString currentHtml = data[ "main_info" ].toString();
        if ( !currentHtml.isEmpty() )
        {
            QColor highlight( App::instance()->palette().highlight().color() );
            highlight.setHsvF( highlight.hueF(), 0.3, .95, highlight.alphaF() );
            currentHtml = currentHtml.replace( "{text_color}", App::instance()->palette().brush( QPalette::Text ).color().name() );
            currentHtml = currentHtml.replace( "{content_background_color}", highlight.name() );
            currentHtml = currentHtml.replace( "{background_color}", PaletteHandler::highlightColor().lighter( 150 ).name());
            currentHtml = currentHtml.replace( "{border_color}", PaletteHandler::highlightColor().lighter( 150 ).name() );
            
            m_webView->setHtml( currentHtml, KUrl( QString() ) );
        }
        else
        {
            currentHtml = s_defaultHtml;
            currentHtml = currentHtml.replace( "%%SUBJECT_NAME%%", data[ "subject_name" ].toString() );
            m_webView->setHtml( currentHtml );
        }

        m_webView->page()->setLinkDelegationPolicy( QWebPage::DelegateAllLinks );
        updateConstraints();
    }
}
Esempio n. 3
0
 void Solver::move( shared_ptr<Building>& building, int newPosition )
 {
   grid.clear( *building );
   building->setPos( newPosition );
   grid.add( *building );
   updateConstraints( vecConstraints, grid );
 }
Esempio n. 4
0
  void Solver::reset()
  {
    int xPos;
    int yPos;

    string shortName;
    //bool supplyIncluded = false;

    clearAllInGrid( vecBuildings, grid );

    for( auto b : vecBuildings )
    {
      // 1 chance over 3 to be placed on the grid
      if( randomVar.getRandNum(3) == 0)
      {
	shortName = b->getShort();
		  
	xPos = randomVar.getRandNum( grid.getNberRows() - b->getLength() );
	yPos = randomVar.getRandNum( grid.getNberCols() - b->getHeight() );
	b->setPos( grid.mat2lin( xPos, yPos ) );
	
	grid.add( *b );
      }
      else
	b->setPos( -1 );
    }

    updateConstraints( vecConstraints, grid );
  }
Esempio n. 5
0
void
Context::Applet::collapseAnimationFinished()
{
    emit sizeHintChanged( Qt::PreferredSize );
    updateConstraints();
    update();
}
Esempio n. 6
0
static void handleViewResized(void *self, WMNotification * notification)
{
	WMSplitView *sPtr = (WMSplitView *) self;

#if 0
	printf("---- (handleViewResized - 1) ----\n");
	dumpSubviews(sPtr);
#endif

	updateConstraints(sPtr);
	checkSizes(sPtr);

	if (sPtr->constrainProc || sPtr->flags.subviewsWereManuallyMoved) {
		distributeOffsetFormEnd(sPtr, _GetSplitViewSize() - getTotalSize(sPtr));
		checkPositions(sPtr);
		updateSubviewsGeom(sPtr);
	} else
		adjustSplitViewSubviews(sPtr);

	assert(checkSizes(sPtr) == 0);

#if 0
	printf("---- (handleViewResized - 2) ----\n");
	dumpSubviews(sPtr);
#endif
}
Esempio n. 7
0
void
PhotosApplet::stopped()
{
    DEBUG_BLOCK
    setHeaderText( i18n( "Photos: No Track Playing" ) );
    m_widget->clear();
    m_widget->hide();
    setBusy( false );
    setMinimumHeight( m_header->height() );
    setCollapseHeight( m_header->height() );
    setCollapseOn();
    updateConstraints();
}
Esempio n. 8
0
void
TabsApplet::updateInterface( const AppletState appletState )
{
    // return if state has not changed (except for init state)
    if( m_currentState == appletState && appletState != InitState )
        return;

    debug() << "updating interface from state " << m_currentState << " to " << appletState;
    m_currentState = appletState;
    bool collapse = false;

    switch( m_currentState )
    {
        case InitState:
        case StoppedState:
            m_reloadIcon.data()->setEnabled( false );
            m_showTabBrowser = false;
            collapse = true;
            break;
        case NoTabsState:
            m_reloadIcon.data()->setEnabled( true );
            m_showTabBrowser = false;
            collapse = true;
            break;
        case FetchingState:
            m_reloadIcon.data()->setEnabled( false );
            m_showTabBrowser = false;
            break;
        case TabState:
            m_reloadIcon.data()->setEnabled( true );
            m_showTabBrowser = true;
            break;
    }

    QGraphicsLinearLayout *lo = static_cast<QGraphicsLinearLayout*>( layout() );

    m_showTabBrowser ? lo->addItem( m_tabsView ) : lo->removeItem( m_tabsView );
    m_showTabBrowser ? m_tabsView->show() : m_tabsView->hide();

    collapse ? setCollapseOn() : setCollapseOff();

    updateConstraints();
    update();
}
Esempio n. 9
0
void Albums::init()
{
    DEBUG_BLOCK

    // Call the base implementation.
    Context::Applet::init();

    enableHeader( true );
    setHeaderText( i18n( "Recently Added Albums" ) );

    setCollapseOffHeight( -1 );
    setCollapseHeight( m_header->height() );
    setMinimumHeight( collapseHeight() );

    QAction *settingsAction = new QAction( this );
    settingsAction->setIcon( KIcon( "preferences-system" ) );
    settingsAction->setEnabled( true );
    settingsAction->setToolTip( i18n( "Settings" ) );
    addRightHeaderAction( settingsAction );
    connect( settingsAction, SIGNAL(triggered()), this, SLOT(showConfigurationInterface()) );

    QAction *filterAction = new QAction( this );
    filterAction->setIcon( KIcon( "view-filter" ) );
    filterAction->setEnabled( true );
    filterAction->setToolTip( i18n( "Filter Albums" ) );
    m_filterIcon = addLeftHeaderAction( filterAction );
    connect( filterAction, SIGNAL(triggered()), this, SLOT(showFilterBar()) );

    m_albumsView = new AlbumsView( this );
    m_albumsView->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
    if( m_rightAlignLength )
        m_albumsView->setLengthAlignment( Qt::AlignRight );

    QGraphicsLinearLayout *layout = new QGraphicsLinearLayout( Qt::Vertical );
    layout->addItem( m_header );
    layout->addItem( m_albumsView );
    setLayout( layout );

    dataEngine( "amarok-current" )->connectSource( "albums", this );
    connect( CollectionManager::instance(), SIGNAL(collectionDataChanged(Collections::Collection*)),
             this, SLOT(collectionDataChanged(Collections::Collection*)) );

    updateConstraints();
}
Esempio n. 10
0
//-----------------------------------------------------------------------------------------------
// processes the model after the reservoir simulator is run
//-----------------------------------------------------------------------------------------------
void DecoupledModel::process()
{
    // update the streams in the pipe network
    updateStreams();


    // calculating pressures in the Pipe network
    calculatePipePressures();


    // updating the constraints (this must be done after the pressure calc)
    updateConstraints();

    // updating the objective
    updateObjectiveValue();


    // updating the status of the model
    setUpToDate(true);

}
Esempio n. 11
0
void InfoApplet::init()
{
    // Call the base implementation.
    Context::Applet::init();

    dataEngine( "amarok-info" )->connectSource( "info", this );

    m_webView = new KGraphicsWebView( this );

    QPalette p = m_webView->palette();
    p.setColor( QPalette::Dark, QColor( 255, 255, 255, 0)  );
    p.setColor( QPalette::Window, QColor( 255, 255, 255, 0)  );
    m_webView->setPalette( p );

    QGraphicsLinearLayout *layout = new QGraphicsLinearLayout( Qt::Vertical, this );
    layout->addItem( m_webView );

    connect( m_webView->page(), SIGNAL(linkClicked(QUrl)), SLOT(linkClicked(QUrl)) );

    updateConstraints();
}
Esempio n. 12
0
void VRPhysics::update() {
    OSG::VRScene* scene = OSG::VRSceneManager::getCurrent();
    if (scene == 0) return;

    if (world == 0) world = scene->bltWorld();
    if (world == 0) return;

    Lock lock(mtx());
    scene->unphysicalize(vr_obj);

    if (body != 0) {
        for (auto j : joints) {
            if (j.second->btJoint != 0) {
                VRPhysicsJoint* joint = j.second;
                world->removeConstraint(joint->btJoint);
                delete joint->btJoint;
                joint->btJoint = 0;
            }
        }

        for (auto j : joints2) {
            if (j.first->joints.count(this) == 0) continue;
            VRPhysicsJoint* joint = j.first->joints[this];
            if (joint->btJoint != 0) {
                world->removeConstraint(joint->btJoint);
                delete joint->btJoint;
                joint->btJoint = 0;
            }
        }

        world->removeRigidBody(body);
        delete body;
        body = 0;
    }

    if (ghost_body != 0) {
        world->removeCollisionObject(ghost_body);
        delete ghost_body;
        ghost_body = 0;
    }

    if (shape != 0) { delete shape; shape = 0; }
    if (motionState != 0) { delete motionState; motionState = 0; }

    if (!physicalized) return;

    motionState = new btDefaultMotionState(fromVRTransform( vr_obj, scale ));

    if (physicsShape == "Box") shape = getBoxShape();
    if (physicsShape == "Sphere") shape = getSphereShape();
    if (physicsShape == "Convex") shape = getConvexShape();
    if (physicsShape == "Concave") shape = getConcaveShape();
    if (shape == 0) return;

    btVector3 inertiaVector(0,0,0);
    float _mass = mass;
    if (!dynamic) _mass = 0;

    if (_mass != 0) shape->calculateLocalInertia(_mass, inertiaVector);

    btRigidBody::btRigidBodyConstructionInfo rbInfo( _mass, motionState, shape, inertiaVector );
    if (ghost) {
        ghost_body = new btPairCachingGhostObject();
        ghost_body->setCollisionShape( shape );
        ghost_body->setUserPointer( vr_obj );
        ghost_body->setCollisionFlags( btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CF_NO_CONTACT_RESPONSE );
        world->addCollisionObject(ghost_body, collisionGroup, collisionMask);
    } else {
        body = new btRigidBody(rbInfo);
        body->setActivationState(activation_mode);
        world->addRigidBody(body, collisionGroup, collisionMask);
    }

    scene->physicalize(vr_obj);
    updateConstraints();
}
Esempio n. 13
0
void Albums::dataUpdated( const QString &name, const Plasma::DataEngine::Data &data )
{
    if( name != QLatin1String("albums") )
        return;

    Meta::AlbumList albums = data[ "albums" ].value<Meta::AlbumList>();
    Meta::TrackPtr track = data[ "currentTrack" ].value<Meta::TrackPtr>();
    QString headerText = data[ "headerText" ].toString();
    setHeaderText( headerText.isEmpty() ? i18n("Albums") : headerText );

    //Don't keep showing the albums for the artist of the last track that had album in the collection
    if( (m_currentTrack == track) && (m_albums == albums) )
        return;

    if( albums.isEmpty() )
    {
        debug() << "received albums is empty";
        setCollapseOn();
        m_albums.clear();
        m_albumsView->clear();
        return;
    }

    setCollapseOff();

    m_albums = albums;
    m_currentTrack = track;
    m_albumsView->clear();
    m_albumsView->setMode( track ? AlbumsProxyModel::SortByYear : AlbumsProxyModel::SortByCreateDate );
    QStandardItem *currentItem( 0 );

    foreach( Meta::AlbumPtr albumPtr, albums )
    {
        // do not show all tracks without an album from the collection, this takes ages
        // TODO: show all tracks from this artist that are not part of an album
        if( albumPtr->name().isEmpty() )
            continue;

        Meta::TrackList tracks = albumPtr->tracks();
        if( tracks.isEmpty() )
            continue;

        AlbumItem *albumItem = new AlbumItem();
        albumItem->setIconSize( 50 );
        albumItem->setAlbum( albumPtr );
        albumItem->setShowArtist( !m_currentTrack );

        int numberOfDiscs = 0;
        int childRow = 0;

        qStableSort( tracks.begin(), tracks.end(), Meta::Track::lessThan );

        QMultiHash< int, TrackItem* > trackItems; // hash of tracks items for each disc
        foreach( Meta::TrackPtr trackPtr, tracks )
        {
            if( numberOfDiscs < trackPtr->discNumber() )
                numberOfDiscs = trackPtr->discNumber();

            TrackItem *trackItem = new TrackItem();
            trackItem->setTrack( trackPtr );

            // bold the current track to make it more visible
            if( m_currentTrack && *m_currentTrack == *trackPtr )
            {
                currentItem = trackItem;
                trackItem->bold();
            }

            // If compilation and same artist, then highlight, but only if there's a current track
            if( m_currentTrack
                && m_currentTrack->artist() && trackPtr->artist()
                && (*m_currentTrack->artist() == *trackPtr->artist())
                && albumPtr->isCompilation() )
            {
                trackItem->italicise();
            }
            trackItems.insert( trackPtr->discNumber(), trackItem );
        }

        for( int i = 0; i <= numberOfDiscs; ++i )
        {
            QList<TrackItem*> items = trackItems.values( i );
            if( !items.isEmpty() )
            {
                const TrackItem *item = items.first();
                QStandardItem *discItem( 0 );
                if( numberOfDiscs > 1 )
                {
                    discItem = new QStandardItem( i18n("Disc %1", item->track()->discNumber()) );
                    albumItem->setChild( childRow++, discItem );
                    int discChildRow = 0;
                    foreach( TrackItem *trackItem, items )
                        discItem->setChild( discChildRow++, trackItem );
                }
                else
                {
                    foreach( TrackItem *trackItem, items )
                        albumItem->setChild( childRow++, trackItem );
                }
            }
        }
        m_albumsView->appendAlbum( albumItem );
    }

    m_albumsView->sort();
    if( currentItem )
    {
        m_albumsView->setRecursiveExpanded( currentItem, true );
        m_albumsView->scrollTo( currentItem );
    }

    updateConstraints();
}
Esempio n. 14
0
void
PhotosApplet::dataUpdated( const QString& name, const Plasma::DataEngine::Data& data ) // SLOT
{
    if( name != QLatin1String("photos") || data.isEmpty() )
        return;

    QString text;

    if( data.contains( "message" ) )
    {
        text = data["message"].toString();
        if( text.contains( QLatin1String("Fetching") ) )
        {
            debug() << "received message: Fetching";
            setHeaderText( i18n( "Photos: %1", text ) );
            setMinimumHeight( m_header->height() );
            setCollapseHeight( m_header->height() );
            setCollapseOn();
            m_widget->clear();
            m_widget->hide();
            if( canAnimate() )
                setBusy( true );
        }
        else if( text.contains( QLatin1String("stopped") ) )
        {
            debug() << "received message: stopped";
            stopped();
        }
        else
        {
            debug() << "received message:" << text;
            setHeaderText( i18n( "Photos: %1", text ) );
            m_widget->hide();
            setMinimumHeight( m_header->height() );
            setCollapseHeight( m_header->height() );
            setCollapseOn();
            setBusy( false );
        }
    }
    else if( data.contains( "data" ) )
    {
        m_widget->clear();
        m_currentArtist = text = data["artist"].toString();
        PhotosInfo::List photos = data["data"].value< PhotosInfo::List >();
        debug() << "received data for:" << text << photos.count();
        setHeaderText( i18n( "Photos: %1", text ) );
        if( photos.isEmpty() )
        {
            setBusy( false );
            setMinimumHeight( m_header->height() );
            setCollapseHeight( m_header->height() );
            setCollapseOn();
            return;
        }
        setBusy( true );
        m_widget->setPhotosInfoList( photos );
        setMinimumHeight( 220 );
        setCollapseOff();
        m_widget->show();
        layout()->invalidate();
    }
    else
    {
        setMinimumHeight( m_header->height() );
        setCollapseHeight( m_header->height() );
        setCollapseOn();
        m_widget->clear();
        m_widget->hide();
        setBusy( false );
    }
    updateConstraints();
}
Esempio n. 15
0
void MeCtNewLocomotion::play(float t, bool useTemp)
{
	if(useTemp)
		BufferRef = &tempBuffer;
	float dt = 1.0f / 60.0f;
	if (_lastTime > 0.0)
		dt = float(t - _lastTime);
	dt *= walkSpeedGain;
	_lastTime = t;
	if(_prevTime > 0.0f)
		t = _prevTime + dt;
	else
		_prevTime = 0.0f;
	_prevTime = t;
	if(startTime < 0.0)
		startTime = t;
	motionTime = fmod(t-startTime, smoothCycle->duration());
	float x, y, z, yaw, pitch, roll;		
 	character->get_world_offset(x, y, z, yaw, pitch, roll); 
 	yaw = desiredHeading;
 	float movingDist = motionSpd * dt;
 	x += movingDist * sin(yaw * (float)M_PI / 180.0f);
 	z += movingDist * cos(yaw * (float)M_PI / 180.0f);

	gwiz::quat_t q = gwiz::euler_t(pitch,yaw,roll);
	SrQuat woQuat = SrQuat(q.wf() ,q.xf(),q.yf(),q.zf());
	SrVec woPos = SrVec(x,y,z); 		
	//*/
	std::vector<SrQuat> tempQuatList(ik_scenario.ikTreeNodes.size()); 
	if (fabs(LeftFading.prev_time + RightFading.prev_time + 2.0f) <0.001f ) // first start
	{					
		updateChannelBuffer(*BufferRef, motionTime);//Read from skeleton->Write on Buffer
		updateWorldOffset(*BufferRef, woQuat, woPos);
		updateChannelBuffer(*BufferRef,tempQuatList, true);//Read from Buffer->Write on tempQuatList
		
		ik_scenario.setTreeNodeQuat(tempQuatList,QUAT_INIT);
		ik_scenario.setTreeNodeQuat(tempQuatList,QUAT_PREVREF);
		ik_scenario.setTreeNodeQuat(tempQuatList,QUAT_CUR);
	}

	LeftFading.updateDt(t);
	RightFading.updateDt(t);

	updateChannelBuffer(*BufferRef, motionTime);//Read from skeleton->Write on Buffer
	updateWorldOffset(*BufferRef, woQuat, woPos);
	updateChannelBuffer(*BufferRef,tempQuatList, true);//Read from Buffer->Write on tempQuatList

	updateConstraints(motionTime/(float)smoothCycle->getFrameRate());
		
	ik_scenario.setTreeNodeQuat(tempQuatList,QUAT_REF);	
	character->getSkeleton()->update_global_matrices();
	ik_scenario.ikGlobalMat = character->getSkeleton()->getJointByName(hipjoint)->gmat();
	
	for (int i=0;i<3;i++)
		ik_scenario.ikTreeRootPos[i] = character->getSkeleton()->getJointByName(hipjoint)->pos()->value(i);
	//*/Character pose
	ik.setDt(LeftFading.dt);
	if (LeftFading.fadeMode == Fading::FADING_MODE_IN)
		useIKLf = true;
	if (RightFading.fadeMode == Fading::FADING_MODE_IN)
		useIKRt = true;
	if (LeftFading.updateFading(LeftFading.dt))
		useIKLf = false;
	if( RightFading.updateFading(RightFading.dt))
		useIKRt = false;

	if(useIKLf && _analysis && LeftFading.fadeMode == Fading::FADING_MODE_OFF)
	{
		errorSum += max(legDistance(1), 0.0f);
	}
	if(useIKRt && _analysis && RightFading.fadeMode == Fading::FADING_MODE_OFF)
	{
		errorSum += max(legDistance(0), 0.0f);
	}
	//*/Left
	ik_scenario.ikPosEffectors = &posConsLf;
	ik_scenario.ikRotEffectors = &rotConsLf;
	ik.update(&ik_scenario);
	ik_scenario.copyTreeNodeQuat(QUAT_CUR,QUAT_INIT);			
	for (unsigned int i = 0; i < ik_scenario.ikTreeNodes.size(); i++)
	{
		MeCtIKTreeNode* node = ik_scenario.ikTreeNodes[i];
		SrQuat qEval = node->getQuat(QUAT_CUR);
		SrQuat qInit = node->getQuat(QUAT_REF);
		qEval.normalize();
		qInit.normalize();
		char a=node->getNodeName().c_str()[0];
		if(a!='l')
			continue;
		float tempdist = d(qInit,qEval);
		//if(tempdist>0.7f)
			//LOG("%s  :  %f", node->getNodeName().c_str(), tempdist);
		tempQuatList[i] = slerp(qInit,qEval,LeftFading.blendWeight);
	}
	//*/
	//*/Right
	ik_scenario.ikPosEffectors = &posConsRt;
	ik_scenario.ikRotEffectors = &rotConsRt;
	ik.update(&ik_scenario);
	ik_scenario.copyTreeNodeQuat(QUAT_CUR,QUAT_INIT);	
	for (unsigned int i = 0; i < ik_scenario.ikTreeNodes.size(); i++)
	{
		MeCtIKTreeNode* node = ik_scenario.ikTreeNodes[i];
		SrQuat qEval = node->getQuat(QUAT_CUR);
		SrQuat qInit = node->getQuat(QUAT_REF);
		qEval.normalize();
		qInit.normalize();
		char a=node->getNodeName().c_str()[0];
		if(a!='r')
			continue;
		float tempdist = d(qInit,qEval);
		//if(tempdist>0.7f)
		//{
			//LOG("%s  :  %f", node->getNodeName().c_str(), tempdist);
		//}
		tempQuatList[i] = slerp(qInit,qEval,RightFading.blendWeight);
	}
	//*/
	updateChannelBuffer(*BufferRef,tempQuatList);//Read from tempQuatList->Write on Buffer
	updateWorldOffset(*BufferRef, woQuat, woPos);	
	character->set_world_offset(x, y, z, yaw, pitch, roll); 
	RightFading.prev_time=LeftFading.prev_time = t;
	if(_analysis)
	{
		writeToSkeleton(*BufferRef);
		check_collision();
	}
}
Esempio n. 16
0
  double Solver::solve( double timeout )
  {
    chrono::duration<double,milli> elapsedTime;
    chrono::duration<double,milli> elapsedTimeTour;
    chrono::duration<double,milli> postprocessGap(0);
    chrono::time_point<chrono::system_clock> start;
    chrono::time_point<chrono::system_clock> startTour;
    start = chrono::system_clock::now();

    // to time simulateCost and cost functions
    chrono::duration<double,milli> timeSimCost(0);
    chrono::time_point<chrono::system_clock> startSimCost; 

#ifndef NDEBUG
    chrono::duration<double,milli> toverlap(0), tbuildable(0), tnoholes(0), tstt(0);
    chrono::time_point<chrono::system_clock> soverlap, sbuildable, snoholes, sstt; 
#endif

    int sizeGrid = grid.getNberRows() * grid.getNberCols() + 1; // + 1 for the "position -1" outside the grid
    vector< vector< double > >  vecConstraintsCosts( vecConstraints.size() );
    vector< double >		vecGlobalCosts( sizeGrid );
    vector< vector< double > >  vecVarSimCosts( sizeGrid );
    objective->initHelper( sizeGrid );

    bestCost = numeric_limits<int>::max();
    double beforePostProc = bestCost;
    double bestGlobalCost = numeric_limits<int>::max();
    double globalCost;
    double currentCost;
    double estimatedCost;
    double bestEstimatedCost;
    int    bestPosition;

    vector<int> worstBuildings;
    double worstVariableCost;
    int worstBuildingId;
    int sizeWall;

    shared_ptr<Building> oldBuilding;
    vector<int> possiblePositions;
    vector<double> varSimCost( vecBuildings.size() );
    vector<double> bestSimCost( vecBuildings.size() );

    int tour = 0;
    int iterations = 0;

    do // optimization loop
    {
      startTour = chrono::system_clock::now();
      ++tour;
      globalCost = numeric_limits<int>::max();
      bestEstimatedCost = numeric_limits<int>::max();
      sizeWall  = numeric_limits<int>::max();
      std::fill( varSimCost.begin(), varSimCost.end(), 0. );
      std::fill( bestSimCost.begin(), bestSimCost.end(), 0. );
      std::fill( vecConstraintsCosts.begin(), vecConstraintsCosts.end(), vector<double>( vecBuildings.size(), 0. ) );
      std::fill( vecVarSimCosts.begin(), vecVarSimCosts.end(), vector<double>( vecBuildings.size(), 0. ) );
      std::fill( variableCost.begin(), variableCost.end(), 0. );
      std::fill( tabuList.begin(), tabuList.end(), 0 );

      do // solving loop 
      {
	++iterations;

	if( globalCost == numeric_limits<int>::max() )
	{
	  currentCost = 0.;

	  for( auto c : vecConstraints )
	    currentCost += c->cost( variableCost );

	  if( currentCost < globalCost )
	    globalCost = currentCost;
	  else
	  {
	    reset();
	    continue;
	  }
	}

	// make sure there is at least one untabu variable
	bool freeVariables = false;

	// Update tabu list
	for( int i = 0; i < tabuList.size(); ++i )
	{
	  if( tabuList[i] <= 1 )
	  {
	    tabuList[i] = 0;
	    if( !freeVariables )
	      freeVariables = true;      
	  }
	  else
	    --tabuList[i];
	}

	// Here, we look at neighbor configurations with the lowest cost.
	worstBuildings.clear();
	worstVariableCost = 0;
	for( int i = 0; i < variableCost.size(); ++i )
	{
	  if( !freeVariables || tabuList[i] == 0 )
	  {
	    if( worstVariableCost < variableCost[i] )
	    {
	      worstVariableCost = variableCost[i];
	      worstBuildings.clear();
	      worstBuildings.push_back( i );
	    }
	    else 
	      if( worstVariableCost == variableCost[i] )
		worstBuildings.push_back( i );	  
	  }
	}
      
	// can apply some heuristics here, according to the objective function
	worstBuildingId = objective->heuristicVariable( worstBuildings, vecBuildings, grid );
	oldBuilding = vecBuildings[ worstBuildingId ];
      
	// get possible positions for oldBuilding.
	possiblePositions = grid.possiblePos( *oldBuilding );

	// time simulateCost
	startSimCost = chrono::system_clock::now();

	// variable simulated costs
	fill( bestSimCost.begin(), bestSimCost.end(), 0. );

#ifndef NDEBUG
	soverlap = chrono::system_clock::now();
	vecConstraintsCosts[0] = vecConstraints[0]->simulateCost( *oldBuilding, possiblePositions, sizeGrid, vecVarSimCosts, objective );
	toverlap += chrono::system_clock::now() - soverlap;

	sbuildable = chrono::system_clock::now();
	vecConstraintsCosts[1] = vecConstraints[1]->simulateCost( *oldBuilding, possiblePositions, sizeGrid, vecVarSimCosts );
	tbuildable += chrono::system_clock::now() - sbuildable;

	snoholes = chrono::system_clock::now();
	vecConstraintsCosts[2] = vecConstraints[2]->simulateCost( *oldBuilding, possiblePositions, sizeGrid, vecVarSimCosts );
	tnoholes += chrono::system_clock::now() - snoholes;

	sstt = chrono::system_clock::now();
	vecConstraintsCosts[3] = vecConstraints[3]->simulateCost( *oldBuilding, possiblePositions, sizeGrid, vecVarSimCosts );
	tstt += chrono::system_clock::now() - sstt;
#else
	vecConstraintsCosts[0] = vecConstraints[0]->simulateCost( *oldBuilding, possiblePositions, sizeGrid, vecVarSimCosts, objective );
	for( int i = 1; i < vecConstraints.size(); ++i )
	  vecConstraintsCosts[i] = vecConstraints[i]->simulateCost( *oldBuilding, possiblePositions, sizeGrid, vecVarSimCosts );
#endif

	fill( vecGlobalCosts.begin(), vecGlobalCosts.end(), 0. );

	// sum all numbers in the vector vecConstraintsCosts[i] and put it into vecGlobalCosts[i] 
	for( auto v : vecConstraintsCosts )
	  transform( vecGlobalCosts.begin(), 
		     vecGlobalCosts.end(), 
		     v.begin(), 
		     vecGlobalCosts.begin(), 
		     plus<double>() );

	// replace all negative numbers by the max value for double
	replace_if( vecGlobalCosts.begin(), 
		    vecGlobalCosts.end(), 
		    bind( less<double>(), placeholders::_1, 0. ), 
		    numeric_limits<int>::max() );

	// look for the first smallest cost, according to objective heuristic
	int b = objective->heuristicValue( vecGlobalCosts, bestEstimatedCost, bestPosition, grid);
	bestSimCost = vecVarSimCosts[ b ];

	timeSimCost += chrono::system_clock::now() - startSimCost;

	currentCost = bestEstimatedCost;

	if( bestEstimatedCost < globalCost )
	{
	  globalCost = bestEstimatedCost;

	  if( globalCost < bestGlobalCost )
	    bestGlobalCost = globalCost;

	  variableCost = bestSimCost;
	  move( oldBuilding, bestPosition );
	}
	else // local minima
	  tabuList[ worstBuildingId ] = TABU;

	elapsedTimeTour = chrono::system_clock::now() - startTour;
      } while( globalCost != 0. && elapsedTimeTour.count() < timeout );

      // remove useless buildings
      if( globalCost == 0 )
      {
	bool change;
	double cost;
	NoHoles nh( vecBuildings, grid );

	// remove all unreachable buildings from the starting building out of the grid
	set< shared_ptr<Building> > visited = getNecessaryBuildings();
	for( auto b : vecBuildings )
	  if( visited.find( b ) == visited.end() )
	  {
	    grid.clear( *b );
	    b->setPos( -1 );
	  }

	// clean wall from unnecessary buildings.
	do
	{
	  for( auto b : vecBuildings )
	    if( ! grid.isStartingOrTargetTile( b->getId() ) )
	    {
	      change = false;
	      if( b->isOnGrid() )
	      {
		cost = 0.;
		fill( varSimCost.begin(), varSimCost.end(), 0. );
	      
		cost = nh.simulateCost( *b, -1, varSimCost );
	      
		if( cost == 0. )
		{
		  grid.clear( *b );
		  b->setPos( -1 );
		  nh.update( grid );
		  change = true;
		}	  
	      }
	    }
	} while( change );

	double objectiveCost = objective->cost( vecBuildings, grid );
	int currentSizeWall = countBuildings( vecBuildings );

	if( objectiveCost < bestCost || ( objectiveCost == bestCost && currentSizeWall < sizeWall ) )
	{
	  sizeWall = currentSizeWall;
	  bestCost = objectiveCost;
	  for( int i = 0; i < vecBuildings.size(); ++i )
	    bestSolution[i] = vecBuildings[i]->getPosition();
	}
      }
      reset();
      elapsedTime = chrono::system_clock::now() - start;
    }
    while( ( objective->getName().compare("none") != 0 || loops == 0 )  && ( elapsedTime.count() < OPT_TIME )//|| ( elapsedTime.count() >= OPT_TIME && bestGlobalCost != 0 && elapsedTime.count() < 10 * OPT_TIME ) ) 
	   || ( objective->getName().compare("none") == 0 && elapsedTime.count() < timeout * loops ) );

    clearAllInGrid( vecBuildings, grid );

    for( int i = 0; i < vecBuildings.size(); ++i )
      vecBuildings[i]->setPos( bestSolution[i] );
    
    addAllInGrid( vecBuildings, grid );

    // For gap objective, try now to decrease the number of gaps.
    if( ( objective->getName().compare("gap") == 0 || objective->getName().compare("techtree") == 0 ) && bestGlobalCost == 0 )
    {
      //objective.reset( new GapObj("gap") );
      std::fill( tabuList.begin(), tabuList.end(), 0 );
        
      for( auto v : vecBuildings )
	buildingSameSize.insert( make_pair( v->getSurface(), v ) );

      vector<int> goodVar;
      shared_ptr<Building> toSwap;
      bool mustSwap;

      chrono::time_point<chrono::system_clock> startPostprocess = chrono::system_clock::now(); 
    
      bestCost = objective->cost( vecBuildings, grid );
      double currentCost = bestCost;
      beforePostProc = bestCost;

      while( (postprocessGap = chrono::system_clock::now() - startPostprocess).count() < static_cast<int>( ceil(OPT_TIME / 100) ) && bestCost > 0 )
      {
	goodVar.clear();

	for( int i = 0; i < tabuList.size(); ++i )
	{
	  if( tabuList[i] <= 1 )
	    tabuList[i] = 0;
	  else
	    --tabuList[i];
	}

	for( int i = 0; i < vecBuildings.size(); ++i )
	{
	  if( tabuList[i] == 0 )
	    goodVar.push_back( i );
	}

	if( goodVar.empty() )
	  for( int i = 0; i < vecBuildings.size(); ++i )
	    goodVar.push_back( i );	

	int index = objective->heuristicVariable( goodVar, vecBuildings, grid );
	oldBuilding = vecBuildings[ index ];
	auto surface = buildingSameSize.equal_range( oldBuilding->getSurface() );
	
	for( auto it = surface.first; it != surface.second; ++it )
	{
	  mustSwap = false;
	  if( it->second->getId() != oldBuilding->getId() )
	  {
	    grid.swap( *it->second, *oldBuilding );
	    
	    currentCost = objective->cost( vecBuildings, grid );
	    if( currentCost < bestCost )
	    {
	      bestCost = currentCost;
	      toSwap = it->second;
	      mustSwap = true;
	    }

	    grid.swap( *it->second, *oldBuilding );
	  }
	  
	  if( mustSwap )
	    grid.swap( *toSwap, *oldBuilding );
	}

	tabuList[ index ] = 2;//std::max(2, static_cast<int>( ceil(TABU / 2) ) );
      }
    }
 
    cout << "Grids:" << grid << endl;

    if( objective->getName().compare("none") == 0 )
      cout << "SATISFACTION run: try to find a sound wall only!" << endl;
    else
      cout << "OPTIMIZATION run with objective " << objective->getName() << endl;
      
    cout << "Elapsed time: " << elapsedTime.count() << endl
	 << "Global cost: " << bestGlobalCost << endl
	 << "Number of tours: " << tour << endl
	 << "Number of iterations: " << iterations << endl;

    if( objective->getName().compare("none") == 0 )
    {
      if( bestGlobalCost == 0 )
      {
	BuildingObj bObj("building");
	GapObj gObj("gap");
	TechTreeObj tObj("techtree");
	
	cout << "Opt Cost if the objective was building: " << bObj.cost( vecBuildings, grid ) << endl
	     << "Opt Cost if the objective was gap: \t" << gObj.cost( vecBuildings, grid ) << endl
	     << "Opt Cost if the objective was techtree: " << tObj.cost( vecBuildings, grid ) << endl;
      }
    }
    else
    {
      cout << "Optimization cost: " << bestCost << endl
	   << "Opt Cost BEFORE post-processing: " << beforePostProc << endl;
    }

    if( objective->getName().compare("gap") == 0 || objective->getName().compare("techtree") == 0 )
      cout << "Post-processing time: " << postprocessGap.count() << endl; 

#ifndef NDEBUG
    cout << endl << "Elapsed time to simulate cost: " << timeSimCost.count() << endl
	 << "Overlap: " << toverlap.count() << endl
	 << "Buildable: " << tbuildable.count() << endl
	 << "NoHoles: " << tnoholes.count() << endl
	 << "STT: " << tstt.count() << endl;

    updateConstraints( vecConstraints, grid );

    // print cost for each constraint
    for( auto c : vecConstraints )
    {
      fill( varSimCost.begin(), varSimCost.end(), 0. );
      cout << "Cost of " << typeid(*c).name() << ": " << c->cost( varSimCost ) << " [";

      for( auto v : varSimCost )
	cout << " " << v;

      cout << " ]" << endl;
    }      
    
    cout << endl;
#endif

    if( objective->getName().compare("none") == 0 )
      return bestGlobalCost;
    else
      return bestCost;
  }
Esempio n. 17
0
static void dragDivider(WMSplitView * sPtr, int clickX, int clickY)
{
	int divider, pos, ofs, done, dragging;
	int i, count;
	XEvent ev;
	WMScreen *scr;
	int minCoord, maxCoord, coord;

	if (sPtr->constrainProc) {
		updateConstraints(sPtr);
		checkSizes(sPtr);
		distributeOffsetFormEnd(sPtr, _GetSplitViewSize() - getTotalSize(sPtr));
		checkPositions(sPtr);
		updateSubviewsGeom(sPtr);
	}

	scr = sPtr->view->screen;
	divider = ofs = pos = done = 0;
	coord = (sPtr->flags.vertical) ? clickX : clickY;
	count = _GetSubviewsCount();
	if (count < 2)
		return;

	for (i = 0; i < count - 1; i++) {
		pos += _GetSizeAt(i) + DIVIDER_THICKNESS;
		if (coord < pos) {
			ofs = coord - pos + DIVIDER_THICKNESS;
			done = 1;
			break;
		}
		divider++;
	}

	if (!done)
		return;

	getMinMaxDividerCoord(sPtr, divider, &minCoord, &maxCoord);

	done = 0;
	dragging = 0;
	while (!done) {
		WMMaskEvent(scr->display, ButtonMotionMask | ButtonReleaseMask | ExposureMask, &ev);

		coord = (sPtr->flags.vertical) ? ev.xmotion.x : ev.xmotion.y;

		switch (ev.type) {
		case ButtonRelease:
			done = 1;
			if (dragging)
				drawDragingRectangle(sPtr, pos);
			break;

		case MotionNotify:
			if (dragging)
				drawDragingRectangle(sPtr, pos);
			if (coord - ofs < minCoord)
				pos = minCoord;
			else if (coord - ofs > maxCoord)
				pos = maxCoord;
			else
				pos = coord - ofs;
			drawDragingRectangle(sPtr, pos);
			dragging = 1;
			break;

		default:
			WMHandleEvent(&ev);
			break;
		}
	}

	if (dragging) {
		W_SplitViewSubview *p1, *p2;
		int totSize;

		p1 = _GetPSubviewStructAt(divider);
		p2 = _GetPSubviewStructAt(divider + 1);

		totSize = p1->size + DIVIDER_THICKNESS + p2->size;

		p1->size = pos - p1->pos;
		p2->size = totSize - p1->size - DIVIDER_THICKNESS;
		p2->pos = p1->pos + p1->size + DIVIDER_THICKNESS;

		resizeView(sPtr, p1->view, p1->size);
		moveView(sPtr, p2->view, p2->pos);
		resizeView(sPtr, p2->view, p2->size);
		sPtr->flags.subviewsWereManuallyMoved = 1;
	}
}