Ejemplo n.º 1
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
Scalar
Line3D::GetDistanceTo(
    const Sphere &sphere,
    Scalar *penetration
) const
{
    Check_Object(this);
    Check_Object(&sphere);
    Check_Pointer(penetration);

    //
    //-------------------------------------------------------------------
    // Determine if ray intersects bounding sphere of object.  If sphere
    // is (X-C)*(X-C) = R^2 and ray is X = t*D+L for t >= 0, then
    // intersection is obtained by plugging X into sphere equation to
    // get quadratic:  (D*D)t^2 + 2*(D*(L-C))t + (L-C)*(L-C) = 0
    // Define a = D*D = 1.0f, b = 2*(D*(L-C)), and c = (L-C)*(L-C).
    //-------------------------------------------------------------------
    //
    Vector3D diff;
    diff.Subtract(origin, sphere.center);
    Scalar b = (direction*diff) * 2.0f;
    Scalar c = (diff*diff) - sphere.radius*sphere.radius;

    //
    //-------------------------------------------------------------------------
    // If penetration is negative, we couldn't hit the sphere at all.  If it is
    // really small, it touches at only one place
    //-------------------------------------------------------------------------
    //
    *penetration = b*b - 4.0f*c;
    if (*penetration < -SMALL)
    {
        return -1.0f;
    }
    b *= -0.5f;
    if (*penetration<SMALL)
    {
        *penetration = 0.0f;
        Min_Clamp(b, 0.0f);
        return (b > length) ? -1.0f : b;
    }

    //
    //-------------------------------------------------------------
    // We know we hit the sphere, so figure out where it first hits
    //-------------------------------------------------------------
    //
    *penetration = 0.5f * Sqrt(*penetration);
    if (b + *penetration < -SMALL)
    {
        return -1.0f;
    }
    b -= *penetration;
    if (b > length)
    {
        return -1.0f;
    }
    Min_Clamp(b, 0.0f);
    return b;
}
Ejemplo n.º 2
0
void Matrix3DUtils::getDown(const Matrix3D &m, Vector3D &out) {
    m.copyColumnTo(1, out);
    out.negate();
}
Vector3D Vector3D :: projectOnto(Vector3D v) {
    return v.multiply(v.getDotProduct(Vector3D(x,y,z)) / v.getSquaredLength()  );
}
Ejemplo n.º 4
0
void CSpring::update()
{
	if(status == 1)
	{
		Vector3D springVector;
		springVector = p1->getPos() - p2->getPos();

		double r = springVector.length();

		if((r <= 0.05)||(r >= 2))
		{
			status = 0;
			return;
		}
//Now Spring can be broken;
		
	
		Vector3D force;	
		if(r != 0)
		{
			force = (springVector / r) * (r - length) * (- stiffnessCoefficient);
		}
			
		force += -(p1->getVel() - p2->getVel()) * frictionCoefficient;

		p1->applyForce(force);
		p2->applyForce(-force);

	/*
		//Ground 
		Vector3D p1Pos;
		Vector3D p2Pos;
		Vector3D p1Vel;
		Vector3D p2Vel;
		Vector3D slip;
		double coeff;

		p1Pos = p1->getPos();
		p2Pos = p2->getPos();
		p1Vel = p1->getVel();
		p2Vel = p2->getVel();
		slip = p2Pos - p1Pos;
	
		if(p1Pos.z <= 0)
		{
			p1Vel.z = 0;
			slip.z = 0;	
			if(p1Vel.scaleM(slip) / p1Vel.meas() / slip.meas() > 0.95)
			{
				p1->applyForce(- p1Vel * (0 * GroundFrictionConstant));					
			}
			else
			{
				p1->applyForce(- p1Vel * GroundFrictionConstant);
			}
		
		}

		if(p2Pos.z <= 0)
		{
			p2Vel.z = 0;
			slip.z = 0;
			if(p2Vel.scaleM(slip) / p2Vel.meas() / slip.meas() < - 0.95)
			{
				p2->applyForce(- p2Vel * (0 * GroundFrictionConstant));					
			}
			else
			{
				p2->applyForce(- p2Vel * GroundFrictionConstant);
			}

		}
*/


	}
}
Ejemplo n.º 5
0
void
  mitk::SlicedGeometry3D::InitializeEvenlySpaced(
  mitk::PlaneGeometry* geometry2D, mitk::ScalarType zSpacing,
  unsigned int slices, bool flipped )
{
  assert( geometry2D != nullptr );
  assert( geometry2D->GetExtent(0) > 0 );
  assert( geometry2D->GetExtent(1) > 0 );

  geometry2D->Register();

  Superclass::Initialize();
  m_Slices = slices;

  BoundingBox::BoundsArrayType bounds = geometry2D->GetBounds();
  bounds[4] = 0;
  bounds[5] = slices;

  // clear and reserve
  PlaneGeometry::Pointer gnull = nullptr;
  m_PlaneGeometries.assign( m_Slices, gnull );

  Vector3D directionVector = geometry2D->GetAxisVector(2);
  directionVector.Normalize();
  directionVector *= zSpacing;

  if ( flipped == false )
  {
    // Normally we should use the following four lines to create a copy of
    // the transform contrained in geometry2D, because it may not be changed
    // by us. But we know that SetSpacing creates a new transform without
    // changing the old (coming from geometry2D), so we can use the fifth
    // line instead. We check this at (**).
    //
    // AffineTransform3D::Pointer transform = AffineTransform3D::New();
    // transform->SetMatrix(geometry2D->GetIndexToWorldTransform()->GetMatrix());
    // transform->SetOffset(geometry2D->GetIndexToWorldTransform()->GetOffset());
    // SetIndexToWorldTransform(transform);

    this->SetIndexToWorldTransform( const_cast< AffineTransform3D * >(
      geometry2D->GetIndexToWorldTransform() ));
  }
  else
  {
    directionVector *= -1.0;
    this->SetIndexToWorldTransform( AffineTransform3D::New());
    this->GetIndexToWorldTransform()->SetMatrix(
      geometry2D->GetIndexToWorldTransform()->GetMatrix() );

    AffineTransform3D::OutputVectorType scaleVector;
    FillVector3D(scaleVector, 1.0, 1.0, -1.0);
    this->GetIndexToWorldTransform()->Scale(scaleVector, true);
    this->GetIndexToWorldTransform()->SetOffset(
      geometry2D->GetIndexToWorldTransform()->GetOffset() );
  }

  mitk::Vector3D spacing;
  FillVector3D( spacing,
    geometry2D->GetExtentInMM(0) / bounds[1],
    geometry2D->GetExtentInMM(1) / bounds[3],
    zSpacing );

  this->SetDirectionVector( directionVector );
  this->SetBounds( bounds );
  this->SetPlaneGeometry( geometry2D, 0 );
  this->SetSpacing( spacing, true);
  this->SetEvenlySpaced();

  //this->SetTimeBounds( geometry2D->GetTimeBounds() );

  assert(this->GetIndexToWorldTransform()
    != geometry2D->GetIndexToWorldTransform()); // (**) see above.

  this->SetFrameOfReferenceID( geometry2D->GetFrameOfReferenceID() );
  this->SetImageGeometry( geometry2D->GetImageGeometry() );

  geometry2D->UnRegister();
}
bool inDaBox(Vector3D centre, float rayonf, Vector3D vertex)
{
	//std::cout << vertex.x() << "  " << vertex.y() << "  " << vertex.z() << std::endl;
	if (vertex.x() >= centre.x() - rayonf &&  vertex.x() < centre.x() + rayonf &&
		vertex.y() >= centre.y() - rayonf &&  vertex.y() < centre.y() + rayonf &&
		vertex.z() >= centre.z() - rayonf &&  vertex.z() < centre.z() + rayonf)
		return true;
	else
		return false;
}
void cube(Vector3D centre, float rayon)
{

	glBegin(GL_LINE_LOOP);
	glColor3f(1.0, 1.0, 1.0);
	glVertex3f(centre.x() - rayon, centre.y() - rayon, centre.z() - rayon);
	glVertex3f(centre.x() - rayon, centre.y() + rayon, centre.z() - rayon);
	glVertex3f(centre.x() + rayon, centre.y() + rayon, centre.z() - rayon);
	glVertex3f(centre.x() + rayon, centre.y() - rayon, centre.z() - rayon);
	glEnd();

	glBegin(GL_LINE_LOOP);
	glColor3f(1.0, 1.0, 1.0);
	glVertex3f(centre.x() - rayon, centre.y() - rayon, centre.z() + rayon);
	glVertex3f(centre.x() - rayon, centre.y() + rayon, centre.z() + rayon);
	glVertex3f(centre.x() + rayon, centre.y() + rayon, centre.z() + rayon);
	glVertex3f(centre.x() + rayon, centre.y() - rayon, centre.z() + rayon);
	glEnd();

	glBegin(GL_LINE_LOOP);
	glColor3f(1.0, 1.0, 1.0);
	glVertex3f(centre.x() - rayon, centre.y() - rayon, centre.z() - rayon);
	glVertex3f(centre.x() - rayon, centre.y() + rayon, centre.z() - rayon);
	glVertex3f(centre.x() - rayon, centre.y() + rayon, centre.z() + rayon);
	glVertex3f(centre.x() - rayon, centre.y() - rayon, centre.z() + rayon);
	glEnd();


	glBegin(GL_LINE_LOOP);
	glColor3f(1.0, 1.0, 1.0);
	glVertex3f(centre.x() + rayon, centre.y() - rayon, centre.z() - rayon);
	glVertex3f(centre.x() + rayon, centre.y() + rayon, centre.z() - rayon);
	glVertex3f(centre.x() + rayon, centre.y() + rayon, centre.z() + rayon);
	glVertex3f(centre.x() + rayon, centre.y() - rayon, centre.z() + rayon);
	glEnd();



	glBegin(GL_LINE_LOOP);
	glColor3f(1.0, 1.0, 1.0);
	glVertex3f(centre.x() - rayon, centre.y() - rayon, centre.z() - rayon);
	glVertex3f(centre.x() + rayon, centre.y() - rayon, centre.z() - rayon);
	glVertex3f(centre.x() + rayon, centre.y() - rayon, centre.z() + rayon);
	glVertex3f(centre.x() - rayon, centre.y() - rayon, centre.z() + rayon);
	glEnd();



	glBegin(GL_LINE_LOOP);
	glColor3f(1.0, 1.0, 1.0);
	glVertex3f(centre.x() - rayon, centre.y() + rayon, centre.z() - rayon);
	glVertex3f(centre.x() + rayon, centre.y() + rayon, centre.z() - rayon);
	glVertex3f(centre.x() + rayon, centre.y() + rayon, centre.z() + rayon);
	glVertex3f(centre.x() - rayon, centre.y() + rayon, centre.z() + rayon);
	glEnd();
}
Ejemplo n.º 8
0
Vector3D Vector3D::getVectorTo(const Vector3D &other) {
	Length x = other.getX().minus(_x);
	Length y = other.getY().minus(_y);
	Length z = other.getZ().minus(_z);
	return Vector3D(x, y, z);
}
Ejemplo n.º 9
0
Vector3D Vector3D::move(const Vector3D &movement) {
	Length x = movement.getX().plus(_x);
	Length y = movement.getY().plus(_y);
	Length z = movement.getZ().plus(_z);
	return Vector3D(x, y, z);
}
void mitk::ExtractDirectedPlaneImageFilterNew::ItkSliceExtraction(const itk::Image<TPixel, VImageDimension> *inputImage)
{
  typedef itk::Image<TPixel, VImageDimension> InputImageType;
  typedef itk::Image<TPixel, VImageDimension - 1> SliceImageType;

  typedef itk::ImageRegionConstIterator<SliceImageType> SliceIterator;

  // Creating an itk::Image that represents the sampled slice
  typename SliceImageType::Pointer resultSlice = SliceImageType::New();

  typename SliceImageType::IndexType start;

  start[0] = 0;
  start[1] = 0;

  Point3D origin = m_CurrentWorldPlaneGeometry->GetOrigin();
  Vector3D right = m_CurrentWorldPlaneGeometry->GetAxisVector(0);
  Vector3D bottom = m_CurrentWorldPlaneGeometry->GetAxisVector(1);

  // Calculation the sample-spacing, i.e the half of the smallest spacing existing in the original image
  Vector3D newPixelSpacing = m_ImageGeometry->GetSpacing();
  float minSpacing = newPixelSpacing[0];
  for (unsigned int i = 1; i < newPixelSpacing.Size(); i++)
  {
    if (newPixelSpacing[i] < minSpacing)
    {
      minSpacing = newPixelSpacing[i];
    }
  }

  newPixelSpacing[0] = 0.5 * minSpacing;
  newPixelSpacing[1] = 0.5 * minSpacing;
  newPixelSpacing[2] = 0.5 * minSpacing;

  float pixelSpacing[2];
  pixelSpacing[0] = newPixelSpacing[0];
  pixelSpacing[1] = newPixelSpacing[1];

  // Calculating the size of the sampled slice
  typename SliceImageType::SizeType size;
  Vector2D extentInMM;
  extentInMM[0] = m_CurrentWorldPlaneGeometry->GetExtentInMM(0);
  extentInMM[1] = m_CurrentWorldPlaneGeometry->GetExtentInMM(1);

  // The maximum extent is the lenght of the diagonal of the considered plane
  double maxExtent = sqrt(extentInMM[0] * extentInMM[0] + extentInMM[1] * extentInMM[1]);
  unsigned int xTranlation = (maxExtent - extentInMM[0]);
  unsigned int yTranlation = (maxExtent - extentInMM[1]);
  size[0] = (maxExtent + xTranlation) / newPixelSpacing[0];
  size[1] = (maxExtent + yTranlation) / newPixelSpacing[1];

  // Creating an ImageRegion Object
  typename SliceImageType::RegionType region;

  region.SetSize(size);
  region.SetIndex(start);

  // Defining the image`s extent and origin by passing the region to it and allocating memory for it
  resultSlice->SetRegions(region);
  resultSlice->SetSpacing(pixelSpacing);
  resultSlice->Allocate();

  /*
  * Here we create an new geometry so that the transformations are calculated correctly (our resulting slice has a
  * different bounding box and spacing)
  * The original current worldgeometry must be cloned because we have to keep the directions of the axis vector which
  * represents the rotation
  */
  right.Normalize();
  bottom.Normalize();
  // Here we translate the origin to adapt the new geometry to the previous calculated extent
  origin[0] -= xTranlation * right[0] + yTranlation * bottom[0];
  origin[1] -= xTranlation * right[1] + yTranlation * bottom[1];
  origin[2] -= xTranlation * right[2] + yTranlation * bottom[2];

  // Putting it together for the new geometry
  mitk::BaseGeometry::Pointer newSliceGeometryTest =
    dynamic_cast<BaseGeometry *>(m_CurrentWorldPlaneGeometry->Clone().GetPointer());
  newSliceGeometryTest->ChangeImageGeometryConsideringOriginOffset(true);

  // Workaround because of BUG (#6505)
  newSliceGeometryTest->GetIndexToWorldTransform()->SetMatrix(
    m_CurrentWorldPlaneGeometry->GetIndexToWorldTransform()->GetMatrix());
  // Workaround end

  newSliceGeometryTest->SetOrigin(origin);
  ScalarType bounds[6] = {0, static_cast<ScalarType>(size[0]), 0, static_cast<ScalarType>(size[1]), 0, 1};
  newSliceGeometryTest->SetBounds(bounds);
  newSliceGeometryTest->SetSpacing(newPixelSpacing);
  newSliceGeometryTest->Modified();

  // Workaround because of BUG (#6505)
  itk::MatrixOffsetTransformBase<mitk::ScalarType, 3, 3>::MatrixType tempTransform =
    newSliceGeometryTest->GetIndexToWorldTransform()->GetMatrix();
  // Workaround end

  /*
  * Now we iterate over the recently created slice.
  * For each slice - pixel we check whether there is an according
  * pixel in the input - image which can be set in the slice.
  * In this way a slice is sampled out of the input - image regrading to the given PlaneGeometry
  */
  Point3D currentSliceIndexPointIn2D;
  Point3D currentImageWorldPointIn3D;
  typename InputImageType::IndexType inputIndex;

  SliceIterator sliceIterator(resultSlice, resultSlice->GetLargestPossibleRegion());
  sliceIterator.GoToBegin();

  while (!sliceIterator.IsAtEnd())
  {
    /*
    * Here we add 0.5 to to assure that the indices are correctly transformed.
    * (Because of the 0.5er Bug)
    */
    currentSliceIndexPointIn2D[0] = sliceIterator.GetIndex()[0] + 0.5;
    currentSliceIndexPointIn2D[1] = sliceIterator.GetIndex()[1] + 0.5;
    currentSliceIndexPointIn2D[2] = 0;

    newSliceGeometryTest->IndexToWorld(currentSliceIndexPointIn2D, currentImageWorldPointIn3D);

    m_ImageGeometry->WorldToIndex(currentImageWorldPointIn3D, inputIndex);

    if (m_ImageGeometry->IsIndexInside(inputIndex))
    {
      resultSlice->SetPixel(sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex));
    }
    else
    {
      resultSlice->SetPixel(sliceIterator.GetIndex(), 0);
    }

    ++sliceIterator;
  }

  Image::Pointer resultImage = ImageToImageFilter::GetOutput();
  GrabItkImageMemory(resultSlice, resultImage, nullptr, false);
  resultImage->SetClonedGeometry(newSliceGeometryTest);
  // Workaround because of BUG (#6505)
  resultImage->GetGeometry()->GetIndexToWorldTransform()->SetMatrix(tempTransform);
  // Workaround end
}
Ejemplo n.º 11
0
Vector3D::Vector3D(const Vector3D &vec) {
	_x = vec.getX();
	_y = vec.getY();
	_z = vec.getZ();
}
Ejemplo n.º 12
0
void GL3CalculateProjectionShadowMapMatrix(Vector3D viewp, Vector3D light_direction,
Vector3D x_direction, Vector3D y_direction, float zmin, float zmax) {
#if 0
    char *s1 = light_direction.GetString();
    char *s2 = x_direction.GetString();
    char *s3 = y_direction.GetString();
    sreMessage(SRE_MESSAGE_LOG, "GL3CalculateProjectionShadowMapMatrix: light_dir = %s, "
        "x_dir = %s, y_dir = %s, dot products: %f, %f, %f", s1, s2, s3,
        Dot(light_direction, x_direction), Dot(light_direction, y_direction),
        Dot(x_direction, y_direction));
    delete s1;
    delete s2;
    delete s3;
#endif
    Vector3D fvec = light_direction;
    Vector3D s = x_direction;
    Vector3D u = y_direction;
    Matrix4D M;
    // Note that the y direction has to be negated in order to preserve the handedness of
    // triangles when rendering the shadow map.
    M.Set(
        s.x, s.y, s.z, 0,
        - u.x, - u.y, - u.z, 0,
        - fvec.x, - fvec.y, - fvec.z, 0,
        0.0f, 0.0f, 0.0f, 1.0f);
    Matrix4D T;
    T.AssignTranslation(- viewp);
    // Calculate the projection matrix with a field of view of 90 degrees.
    float aspect = 1.0;
    float e = 1 / tanf((90.0 * M_PI / 180) / 2);
    float n = zmin;
    float f = zmax;
    float l = - n / e;
    float r = n / e;
    float b = - (1.0f / aspect) * n / e;
    float t = (1.0f / aspect) * n / e;
    Matrix4D projection_matrix;
    projection_matrix.Set(
        2 * n / (r - l), 0.0f, (r + l) / (r - l), 0.0f,
        0.0f, 2 * n / (t - b), (t + b) / (t - b), 0.0f,
        0.0f, 0.0f, - (f + n) / (f - n), - 2 * n * f / (f - n),
        0.0f, 0.0f, - 1.0f, 0.0f);
    projection_shadow_map_matrix = projection_matrix * (M * T);
    MatrixTransform shadow_map_viewport_matrix;
    shadow_map_viewport_matrix.Set(
        0.5f, 0.0f, 0.0f, 0.5f,
        0.0f, 0.5f, 0.0f, 0.5f,
        0.0f, 0.0f, 0.5f, 0.5f);
    projection_shadow_map_lighting_pass_matrix = shadow_map_viewport_matrix *
        projection_shadow_map_matrix;
//    projection_shadow_map_lighting_pass_matrix = projection_shadow_map_matrix;

#if 0
    Point3D P1 = viewp + light_direction * n;
    Point3D P2 = viewp + light_direction * f;
    Point3D P3 = viewp + light_direction * f + x_direction * f + y_direction * f;
    Vector4D P1_proj = projection_shadow_map_matrix * P1;
    Vector4D P2_proj = projection_shadow_map_matrix * P2;
    Vector4D P3_proj = projection_shadow_map_matrix * P3;
    Vector3D P1_norm = P1_proj.GetVector3D() / P1_proj.w;
    Vector3D P2_norm = P2_proj.GetVector3D() / P2_proj.w;
    Vector3D P3_norm = P3_proj.GetVector3D() / P3_proj.w;
    char *P1_norm_str = P1_norm.GetString();
    char *P2_norm_str = P2_norm.GetString();
    char *P3_norm_str = P3_norm.GetString();
    sreMessage(SRE_MESSAGE_LOG, "CalculateProjectionShadowMapMatrix: Point transformations "
        "%s, %s and %s.", P1_norm_str, P2_norm_str, P3_norm_str);
    delete P1_norm_str;
    delete P2_norm_str;
    delete P3_norm_str;
#endif
}
Ejemplo n.º 13
0
double mitk::BaseGeometry::GetDiagonalLength2() const
{
  Vector3D diagonalvector = GetCornerPoint()-GetCornerPoint(false, false, false);
  return diagonalvector.GetSquaredNorm();
}
Ejemplo n.º 14
0
Vector3D reflectionDirection(const Vector3D& incomingVec, const Vector3D& normalVec) {
    Vector3D vout = incomingVec - 2.0*(DotProduct(incomingVec, normalVec))*normalVec;
    return vout.Normalize();
}
Ejemplo n.º 15
0
//------------------------------------------------------------------------------
//! Computes the Jacobian for all Edges Internal and Boundary
//! Note: Jacobian is computed using first order Q's
//------------------------------------------------------------------------------
void Compute_Jacobian_Approximate_Roe(int AddTime, int Iteration) {
    int i, j, k, iNode, iEdge, ibEdge;
    int node_L, node_R;
    int idgn, idgnL, idgnR, ofdgnL, ofdgnR;
    double area;
    double Q_L[NEQUATIONS];
    double Q_R[NEQUATIONS];
    double **dFdL;
    double **dFdR;
    double **ARoe;
    Vector3D areavec;
    
    // Create the Helper Matrix
    dFdL = (double **) malloc(NEQUATIONS*sizeof(double*));
    dFdR = (double **) malloc(NEQUATIONS*sizeof(double*));
    ARoe = (double **) malloc(NEQUATIONS*sizeof(double*));
    for (i = 0; i < NEQUATIONS; i++) {
        dFdL[i] = (double *) malloc(NEQUATIONS*sizeof(double));
        dFdR[i] = (double *) malloc(NEQUATIONS*sizeof(double));
        ARoe[i] = (double *) malloc(NEQUATIONS*sizeof(double));
    }
    
    // Initialize the CRS Matrix
    for (i = 0; i < SolverBlockMatrix.DIM; i++) {
        for (j = 0; j < SolverBlockMatrix.Block_nRow; j++) {
            for (k = 0; k < SolverBlockMatrix.Block_nCol; k++)
                SolverBlockMatrix.A[i][j][k] = 0.0;
        }
    }
    
    // Copy the Residuals to Block Matrix which is B
    // And Copy I/DeltaT
    for (iNode = 0; iNode < nNode; iNode++) {
        // Get the diagonal location
        idgn = SolverBlockMatrix.IAU[iNode];
        // Get the LHS
        SolverBlockMatrix.B[iNode][0] = -Res1[iNode];
        SolverBlockMatrix.B[iNode][1] = -Res2[iNode];
        SolverBlockMatrix.B[iNode][2] = -Res3[iNode];
        SolverBlockMatrix.B[iNode][3] = -Res4[iNode];
        SolverBlockMatrix.B[iNode][4] = -Res5[iNode];
        for (j = 0; j < SolverBlockMatrix.Block_nRow; j++) {
            if (AddTime == 1) {
                for (k = 0; k < SolverBlockMatrix.Block_nCol; k++)
                    if (k == j)
                        SolverBlockMatrix.A[idgn][j][k] = cVolume[iNode]/DeltaT[iNode];
            }
        }
    }
    
    // Internal Edges
    for (iEdge = 0; iEdge < nEdge; iEdge++) {
        // Get two nodes of edge
        node_L = intEdge[iEdge].node[0];
        node_R = intEdge[iEdge].node[1];
        
        // Get area vector
        areavec = intEdge[iEdge].areav;
        area    = areavec.magnitude();
        
        // Backup the Copy of Q_L and Q_R
        // Left
        Q_L[0] = Q1[node_L];
        Q_L[1] = Q2[node_L];
        Q_L[2] = Q3[node_L];
        Q_L[3] = Q4[node_L];
        Q_L[4] = Q5[node_L];
        // Right
        Q_R[0] = Q1[node_R];
        Q_R[1] = Q2[node_R];
        Q_R[2] = Q3[node_R];
        Q_R[3] = Q4[node_R];
        Q_R[4] = Q5[node_R];
        
        // Get the diagonal Locations
        idgnL = SolverBlockMatrix.IAU[node_L];
        idgnR = SolverBlockMatrix.IAU[node_R];
        
        // Get the Off-Diagonal Locations
        // node_L: ofdgnL-> node_R;
        // node_R: ofdgnR-> node_L;
        ofdgnL = -1;
        for (i = SolverBlockMatrix.IA[node_L]; i < SolverBlockMatrix.IA[node_L+1]; i++) {
            if (SolverBlockMatrix.JA[i] == node_R) {
                ofdgnL = i;
                break;
            }
        }
        ofdgnR = -1;
        for (i = SolverBlockMatrix.IA[node_R]; i < SolverBlockMatrix.IA[node_R+1]; i++) {
            if (SolverBlockMatrix.JA[i] == node_L) {
                ofdgnR = i;
                break;
            }
        }
        
        // Initialize the Helper Matrix
        for (i = 0; i < NEQUATIONS; i++) {
            for (j = 0; j < NEQUATIONS; j++) {
                dFdL[i][j] = 0.0;
                dFdR[i][j] = 0.0;
                ARoe[i][j] = 0.0;
            }
        }
        
        // Compute dFdL
        ConservativeEulerFluxJacobian(Q_L, areavec, dFdL, Gamma);
        
        // Compute dFdR
        ConservativeEulerFluxJacobian(Q_R, areavec, dFdR, Gamma);
        
        // Compute Roe Jacobian
        Compute_RoeAJacobian(Q_L, Q_R, areavec, ARoe);
        
        // Finally Compute the dFlux/dQ_L and dFlux/dQ_R
        for (i = 0; i < NEQUATIONS; i++) {
            for (j = 0; j < NEQUATIONS; j++) {
                dFdL[i][j] = 0.5*(dFdL[i][j] + ARoe[i][j])*area;
                dFdR[i][j] = 0.5*(dFdR[i][j] - ARoe[i][j])*area;
            }
        }
        
        // Update the Diagonal and Off-Diagonal Terms
        for (i = 0; i < NEQUATIONS; i++) {
            for (j = 0; j < NEQUATIONS; j++) {
                // Diagonal
                SolverBlockMatrix.A[idgnL][i][j] += dFdL[i][j];
                SolverBlockMatrix.A[idgnR][i][j] -= dFdR[i][j];
                // Off-Diagonal
                SolverBlockMatrix.A[ofdgnL][i][j] += dFdR[i][j];
                SolverBlockMatrix.A[ofdgnR][i][j] -= dFdL[i][j];
            }
        }
    }
    
    // Boundary Edges
    for (ibEdge = 0; ibEdge < nBEdge; ibEdge++) {
        // Get two nodes of edge
        node_L = bndEdge[ibEdge].node[0];
        node_R = bndEdge[ibEdge].node[1];
        
        // Get area vector
        areavec = bndEdge[ibEdge].areav;
        area    = areavec.magnitude();
        
        // Backup the Copy of Q_L and Q_R
        // Left - Physical
        Q_L[0] = Q1[node_L];
        Q_L[1] = Q2[node_L];
        Q_L[2] = Q3[node_L];
        Q_L[3] = Q4[node_L];
        Q_L[4] = Q5[node_L];
        // Right - Ghost
        Q_R[0] = Q1[node_R];
        Q_R[1] = Q2[node_R];
        Q_R[2] = Q3[node_R];
        Q_R[3] = Q4[node_R];
        Q_R[4] = Q5[node_R];
        
        // Get the diagonal Locations - Only Physical
        // No diagonal and off-diagonal locations exists for Ghost Nodes
        idgnL = SolverBlockMatrix.IAU[node_L];
        
        // Initialize the Helper Matrix - Only Physical
        for (i = 0; i < NEQUATIONS; i++) {
            for (j = 0; j < NEQUATIONS; j++) {
                dFdL[i][j] = 0.0;
                ARoe[i][j] = 0.0;
            }
        }
        
        // Compute dFdL
        ConservativeEulerFluxJacobian(Q_L, areavec, dFdL, Gamma);
        
        // Compute Roe Jacobian
        Compute_RoeAJacobian(Q_L, Q_R, areavec, ARoe);
        
        // Finally Compute the dFlux/dQ_L
        for (i = 0; i < NEQUATIONS; i++) {
            for (j = 0; j < NEQUATIONS; j++)
                dFdL[i][j] = 0.5*(dFdL[i][j] + ARoe[i][j])*area;
        }
        
        // Update the Diagonal Term of Physical Node Only
        for (i = 0; i < NEQUATIONS; i++) {
            for (j = 0; j < NEQUATIONS; j++)
                SolverBlockMatrix.A[idgnL][i][j] += dFdL[i][j];
        }
    }
    
    // Delete the Helper Matrix
    for (i = 0; i < NEQUATIONS; i++) {
        free(ARoe[i]);
        free(dFdL[i]);
        free(dFdR[i]);
    }
    free(ARoe);
    free(dFdL);
    free(dFdR);
}
Ejemplo n.º 16
0
void Object3D::getBackVector(Vector3D& result)
{
	getForwardVector(result);
	result.negate();
}
void subdivision(Vector3D centre, float rayon, float rayonMin)
{
	std::vector<Vector3D> lesCentres;
	if (rayon > rayonMin)
	{
		lesCentres.push_back(Vector3D(centre.x() - rayon / 2, centre.y() - rayon / 2, centre.z() - rayon / 2));
		lesCentres.push_back(Vector3D(centre.x() - rayon / 2, centre.y() + rayon / 2, centre.z() - rayon / 2));
		lesCentres.push_back(Vector3D(centre.x() + rayon / 2, centre.y() - rayon / 2, centre.z() - rayon / 2));
		lesCentres.push_back(Vector3D(centre.x() + rayon / 2, centre.y() + rayon / 2, centre.z() - rayon / 2));

		lesCentres.push_back(Vector3D(centre.x() - rayon / 2, centre.y() - rayon / 2, centre.z() + rayon / 2));
		lesCentres.push_back(Vector3D(centre.x() - rayon / 2, centre.y() + rayon / 2, centre.z() + rayon / 2));
		lesCentres.push_back(Vector3D(centre.x() + rayon / 2, centre.y() - rayon / 2, centre.z() + rayon / 2));
		lesCentres.push_back(Vector3D(centre.x() + rayon / 2, centre.y() + rayon / 2, centre.z() + rayon / 2));

		for (int i = 0; i < lesCentres.size(); i++)
		{
			subdivision(lesCentres.at(i), rayon / 2, rayonMin);
		}
	}
	else
	{
		finalSize = rayon;
		centreCube.push_back(centre);
		//cube(centre, rayon);
	}
}
Ejemplo n.º 18
0
void Object3D::getLeftVector(Vector3D& result)
{
	getRightVector(result);
	result.negate();
}
GLvoid afficheMaille()
{
	Vector3D a;
	Vector3D b;
	Vector3D c;
	double facteur = 100.0;
	int cptNormale = 0;

	std::vector<Vector3D> geometrie = maille.getGeom();
	std::vector<Vector3D> normales = maille.getNormales();
	std::vector<int> topologie = maille.getTopo();
	Vector3D centre = maille.getCentreGravite();
	double scale = maille.getScale();

	
	//std::cout << maille.getTopo().size() << std::endl;
	for (int i = 0; i < topologie.size(); i += 3)
	{
		a = (geometrie.at(topologie.at(i)));// -centre) / scale;
		b = (geometrie.at(topologie.at(i + 1)));// -centre) / scale;
		c = (geometrie.at(topologie.at(i + 2)));// -centre) / scale;

		//std::cout << "a : " << a.x() << " | " <<  a.y()<< " | " <<  a.z() << std::endl;
		//std::cout << "b : " << b.x() << " | " <<  b.y()<< " | " <<  b.z() << std::endl;
		//std::cout << "c : " << c.x() << " | " <<  c.y()<< " | " <<  c.z() << std::endl;

		//glNormal3d(normales.at(cptNormale).x(), normales.at(cptNormale).y(), normales.at(cptNormale).z());
		//std::cout << normales.at(cptNormale).x() << " | " <<  normales.at(cptNormale).y()<< " | " <<  normales.at(cptNormale).z() << std::endl;
		glBegin(GL_TRIANGLES);
		glVertex3f(a.x(), a.y(), a.z());
		glVertex3f(b.x(), b.y(), b.z());
		glVertex3f(c.x(), c.y(), c.z());
		glEnd();

		cptNormale++;
	}

	//std::cout << "endload" << std::endl;
}
Ejemplo n.º 20
0
void Object3D::getDownVector(Vector3D& result)
{
	getUpVector(result);
	result.negate();
}
Ejemplo n.º 21
0
void Plant::draw( Vector3D *inPosition, double inScale,
                  double inMaxZ, double inMinZ ) {


    if( mPoisoned && mPoisonStatus >= 1) {
        // draw nothing
        return;
        }

    
    double drawScale = inScale;

    if( mPoisoned ) {
        // shrink with poisoning
        
        drawScale *= ( 1 - mPoisonStatus );
        }

    
    double radius = drawScale * ( mGrowth * 0.8 + 0.2 );


    // leaves become black with poisoning
    // (shades of white to allow texture color to dominate) 
    Color leafColor( 1 - mPoisonStatus,
                     1 - mPoisonStatus,
                     1 - mPoisonStatus, 1 );

    
    if( ! Features::drawNicePlantLeaves ) {
        // set color to shades of green green for leaves if we're drawing
        // simple boxes, since there's no texture color

        leafColor.setValues( 0, 1 - mPoisonStatus, 0, 1 );
        }

    
    Angle3D zeroAngle( 0, 0, 0 );
    

    PlantGenetics *genetics = &( mSeeds.mGenetics );

    
    
    int maxNumJoints = (int)( genetics->getParameter( jointCount ) );

    double growthFactor = mGrowth * 0.8 + 0.2;
    
    int numFullJoints = (int)( growthFactor * maxNumJoints );

    double partialJoint = growthFactor * maxNumJoints - numFullJoints;

    int numLeavesPerJoint = (int)( genetics->getParameter( leavesPerJoint ) );

    Angle3D angleIncrement( 0, 0, 2 * M_PI / numLeavesPerJoint );
    Angle3D startAngle( 0, 0, mStartZAngle );

    double currentScale = 1;

    double scaleDecrement = currentScale / ( maxNumJoints + 1 );

    Vector3D leafPosition( inPosition );

    Vector3D positionIncrement( 0, 0, -0.5 );

    Vector3D leafWalkerTerminus;

    SimpleVector<Vector3D *> thisLayerLeafTerminii;
    
    
    for( int j=0; j<numFullJoints; j++ ) {

        // lower leaves are darker
        double colorScaleFactor = (double)(j+1) / (double)maxNumJoints; 
        // min scaling of 0.5
        colorScaleFactor = colorScaleFactor * 0.5 + 0.5;
        
        
        Color thisLevelColor;
        thisLevelColor.setValues( &leafColor );
        thisLevelColor.weightColor( colorScaleFactor );
        
        
        
        
        Angle3D currentAngle( &startAngle );

        double zValue = leafPosition.mZ;

        if( zValue <= inMaxZ && zValue >= inMaxZ ) {
            // draw this joint
            for( int g=0; g<numLeavesPerJoint; g++ ) {

                if( Features::drawShadows ) {
                    // draw shadow
                    glColor4f( 0, 0, 0, 0.5 );
                    mLeaf.draw( &leafPosition, &currentAngle,
                                currentScale * radius * 1.05 );
                    }
                
                // draw leaf
                setGLColor( &thisLevelColor );
                
                mLeaf.draw( &leafPosition, &currentAngle,
                            currentScale * radius,
                            &leafWalkerTerminus );


                thisLayerLeafTerminii.push_back(
                    new Vector3D( &leafWalkerTerminus ) );

                
                currentAngle.add( &angleIncrement );
                }

            // finally cap this joint
            setGLColor( &thisLevelColor );
            mJointCapTexture->enable();
            glBegin( GL_QUADS ); {

                double capRadius = currentScale * radius * 0.1;
                double capZ = leafPosition.mZ;
                
                glTexCoord2f( 0, 0 );
                glVertex3d( leafPosition.mX - capRadius,
                            leafPosition.mY - capRadius, capZ );

                glTexCoord2f( 1, 0 );
                glVertex3d( leafPosition.mX + capRadius,
                            leafPosition.mY - capRadius, capZ );
                
                glTexCoord2f( 1, 1 );
                glVertex3d( leafPosition.mX + capRadius,
                            leafPosition.mY + capRadius, capZ );

                glTexCoord2f( 0, 1 );
                glVertex3d( leafPosition.mX - capRadius,
                            leafPosition.mY + capRadius, capZ );
                }
            glEnd();
            mJointCapTexture->disable();        
            }
        
        
        Angle3D angleToNextJoint( &angleIncrement );

        angleToNextJoint.scale( 0.5 );

        currentAngle.add( &angleToNextJoint );

        // start next joint at our current angle
        startAngle.setComponents( &currentAngle );

        currentScale -= scaleDecrement;

        leafPosition.add( &positionIncrement );
        }

    if( partialJoint > 0 ) {
        Angle3D currentAngle( &startAngle );

        // darker as growing completes


        // lower leaves are darker
        double colorScaleFactor =
            (double)(numFullJoints+1) / (double)maxNumJoints; 

        // min scaling of 0.5
        colorScaleFactor = colorScaleFactor * 0.5 + 0.5;

        // scale factor comes into effect as partial joint reaches 1
        colorScaleFactor = (1 - partialJoint) +
            colorScaleFactor * partialJoint;
        
        Color thisLevelColor;
        thisLevelColor.setValues( &leafColor );
        thisLevelColor.weightColor( colorScaleFactor );
        
        

        double zValue = leafPosition.mZ;

        if( zValue <= inMaxZ && zValue >= inMaxZ ) {
            // draw this joint
        
            for( int g=0; g<numLeavesPerJoint; g++ ) {

                if( Features::drawShadows ) {
                    // draw shadow
                    glColor4f( 0, 0, 0, 0.5 );
                    mLeaf.draw( &leafPosition, &currentAngle,
                                partialJoint * currentScale * radius * 1.05 );
                    }
                
                setGLColor( &thisLevelColor );

                mLeaf.draw( &leafPosition, &currentAngle,
                            // scale down further by partial fraction
                            partialJoint * currentScale * radius );

                currentAngle.add( &angleIncrement );
                }

            // finally cap this joint
            setGLColor( &thisLevelColor );
            mJointCapTexture->enable();
            glBegin( GL_QUADS ); {

                double capRadius = currentScale * radius * 0.1;
                double capZ = leafPosition.mZ;
                
                glTexCoord2f( 0, 0 );
                glVertex3d( leafPosition.mX - capRadius,
                            leafPosition.mY - capRadius, capZ );

                glTexCoord2f( 1, 0 );
                glVertex3d( leafPosition.mX + capRadius,
                            leafPosition.mY - capRadius, capZ );
                
                glTexCoord2f( 1, 1 );
                glVertex3d( leafPosition.mX + capRadius,
                            leafPosition.mY + capRadius, capZ );

                glTexCoord2f( 0, 1 );
                glVertex3d( leafPosition.mX - capRadius,
                            leafPosition.mY + capRadius, capZ );
                }
            glEnd();
            mJointCapTexture->disable();
            }
        }

    int numTerminii = thisLayerLeafTerminii.size();
    int t;
    
    if( mGrowth >= 1 ) {

        // NOTE:
        // This method of collecting all leaf terminii for the plant ASSUMES
        // that each terminus is at a unique location
        // This seems like a safe assumption, given the way leaves are
        // arranged now, but it is not safe in the general case.
        
        // If two terminii are at the same location, the terminus collection
        // would finish before collecting all terminii
        
        
        if( !mLeafTerminiiSet ) {
            // not done collecting leaf terminii for full-growth plant

            int numExisting = mLeafTerminii.size();
            char collision = false;
            
            for( int t=0; t<numTerminii && !collision; t++ ) {
                Vector3D *newTerminus =
                    *( thisLayerLeafTerminii.getElement( t ) );
                
                // make sure not the same as existing
                char same = false;
                for( int e=0; e<numExisting && !same; e++ ) {
                    Vector3D *existing = *( mLeafTerminii.getElement( e ) );

                    if( existing->equals( newTerminus ) ) {
                        same = true;
                        collision = true;
                        }
                    }

                if( !same ) {
                    // add to list of all terminii
                    mLeafTerminii.push_back( new Vector3D( newTerminus ) );
                    }                
                }

            if( collision ) {
                // we are back to drawing a layer that we've already drawn
                // before

                // so we're not gathering new leaf terminii anymore

                mLeafTerminiiSet = true;
                }
            }
        else {
        
            // don't try adding flowers if we already have more than
            // numTerminii
            // flowers
            int numTotalTerminii = mLeafTerminii.size();
            int numFlowers = mFlowerTerminusIndicies.size();
            int numFruit = mFruitTerminusIndices.size();
            
            if( numFlowers < numTotalTerminii &&
                mTimeSinceLastFlower >=
                genetics->getParameter( timeBetweenFlowers ) ) {
                // new flower

                // pick random, unflowered, unfruited terminus
            

                int numTries = 0;
                char found = false;
                int foundIndex = -1;
                while( ! found && numTries < 100 ) {
                    foundIndex =
                        globalRandomSource.getRandomBoundedInt(
                            0,
                            numTotalTerminii - 1 );
                    found = true;
                    int f;
                    for( f=0; f<numFlowers && found; f++ ) {
                        if( *( mFlowerTerminusIndicies.getElement( f ) )
                            ==
                            foundIndex ) {
                            // collision with existing flower location
                            found = false;
                            }
                        }
                    for( f=0; f<numFruit && found; f++ ) {
                        if( *( mFruitTerminusIndices.getElement( f ) )
                            ==
                            foundIndex ) {
                            // collision with existing fruit location
                            found = false;
                            }
                        }
                    numTries++;
                    }

                if( found ) {
                    mFlowerTerminusIndicies.push_back( foundIndex );
                    mFlowerStages.push_back( 0 );
                    mFlowerAngles.push_back(
                        new Angle3D(
                            0, 0,
                            globalRandomSource.getRandomBoundedDouble(
                                0, 2 * M_PI ) ) );
                    }
            
                mTimeSinceLastFlower = 0;
                }

        
            // recount, since we may have added some
            numFlowers = mFlowerTerminusIndicies.size();
            
            for( int f=0; f<numFlowers; f++ ) {
                int terminusIndex =
                    *( mFlowerTerminusIndicies.getElement( f ) );
                
                Vector3D *terminus =
                    *( mLeafTerminii.getElement( terminusIndex ) );
            
                double zValue = terminus->mZ;
                
                if( zValue <= inMaxZ && zValue >= inMaxZ ) {
                    
                    Angle3D *flowerAngle = *( mFlowerAngles.getElement( f ) );
                    
                    double flowerStage = *( mFlowerStages.getElement( f ) );
                    
                    mFlower.draw( terminus,
                                  flowerAngle, drawScale, flowerStage );
                    }
                }
            }

        // draw fruit
        int numFruit = mFruit.size();

        
        for( int f=0; f<numFruit; f++ ) {
            int terminusIndex =
                *( mFruitTerminusIndices.getElement( f ) );
                
            Vector3D *terminus =
                *( mLeafTerminii.getElement( terminusIndex ) );
            
            double zValue = terminus->mZ;
            
            if( zValue <= inMaxZ && zValue >= inMaxZ ) {
                Angle3D *fruitAngle = *( mFruitAngles.getElement( f ) );
                Fruit *thisFruit = *( mFruit.getElement( f ) );

                double fruitScale = drawScale * 0.2;
                
                thisFruit->draw( terminus,
                                 fruitAngle, fruitScale );

                if( mHighlightRipeFruit && thisFruit->isRipe() ) {

                    // make sure this is the fruit that we will harvest
                    // next
                    // (the z-range drawing can screw us
                    // up here, since we might draw fruits out-of-order)
                    // thus, the first-drawn ripe fruit is not necessarily
                    // the fruit that will be next harvested
                    Fruit *fruitNextHarvested = peekAtRipeFruit();

                    
                    if( thisFruit == fruitNextHarvested ) {
                        // this fruit will be harvested next
                                            
                        glColor4f( 1, 1, 1, 0.25 );
                        
                        // highlight brightens only
                        glBlendFunc( GL_SRC_ALPHA, GL_ONE );

                        drawBlurCircle( terminus, fruitScale );

                        // back to normal blend function
                        glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

                        // only highlight one
                        mHighlightRipeFruit = false;
                        }
                    }
                }
            }
        }

    // delete this layer's terminus points
    for( t=0; t<numTerminii; t++ ) {
        delete *( thisLayerLeafTerminii.getElement( t ) );
        }
    }
Ejemplo n.º 22
0
bool AffineInteractor3D
::ExecuteAction( Action *action, StateEvent const *stateEvent )
{
  bool ok = false;

  // Get data object
  BaseData *data = m_DataNode->GetData();
  if ( data == NULL )
  {
    MITK_ERROR << "No data object present!";
    return ok;
  }

  // Get Event and extract renderer
  const Event *event = stateEvent->GetEvent();
  BaseRenderer *renderer = NULL;
  vtkRenderWindow *renderWindow = NULL;
  vtkRenderWindowInteractor *renderWindowInteractor = NULL;
  vtkRenderer *currentVtkRenderer = NULL;
  vtkCamera *camera = NULL;

  if ( event != NULL )
  {
    renderer = event->GetSender();
    if ( renderer != NULL )
    {
      renderWindow = renderer->GetRenderWindow();
      if ( renderWindow != NULL )
      {
        renderWindowInteractor = renderWindow->GetInteractor();
        if ( renderWindowInteractor != NULL )
        {
          currentVtkRenderer = renderWindowInteractor
            ->GetInteractorStyle()->GetCurrentRenderer();
          if ( currentVtkRenderer != NULL )
          {
            camera = currentVtkRenderer->GetActiveCamera();
          }
        }
      }
    }
  }

  // Check if we have a DisplayPositionEvent
  const DisplayPositionEvent *dpe =
    dynamic_cast< const DisplayPositionEvent * >( stateEvent->GetEvent() );
  if ( dpe != NULL )
  {
    m_CurrentPickedPoint = dpe->GetWorldPosition();
    m_CurrentPickedDisplayPoint = dpe->GetDisplayPosition();
  }

  // Get the timestep to also support 3D+t
  int timeStep = 0;
  ScalarType timeInMS = 0.0;
  if ( renderer != NULL )
  {
    timeStep = renderer->GetTimeStep( data );
    timeInMS = renderer->GetTime();
  }

  // If data is an mitk::Surface, extract it
  Surface *surface = dynamic_cast< Surface * >( data );
  vtkPolyData *polyData = NULL;
  if ( surface != NULL )
  {
    polyData = surface->GetVtkPolyData( timeStep );

    // Extract surface normal from surface (if existent, otherwise use default)
    vtkPointData *pointData = polyData->GetPointData();
    if ( pointData != NULL )
    {
      vtkDataArray *normal = polyData->GetPointData()->GetVectors( "planeNormal" );
      if ( normal != NULL )
      {
        m_ObjectNormal[0] = normal->GetComponent( 0, 0 );
        m_ObjectNormal[1] = normal->GetComponent( 0, 1 );
        m_ObjectNormal[2] = normal->GetComponent( 0, 2 );
      }
    }
  }

  // Get geometry object
  m_Geometry = data->GetGeometry( timeStep );


  // Make sure that the data (if time-resolved) has enough entries;
  // if not, create the required extra ones (empty)
  data->Expand( timeStep+1 );


  switch (action->GetActionId())
  {
  case AcDONOTHING:
    ok = true;
    break;


  case AcCHECKOBJECT:
    {
      // Re-enable VTK interactor (may have been disabled previously)
      if ( renderWindowInteractor != NULL )
      {
        renderWindowInteractor->Enable();
      }

      // Check if we have a DisplayPositionEvent
      const DisplayPositionEvent *dpe =
        dynamic_cast< const DisplayPositionEvent * >( stateEvent->GetEvent() );
      if ( dpe == NULL )
      {
        ok = true;
        break;
      }

      // Check if an object is present at the current mouse position
      DataNode *pickedNode = dpe->GetPickedObjectNode();
      StateEvent *newStateEvent;
      if ( pickedNode == m_DataNode )
      {
        // Yes: object will be selected
        newStateEvent = new StateEvent( EIDYES );
      }
      else
      {
        // No: back to start state
        newStateEvent = new StateEvent( EIDNO );
      }

      this->HandleEvent( newStateEvent );

      ok = true;
      break;
    }

  case AcDESELECTOBJECT:
    {
      // Color object white
      m_DataNode->SetColor( 1.0, 1.0, 1.0 );
      RenderingManager::GetInstance()->RequestUpdateAll();

      // Colorize surface / wireframe as inactive
      this->ColorizeSurface( polyData,
        m_CurrentPickedPoint, -1.0 );

      ok = true;
      break;
    }

  case AcSELECTPICKEDOBJECT:
    {
      // Color object red
      m_DataNode->SetColor( 1.0, 0.0, 0.0 );
      RenderingManager::GetInstance()->RequestUpdateAll();

      // Colorize surface / wireframe dependend on distance from picked point
      this->ColorizeSurface( polyData,
        m_CurrentPickedPoint, 0.0 );

      ok = true;
      break;
    }

  case AcINITMOVE:
    {
      // Disable VTK interactor until MITK interaction has been completed
      if ( renderWindowInteractor != NULL )
      {
        renderWindowInteractor->Disable();
      }

      // Check if we have a DisplayPositionEvent
      const DisplayPositionEvent *dpe =
        dynamic_cast< const DisplayPositionEvent * >( stateEvent->GetEvent() );
      if ( dpe == NULL )
      {
        ok = true;
        break;
      }

      //DataNode *pickedNode = dpe->GetPickedObjectNode();

      m_InitialPickedPoint = m_CurrentPickedPoint;
      m_InitialPickedDisplayPoint = m_CurrentPickedDisplayPoint;

      if ( currentVtkRenderer != NULL )
      {
        vtkInteractorObserver::ComputeDisplayToWorld(
          currentVtkRenderer,
          m_InitialPickedDisplayPoint[0],
          m_InitialPickedDisplayPoint[1],
          0.0, //m_InitialInteractionPickedPoint[2],
          m_InitialPickedPointWorld );
      }


      // Make deep copy of current Geometry3D of the plane
      data->UpdateOutputInformation(); // make sure that the Geometry is up-to-date
      m_OriginalGeometry = static_cast< BaseGeometry * >(
        data->GetGeometry( timeStep )->Clone().GetPointer() );

      ok = true;
      break;
    }

  case AcMOVE:
    {
      // Check if we have a DisplayPositionEvent
      const DisplayPositionEvent *dpe =
        dynamic_cast< const DisplayPositionEvent * >( stateEvent->GetEvent() );
      if ( dpe == NULL )
      {
        ok = true;
        break;
      }

      if ( currentVtkRenderer != NULL )
      {
        vtkInteractorObserver::ComputeDisplayToWorld(
          currentVtkRenderer,
          m_CurrentPickedDisplayPoint[0],
          m_CurrentPickedDisplayPoint[1],
          0.0, //m_InitialInteractionPickedPoint[2],
          m_CurrentPickedPointWorld );
      }


      Vector3D interactionMove;
      interactionMove[0] = m_CurrentPickedPointWorld[0] - m_InitialPickedPointWorld[0];
      interactionMove[1] = m_CurrentPickedPointWorld[1] - m_InitialPickedPointWorld[1];
      interactionMove[2] = m_CurrentPickedPointWorld[2] - m_InitialPickedPointWorld[2];

      if ( m_InteractionMode == INTERACTION_MODE_TRANSLATION )
      {
        Point3D origin = m_OriginalGeometry->GetOrigin();

        Vector3D transformedObjectNormal;
        data->GetGeometry( timeStep )->IndexToWorld(
          m_ObjectNormal, transformedObjectNormal );

        data->GetGeometry( timeStep )->SetOrigin(
          origin + transformedObjectNormal * (interactionMove * transformedObjectNormal) );
      }
      else if ( m_InteractionMode == INTERACTION_MODE_ROTATION )
      {
        if ( camera )
        {
          double vpn[3];
          camera->GetViewPlaneNormal( vpn );

          Vector3D viewPlaneNormal;
          viewPlaneNormal[0] = vpn[0];
          viewPlaneNormal[1] = vpn[1];
          viewPlaneNormal[2] = vpn[2];

          Vector3D rotationAxis =
            itk::CrossProduct( viewPlaneNormal, interactionMove );
          rotationAxis.Normalize();

          int *size = currentVtkRenderer->GetSize();
          double l2 =
            (m_CurrentPickedDisplayPoint[0] - m_InitialPickedDisplayPoint[0]) *
            (m_CurrentPickedDisplayPoint[0] - m_InitialPickedDisplayPoint[0]) +
            (m_CurrentPickedDisplayPoint[1] - m_InitialPickedDisplayPoint[1]) *
            (m_CurrentPickedDisplayPoint[1] - m_InitialPickedDisplayPoint[1]);

          double rotationAngle = 360.0 * sqrt(l2/(size[0]*size[0]+size[1]*size[1]));

          // Use center of data bounding box as center of rotation
          Point3D rotationCenter = m_OriginalGeometry->GetCenter();;

          // Reset current Geometry3D to original state (pre-interaction) and
          // apply rotation
          RotationOperation op( OpROTATE, rotationCenter, rotationAxis, rotationAngle );
          BaseGeometry::Pointer newGeometry = static_cast< BaseGeometry * >(
            m_OriginalGeometry->Clone().GetPointer() );
          newGeometry->ExecuteOperation( &op );
          data->SetClonedGeometry(newGeometry, timeStep);
        }
      }

      RenderingManager::GetInstance()->RequestUpdateAll();
      ok = true;
      break;
    }



  default:
    return Superclass::ExecuteAction( action, stateEvent );
  }

  return ok;
}
Ejemplo n.º 23
0
void CMuscle::draw()
{

	double pi = 3.14159;
//	double colorCoef;
	GLUquadricObj *quadObj; 
	quadObj = gluNewQuadric(); 

	/*
	if(strength >= income - threshold)
	{
		colorCoef = (income > threshold) * (income - threshold) / strength;
	}
	else
	{
		colorCoef = 1;
	}
	*/

	//if(activity == 1)
	//{
		//glColor3ub(250 / MStrength * (income - threshold) , 0, 0);
	//}
	//else 
	//{
	//	glColor3ub(50 + (int)(150 *colorCoef), 70, 70);
	//}

	float act;
	int r,g,b;
	r = 80;
	g = 80;
	b = 80;
	/*
	double dl = (getP1Pos()-getP2Pos()).length() - getLength0();
	
	if( (act = getActivity())<=1 || dl < 0.0) 
	{

		r += (int)((float)r*2.f*act);
	}
	*/
	r += (255-80)*min(getActivity(),1.f);

	/**/
	//double dl = (getP1Pos()-getP2Pos()).length() - getLength0();
	//if( dl < 0.0) g+= -dl*300;
	/*if( dl < 0.0) { r+= -(int)(dl*500); g+= (int)dl*200; b += (int)dl*200; }
	if(r>255) r = 255;
	if(g<0) g = 0;
	if(b<0) b = 0;*/
	/**/
		//(i_p1->getPos() - i_p2->getPos()).length()
	
	glColor3ub(r,g,b);
	//Vector3D rp1 = (ort1*p1->getX() + ort2*p1->getY() + ort3*p1->getZ())*scale + vcenter;
	Vector3D rp1 = (ort1*(p1->getX()-pos_rc.x) + ort2*(p1->getY()-pos_rc.y) + ort3*(p1->getZ()-pos_rc.z))*scale + vcenter;
	//Vector3D rp2 = (ort1*p2->getX() + ort2*p2->getY() + ort3*p2->getZ())*scale + vcenter;
	Vector3D rp2 = (ort1*(p2->getX()-pos_rc.x) + ort2*(p2->getY()-pos_rc.y) + ort3*(p2->getZ()-pos_rc.z))*scale + vcenter;

	Vector3D p = rp2 - rp1;
	double h = p.length();// /2;

	glPushMatrix();
	
	glTranslated(rp1.x, rp1.y, rp1.z);
	glRotated(180.0f*(double)atan2(p.x,p.z)/pi,0,1,0); 
	glRotated(-180.0f*(double)atan2(p.y,sqrt(p.x*p.x+p.z*p.z))/pi,1,0,0); 
	
	if(mode==0)
		gluCylinder(quadObj, 0, 0.02*scale, h, 16, 16);
	else
		gluCylinder(quadObj, 0, 0.05*scale, h, 16, 16);

	glPopMatrix();

	//p = p1->getPos() - p2->getPos();
	/*
	p = rp1 - rp2;

	glPushMatrix();

	glTranslated(rp2.x, rp2.y, rp2.z);
	glRotated(180.0f*(double)atan2(p.x,p.z)/pi,0,1,0); 
	glRotated(-180.0f*(double)atan2(p.y,sqrt(p.x*p.x+p.z*p.z))/pi,1,0,0);

	gluCylinder(quadObj, 0, 0.05*scale, h, 16, 16);

	glPopMatrix();
	*/

	gluDeleteQuadric(quadObj);
}
Ejemplo n.º 24
0
void mitk::PolyDataGLMapper2D::Paint( mitk::BaseRenderer * renderer )
{
    if ( IsVisible( renderer ) == false )
        return ;

    // ok, das ist aus GenerateData kopiert
    mitk::BaseData::Pointer input = const_cast<mitk::BaseData*>( GetData() );

    assert( input );

    input->Update();

    vtkPolyData * vtkpolydata = this->GetVtkPolyData();
    assert( vtkpolydata );


    vtkLinearTransform * vtktransform = GetDataNode() ->GetVtkTransform();

    if (vtktransform)
    {
      vtkLinearTransform * inversetransform = vtktransform->GetLinearInverse();

      Geometry2D::ConstPointer worldGeometry = renderer->GetCurrentWorldGeometry2D();
      PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast<const PlaneGeometry*>( worldGeometry.GetPointer() );

      if ( vtkpolydata != NULL )
      {
          Point3D point;
          Vector3D normal;

          if(worldPlaneGeometry.IsNotNull())
          {
            // set up vtkPlane according to worldGeometry
            point=worldPlaneGeometry->GetOrigin();
            normal=worldPlaneGeometry->GetNormal(); normal.Normalize();
            m_Plane->SetTransform((vtkAbstractTransform*)NULL);
          }
          else
          {
            //@FIXME: does not work correctly. Does m_Plane->SetTransform really transforms a "plane plane" into a "curved plane"?
            return;
            AbstractTransformGeometry::ConstPointer worldAbstractGeometry = dynamic_cast<const AbstractTransformGeometry*>(renderer->GetCurrentWorldGeometry2D());
            if(worldAbstractGeometry.IsNotNull())
            {
              // set up vtkPlane according to worldGeometry
              point=const_cast<mitk::BoundingBox*>(worldAbstractGeometry->GetParametricBoundingBox())->GetMinimum();
              FillVector3D(normal, 0, 0, 1);
              m_Plane->SetTransform(worldAbstractGeometry->GetVtkAbstractTransform()->GetInverse());
            }
            else
              return;
          }

          vtkFloatingPointType vp[ 3 ], vnormal[ 3 ];

          vnl2vtk(point.Get_vnl_vector(), vp);
          vnl2vtk(normal.Get_vnl_vector(), vnormal);

          //normally, we would need to transform the surface and cut the transformed surface with the cutter.
          //This might be quite slow. Thus, the idea is, to perform an inverse transform of the plane instead.
          //@todo It probably does not work for scaling operations yet:scaling operations have to be
          //dealed with after the cut is performed by scaling the contour.
          inversetransform->TransformPoint( vp, vp );
          inversetransform->TransformNormalAtPoint( vp, vnormal, vnormal );

          m_Plane->SetOrigin( vp );
          m_Plane->SetNormal( vnormal );

          // set data into cutter
          m_Cutter->SetInput( vtkpolydata );
          //    m_Cutter->GenerateCutScalarsOff();
          //    m_Cutter->SetSortByToSortByCell();

          // calculate the cut
          m_Cutter->Update();

          // fetch geometry
          mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
          assert( displayGeometry );
          //  float toGL=displayGeometry->GetSizeInDisplayUnits()[1];

          //apply color and opacity read from the PropertyList
          ApplyProperties( renderer );

          // traverse the cut contour
          vtkPolyData * contour = m_Cutter->GetOutput();

          vtkPoints *vpoints = contour->GetPoints();
          vtkCellArray *vpolys = contour->GetLines();
          vtkPointData *vpointdata = contour->GetPointData();
          vtkDataArray* vscalars = vpointdata->GetScalars();

          vtkCellData *vcelldata = contour->GetCellData();
          vtkDataArray* vcellscalars = vcelldata->GetScalars();

          int i, numberOfCells = vpolys->GetNumberOfCells();

          Point3D p;
          Point2D p2d, last, first;

          vpolys->InitTraversal();
          vtkScalarsToColors* lut = GetVtkLUT();
          assert ( lut != NULL );

          for ( i = 0;i < numberOfCells;++i )
          {
              vtkIdType *cell(NULL);
              vtkIdType cellSize(0);

              vpolys->GetNextCell( cellSize, cell );

              if ( m_ColorByCellData )
              {  // color each cell according to cell data
                vtkFloatingPointType* color = lut->GetColor( vcellscalars->GetComponent( i, 0 ) );
                glColor3f( color[ 0 ], color[ 1 ], color[ 2 ] );
              }
              if ( m_ColorByPointData )
              {
                vtkFloatingPointType* color = lut->GetColor( vscalars->GetComponent( cell[0], 0 ) );
                glColor3f( color[ 0 ], color[ 1 ], color[ 2 ] );
              }

              glBegin ( GL_LINE_LOOP );
              for ( int j = 0;j < cellSize;++j )
              {
                  vpoints->GetPoint( cell[ j ], vp );
                  //take transformation via vtktransform into account
                  vtktransform->TransformPoint( vp, vp );

                  vtk2itk( vp, p );

                  //convert 3D point (in mm) to 2D point on slice (also in mm)
                  worldGeometry->Map( p, p2d );

                  //convert point (until now mm and in worldcoordinates) to display coordinates (units )
                  displayGeometry->WorldToDisplay( p2d, p2d );

                  //convert display coordinates ( (0,0) is top-left ) in GL coordinates ( (0,0) is bottom-left )
                  //p2d[1]=toGL-p2d[1];

                  //add the current vertex to the line
                  glVertex2f( p2d[0], p2d[1] );
              }
              glEnd ();
          }
      }
    }
}
Ejemplo n.º 25
0
void Matrix3DUtils::getBackward(const Matrix3D &m, Vector3D &out) {
    m.copyColumnTo(2, out);
    out.negate();
}
Ejemplo n.º 26
0
void ScreenGL::applyViewTransform() {
    // compute view angle

    // default angle is 90, but we want to force a 1:1 aspect ratio to avoid
    // distortion.
    // If our screen's width is different than its height, we need to decrease
    // the view angle so that the angle coresponds to the smaller dimension.
    // This keeps the zoom factor constant in the smaller dimension.

    // Of course, because of the way perspective works, only one Z-slice
    // will have a constant zoom factor
    // The zSlice variable sets the distance of this slice from the picture
    // plane
    double zSlice = .31;

    double maxDimension = mWide;
    if( mHigh > mWide ) {
        maxDimension = mHigh;
        }
    double aspectDifference = fabs( mWide / 2 - mHigh / 2 ) / maxDimension;
    // default angle is 90 degrees... half the angle is PI/4
    double angle = atan( tan( M_PI / 4 ) +
                         aspectDifference / zSlice );

    // double it to get the full angle
    angle *= 2;
    
    
    // convert to degrees
    angle = 360 * angle / ( 2 * M_PI );


    // set up the projection matrix
    glMatrixMode( GL_PROJECTION );

	glLoadIdentity();
    
    //gluPerspective( 90, mWide / mHigh, 1, 9999 );
    gluPerspective( angle,
                    1,
                    1, 9999 );

    
    // set up the model view matrix
    glMatrixMode( GL_MODELVIEW );
    
    glLoadIdentity();

	// create default view and up vectors, 
	// then rotate them by orientation angle
	Vector3D *viewDirection = new Vector3D( 0, 0, 1 );
	Vector3D *upDirection = new Vector3D( 0, 1, 0 );
	
	viewDirection->rotate( mViewOrientation );
	upDirection->rotate( mViewOrientation );
	
	// get a point out in front of us in the view direction
	viewDirection->add( mViewPosition );
	
	// look at takes a viewer position, 
	// a point to look at, and an up direction
	gluLookAt( mViewPosition->mX, 
				mViewPosition->mY, 
				mViewPosition->mZ,
				viewDirection->mX, 
				viewDirection->mY, 
				viewDirection->mZ,
				upDirection->mX, 
				upDirection->mY, 
				upDirection->mZ );
	
	delete viewDirection;
	delete upDirection;
    }
Ejemplo n.º 27
0
void Matrix3DUtils::setOrientation(Matrix3D &m, const Vector3D &dir, const Vector3D &up, const float smooth) {
    getScale(m, _scale);
    
    Vector3D upp;
    Vector3D dirr;
    
    upp.copyFrom(up);
    dirr.copyFrom(dir);
    
    if (smooth != 1) {
        getDir(m, _dir);
        _dir.x += (dir.x - _dir.x) * smooth;
        _dir.y += (dir.y - _dir.y) * smooth;
        _dir.z += (dir.z - _dir.z) * smooth;
        dirr = _dir;
        
        getUp(m, _up);
        _up.x += (up.x - _up.x) * smooth;
        _up.y += (up.y - _up.y) * smooth;
        _up.z += (up.z - _up.z) * smooth;
        upp = _up;
    } else {
        dirr = dir;
    }
    dirr.normalize();
    
    Vector3D rVec;
    Vector3D::crossProduct(upp, dirr, &rVec);
    rVec.normalize();
    
    Vector3D uVec;
    Vector3D::crossProduct(dirr, rVec, &uVec);
    
    rVec.scaleBy(_scale.x);
    uVec.scaleBy(_scale.y);
    dirr.scaleBy(_scale.z);
    
    rVec.w = 0.0f;
    uVec.w = 0.0f;
    dirr.w = 0.0f;
    
    setVectors(m,rVec, uVec, dirr);
}
Ejemplo n.º 28
0
bool Datafile::write(const string &filename, bool append)
{
  if(!enabled)
    return true; // Just pretend it worked
  
  // Record starting time
  real tstart = MPI_Wtime();

  if(!file->openw(filename, append))
    return false;

  if(!file->is_valid())
    return false;
  
  file->setRecord(-1); // Latest record

  // Write integers
  for(std::vector< VarStr<int> >::iterator it = int_arr.begin(); it != int_arr.end(); it++) {
    if(it->grow) {
      file->write_rec(it->ptr, it->name);
    }else {
      file->write(it->ptr, it->name);
    }
  }
  
  // Write reals
  for(std::vector< VarStr<real> >::iterator it = real_arr.begin(); it != real_arr.end(); it++) {
    if(it->grow) {
      file->write_rec(it->ptr, it->name);
    }else {
      file->write(it->ptr, it->name);
    }
  }

  // Write 2D fields
  
  for(std::vector< VarStr<Field2D> >::iterator it = f2d_arr.begin(); it != f2d_arr.end(); it++) {
    write_f2d(it->name, it->ptr, it->grow);
  }

  // Write 3D fields
  
  for(std::vector< VarStr<Field3D> >::iterator it = f3d_arr.begin(); it != f3d_arr.end(); it++) {
    write_f3d(it->name, it->ptr, it->grow);
  }
  
  // 2D vectors
  
  for(std::vector< VarStr<Vector2D> >::iterator it = v2d_arr.begin(); it != v2d_arr.end(); it++) {
    if(it->covar) {
      // Writing covariant vector
      Vector2D v  = *(it->ptr);
      v.to_covariant();
      
      write_f2d(it->name+string("_x"), &(v.x), it->grow);
      write_f2d(it->name+string("_y"), &(v.y), it->grow);
      write_f2d(it->name+string("_z"), &(v.z), it->grow);
    }else {
      // Writing contravariant vector
      Vector2D v  = *(it->ptr);
      v.to_contravariant();
      
      write_f2d(it->name+string("x"), &(v.x), it->grow);
      write_f2d(it->name+string("y"), &(v.y), it->grow);
      write_f2d(it->name+string("z"), &(v.z), it->grow);
    }
  }

  // 3D vectors
  
  for(std::vector< VarStr<Vector3D> >::iterator it = v3d_arr.begin(); it != v3d_arr.end(); it++) {
    if(it->covar) {
      // Writing covariant vector
      Vector3D v  = *(it->ptr);
      v.to_covariant();
      
      write_f3d(it->name+string("_x"), &(v.x), it->grow);
      write_f3d(it->name+string("_y"), &(v.y), it->grow);
      write_f3d(it->name+string("_z"), &(v.z), it->grow);
    }else {
      // Writing contravariant vector
      Vector3D v  = *(it->ptr);
      v.to_contravariant();
      
      write_f3d(it->name+string("x"), &(v.x), it->grow);
      write_f3d(it->name+string("y"), &(v.y), it->grow);
      write_f3d(it->name+string("z"), &(v.z), it->grow);
    }
  }

  file->close();

  wtime += MPI_Wtime() - tstart;

  return true;
}
Ejemplo n.º 29
0
void PointDomain::vertex_normal_at( Mesh::VertexHandle ,
                                    Vector3D &coordinate) const
  { coordinate.set(0,0,0); }
Ejemplo n.º 30
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
Scalar
Line3D::GetDistanceTo(
    const OBB& box,
    int *first_axis
)
{
    Check_Object(this);
    Check_Object(&box);
    Check_Pointer(first_axis);

    //
    //------------------------------------------------------------------------
    // Get the vector from the line to the centerpoint of the OBB.  All planes
    // will be generated relative to this
    //------------------------------------------------------------------------
    //
    Point3D center;
    center = box.localToParent;
    Vector3D delta;
    delta.Subtract(center, origin);

    //
    //--------------------------------------------------
    // Set up the loop to examine each of the three axes
    //--------------------------------------------------
    //
    Scalar enters = -100.0f - length;
    Scalar leaves = length + 100.0f;
    for (int axis=X_Axis; axis <= Z_Axis; ++axis)
    {
        UnitVector3D
        normal(
            box.localToParent(axis, X_Axis),
            box.localToParent(axis, Y_Axis),
            box.localToParent(axis, Z_Axis)
        );

        //
        //----------------------------------------------------------------------
        // Now, we have to calculate how far the line moves along the normal per
        // unit traveled down the line.  If it is perpendicular to the normal,
        // then it will hit or miss based solely upon the origin location
        //----------------------------------------------------------------------
        //
        Scalar drift = direction * normal;
        Scalar distance;
        if (Small_Enough(drift))
        {
            distance = delta * normal;
            if (Fabs(distance) > box.axisExtents[axis])
                return -1.0f;
            else
                continue;
        }

        //
        //--------------------------------------------------------------------
        // We know the line is not parallel, so we will now calculate how long
        // the line will stay inside the box.  We also will calculate how far
        // from the origin to the centerplane of the OBB
        //--------------------------------------------------------------------
        //
        drift = 1.0f / drift;
        Scalar span = box.axisExtents[axis] * Fabs(drift);
        distance = (delta * normal) * drift;

        //
        //--------------------------------------------------------------------
        // Now adjust where the line can enter and leave the OBB, and if it is
        // no longer possible to hit, stop checking
        //--------------------------------------------------------------------
        //
        Scalar enter = distance - span;
        Scalar leave = distance + span;
        if (enter > enters)
        {
            *first_axis = axis;
            enters = enter;
        }
        if (leave < leaves)
            leaves = leave;
        if (enters > leaves)
            return -1.0f;
    }

    //
    //-------------------------------------------------------------------------
    // If we got here, then the line in theory can hit the OBB, so now we check
    // to make sure it hits it within the allowed span of the line
    //-------------------------------------------------------------------------
    //
    if (leaves < 0.0f || enters > length)
        return -1.0f;
    Min_Clamp(enters, 0.0f);
    return enters;
}