Beispiel #1
0
//=====================================================
void GlCurve::draw(float, Camera *) {
  //    tlp::warning() << ".";

  glDisable(GL_CULL_FACE);
  glDisable(GL_LIGHTING);
  //glEnable(GL_COLOR_MATERIAL);
  vector<Coord> newPoints(_points.size());

  for(unsigned int i=0; i < _points.size(); ++i) {
    newPoints[i] = _points[i];
  }

  glLineWidth(2);
  glPushAttrib(GL_ALL_ATTRIB_BITS);
  tlp::splineLine(newPoints,
                  _beginFillColor,
                  _endFillColor);
  glPopAttrib();

  if(texture!="") {
    GlTextureManager::getInst().activateTexture(texture);
  }

  tlp::splineQuad(newPoints,
                  _beginFillColor,
                  _endFillColor,
                  _beginSize,
                  _endSize,
                  newPoints[0] - Coord(1.  , 0.0, 0.),
                  newPoints[3] + Coord(1.  , 0.0, 0.));

  GlTextureManager::getInst().desactivateTexture();
  glEnable(GL_LIGHTING);
  glEnable(GL_CULL_FACE);
}
void Foam::layeredEngineMesh::move()
{
    scalar deltaZ = engineDB_.pistonDisplacement().value();
    Info<< "deltaZ = " << deltaZ << endl;

    // Position of the top of the static mesh layers above the piston
    scalar pistonPlusLayers = pistonPosition_.value() + pistonLayers_.value();

    pointField newPoints(points());

    forAll(newPoints, pointi)
    {
        point& p = newPoints[pointi];

        if (p.z() < pistonPlusLayers)           // In piston bowl
        {
            p.z() += deltaZ;
        }
        else if (p.z() < deckHeight_.value())   // In liner region
        {
            p.z() +=
                deltaZ
               *(deckHeight_.value() - p.z())
               /(deckHeight_.value() - pistonPlusLayers);
        }
    }
    void SwaptionVolCube1::Cube::expandLayers(
                                                 Size i, bool expandOptionTimes,
                                                 Size j, bool expandSwapLengths) {
        QL_REQUIRE(i<=optionTimes_.size(),"Cube::expandLayers: incompatible size 1");
        QL_REQUIRE(j<=swapLengths_.size(),"Cube::expandLayers: incompatible size 2");

        if (expandOptionTimes) {
            optionTimes_.insert(optionTimes_.begin()+i,0.);
            optionDates_.insert(optionDates_.begin()+i, Date());
        }
        if (expandSwapLengths) {
            swapLengths_.insert(swapLengths_.begin()+j,0.);
            swapTenors_.insert(swapTenors_.begin()+j, Period());
        }

        std::vector<Matrix> newPoints(nLayers_,Matrix(optionTimes_.size(),
                                                      swapLengths_.size(), 0.));

        for (Size k=0; k<nLayers_; ++k) {
            for (Size u=0; u<points_[k].rows(); ++u) {
                 Size indexOfRow = u;
                 if (u>=i && expandOptionTimes) indexOfRow = u+1;
                 for (Size v=0; v<points_[k].columns(); ++v) {
                      Size indexOfCol = v;
                      if (v>=j && expandSwapLengths) indexOfCol = v+1;
                      newPoints[k][indexOfRow][indexOfCol]=points_[k][u][v];
                 }
            }
        }
        setPoints(newPoints);
    }
Beispiel #4
0
void QLCDNumberPrivate::internalSetString(const QString& s)
{
    Q_Q(QLCDNumber);
    QString buffer;
    int i;
    int len = s.length();
    QBitArray newPoints(ndigits);

    if (!smallPoint) {
        if (len == ndigits)
            buffer = s;
        else
            buffer = s.right(ndigits).rightJustified(ndigits, QLatin1Char(' '));
    } else {
        int  index = -1;
        bool lastWasPoint = true;
        newPoints.clearBit(0);
        for (i=0; i<len; i++) {
            if (s[i] == QLatin1Char('.')) {
                if (lastWasPoint) {           // point already set for digit?
                    if (index == ndigits - 1) // no more digits
                        break;
                    index++;
                    buffer[index] = QLatin1Char(' ');        // 2 points in a row, add space
                }
                newPoints.setBit(index);        // set decimal point
                lastWasPoint = true;
            } else {
                if (index == ndigits - 1)
                    break;
                index++;
                buffer[index] = s[i];
                newPoints.clearBit(index);      // decimal point default off
                lastWasPoint = false;
            }
        }
        if (index < ((int) ndigits) - 1) {
            for(i=index; i>=0; i--) {
                buffer[ndigits - 1 - index + i] = buffer[i];
                newPoints.setBit(ndigits - 1 - index + i,
                                   newPoints.testBit(i));
            }
            for(i=0; i<ndigits-index-1; i++) {
                buffer[i] = QLatin1Char(' ');
                newPoints.clearBit(i);
            }
        }
    }

    if (buffer == digitStr)
        return;

    digitStr = buffer;
    if (smallPoint)
        points = newPoints;
    q->update();
}
Beispiel #5
0
void
MainWindow::newPointSet()
{
  bool ok;

  int numberOfPoints = QInputDialog::getInt(this,
      "Periodic Lloyd", "Number of points: ", 100, 0, 2147483647, 1, &ok );
  
  if (ok) newPoints(numberOfPoints);
}
Beispiel #6
0
void Spline::refineAt(real knotValue, uint multiplicity) {
    //A multiplicity of 0 would mean no knot insertion and
    //an insertion with multiplicity > m_degree would lead to a hole in the spline curve!
    if(multiplicity == 0 || multiplicityOfKnotValue(knotValue) + multiplicity > m_degree)
        return;
    //Use de Boor scheme to get the new point(s)
    uint n = lowerNextKnot(knotValue); // knotValue is element of [knot[n], knot[n+1])
    vector<vec2> controlPointsCopy(m_degree + 1);
    for(uint i = 0; i <= m_degree; ++i) {
        controlPointsCopy[i] = m_controlPoints.at(n - m_degree + 1 + i);
    }

    vector<vec2> newPoints(m_degree + multiplicity - 1);

    //When the new knotVaue is inserted r-times (multiplicity = r) the new points are equal
    //to the points of the de boor scheme in the r-th column and the outer way to this column
    for(uint i = 1; i <= multiplicity; ++i) {

        //do only one step of the de boor algorithm each iteration
        //and only multiplicity times
        //(so for multiplicity == 1 only one step is done)
        deBoor(controlPointsCopy, knotValue, n, m_degree - i + 1, m_degree - i);

        if(i == multiplicity) {
            //copy all up to now calculated points to the new points
            //except first one, which didn't change (exists already in spline)
            for(uint j = 1; j <= m_degree; ++j) {
                newPoints[j - 1] = controlPointsCopy.at(j);
            }

        } else {
            //copy only last point, as it will be overwritten in next deBoor step
            newPoints[newPoints.size() - i] = controlPointsCopy.back();
        }
    }

    //copy now new points into control points vector:
    m_controlPoints.resize(m_controlPoints.size() + multiplicity);
    int n_int = (int) n;
    int i = m_controlPoints.size() - 1 - multiplicity;
    for(; i > n_int; --i) {
        m_controlPoints[i + multiplicity] = m_controlPoints.at(i);
    }
    //do NOT replace 'int j' by 'uint j'!!!
    for(int j = newPoints.size() - 1; j >= 0; --j, --i) {
        m_controlPoints[i + multiplicity] = newPoints[j];
    }
    for(uint k = 1; k <= multiplicity; ++k) {
        m_knots.insert(m_knots.begin() + n + k, knotValue);
    }
}
int main(int argc, char *argv[])
{
#   include "setRootCase.H"
#   include "createTime.H"
#   include "createMesh.H"

    Info<< "Mesh read in = "
        << runTime.cpuTimeIncrement()
        << " s\n" << endl << endl;


    Info<< "Time now = " << runTime.timeName() << endl;

    // Wall distance

    wallDist y(mesh, true);

    if (y.nUnset() != 0)
    {
        WarningIn(args.executable())
            << "There are " << y.nUnset()
            << " remaining unset cells and/or boundary values" << endl;
    }



    y.write();


    runTime++;

    Info<< "Time now = " << runTime.timeName() << endl;


    // Move points

    boundBox meshBb(mesh.points());

    pointField newPoints(mesh.points());

    const point half(0.5*(meshBb.min() + meshBb.max()));

    forAll(newPoints, pointI)
    {
        point& pt = newPoints[pointI];

        // expand around half
        pt.y() +=  pt.y() - half.y();
    }
Foam::mirrorFvMesh::mirrorFvMesh(const IOobject& io)
:
    fvMesh(io),
    mirrorMeshDict_
    (
        IOobject
        (
            "mirrorMeshDict",
            time().system(),
            *this,
            IOobject::MUST_READ,
            IOobject::NO_WRITE
        )
    ),
    mirrorMeshPtr_(NULL)
{
    plane mirrorPlane(mirrorMeshDict_);

    scalar planeTolerance
    (
        readScalar(mirrorMeshDict_.lookup("planeTolerance"))
    );

    const pointField& oldPoints = points();
    const faceList& oldFaces = faces();
    const cellList& oldCells = cells();
    const label nOldInternalFaces = nInternalFaces();
    const polyPatchList& oldPatches = boundaryMesh();

    // Mirror the points
    Info << "Mirroring points. Old points: " << oldPoints.size();

    pointField newPoints(2*oldPoints.size());
    label nNewPoints = 0;

    labelList mirrorPointLookup(oldPoints.size(), -1);

    // Grab the old points
    forAll (oldPoints, pointI)
    {
        newPoints[nNewPoints] = oldPoints[pointI];
        nNewPoints++;
    }
Beispiel #9
0
int SimplePolygon::intersectPolygon( DCTPVec2dvector &globalverts, simplepolygonvector &polylist )
{
  int oldNum = vertices.size();
  int i1, i2;
  Vec2d min, max;
  Vec2d p3, p4;
  unsigned char test, ptest;

//  std::cerr << "Removing intersections... " << oldNum << std::endl;

  for( i2 = 2; i2 < oldNum; ++i2 )
  {
    const Vec2d &p1 = globalverts[ vertices[ i2 ] ];
    const Vec2d &p2 = globalverts[ vertices[ ( i2 + 1 ) % oldNum ] ];

    min = max = p1;
    if( min[0] > p2[0] )
      min[0] = p2[0];
    else if( max[0] < p2[0] )
      max[0] = p2[0];
    if( min[1] > p2[1] )
      min[1] = p2[1];
    else if( max[1] < p2[1] )
      max[1] = p2[1];

    const unsigned int start = ( i2 == oldNum - 1 ) ? 1 : 0;

    p4 = globalverts[ vertices[ start ] ];
    test = 0;
    if( p4[0] - max[0] > DCTP_EPS ) test |= 0x01;
    if( min[0] - p4[0] > DCTP_EPS ) test |= 0x02;
    if( p4[1] - max[1] > DCTP_EPS ) test |= 0x04;
    if( min[1] - p4[1] > DCTP_EPS ) test |= 0x08;

    for( i1 = start; i1 < i2 - 1; ++i1 )
    {
      p3 = p4;
      p4 = globalverts[ vertices[ i1 + 1 ] ];
      ptest = test;
      test = 0;
      if( p4[0] - max[0] > DCTP_EPS ) test |= 0x01;
      if( min[0] - p4[0] > DCTP_EPS ) test |= 0x02;
      if( p4[1] - max[1] > DCTP_EPS ) test |= 0x04;
      if( min[1] - p4[1] > DCTP_EPS ) test |= 0x08;
      if( ( test & ptest ) == 0 )
      {
//         std::cerr << i1 << "," << i1 + 1 << " overlaps " << i2 << "," << i2 + 1 << std::endl;
        // the bounding boxes overlap
        int iip = -1;
        bool intersect = false;
        double d1[ 2 ] = { p1[0], p1[1] };
        double d2[ 2 ] = { p2[0], p2[1] };
        double d3[ 2 ] = { p3[0], p3[1] };
        double d4[ 2 ] = { p4[0], p4[1] };

        if( ( orient2d( d1, d2, d3 ) == 0.0 ) &&
            ( orient2d( d1, d2, d4 ) == 0.0 ) )
        {
          // the lines are colinear => ... p1 p4 ... ; p2 ... p3
          intersect = true;
        }
        else
        {
          if( doIntersect( globalverts, i1, i1 + 1, i2, ( i2 + 1 ) % oldNum ) )
          {
            // the lines intersect => ... p1 ip p4 ... ; ip p2 ... p3
            Vec2d v1 = p2 - p1;
            Vec2d v2 = p4 - p3;
            Vec2d pp = p3 - p1;
            double a = pp[0] * v2[1] - pp[1] * v2[0];
            double b = v1[0] * v2[1] - v1[1] * v2[0];
            Vec2d ip = p1 + v1 * ( a / b );

            if( DCTPVecIsEqual( ip , p1 ) )
            {
              iip = vertices[ i1 ];
            }
            else if( DCTPVecIsEqual( ip , p2 ) )
            {
              iip = vertices[ i1 + 1 ];
            }
            else if( DCTPVecIsEqual( ip , p3 ) )
            {
              iip = vertices[ i2 ];
            }
            else if( DCTPVecIsEqual( ip , p4 ) )
            {
              iip = vertices[ ( i2 + 1 ) % oldNum ];
            }
            else
            {
              iip = globalverts.size();
              globalverts.resize( iip + 1 );
              globalverts[ iip ] = ip;
            }

//			std::cerr << p1[0] << "," << p1[1] << " - " << p2[0] << "," << p2[1] << std::endl;
//			std::cerr << p3[0] << "," << p3[1] << " - " << p4[0] << "," << p4[1] << std::endl;
//			std::cerr << globalverts[ iip ][0] << "," << globalverts[ iip ][1] << " - " << std::endl;
            intersect = true;
          }
        }
        if( intersect )
        {
          int i;
          int newNum;
          DCTPivector newPoints( oldNum );
          SimplePolygon poly;

//          std::cerr << i1 << "," << i1 + 1 << " intersects " << i2 << "," << i2 + 1 << std::endl;

          // copy points 0 ... i1
          for( i = 0; i <= i1; ++i )
          {
            newPoints[ i ] = vertices[ i ];
          }
          newNum = i;

          // copy iip's
          if( iip >= 0 )
          {
            if( ( iip != vertices[ i1 ] ) &&
                ( iip != vertices[ ( i2 + 1 ) % oldNum ] ) )
            {
              newPoints[ newNum ] = iip;
              ++newNum;
            }
            if( ( iip != vertices[ i2 ] ) &&
                ( iip != vertices[ i1 + 1 ] ) )
            {
              poly.vertices.resize( i2 + 1 - i1 );
              poly.vertices[ i2 - i1 ] = iip;
            }
            else
            {
              poly.vertices.resize( i2 - i1 );
            }
          }
          else
          {
            poly.vertices.resize( i2 - i1 );
          }

          // copy i1+1 ... i2
          for( i = 0; i < i2 - i1; ++i )
          {
            poly.vertices[ i ] = vertices[ i1 + i + 1 ];
          }

          // copy i2+1 ... n
          for( i = i2 + 1; i < oldNum; ++i )
          {
            newPoints[ newNum ] = vertices[ i ];
            ++newNum;
          }

          // copy new points back to polygon
          vertices.resize( newNum );
          for( i2 = 0; i2 < newNum; ++i2 )
          {
            vertices[ i2 ] = newPoints[ i2 ];
          }

//          std::cerr << "split in " << newNum << "," << poly.vertices.size() << std::endl;

          // triangulate the new polygon
          while( poly.intersectPolygon( globalverts, polylist ) ) { }
          if( poly.isReversed( globalverts ) )
          {
//            std::cerr << "Ignoring reversed polygon." << std::endl;
          }
          else
          {
            // Ok, we have a valid polygon, so triangulate it.
            poly.triangulate( globalverts, polylist );
          }

          // check if there are other intersections
          return 1;
        }
      }
    }
  }

  // polygon had no intersections so we are finished
  return 0;
}
Beispiel #10
0
int SimplePolygon::splitPolygon( DCTPVec2dvector &globalverts, simplepolygonvector &polylist, const Vec2d min, const Vec2d max )
{
  DCTPVec2dset vset;
  std::pair< DCTPVec2dset::iterator, bool > siv;
  int oldNum = vertices.size();
  int i1;

//  std::cerr << "Removing double vertices... " << oldNum << std::endl;

  for( i1 = 0; i1 < oldNum; ++i1 )
  {
    siv = vset.insert( globalverts[ vertices[ i1 ] ] );
    if( !siv.second )
    {
      // here we need to split the polygon and start with the new ones again.
      int i;
      DCTPivector newPoints( oldNum ); // waste some memory to have nlogn time
      int newNum = 0;
      int i2 = 0;
      SimplePolygon poly;

      // copy points before first intersection
      while( DCTPVecIsNotEqual( globalverts[ vertices[ i2 ] ] , globalverts[ vertices[ i1 ] ] ) )
      {
        newPoints[ i2 ] = vertices[ i2 ];
        ++i2;
      }
      newNum = i2;

//      std::cerr << i2 << " = " << i1 << std::endl;

      // construct new polygon
      poly.vertices.resize( i1 - i2 );
      for( i = i2; i < i1; ++i )
      {
        poly.vertices[ i - i2 ] = vertices[ i ];
//        std::cerr << vertices[ i ] << " ";
      }
//      std::cerr << std::endl;

      // copy points from second intersection to the end
      for( i = i1; i < oldNum; ++i )
      {
        newPoints[ newNum ] = vertices[ i ];
        ++newNum;
      }

      // copy new points back to polygon
      vertices.resize( newNum );
      for( i = 0; i < newNum; ++i )
      {
        vertices[ i ] = newPoints[ i ];
//        std::cerr << vertices[ i ] << " ";
      }
//      std::cerr << std::endl;

      // triangulate the new polygon
//      std::cerr << oldNum << " split in " << vertices.size() << "," << poly.vertices.size() << std::endl;
      // need to check for new liear points
//      while( poly.removeLinearPoints( globalverts, min, max ) ) { }
      while( poly.intersectPolygon( globalverts, polylist ) ) { }
      if( poly.isReversed( globalverts ) )
      {
//        std::cerr << "Ignoring reversed polygon." << std::endl;
      }
      else
      {
        // Ok, we have a valid polygon, so triangulate it.
        poly.triangulate( globalverts, polylist );
      }

      // need to check for new liear points
//      while( removeLinearPoints( globalverts, min, max ) ) { }
      // check if there are other double vertices
      return 1;
    }
  }

  // polygon had no double vertices so we are finished
  return 0;
}
Beispiel #11
0
/*!
 *  Note that this has complexity O(n).
 *
 *  \param globalverts the global vertices vector
 *  \return zero on success, and a negative integer if some error occured.
 */
int SimplePolygon::removeLinearPoints( DCTPVec2dvector &globalverts, const Vec2d min, const Vec2d max )
{
  int oldNum = vertices.size( );
  int newNum = 0;
  DCTPivector newPoints( oldNum ); // waste some memory to have linear time
  int i;
  int last = oldNum - 1;

//  std::cerr << "Removing linear points... " << oldNum << std::endl;

  // insert nonlienaer points in new array
  for( i = 0; i < oldNum; ++i )
  {
    Vec2d p = globalverts[ vertices[ i ] ];
    // check for double vertices
    if( DCTPVecIsNotEqual( p , globalverts[ vertices[ last ] ] ) )
    {
      Vec2d pp = globalverts[ vertices[ last ] ];
      Vec2d pn = globalverts[ vertices[ ( i + 1 ) % oldNum ] ];

      if( ( ( p[0] - min[0] < DCTP_EPS ) && ( pn[0] - min[0] < DCTP_EPS ) ) ||
          ( ( p[1] - min[1] < DCTP_EPS ) && ( pn[1] - min[1] < DCTP_EPS ) ) ||
          ( ( max[0] - p[0] < DCTP_EPS ) && ( max[0] - pn[0] < DCTP_EPS ) ) ||
          ( ( max[1] - p[1] < DCTP_EPS ) && ( max[1] - pn[1] < DCTP_EPS ) ) )
      {
        newPoints[ newNum ] = vertices[ i ];
        ++newNum;
        last = i;
      }
      else
      {
        double d1[ 2 ], d2[ 2 ], d3[ 2 ];
        d1[ 0 ] = pp[0];
        d1[ 1 ] = pp[1];
        d2[ 0 ] = p[0];
        d2[ 1 ] = p[1];
        d3[ 0 ] = pn[0];
        d3[ 1 ] = pn[1];
        if( orient2d( d1, d2, d3 ) != 0 )
        {
          newPoints[ newNum ] = vertices[ i ];
          ++newNum;
          last = i;
        }
/*        else if( ( pp[1] != pn[1] ) && ( pp[0] != pn[0] ) )
        {
          std::cerr << "removing point " <<std::endl;
          std::cerr << pp[0] << "," << pp[1] << std::endl;
          std::cerr << "(" << p[0] << "," << p[1] << ")" << std::endl;
          std::cerr << pn[0] << "," << pn[1] << std::endl;
          char x[ 256 ];
          gets( x );
        }*/
      }
    }
  }

//  std::cerr << newNum << " points left." << std::endl;

  // copy new points
  if( newNum != oldNum )
  {
    vertices.resize( newNum );
    for( i = 0; i < newNum; ++i )
    {
      vertices[ i ] = newPoints[ i ];
    }
    return 1;
  }

  return 0;
}
Beispiel #12
0
void QLCDNumber::internalSetString( const QString& s )
{
    QString buffer;
    int i;
    int len = s.length();
    QBitArray newPoints(ndigits);

    if ( !smallPoint ) {
	if ( len == ndigits )
	    buffer = s;
	else
	    buffer = s.right( ndigits ).rightJustify( ndigits, ' ' );
    } else {
	int  index = -1;
	bool lastWasPoint = TRUE;
	newPoints.clearBit(0);
	for ( i=0; i<len; i++ ) {
	    if ( s[i] == '.' ) {
		if ( lastWasPoint ) {		// point already set for digit?
		    if ( index == ndigits - 1 ) // no more digits
			break;
		    index++;
		    buffer[index] = ' ';	// 2 points in a row, add space
		}
		newPoints.setBit(index);	// set decimal point
		lastWasPoint = TRUE;
	    } else {
		if ( index == ndigits - 1 )
		    break;
		index++;
		buffer[index] = s[i];
		newPoints.clearBit(index);	// decimal point default off
		lastWasPoint = FALSE;
	    }
	}
	if ( index < ((int) ndigits) - 1 ) {
	    for( i=index; i>=0; i-- ) {
		buffer[ndigits - 1 - index + i] = buffer[i];
		newPoints.setBit( ndigits - 1 - index + i,
				   newPoints.testBit(i) );
	    }
	    for( i=0; i<ndigits-index-1; i++ ) {
		buffer[i] = ' ';
		newPoints.clearBit(i);
	    }
	}
    }

    if ( buffer == digitStr )
	return;

    if ( backgroundMode() == FixedPixmap
	 || colorGroup().brush( QColorGroup::Background ).pixmap() ) {
	digitStr = buffer;
	if ( smallPoint )
	    points = newPoints;
	repaint( contentsRect() );
    }
    else {
	QPainter p( this );
	if ( !smallPoint )
	    drawString( buffer, p );
	else
	    drawString( buffer, p, &newPoints );
    }
}
Beispiel #13
0
MStatus puttyNode::deform( MDataBlock& block, MItGeometry& iter, const MMatrix& worldMatrix, unsigned int multiIndex)
{
//	MGlobal::displayInfo("deform");
    MStatus status = MS::kSuccess;

    /////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // get inputs
    //
	
	// get the node ready flag
	MDataHandle dh = block.inputValue(aScriptSourced,&status);
	SYS_ERROR_CHECK(status, "Error getting aScriptSourced data handle\n");
	bool scriptSourced = dh.asBool();
	if (!scriptSourced)
		return MS::kSuccess;


	dh = block.inputValue(aNodeReady,&status);
	SYS_ERROR_CHECK(status, "Error getting node ready data handle\n");
	bool nodeReady = dh.asBool();

	// if it's not ready, don't do anything
	if (!nodeReady)
		return MS::kSuccess;

    dh = block.inputValue(aDefSpace,&status);
    SYS_ERROR_CHECK(status, "Error getting defSpace data handle\n");
    short defSpace = dh.asShort();
    
    dh = block.inputValue(aDefWeights,&status);
    SYS_ERROR_CHECK(status, "Error getting defWeights data handle\n");
    short defWeights = dh.asShort();
 
    dh = block.inputValue(aDefEnvelope,&status);
    SYS_ERROR_CHECK(status, "Error getting defEnvelope data handle\n");
    short defEnvelope = dh.asShort();
    

    
    // get the command
    dh = block.inputValue(aCmdBaseName,&status);
    SYS_ERROR_CHECK(status, "Error getting aCmdBaseName  handle\n");    
    MString script =  dh.asString(); 
        
 /*   if (script == "")
    {
        status = MS::kFailure;
        USER_ERROR_CHECK(status, "no script provided!\n");    
    }
   */ 
    /////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // build mel cmd string
    //
    
    // check if it's a valid cmd
        
   
    // get the envelope
    //
    double env = 1;
    
    if (defEnvelope == MSD_ENVELOPE_AUTO)
    {
        dh = block.inputValue(envelope,&status);
    	SYS_ERROR_CHECK(status, "Error getting envelope data handle\n");	
	    env = double(dh.asFloat());	
        
        // early stop 'cause there is nothing more to do
        if (env == 0.0)
            return MS::kSuccess;
    }
    
    // get the points, transform them into the right space if needed
    //
    int count = iter.count();
    MVectorArray points(count);
    for ( ; !iter.isDone(); iter.next()) 
        points[iter.index()] = iter.position();
        
    if ( defSpace == MSD_SPACE_WORLD )
    {
        for (int i = 0;i<count;i++)
            points[i] = MPoint(points[i]) * worldMatrix;
    }
    
    
    // get the weights
    //
    MDoubleArray weights;
    if ( defWeights == MSD_WEIGHTS_AUTO)
    {
        weights.setLength(count);
        
        for (int i = 0;i<count;i++)
            weights[i]  = weightValue(block,multiIndex,i);
        
    }


    // get the object name and type
    // get the input geometry, traverse through the data handles    
    MArrayDataHandle adh = block.outputArrayValue( input, &status );
    SYS_ERROR_CHECK(status,"error getting input array data handle.\n");

    status = adh.jumpToElement( multiIndex );
    SYS_ERROR_CHECK(status, "input jumpToElement failed.\n");

    // compound data 
    MDataHandle cdh = adh.inputValue( &status );
    SYS_ERROR_CHECK(status, "error getting input inputValue\n");
   
    // input geometry child
    dh = cdh.child( inputGeom );
    MObject dInputGeometry = dh.data();
   
    // get the type      
    MString geometryType = dInputGeometry.apiTypeStr();

    // get the name    
//    MFnDagNode dagFn( dInputGeometry, &status);
//    SYS_ERROR_CHECK(status, "error converting geometry obj to dag node\n");
   
//    MString geometryName = dagFn.fullPathName(&status);
//    SYS_ERROR_CHECK(status, "error getting full path name \n");

//    MString geometryType = "";
//    MString geometryName = "";
    
    /////////////////////////////////////////////////////////////////////////////////////////////////
    //  
    //  set the current values on the temp plugs for the script to be picked up
    //
    
    // the position
    MObject thisNode = thisMObject();
    
    MPlug currPlug(thisNode,aCurrPosition);
    MFnVectorArrayData vecD;
    MObject currObj = vecD.create(points,&status);
    currPlug.setValue(currObj);
    SYS_ERROR_CHECK(status, "error setting currPosPlug value\n");
    
    // the weights
    currPlug =MPlug(thisNode,aCurrWeight);
    MFnDoubleArrayData dblD;
    currObj = dblD.create(weights,&status);
    currPlug.setValue(currObj);
    SYS_ERROR_CHECK(status, "error setting currWeightsPlug value\n");
    
    // world matrix
    currPlug =MPlug(thisNode,aCurrWorldMatrix);
    MFnMatrixData matD;
    currObj = matD.create(worldMatrix,&status);
    currPlug.setValue(currObj);
    SYS_ERROR_CHECK(status, "error setting currWorldMatrixPlug value\n");

    // the multi index
    currPlug =MPlug(thisNode,aCurrMultiIndex);
    currPlug.setValue(int(multiIndex));
    SYS_ERROR_CHECK(status, "error setting currMultiIndexPlug value\n");
    
    // geometry name/type
//    currPlug =MPlug(thisNode,aCurrGeometryName);
//    currPlug.setValue(geometryName);
//    SYS_ERROR_CHECK(status, "error setting aCurrGeometryName value\n");

    currPlug =MPlug(thisNode,aCurrGeometryType);
    currPlug.setValue(geometryType);
    SYS_ERROR_CHECK(status, "error setting aCurrGeometryType value\n");

   
    /////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // execute the mel script
    //
    MString melCmd = script+"(\"" +name()+"\","+count+")";
    
    MCommandResult melResult;
    status = MGlobal::executeCommand(melCmd,melResult);
	
	// if the command did not work, then try to resource the script
	// (might have been that we were in a fresh scene and nothing was ready yet
	if (status != MS::kSuccess)
	{
		dh = block.inputValue(aScript,&status);
	    SYS_ERROR_CHECK(status, "Error getting aCmdBaseName  handle\n");    
		MString scriptFile =  dh.asString(); 	

		// try to source the script
		MString cmd = "source \"" + scriptFile+"\"";
			
		MCommandResult melResult;
		status = MGlobal::executeCommand(cmd,melResult);
		// if successfull, retry the command 
		if (!status.error())
		{
			status = MGlobal::executeCommand(melCmd,melResult);
		}
	}

	USER_ERROR_CHECK(status, "Error executing mel command, please check the function you provided is valid, error free and has the appropriate parameters!");

    // check the result type
    if ((melResult.resultType()) != (MCommandResult::kDoubleArray))
    {
        USER_ERROR_CHECK(MS::kFailure, "result of mel command has wrong type, should be doubleArray (which will be interpreted as vectorArray)!");
    }
    
    // get the result as a double array
    MDoubleArray newP;  
    status = melResult.getResult(newP);
    USER_ERROR_CHECK(status, "Error getting result of mel command!");
    
    int newCount = newP.length()/3;
    // size check
    if (newCount != count)
    {
        USER_ERROR_CHECK(MS::kFailure, "the size of the result does not match the size of the input!");
    }

    // convert the double array into a vector array
    MPointArray newPoints(newCount);
    
    for(int i=0;i<newCount;i++)
        newPoints[i]=MPoint(newP[i*3],newP[i*3+1],newP[i*3+2]);
    
    /////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // interprete and apply the result
    //


  
    // do the envelope and weights   
    if ((defEnvelope == MSD_ENVELOPE_AUTO)||((defWeights == MSD_WEIGHTS_AUTO)))
    {
        MDoubleArray envPP(count, env);
    
        if (defWeights == MSD_WEIGHTS_AUTO)
        { 
            for (int i = 0;i<count;i++)
                envPP[i] *= weights[i];
        }

        // linear interpolation between old and new points
        for (int i = 0;i<count;i++)
            newPoints[i] = (points[i] * (1-envPP[i])) + (newPoints[i] * envPP[i]);
    }


    // retransform the result if it was in world space
    if ( defSpace == MSD_SPACE_WORLD )
    {
        MMatrix worldMatrixInv = worldMatrix.inverse();
        
        for (int i = 0;i<count;i++)
            newPoints[i] *= worldMatrixInv;
    }
 
 
    // set the points    
    iter.reset();
  	for ( ; !iter.isDone(); iter.next()) 
     	iter.setPosition(newPoints[iter.index()]);    

    return status;
}
// Collapses small edge to point, thus removing triangle.
label collapseEdge(triSurface& surf, const scalar minLen)
{
    label nTotalCollapsed = 0;

    while (true)
    {
        const pointField& localPoints = surf.localPoints();
        const List<labelledTri>& localFaces = surf.localFaces();


        // Mapping from old to new points
        labelList pointMap(surf.nPoints());
        forAll(pointMap, i)
        {
            pointMap[i] = i;
        }

        // Storage for new points.
        pointField newPoints(localPoints);

        // To protect neighbours of collapsed faces.
        boolList okToCollapse(surf.size(), true);
        label nCollapsed = 0;

        forAll(localFaces, faceI)
        {
            if (okToCollapse[faceI])
            {
                // Check edge lengths.
                const triSurface::FaceType& f = localFaces[faceI];

                forAll(f, fp)
                {
                    label v = f[fp];
                    label v1 = f[f.fcIndex(fp)];

                    if (mag(localPoints[v1] - localPoints[v]) < minLen)
                    {
                        // Collapse f[fp1] onto f[fp].
                        pointMap[v1] = v;
                        newPoints[v] = 0.5*(localPoints[v1] + localPoints[v]);

                        Pout<< "Collapsing triange " << faceI << " to edge mid "
                            << newPoints[v] << endl;

                        nCollapsed++;
                        okToCollapse[faceI] = false;

                        // Protect point neighbours from collapsing.
                        markPointNbrs(surf, faceI, false, okToCollapse);

                        break;
                    }
                }
            }
        }

        Pout<< "collapseEdge : collapsing " << nCollapsed << " triangles"
            << endl;

        nTotalCollapsed += nCollapsed;

        if (nCollapsed == 0)
        {
            break;
        }

        // Pack the triangles
        surf = pack(surf, newPoints, pointMap);
    }
void Foam::meshRefinement::snapToSurface
(
    labelList& pointSurfaceRegion,
    labelList& edgeSurfaceRegion,
    scalarField& edgeWeight
)
{
    const edgeList& edges = mesh_.edges();
    const pointField& points = mesh_.points();

    pointSurfaceRegion.setSize(points.size());
    pointSurfaceRegion = -1;

    edgeSurfaceRegion.setSize(edges.size());
    edgeSurfaceRegion = -1;

    edgeWeight.setSize(edges.size());
    edgeWeight = -GREAT;


    // Do test for intersections
    // ~~~~~~~~~~~~~~~~~~~~~~~~~

    labelList surface1;
    List<pointIndexHit> hit1;
    labelList region1;
    //vectorField normal1;

    labelList surface2;
    List<pointIndexHit> hit2;
    labelList region2;
    //vectorField normal2;
    {
        vectorField start(edges.size());
        vectorField end(edges.size());
        forAll(edges, edgei)
        {
            const edge& e = edges[edgei];
            start[edgei] = points[e[0]];
            end[edgei] = points[e[1]];
        }
        
        surfaces_.findNearestIntersection
        (
            //labelList(1, 0),    //identity(surfaces_.surfaces().size()),
            identity(surfaces_.surfaces().size()),
            start,
            end,

            surface1,
            hit1,
            region1,
            //normal1,

            surface2,
            hit2,
            region2
            //normal2
        );
    }

    // Adjust location
    // ~~~~~~~~~~~~~~~

    pointField newPoints(points);
    label nAdjusted = 0;

    const labelListList& pointEdges = mesh_.pointEdges();
    forAll(pointEdges, pointi)
    {
        const point& pt = points[pointi];
        const labelList& pEdges = pointEdges[pointi];

        // Get the nearest intersection
        label minEdgei = -1;
        scalar minFraction = 0.5;   // Harpoon 0.25; // Samm?
        forAll(pEdges, pEdgei)
        {
            label edgei = pEdges[pEdgei];
            if (hit1[edgei].hit())
            {
                const point& hitPt = hit1[edgei].hitPoint();

                const edge& e = edges[edgei];
                label otherPointi = e.otherVertex(pointi);
                const point& otherPt = points[otherPointi];

                vector eVec(otherPt-pt);
                scalar f = eVec&(hitPt-pt)/magSqr(eVec);

                if (f < minFraction)
                {
                    minEdgei = edgei;
                    minFraction = f;
                }
            }
        }
        if (minEdgei != -1 && minFraction >= 0.01)
        {
            // Move point to intersection with minEdgei
            if (pointSurfaceRegion[pointi] == -1)
            {
                pointSurfaceRegion[pointi] = surfaces_.globalRegion
                (
                    surface1[minEdgei],
                    region1[minEdgei]
                );
                newPoints[pointi] = hit1[minEdgei].hitPoint();
                nAdjusted++;
            }
        }
    }