Exemplo n.º 1
0
Connections::Connections(QString nname, QString ename)
{
    selected = NULL;
    QFile n(nname);
    qDebug() << nname;
    if (!n.open(QIODevice::ReadOnly)) qDebug("nodes unreadable");
    QTextStream ns(&n);
    QString nl;

    while(!ns.atEnd()) {
        nl = ns.readLine();

        QStringList vals = nl.split(" ", QString::SkipEmptyParts);
        QVector3D* anode;
        //x,y,z
        anode = new QVector3D(((QString)(vals.at(0))).toFloat(),
                              ((QString)(vals.at(1))).toFloat(),
                              ((QString)(vals.at(2))).toFloat());
        nodes << *anode;

    }
    n.close();
    qDebug() << "nodes read";
    calculateBounds();

    QFile e(ename);
    if (!e.open(QIODevice::ReadOnly)) qDebug("edges unreadable");
    QTextStream es(&e);
    QString el;
    while(!es.atEnd()) {
        int f;
        int t;
        el = es.readLine();

        QStringList evals = el.split(" ",QString::SkipEmptyParts);
        f = ((QString)(evals.at(0))).toInt();
        t = ((QString)(evals.at(1))).toInt();

        Edge* aedge;
        aedge = new Edge(nodes.at(f), nodes.at(t));
        if (aedge->length() > 0) edges << aedge;
    }
    e.close();

    qDebug() << edges.length() << " edges...";

    calculateBounds();

    createPrims();

}
Exemplo n.º 2
0
void BoundingBox::setAngle(int a)
{
    // correct angle to be between -360 to 360
    if(a >= 360 || a <= -360)
    {
        a - (360 * a/360);
    }
    
    // correct angle further to be between 0 <= angle < 360
    if(a < 0)
    {
        a = 360 + a;
    }
    
    if(a == 360)
        a = 0;
    
    // if angle is 180 or 90 set it to exactly PI or PI/2
    if(a == 180)
        angle = PI;
    else if( a == 90)
        angle = PI/2;
    else
        angle = a * PI/180; // convert to radians
    
    calculateBounds();
}
Exemplo n.º 3
0
Connections::Connections(QString fib){
    selected = NULL;
    QFile n(fib);
    if (!n.open(QIODevice::ReadOnly)) qDebug() << "vtk unreadable: " << fib;
    QTextStream ns(&n);
    QString nl;
    QDataStream ins(&n);
    ins.setByteOrder(QDataStream::BigEndian);
    ins.setFloatingPointPrecision(QDataStream::SinglePrecision);
    nl = ns.readLine(); //skip first lines;
    nl = ns.readLine(); //TODO: Other types of stuff...
    nl = ns.readLine();
    nl = ns.readLine();
    nl = ns.readLine();
    ns.pos();
    QStringList vals = nl.split(" ");
    int np = ((QString)(vals.at(1))).toInt();
    qDebug() << "number of points: " << np;
    for (int i = 0; i < np; i++) {
        QVector3D* anode;
        float x,y,z;
        ins >> x;
        ins >> y;
        ins >> z;
        anode = new QVector3D(x,y,z);
        nodes << *anode;
    }
    ns.pos();
    ns.seek(n.pos() + np*3*4 + 1);
    ns.pos();
    nl = ns.readLine();
    vals = nl.split(" ");
    int ncons = ((QString)(vals.at(1))).toInt();
    int nps = ((QString)(vals.at(2))).toInt();
    qDebug() << "number of connections: " << ncons;

    ns.pos();
    for (int i = 0; i < ncons; i++) {
        qint32 numpoints;
        ins >> numpoints;
        qint32 ps[numpoints];
        for (int pn = 0; pn < numpoints; pn++){
            ins >> ps[pn];
        }
        Edge* aedge;
        aedge = new Edge(nodes.at(ps[0]), nodes.at(ps[numpoints-1]));
        aedge->points.removeLast();
        for (int pn = 1; pn < numpoints; pn++){
            aedge->points << nodes.at(ps[pn]);
        }
        edges << aedge;
    }
    n.close();

    calculateBounds();

    createPrims();

}
Exemplo n.º 4
0
void PUBoxCollider::preUpdateAffector( float deltaTime )
{
    PUBaseCollider::preUpdateAffector(deltaTime);
    // Calculate the affectors' center position in worldspace, set the box and calculate the bounds
    // Applied scaling in V 1.3.1.
    populateAlignedBox(_box, getDerivedPosition(), _affectorScale.x * _width, _affectorScale.y * _height, _affectorScale.z * _depth);
    calculateBounds();
}
const AABB& RenderableParticleStage::getBounds()
{
	if (!_bounds.isValid())
	{
		calculateBounds();
	}

	return _bounds;
}
Exemplo n.º 6
0
void GraphBlock::removeSockets( GraphBlockSocketPosition position, const std::set< std::string >& socketNames )
{
   for ( std::set< std::string >::const_iterator removedSocketNameIt = socketNames.begin(); removedSocketNameIt != socketNames.end(); ++removedSocketNameIt )
   {
      removeSingleSocket( position, *removedSocketNameIt );
   }

   calculateBounds();
}
Exemplo n.º 7
0
// Bounding Box - public
BoundingBox::BoundingBox(int x, int y, int w, int h, int a)
{
    xO = x;
    yO = y;
    width = w;
    height = h;
    setAngle( a ); // convert to radians
    calculateBounds();
}
Exemplo n.º 8
0
void GraphBlock::addSocket( GraphBlockSocket* socket )
{
   if ( !socket )
   {
      return;
   }

   m_sockets.push_back( socket );
   calculateBounds();
}
Exemplo n.º 9
0
void GraphBlock::onPropertyChanged( ReflectionProperty& property )
{
   __super::onPropertyChanged( property );

   if ( property.getName() == "m_caption" )
   {
      // recalculate the block bounds each time the caption changes
      calculateBounds();
   }
}
SConnections::SConnections(QList<QVector3D> nodes, IndexedConnections* ics, QList<QVector3D>* allNodes, int offset){
    params();
    //qDebug() << "SConnections: " << nodes << ics << nodes.length() << ics->length();
    //TODO: Pointers?
    this->nodes = nodes;
    this->icons = ics;
    calculateBounds();
    qDebug("before create Nodes");
    qDebug() << "icons length: " << icons->length() << allNodes->length();
    createNodes(allNodes, offset);
    qDebug("after create Nodes");
}
Exemplo n.º 11
0
Arquivo: Mesh.cpp Projeto: p0iz/Forge
Mesh::Mesh(
    const std::vector<Vertex>& vertices,
    const std::vector<GLuint>& elements)
  : mName(),
    mNumberOfVertices(elements.size()),
    mVertexArrayId(0),
    mVertexBufferId(0)
{
  const size_t vertexSize = sizeof(Vertex);

  // Generate vertex array and buffers
  glGenVertexArrays(1, &mVertexArrayId);
  glGenBuffers(1, &mVertexBufferId);

  glBindVertexArray(mVertexArrayId);

  glBindBuffer(GL_ARRAY_BUFFER, mVertexBufferId);
  glBufferData(GL_ARRAY_BUFFER, vertexSize*vertices.size(), &vertices[0], GL_STATIC_DRAW);

  // Positional attribute
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, vertexSize, 0);
  glEnableVertexAttribArray(0);

  // Texture coordinate attribute
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, vertexSize, &(((Vertex*)0)->texcoord));
  glEnableVertexAttribArray(1);

  // Normal attribute
  glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, vertexSize, &(((Vertex*)0)->normal));
  glEnableVertexAttribArray(2);

  // Tangent attribute
  glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, vertexSize, &(((Vertex*)0)->tangent));
  glEnableVertexAttribArray(3);

  // Bitangent attribute
  glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, vertexSize, &(((Vertex*)0)->bitangent));
  glEnableVertexAttribArray(4);

  glGenBuffers(1, &mElementBufferId);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mElementBufferId);

  glBufferData(
        GL_ELEMENT_ARRAY_BUFFER,
        sizeof(elements[0])*elements.size(),
      &elements[0],
      GL_STATIC_DRAW);

  glBindVertexArray(0);

  calculateBounds(vertices);
}
Exemplo n.º 12
0
sp<ImageSet> PCKLoader::loadShadow(Data &data, UString PckFilename, UString TabFilename,
                                   unsigned shadedIdx)
{
	TRACE_FN;
	auto imageSet = mksp<ImageSet>();
	auto tabFile = data.fs.open(TabFilename);
	if (!tabFile)
	{
		LogWarning("Failed to open tab \"%s\"", TabFilename);
		return nullptr;
	}
	auto pckFile = data.fs.open(PckFilename);
	if (!pckFile)
	{
		LogWarning("Failed to open tab \"%s\"", TabFilename);
		return nullptr;
	}
	imageSet->maxSize = {0, 0};

	uint32_t offset = 0;
	unsigned idx = 0;
	while (tabFile.read(reinterpret_cast<char *>(&offset), sizeof(offset)))
	{
		// shadow TAB files store the offset directly
		pckFile.seekg(offset, std::ios::beg);
		if (!pckFile)
		{
			LogError("Failed to seek to offset %u", offset);
			return nullptr;
		}
		auto img = loadShadowImage(pckFile, shadedIdx);
		if (!img)
		{
			LogError("Failed to load image");
			return nullptr;
		}
		imageSet->images.push_back(img);
		img->owningSet = imageSet;
		img->calculateBounds();
		img->indexInSet = idx++;
		if (img->size.x > imageSet->maxSize.x)
			imageSet->maxSize.x = img->size.x;
		if (img->size.y > imageSet->maxSize.y)
			imageSet->maxSize.y = img->size.y;
	}

	LogInfo("Loaded %u images", static_cast<unsigned>(imageSet->images.size()));

	return imageSet;
}
Exemplo n.º 13
0
void Guideline::updateFromLayout(const double posVal, const bool updatePos)
{
    QPointF position = pos();
    if (updatePos)
    {
        position = QPointF(posVal, posVal);
    }
    QRectF bounds = calculateBounds(position);
    if (updatePos || (pos() == bounds.center()))
    {
        setSize(bounds.width(), bounds.height());
    }
    setPos(bounds.center());
}
Exemplo n.º 14
0
QVariant Guideline::itemChange(GraphicsItemChange change,
        const QVariant &value)
{
    if ((change == QGraphicsItem::ItemPositionChange) && scene() &&
            !scene()->views().empty())
    {
        QPointF newPos = value.toPointF();
        QRectF bounds = calculateBounds(newPos);
        setSize(bounds.width(), bounds.height());
        newPos = bounds.center();
        return newPos;
    }
    return Indicator::itemChange(change, value);
}
Exemplo n.º 15
0
sp<ImageSet> PCKLoader::loadStrat(Data &data, UString PckFilename, UString TabFilename)
{
	auto imageSet = mksp<ImageSet>();
	auto tabFile = data.fs.open(TabFilename);
	if (!tabFile)
	{
		LogWarning("Failed to open tab \"%s\"", TabFilename);
		return nullptr;
	}
	auto pckFile = data.fs.open(PckFilename);
	if (!pckFile)
	{
		LogWarning("Failed to open tab \"%s\"", TabFilename);
		return nullptr;
	}

	uint32_t offset = 0;
	unsigned idx = 0;
	while (tabFile.read(reinterpret_cast<char *>(&offset), sizeof(offset)))
	{
		pckFile.seekg(offset, std::ios::beg);
		if (!pckFile)
		{
			LogError("Failed to seek to offset %u", offset);
			return nullptr;
		}
		auto img = loadStrategy(pckFile);
		if (!img)
		{
			LogError("Failed to load image");
			return nullptr;
		}
		if (img->size != Vec2<unsigned int>{8, 8})
		{
			LogError("Invalid size of {%d,%d} in stratmap image", img->size.x, img->size.y);
			return nullptr;
		}
		imageSet->images.push_back(img);
		img->owningSet = imageSet;
		img->calculateBounds();
		img->indexInSet = idx++;
	}

	imageSet->maxSize = {8, 8};

	LogInfo("Loaded %u images", static_cast<unsigned>(imageSet->images.size()));

	return imageSet;
}
Exemplo n.º 16
0
/** Create OpenGL-specific buffers */
void Mesh::createBuffers()
{
	//nPoints = meshVertices.size();
    
	vao = 0;
    GraphicsSystem::getInstance()->generateVertexArrays(1,vao);
    
	mvbo = 0;
    GraphicsSystem::getInstance()->generateBuffer(1,mvbo,GL_ARRAY_BUFFER,meshVertices.size() * sizeof(MeshVertex),&meshVertices[0],GL_STATIC_DRAW);
    
	ibo = 0;
    GraphicsSystem::getInstance()->generateBuffer(1,ibo,GL_ELEMENT_ARRAY_BUFFER,triangles.size() * sizeof(unsigned short),&triangles[0],GL_STATIC_DRAW);
    
	calculateBounds();
}
Exemplo n.º 17
0
GraphBlock::GraphBlock()
   : QGraphicsItem( NULL )
   , m_caption( "" )
   , m_bounds( QPointF( 0, 0 ), QSizeF( 100, 100 ) )
   , m_captionBounds( QPointF( 0, 0 ), QSizeF( 100, 0 ) )
   , m_font( "Verdana", 15, QFont::Light )
   , m_centralWidget( new QGraphicsProxyWidget( this ) )
   , m_embeddedWidget( NULL )
   , m_socketsFactory( NULL )
{
   m_font.setStyle( QFont::StyleNormal );
   m_font.setStyleHint( QFont::AnyStyle );
   m_font.setStyleStrategy( QFont::PreferAntialias );

   setFlags( QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsFocusable );

   calculateBounds();
}
Exemplo n.º 18
0
void SurfaceProperties::applyBounds(PropertyImpl<canvas::Rect> *prop) {
	bool needRefresh=false;
	
	//	Get new bounds
	canvas::Rect newBounds(_bounds);
	calculateBounds(newBounds);

	LDEBUG("SurfaceProperties", "apply bounds: (%d,%d,%d,%d)", newBounds.x, newBounds.y, newBounds.w, newBounds.h);

	{	//	Compare size
		const canvas::Size newSize( newBounds );
		const canvas::Size &curSize=surface()->getSize();

		if (newSize != curSize) {
			//	Create a new surface from current
			surface()->resize( newSize );
			needRefresh = true;

			//	Notify to dependents
			if (!_onSizeChanged.empty()) {
				_onSizeChanged( newSize );
			}
		}
	}

	{	//	Compare location
		const canvas::Point newPoint( newBounds );
		const canvas::Point &curPoint=surface()->getLocation();
		if (newPoint != curPoint) {
			surface()->setLocation( newPoint );

			//	Notify to dependents
			if (!_onPositionChanged.empty()) {
				_onPositionChanged( newPoint );
			}			
		}
	}

	//	Refresh if necesary
	prop->setNeedResfresh(needRefresh);
}
SConnections::SConnections(QString nname, QString ename)
{
    params();
    QFile n(nname);

    if (nname.endsWith(".asc")){
        qDebug() << "reading from "+nname;
        AFNISurface afnis(nname,"");
        nodes = afnis.nodes;
    } else {

    if (!n.open(QIODevice::ReadOnly)) qDebug("nodes unreadable");
    QTextStream ns(&n);
    QString nl;

    qDebug() << "reading from " << nname << " and " << ename;

    while(!ns.atEnd()) {
        nl = ns.readLine();

        QStringList vals = nl.split(" ", QString::SkipEmptyParts);
        QVector3D* anode;
        anode = new QVector3D(((QString)(vals.at(0))).toFloat(),
                              ((QString)(vals.at(1))).toFloat(),
                              ((QString)(vals.at(2))).toFloat());
        nodes << *anode;

    }
    n.close();

    }

    qDebug() << nodes.length() << " nodes read";
    calculateBounds();

    dn.clear();
    icons = new IndexedConnections(ename);
    createNodes();
}
Exemplo n.º 20
0
void GraphBlock::setCaption( const char* caption )
{
   m_caption = caption;
   calculateBounds();
}
Exemplo n.º 21
0
void GraphBlock::setCentralWidget( QWidget* widget )
{
   m_embeddedWidget = widget;
   m_centralWidget->setWidget( m_embeddedWidget );
   calculateBounds();
}
Exemplo n.º 22
0
bool SurfaceProperties::createSurface() {
	canvas::Rect tmp(_bounds);
	calculateBounds(tmp);
	return createSurface( tmp );
}
Exemplo n.º 23
0
   void CylinderMesh::construct()
   {
      int i, firstTop ;
      int steps = (unsigned int)(complexity * 64.0f) ;
      float angle ;
      Point normal ;
      Box   bounds = getBounds() ;
      Point center = getCenter() ;
      float radius = getRadius() ;

      Primitive p ;
      p.type = Primitive::NoMaterial | Primitive::Strip | Primitive::Indexed ;

      if (steps < 4)  steps = 4 ;
      if (steps > 64) steps = 64 ;
      steps &= ~1 ;

      // Bottom
      addVertex (center.x(), center.y(), bounds.min.z()) ;
      for (angle = 0.0f, i = 0 ; i < steps ; i++, angle += 2.0f*M_PI/(float)steps)
      {
         addVertex (cosf(angle)*radius + center.x(), sinf(angle)*radius + center.y(), 
                    bounds.min.z()) ;
      }

      for (i = 1 ; i <= steps ; i++)
      {
         p.firstElement = indices.size() ;
         p.numElements  = 3 ;
         indices.push_back (0) ;
         indices.push_back (i) ;
         indices.push_back (i == steps ? 1 : i+1) ;
         primitives.push_back(p) ;
      }

      // Top
      firstTop = verts.size() ;
      addVertex (center.x(), center.y(), bounds.max.z()) ;
      for (angle = 0.0f, i = 0 ; i < steps ; i++, angle += 2.0f*M_PI/(float)steps)
      {
         addVertex (cosf(angle)*radius + center.x(), sinf(angle)*radius + center.y(), 
                    bounds.max.z()) ;
      }

      for (i = 1 ; i <= steps ; i++)
      {
         p.firstElement = indices.size() ;
         p.numElements  = 3 ;
         indices.push_back (firstTop) ;
         indices.push_back (firstTop+(i == steps ? 1 : i+1)) ;
         indices.push_back (firstTop+i) ;
         primitives.push_back(p) ;
      }

      // Walls
      int pos ;
      for (pos = indices.size(), i = 0 ; i < steps-1 ; i++, pos += 4)
      {
         indices.push_back (i+1) ;
         indices.push_back (firstTop+i+1) ;
         indices.push_back (i+2) ;
         indices.push_back (firstTop+i+2) ;
         p.firstElement = pos ;
         p.numElements  = 4 ;
         primitives.push_back(p) ;
      }
      indices.push_back (i+1) ;
      indices.push_back (firstTop+i+1) ;
      indices.push_back (1) ;
      indices.push_back (firstTop+1) ;
      p.firstElement = pos ;
      p.numElements  = 4 ;
      primitives.push_back(p) ;

      // Other stuff

      setFrames (1) ;
      setParent (-1) ;
      calculateBounds() ;
      calculateCenter() ;
      calculateRadius() ;
   }
Exemplo n.º 24
0
void BoundingBox::setOrigin(int xp, int yp)
{
    xO = xp;
    yO = yp;
    calculateBounds();
}
Exemplo n.º 25
0
// Return LLC bounding values, calculating first if necessary
Vec3<double> Grid::lowerLeftCorner()
{
	if (boundsLog_ != log_) calculateBounds();
	return lowerLeftCorner_;
}
Exemplo n.º 26
0
/** execution method of primal heuristic */
static
SCIP_DECL_HEUREXEC(heurExecZirounding)
{  /*lint --e{715}*/
   SCIP_HEURDATA*     heurdata;
   SCIP_SOL*          sol;
   SCIP_VAR**         lpcands;
   SCIP_VAR**         zilpcands;

   SCIP_VAR**         slackvars;
   SCIP_Real*         upslacks;
   SCIP_Real*         downslacks;
   SCIP_Real*         activities;
   SCIP_Real*         slackvarcoeffs;
   SCIP_Bool*         rowneedsslackvar;

   SCIP_ROW**         rows;
   SCIP_Real*         lpcandssol;
   SCIP_Real*         solarray;

   SCIP_Longint       nlps;
   int                currentlpcands;
   int                nlpcands;
   int                nimplfracs;
   int                i;
   int                c;
   int                nslacks;
   int                nroundings;

   SCIP_RETCODE       retcode;

   SCIP_Bool          improvementfound;
   SCIP_Bool          numericalerror;

   assert(strcmp(SCIPheurGetName(heur), HEUR_NAME) == 0);
   assert(result != NULL);
   assert(SCIPhasCurrentNodeLP(scip));

   *result = SCIP_DIDNOTRUN;

   /* do not call heuristic of node was already detected to be infeasible */
   if( nodeinfeasible )
      return SCIP_OKAY;

   /* only call heuristic if an optimal LP-solution is at hand */
   if( SCIPgetLPSolstat(scip) != SCIP_LPSOLSTAT_OPTIMAL )
      return SCIP_OKAY;

   /* only call heuristic, if the LP objective value is smaller than the cutoff bound */
   if( SCIPisGE(scip, SCIPgetLPObjval(scip), SCIPgetCutoffbound(scip)) )
      return SCIP_OKAY;

   /* get heuristic data */
   heurdata = SCIPheurGetData(heur);
   assert(heurdata != NULL);

   /* Do not call heuristic if deactivation check is enabled and percentage of found solutions in relation
    * to number of calls falls below heurdata->stoppercentage */
   if( heurdata->stopziround && SCIPheurGetNCalls(heur) >= heurdata->minstopncalls
      && SCIPheurGetNSolsFound(heur)/(SCIP_Real)SCIPheurGetNCalls(heur) < heurdata->stoppercentage )
      return SCIP_OKAY;

   /* assure that heuristic has not already been called after the last LP had been solved */
   nlps = SCIPgetNLPs(scip);
   if( nlps == heurdata->lastlp )
      return SCIP_OKAY;

   heurdata->lastlp = nlps;

   /* get fractional variables */
   SCIP_CALL( SCIPgetLPBranchCands(scip, &lpcands, &lpcandssol, NULL, &nlpcands, NULL, &nimplfracs) );
   nlpcands = nlpcands + nimplfracs;
   /* make sure that there is at least one fractional variable that should be integral */
   if( nlpcands == 0 )
      return SCIP_OKAY;

   assert(nlpcands > 0);
   assert(lpcands != NULL);
   assert(lpcandssol != NULL);

   /* get LP rows data */
   rows    = SCIPgetLPRows(scip);
   nslacks = SCIPgetNLPRows(scip);

   /* cannot do anything if LP is empty */
   if( nslacks == 0 )
      return SCIP_OKAY;

   assert(rows != NULL);
   assert(nslacks > 0);

   /* get the working solution from heuristic's local data */
   sol = heurdata->sol;
   assert(sol != NULL);

   *result = SCIP_DIDNOTFIND;

   solarray = NULL;
   zilpcands = NULL;

   retcode = SCIP_OKAY;
   /* copy the current LP solution to the working solution and allocate memory for local data */
   SCIP_CALL( SCIPlinkLPSol(scip, sol) );
   SCIP_CALL_TERMINATE(retcode, SCIPallocBufferArray(scip, &solarray, nlpcands), TERMINATE);
   SCIP_CALL_TERMINATE(retcode, SCIPallocBufferArray(scip, &zilpcands, nlpcands), TERMINATE);

   /* copy necessary data to local arrays */
   BMScopyMemoryArray(solarray, lpcandssol, nlpcands);
   BMScopyMemoryArray(zilpcands, lpcands, nlpcands);

   /* allocate buffer data arrays */
   SCIP_CALL_TERMINATE(retcode, SCIPallocBufferArray(scip, &slackvars, nslacks), TERMINATE);
   SCIP_CALL_TERMINATE(retcode, SCIPallocBufferArray(scip, &upslacks, nslacks), TERMINATE);
   SCIP_CALL_TERMINATE(retcode, SCIPallocBufferArray(scip, &downslacks, nslacks), TERMINATE);
   SCIP_CALL_TERMINATE(retcode, SCIPallocBufferArray(scip, &slackvarcoeffs, nslacks), TERMINATE);
   SCIP_CALL_TERMINATE(retcode, SCIPallocBufferArray(scip, &rowneedsslackvar, nslacks), TERMINATE);
   SCIP_CALL_TERMINATE(retcode, SCIPallocBufferArray(scip, &activities, nslacks), TERMINATE);

   BMSclearMemoryArray(slackvars, nslacks);
   BMSclearMemoryArray(slackvarcoeffs, nslacks);
   BMSclearMemoryArray(rowneedsslackvar, nslacks);

   numericalerror = FALSE;
   nroundings = 0;

   /* loop over fractional variables and involved LP rows to find all rows which require a slack variable */
   for( c = 0; c < nlpcands; ++c )
   {
      SCIP_VAR* cand;
      SCIP_ROW** candrows;
      int r;
      int ncandrows;

      cand = zilpcands[c];
      assert(cand != NULL);
      assert(SCIPcolGetLPPos(SCIPvarGetCol(cand)) >= 0);

      candrows = SCIPcolGetRows(SCIPvarGetCol(cand));
      ncandrows = SCIPcolGetNLPNonz(SCIPvarGetCol(cand));

      assert(candrows == NULL || ncandrows > 0);

      for( r = 0; r < ncandrows; ++r )
      {
         int rowpos;

         assert(candrows != NULL); /* to please flexelint */
         assert(candrows[r] != NULL);
         rowpos = SCIProwGetLPPos(candrows[r]);

         if( rowpos >= 0 && SCIPisFeasEQ(scip, SCIProwGetLhs(candrows[r]), SCIProwGetRhs(candrows[r])) )
         {
            rowneedsslackvar[rowpos] = TRUE;
            SCIPdebugMessage("  Row %s needs slack variable for variable %s\n", SCIProwGetName(candrows[r]), SCIPvarGetName(cand));
         }
      }
   }

   /* calculate row slacks for every every row that belongs to the current LP and ensure, that the current solution
    * has no violated constraint -- if any constraint is violated, i.e. a slack is significantly smaller than zero,
    * this will cause the termination of the heuristic because Zirounding does not provide feasibility recovering
    */
   for( i = 0; i < nslacks; ++i )
   {
      SCIP_ROW*          row;
      SCIP_Real          lhs;
      SCIP_Real          rhs;

      row = rows[i];

      assert(row != NULL);

      lhs = SCIProwGetLhs(row);
      rhs = SCIProwGetRhs(row);

      /* get row activity */
      activities[i] = SCIPgetRowActivity(scip, row);
      assert(SCIPisFeasLE(scip, lhs, activities[i]) && SCIPisFeasLE(scip, activities[i], rhs));

      /* in special case if LHS or RHS is (-)infinity slacks have to be initialized as infinity */
      if( SCIPisInfinity(scip, -lhs) )
         downslacks[i] = SCIPinfinity(scip);
      else
         downslacks[i] = activities[i] - lhs;

      if( SCIPisInfinity(scip, rhs) )
         upslacks[i] = SCIPinfinity(scip);
      else
         upslacks[i] = rhs - activities[i];

      SCIPdebugMessage("lhs:%5.2f <= act:%5.2g <= rhs:%5.2g --> down: %5.2g, up:%5.2g\n", lhs, activities[i], rhs, downslacks[i], upslacks[i]);

      /* row is an equation. Try to find a slack variable in the row, i.e.,
       * a continuous variable which occurs only in this row. If no such variable exists,
       * there is no hope for an IP-feasible solution in this round
       */
      if( SCIPisFeasEQ(scip, lhs, rhs) && rowneedsslackvar[i] )
      {
         /* @todo: This is only necessary for rows containing fractional variables. */
         rowFindSlackVar(scip, row, &(slackvars[i]), &(slackvarcoeffs[i]));

         if( slackvars[i] == NULL )
         {
            SCIPdebugMessage("No slack variable found for equation %s, terminating ZI Round heuristic\n", SCIProwGetName(row));
            goto TERMINATE;
         }
         else
         {
            SCIP_Real ubslackvar;
            SCIP_Real lbslackvar;
            SCIP_Real solvalslackvar;
            SCIP_Real coeffslackvar;
            SCIP_Real ubgap;
            SCIP_Real lbgap;

            assert(SCIPvarGetType(slackvars[i]) == SCIP_VARTYPE_CONTINUOUS);
            solvalslackvar = SCIPgetSolVal(scip, sol, slackvars[i]);
            ubslackvar = SCIPvarGetUbGlobal(slackvars[i]);
            lbslackvar = SCIPvarGetLbGlobal(slackvars[i]);

            coeffslackvar = slackvarcoeffs[i];
            assert(!SCIPisFeasZero(scip, coeffslackvar));

            ubgap = ubslackvar - solvalslackvar;
            lbgap = solvalslackvar - lbslackvar;

            if( SCIPisFeasZero(scip, ubgap) )
              ubgap = 0.0;
            if( SCIPisFeasZero(scip, lbgap) )
              lbgap = 0.0;

            if( SCIPisFeasPositive(scip, coeffslackvar) )
            {
              if( !SCIPisInfinity(scip, lbslackvar) )
                upslacks[i] += coeffslackvar * lbgap;
              else
                upslacks[i] = SCIPinfinity(scip);
              if( !SCIPisInfinity(scip, ubslackvar) )
                downslacks[i] += coeffslackvar * ubgap;
              else
                downslacks[i] = SCIPinfinity(scip);
            }
            else
            {
               if( !SCIPisInfinity(scip, ubslackvar) )
                  upslacks[i] -= coeffslackvar * ubgap;
               else
                  upslacks[i] = SCIPinfinity(scip);
               if( !SCIPisInfinity(scip, lbslackvar) )
                  downslacks[i] -= coeffslackvar * lbgap;
               else
                  downslacks[i] = SCIPinfinity(scip);
            }
            SCIPdebugMessage("  Slack variable for row %s at pos %d: %g <= %s = %g <= %g; Coeff %g, upslack = %g, downslack = %g  \n",
               SCIProwGetName(row), SCIProwGetLPPos(row), lbslackvar, SCIPvarGetName(slackvars[i]), solvalslackvar, ubslackvar, coeffslackvar,
               upslacks[i], downslacks[i]);
         }
      }
      /* due to numerical inaccuracies, the rows might be feasible, even if the slacks are
       * significantly smaller than zero -> terminate
       */
      if( SCIPisFeasLT(scip, upslacks[i], 0.0) || SCIPisFeasLT(scip, downslacks[i], 0.0) )
         goto TERMINATE;
   }

   assert(nslacks == 0 || (upslacks != NULL && downslacks != NULL && activities != NULL));

   /* initialize number of remaining variables and flag to enter the main loop */
   currentlpcands = nlpcands;
   improvementfound = TRUE;

   /* iterate over variables as long as there are fractional variables left */
   while( currentlpcands > 0 && improvementfound && (heurdata->maxroundingloops == -1 || nroundings < heurdata->maxroundingloops) )
   {  /*lint --e{850}*/
      improvementfound = FALSE;
      nroundings++;
      SCIPdebugMessage("zirounding enters while loop for %d time with %d candidates left. \n", nroundings, currentlpcands);

      /* check for every remaining fractional variable if a shifting decreases ZI-value of the variable */
      for( c = 0; c < currentlpcands; ++c )
      {
         SCIP_VAR* var;
         SCIP_Real oldsolval;
         SCIP_Real upperbound;
         SCIP_Real lowerbound;
         SCIP_Real up;
         SCIP_Real down;
         SCIP_Real ziup;
         SCIP_Real zidown;
         SCIP_Real zicurrent;
         SCIP_Real shiftval;

         DIRECTION direction;

         /* get values from local data */
         oldsolval = solarray[c];
         var = zilpcands[c];

         assert(!SCIPisFeasIntegral(scip, oldsolval));
         assert(SCIPvarGetStatus(var) == SCIP_VARSTATUS_COLUMN);

         /* calculate bounds for variable and make sure that there are no numerical inconsistencies */
         upperbound = SCIPinfinity(scip);
         lowerbound = SCIPinfinity(scip);
         calculateBounds(scip, var, oldsolval, &upperbound, &lowerbound, upslacks, downslacks, nslacks, &numericalerror);

         if( numericalerror )
            goto TERMINATE;

         /* calculate the possible values after shifting */
         up   = oldsolval + upperbound;
         down = oldsolval - lowerbound;

         /* if the variable is integer or implicit binary, do not shift further than the nearest integer */
         if( SCIPvarGetType(var) != SCIP_VARTYPE_BINARY)
         {
            SCIP_Real ceilx;
            SCIP_Real floorx;

            ceilx = SCIPfeasCeil(scip, oldsolval);
            floorx = SCIPfeasFloor(scip, oldsolval);
            up   = MIN(up, ceilx);
            down = MAX(down, floorx);
         }

         /* calculate necessary values */
         ziup      = getZiValue(scip, up);
         zidown    = getZiValue(scip, down);
         zicurrent = getZiValue(scip, oldsolval);

         /* calculate the shifting direction that reduces ZI-value the most,
          * if both directions improve ZI-value equally, take the direction which improves the objective
          */
         if( SCIPisFeasLT(scip, zidown, zicurrent) || SCIPisFeasLT(scip, ziup, zicurrent) )
         {
            if( SCIPisFeasEQ(scip,ziup, zidown) )
               direction  = SCIPisFeasGE(scip, SCIPvarGetObj(var), 0.0) ? DIRECTION_DOWN : DIRECTION_UP;
            else if( SCIPisFeasLT(scip, zidown, ziup) )
               direction = DIRECTION_DOWN;
            else
               direction = DIRECTION_UP;

            /* once a possible shifting direction and value have been found, variable value is updated */
            shiftval = (direction == DIRECTION_UP ? up - oldsolval : down - oldsolval);

            /* this improves numerical stability in some cases */
            if( direction == DIRECTION_UP )
               shiftval = MIN(shiftval, upperbound);
            else
               shiftval = MIN(shiftval, lowerbound);
            /* update the solution */
            solarray[c] = direction == DIRECTION_UP ? up : down;
            SCIP_CALL( SCIPsetSolVal(scip, sol, var, solarray[c]) );

            /* update the rows activities and slacks */
            SCIP_CALL( updateSlacks(scip, sol, var, shiftval, upslacks,
                  downslacks, activities, slackvars, slackvarcoeffs, nslacks) );

            SCIPdebugMessage("zirounding update step : %d var index, oldsolval=%g, shiftval=%g\n",
               SCIPvarGetIndex(var), oldsolval, shiftval);
            /* since at least one improvement has been found, heuristic will enter main loop for another time because the improvement
             * might affect many LP rows and their current slacks and thus make further rounding steps possible */
            improvementfound = TRUE;
         }

         /* if solution value of variable has become feasibly integral due to rounding step,
          * variable is put at the end of remaining candidates array so as not to be considered in future loops
          */
         if( SCIPisFeasIntegral(scip, solarray[c]) )
         {
            zilpcands[c] = zilpcands[currentlpcands - 1];
            solarray[c] = solarray[currentlpcands - 1];
            currentlpcands--;

            /* counter is decreased if end of candidates array has not been reached yet */
            if( c < currentlpcands )
               c--;
         }
         else if( nroundings == heurdata->maxroundingloops - 1 )
            goto TERMINATE;
      }
   }

   /* in case that no candidate is left for rounding after the final main loop
    * the found solution has to be checked for feasibility in the original problem
    */
   if( currentlpcands == 0 )
   {
      SCIP_Bool stored;
      SCIP_CALL(SCIPtrySol(scip, sol, FALSE, FALSE, TRUE, FALSE, &stored));
      if( stored )
      {
#ifdef SCIP_DEBUG
         SCIPdebugMessage("found feasible rounded solution:\n");
         SCIP_CALL( SCIPprintSol(scip, sol, NULL, FALSE) );
#endif
         SCIPstatisticMessage("  ZI Round solution value: %g \n", SCIPgetSolOrigObj(scip, sol));

         *result = SCIP_FOUNDSOL;
      }
   }

   /* free memory for all locally allocated data */
 TERMINATE:
   SCIPfreeBufferArrayNull(scip, &activities);
   SCIPfreeBufferArrayNull(scip, &rowneedsslackvar);
   SCIPfreeBufferArrayNull(scip, &slackvarcoeffs);
   SCIPfreeBufferArrayNull(scip, &downslacks);
   SCIPfreeBufferArrayNull(scip, &upslacks);
   SCIPfreeBufferArrayNull(scip, &slackvars);
   SCIPfreeBufferArrayNull(scip, &zilpcands);
   SCIPfreeBufferArrayNull(scip, &solarray);

   return retcode;
}
Exemplo n.º 27
0
	AABox EditorUtility::calculateBounds(const HSceneObject& object)
	{
		Vector<HSceneObject> objects = { object };

		return calculateBounds(objects);
	}
Exemplo n.º 28
0
void BoundingBox::setDimensions(int w, int h)
{
    width = w;
    height = h;
    calculateBounds();
}
Exemplo n.º 29
0
bool ofxGpx::load(string _path) {
    if(XML.load(_path)){
        ofLog(OF_LOG_NOTICE, "Loaded " + _path);
        
        // metadataType
        if(XML.exists("metadata")) {
            XML.setTo("metadata[0]");
            
            if(XML.exists("name")) {
                gpxMetadata.name = XML.getValue<string>("name");
            }
            
            if(XML.exists("desc")) {
                gpxMetadata.desc = XML.getValue<string>("desc");
            }
            
            if(XML.exists("autor")) {
                //PersonType
            }
            
            if(XML.exists("copyright")) {
                //CopyrightType
            }
            
            if(XML.exists("link")) {
                //LinkType
            }
            
            if(XML.exists("time")) {
                gpxMetadata.time = XML.getValue<string>("//time");
            }
            
            if(XML.exists("keywords")) {
                gpxMetadata.keywords = XML.getValue<string>("keywords");
            }
            
            if(XML.exists("bounds")) {
                XML.setTo("bounds[0]");
                
                gpxMetadata.bounds_lonlat[0] = ofPoint(ofToFloat(XML.getAttribute("minlon")), ofToFloat(XML.getAttribute("minlat")));
                gpxMetadata.bounds_lonlat[1] = ofPoint(ofToFloat(XML.getAttribute("maxlon")), ofToFloat(XML.getAttribute("maxlat")));
                
                XML.setToParent();
            } else {
                gpxMetadata.bounds_lonlat[0] = ofPoint(180, 90);
                gpxMetadata.bounds_lonlat[1] = ofPoint(-180, -90);
            }
            
            XML.setToParent();
        }
        
        // wptType
        for(int i=0; XML.exists("wpt["+ofToString(i)+"]"); i++) {
            XML.setTo("wpt["+ofToString(i)+"]");
            
            GPXWPT point;
            
            double lat = ofToDouble(XML.getAttribute("lat"));
            double lon = ofToDouble(XML.getAttribute("lon"));
            double ele = XML.getValue<double>("ele");
            
            point.coor_lonlat = ofPoint(lon, lat, ele);
            point.coor_mercator = convertToMercator(point.coor_lonlat);
            
            if(XML.exists("time")) {
                point.time = XML.getValue<string>("time");
            }
            
            if(XML.exists("name")) {
                point.name = XML.getValue<string>("name");
            }
            
            if(XML.exists("cmt")) {
                point.cmt = XML.getValue<string>("cmt");
            }
            
            if(XML.exists("desc")) {
                point.desc = XML.getValue<string>("desc");
            }
            
            if(XML.exists("src")) {
                point.src = XML.getValue<string>("src");
            }
            
            if(XML.exists("link")) {
                //LinkType
            }
            
            calculateBounds(point.coor_lonlat);
            
            gpxWaypoints.push_back(point);
            XML.setToParent();
        }
        
        // rteType
        for(int i=0; XML.exists("rte["+ofToString(i)+"]"); i++) {
            XML.setTo("rte["+ofToString(i)+"]");
            
            if(XML.getName() != "rte") {
                break;
            }
            
            GPXRTE route;
            
            if(XML.exists("name")) {
                route.name = XML.getValue<string>("name");
            }
            
            if(XML.exists("cmt")) {
                route.cmt = XML.getValue<string>("cmt");
            }
            
            if(XML.exists("desc")) {
                route.desc = XML.getValue<string>("desc");
            }
            
            if(XML.exists("src")) {
                route.src = XML.getValue<string>("src");
            }
            
            if(XML.exists("link")) {
                //LinkType
            }
            
            if(XML.exists("number")) {
                route.number = XML.getValue<int>("number");
            }
            
            if(XML.exists("type")) {
                route.type = XML.getValue<string>("type");
            }
            
            if(XML.exists("rtept")) {
                XML.setTo("rtept[0]");

                do {
                    GPXWPT point;
                    
                    double lat = ofToDouble(XML.getAttribute("lat"));
                    double lon = ofToDouble(XML.getAttribute("lon"));
                    double ele = XML.getValue<double>("ele");
                    
                    point.coor_lonlat = ofPoint(lon, lat, ele);
                    point.coor_mercator = convertToMercator(point.coor_lonlat);
                    
                    if(XML.exists("time")) {
                        point.time = XML.getValue<string>("time");
                    }
                    
                    if(XML.exists("name")) {
                        point.name = XML.getValue<string>("name");
                    }
                    
                    if(XML.exists("cmt")) {
                        point.cmt = XML.getValue<string>("cmt");
                    }
                    
                    if(XML.exists("desc")) {
                        point.desc = XML.getValue<string>("desc");
                    }
                    
                    if(XML.exists("src")) {
                        point.src = XML.getValue<string>("src");
                    }
                    
                    if(XML.exists("link")) {
                        //LinkType
                    }
                    
                    calculateBounds(point.coor_lonlat);
                    
                    route.rtept.push_back(point);
                }
                while(XML.setToSibling());
                
                XML.setToParent();
            }
            
            gpxRoutes.push_back(route);
            XML.setToParent();
        }
        
        // trkType
        for(int i=0; XML.exists("trk["+ofToString(i)+"]"); i++) {
            XML.setTo("trk["+ofToString(i)+"]");
            
            GPXTRK track;

            if(XML.exists("name")) {
                track.name = XML.getValue<string>("name");
            }
            
            if(XML.exists("cmt")) {
                track.cmt = XML.getValue<string>("cmt");
            }
            
            if(XML.exists("desc")) {
                track.desc = XML.getValue<string>("//desc");
            }
            
            if(XML.exists("src")) {
                track.src = XML.getValue<string>("//src");
            }
            
            if(XML.exists("link")) {
                //LinkType
            }
            
            if(XML.exists("number")) {
                track.number = XML.getValue<int>("number");
            }
            
            if(XML.exists("type")) {
                track.type = XML.getValue<string>("type");
            }
            
            vector<GPXTRKSEG> tracksegments;
            for(int j=0; XML.exists("trkseg["+ofToString(j)+"]"); j++) {
                XML.setTo("trkseg["+ofToString(j)+"]trkpt[0]");

                GPXTRKSEG tracksegment;

                do {
                    GPXWPT point;
                    
                    double lat = ofToDouble(XML.getAttribute("lat"));
                    double lon = ofToDouble(XML.getAttribute("lon"));
                    double ele = XML.getValue<double>("ele");
                    
                    point.coor_lonlat = ofPoint(lon, lat, ele);
                    point.coor_mercator = convertToMercator(point.coor_lonlat);
                    
                    if(XML.exists("time")) {
                        point.time = XML.getValue<string>("time");
                    }
                    
                    if(XML.exists("name")) {
                        point.name = XML.getValue<string>("name");
                    }
                    
                    if(XML.exists("cmt")) {
                        point.cmt = XML.getValue<string>("cmt");
                    }
                    
                    if(XML.exists("desc")) {
                        point.desc = XML.getValue<string>("desc");
                    }
                    
                    if(XML.exists("src")) {
                        point.src = XML.getValue<string>("src");
                    }
                    
                    if(XML.exists("link")) {
                        //LinkType
                    }
                    
                    calculateBounds(point.coor_lonlat);
                    
                    tracksegment.trkpt.push_back(point);
                }
                while(XML.setToSibling());
                
                tracksegments.push_back(tracksegment);
                
                XML.setToParent();
                XML.setToParent();
            }
            
            XML.setToParent();
            
            track.trkseg = tracksegments;
            gpxTracks.push_back(track);
        }
        
        gpxMetadata.bounds_mercator[0] = convertToMercator(gpxMetadata.bounds_lonlat[0]);
        gpxMetadata.bounds_mercator[1] = convertToMercator(gpxMetadata.bounds_lonlat[1]);
        
        return true;
    } else {
        // not found or parsing error
        ofLog(OF_LOG_ERROR, "Could not load " + _path);
        
        return false;
    }
};
Exemplo n.º 30
0
// Return URC bounding values, calculating first if necessary
Vec3<double> Grid::upperRightCorner()
{
	if (boundsLog_ != log_) calculateBounds();
	return upperRightCorner_;
}