bool EdgeLengthQualityMetric::evaluate_vertex(PatchData &pd, MsqVertex* vert,
                                             double &fval, MsqError &err)
{
  fval=0.0;
  size_t this_vert = pd.get_vertex_index(vert);
  size_t other_vert;
  vector<size_t> adj_verts;
  Vector3D edg;
  pd.get_adjacent_vertex_indices(this_vert,adj_verts,err);  MSQ_ERRZERO(err);
  int num_sample_points=adj_verts.size();
  double *metric_values=new double[num_sample_points];
  MsqVertex* verts = pd.get_vertex_array(err);  MSQ_ERRZERO(err);
  int point_counter=0;
  while(!adj_verts.empty()){
    other_vert=adj_verts.back();
    adj_verts.pop_back();
    edg[0]=verts[this_vert][0]-verts[other_vert][0];
    edg[1]=verts[this_vert][1]-verts[other_vert][1];
    edg[2]=verts[this_vert][2]-verts[other_vert][2];    
    metric_values[point_counter]=edg.length();
    ++point_counter;
  }
  fval=average_metrics(metric_values,num_sample_points,err);  MSQ_ERRZERO(err);
  delete[] metric_values;
  
  return true;
  
}
bool AbstractSphere::rayCast(const Ray& r,Segment& sg) const {
    /*
    http://www.siggraph.org/education/materials/HyperGraph/raytrace/rtinter1.htm
    http://www.gamedev.net/topic/476158-ray-sphere-intersection/
    */
    //calc B
    // We solve this second-degree equation in t:
    // distance(p+t*v,center)==radius
    // If we define w = p-center
    // we can write that as
    // <w+t*v,w+t*v> == radius*radius
    // <w,w> + 2.0f*t*<w,v> + t*t*<v,v> - radius*radius == 0
    // <v,v>*t*t + 2.0f*<w,v>*t + <w,w>-radius*radius == 0
    // A*t*t + B*t*t + C*t*t == 0
    Vector3D w = r.point;
    float A = r.dir.dot(r.dir);
    float B = 2*w.dot(r.dir);
    float C = w.dot(w) - radius*radius;
    //calc d
    float D = B*B-4.0f*A*C;
    float sqrtD=sqrt(D);
    //points
    sg.t[0]=r.point+r.dir*(-B - sqrtD)/(2.0f*A);
    sg.t[1]=r.point+r.dir*(-B + sqrtD)/(2.0f*A);
    //
    return D >=0;
}
Example #3
0
mitk::Vector3D mitk::BaseGeometry::GetAxisVector(unsigned int direction) const
{
  Vector3D frontToBack;
  frontToBack.SetVnlVector(m_IndexToWorldTransform->GetMatrix().GetVnlMatrix().get_column(direction));
  frontToBack *= GetExtent(direction);
  return frontToBack;
}
/**
 * Phong Shading
 */
void PointLight::shade( Ray3D& ray ) {
	Intersection intPoint = ray.intersection;

	// construct vectors
	Vector3D n = intPoint.normal;
	Vector3D de = -ray.dir;
	Vector3D s = get_position() - intPoint.point; // light source
	Vector3D m = ((2 * n.dot(s)) * n) - s; // perfect mirror directions

	// normalize
	n.normalize();
	s.normalize();
	m.normalize();
	de.normalize();

	// do the diffuse shading
	do_diffuse(s, n, ray);

	// do the specular shading
	Colour specular(0, 0, 0);

	double mdde = m.dot(de);
	if ( mdde >= 0 ) {
		specular =
			pow(mdde, intPoint.mat->specular_exp)
			* intPoint.mat->specular * _col_specular;
	}

	if ( ray.shadowed ) {
		ray.col = ray.col + (_shadow_opacity * specular);
	} else {
		ray.col = ray.col + specular;
	}
}
void Margin::draw()
{

	Vector3D * scale = getScale();

	getVSML()->loadIdentity(VSMathLib::MODEL);

	// Margin
	getVSML()->pushMatrix(VSMathLib::MODEL);
	getVSML()->translate(getPosition()->getX(), getPosition()->getY(), getPosition()->getZ());
	getVSML()->scale(scale->getX(), scale->getY(), scale->getZ());

	// cube
	getVSML()->pushMatrix(VSMathLib::MODEL);
	getVSML()->translate(-0.5f, -0.5f, -0.5f);
	glUseProgram((*getShader()).getProgramIndex());
	
	getVSML()->matricesToGL();
	glBindVertexArray(vaoMargin);
	glDrawElements(GL_TRIANGLES, faceCountMargin * 3, GL_UNSIGNED_INT, 0);
	getVSML()->popMatrix(VSMathLib::MODEL);
	// cube

	getVSML()->popMatrix(VSMathLib::MODEL);
	// Margin
}
Example #6
0
//left : the other direction of the target plan of camera NORMALIZED and perpendicular to up
Vector3D left(const Camera &c)
{
    Vector3D nrm = c.target()-c.eye();//vector normal of target plan
    double u1 = c.up().get_x(), u2 = c.up().get_y(), u3 = c.up().get_z(),
           v1 = nrm.get_x(),    v2 = nrm.get_y(),    v3 = nrm.get_z();
    return normalize(Vector3D(u2*v3-u3*v2, u3*v1-u1*v3, u1*v2-u2*v1));
}
Example #7
0
double Edge3D::angle(const Point3D &p1, const Point3D &p2) const
{
	Vector3D ab = this->vector();
	Vector3D ac;

    if (this->getP1()->match(p1))
    {
        ac = Vector3D(p1, p2);
    }
    else if (this->getP1()->match(p2))
    {
        ac = Vector3D(p2, p1);
    }
    else if (this->getP2()->match(p1))
    {
    	ac = Vector3D(p1, p2);
    	ab.multiply(-1.0);
    }
    else if (this->getP2()->match(p2))
    {
        ac = Vector3D(p2, p1);
    	ab.multiply(-1.0);
    }
    else
    {
        return -1.0;
    }

    return ab.angle(ac);
}
Example #8
0
  Vector3D Vertex::normal( void ) const
  // TODO Returns an approximate unit normal at this vertex, computed by
  // TODO taking the area-weighted average of the normals of neighboring
  // TODO triangles, then normalizing.
  {
     // TODO Compute and return the area-weighted unit normal.
	 
		//no boundary polygon
		HalfedgeCIter h = this->halfedge();
		Vector3D nrm(0, 0, 0);
		double totalarea = 0;
		do
		{
			h = h->twin();
			FaceCIter f = h->face();
			if(!f->isBoundary())
			{
				VertexCIter v1 = h->vertex();
				VertexCIter v2 = h->next()->twin()->vertex();
				Vector3D out = cross(v1->position - position, v2->position - position);
				nrm += out;
				totalarea += out.norm();
			}
			h = h->next();
		}
		while(h != this->halfedge());
		nrm /= totalarea;
		nrm.normalize();
		return nrm;
 }
Example #9
0
Point3D Shot::getWallIntersectionPoint(BoundingWall* wall) {
    if (!isBeam) {
        return Object3D::getWallIntersectionPoint(wall);
    }

    Point3D toReturn(*position);
    Point3D pointOnPlane = wall->normal.scalarMultiply(-wall->wallSize);

    // Calculate intersection between beam and wall.
    Vector3D normalizedDirection = velocity->getNormalized();
    Vector3D wallNormal = wall->normal.scalarMultiply(-1); // To make it face away from the center.
    double rayDotNormal = normalizedDirection.dot(wallNormal);
    if (rayDotNormal <= 0) {
        wall->actuallyHit = false;
        return toReturn;
    }

    Vector3D rayOriginToPointOnPlane(*position, pointOnPlane);

    double distance = rayOriginToPointOnPlane.dot(wallNormal) / rayDotNormal;
    if (distance < 0) {
        wall->actuallyHit = false;
        return toReturn;
    }

    toReturn.addUpdate(normalizedDirection.scalarMultiply(distance));
    return toReturn;
}
Example #10
0
bool Mesh::intersect(const Ray& ray, Intersection& j) const
{
  bool intersected = false;

  // Check if bounding ball has been intersected first
  // If not then the mesh cannot have been intersected
  Intersection k;
  bool bball_intersected = m_boundingBall.intersect(ray, k);
  if(bball_intersected)
  {
    // Loop through each face and check if there is an intersection
    double prev_t = std::numeric_limits<double>::infinity();
    for(auto face : m_faces)
    {
      // Compute the normal for the face
      Point3D P0 = m_verts[face[0]];
      Point3D P1 = m_verts[face[1]];
      Point3D P2 = m_verts[face[2]];

      Vector3D n = (P1-P0).cross(P2-P0).normalized();

      // Now check if the ray intersects the polygon containing the face
      // If denom is 0 then the ray does not intersect the plane at all
      double denom = n.dot(ray.direction());
      if(fabs(denom) < std::numeric_limits<double>::epsilon()) continue;

      // If t is negative or a previous intersection has a smaller t (meaning it is closer to the
      // ray's origin) then disregard this face and continue
      double t = n.dot(P0 - ray.origin()) / denom;
      if(t < 0 || prev_t < t) continue;

      // Calculate intersection point
      Point3D Q = ray.origin() + t*ray.direction();

      bool outside = false;
      for(size_t i = 0; i < face.size(); i++)
      {
        Point3D Q0 = (i == 0) ? m_verts[face.back()] : m_verts[face[i-1]];
        Point3D Q1 = m_verts[face[i]];

        if((Q1-Q0).cross(Q-Q0).dot(n) < 0)
        {
          outside = true;
          break;
        }
      }

      if(!outside)
      {
        // It is within the bounds of the polygon
        intersected = true;
        prev_t = t;
        j.q = Q;
        j.n = n;
      }
    }
  }

  return intersected;
}
Example #11
0
Vector4D::Vector4D(const Vector3D& v, float w)
{
	vec[0] = v.x();
	vec[1] = v.y();
	vec[2] = v.z();
	vec[3] = w;
}
Example #12
0
void
PlaneGeometry::InitializeStandardPlane( const Vector3D &rightVector,
  const Vector3D &downVector, const Vector3D *spacing )
{
  InitializeStandardPlane( rightVector.GetVnlVector(),
    downVector.GetVnlVector(), spacing );
}
Example #13
0
void Quaternion::AxisToQuat(const Vector3D &v, const float angle)
{
  //float x,y,z;			// temp vars of vector
	double rad, scale;		// temp vars

	if (v.IsZero())			// if axis is zero, then return quaternion (1,0,0,0)
	{
		w	= 1.0f;
		x	= 0.0f;
		y	= 0.0f;
		z	= 0.0f;

		return;
	}

	assert(v.IsUnit());		// make sure the axis is a unit vector

	rad		= angle / 2;

	w		= (float)cos(rad);

	scale	= sin(rad);

	//v.GetValues(x, y, z);

	this->x = float(v.x * scale);
	this->y = float(v.y * scale);
	this->z = float(v.z * scale);

	Normalize();		// make sure a unit quaternion turns up

	return;
}	// end void AxisToQuat(..)
Example #14
0
void Solver::initialize()
{
  for (int id = 0; id < blockManager.getNumBlock(); ++id) {
    BlockBase* block = blockManager.getBlock(id);

    Scalar3D<double>* s
        = dynamic_cast<Scalar3D<double>*>(block->getDataClass(id_s));
    double* sData = s->getData();
    Index3DS sIndex = s->getIndex();

    Vector3D<double>* v
        = dynamic_cast<Vector3D<double>*>(block->getDataClass(id_v));
    double* vData = v->getData();
    Index3DV vIndex = v->getIndex();

    const Vec3d& orig = block->getOrigin();
    const Vec3d& pitch = block->getCellSize();

    for (int k = -vc; k < nz+vc; k++) {
      for (int j = -vc; j < ny+vc; j++) {
        for (int i = -vc; i < nx+vc; i++) {
          double x = orig.x + (i + 0.5) * pitch.x;
          double y = orig.y + (j + 0.5) * pitch.y;
          double z = orig.z + (k + 0.5) * pitch.z;
          sData[sIndex(i,j,k)] = sqrt(x*x + y*y + z*z);
          vData[vIndex(i,j,k)+0] = x;
          vData[vIndex(i,j,k)+1] = y;
          vData[vIndex(i,j,k)+2] = z;
        }
      }
    }

  }
}
Example #15
0
bool Renderer::isChunkVisible(Vector3D origin, Vector3D pos)
{
	Vector3D dist = pos - origin;

	if(dist.magnitude() <= 4.0)
		return true;

	return false;
}
double angle_between_two_vectors(Vector3D A,Vector3D B)
{
  double A_DOT_B=A.DotProduct(B);
  double A_length=A.CalculateLength();
  double B_length=B.CalculateLength();
  double AB=A_length*B_length;
  double angle=180*acos(A_DOT_B/AB)/3.14;
  return angle;
}
Example #17
0
Vector3D
PlaneGeometry::GetNormal() const
{
  Vector3D frontToBack;
  frontToBack.SetVnlVector( m_IndexToWorldTransform
    ->GetMatrix().GetVnlMatrix().get_column(2) );

  return frontToBack;
}
Example #18
0
void ModifierRattle::doExecute(Integrator *i) {
  // estimate the current error in all velocity constraints
  Real error = calcError();

  // delta_t
  Real dt = i->getTimestep() / Constant::TIMEFACTOR;

  int iter = 0;
  while (error > myEpsilon) {
    for (unsigned int i = 0; i < myListOfConstraints->size(); i++) {
      // find the ID#s of the two atoms in the current constraint
      int a1 = (*myListOfConstraints)[i].atom1;
      int a2 = (*myListOfConstraints)[i].atom2;

      // reciprocal atomic masses
      Real rM1 = 1 / app->topology->atoms[a1].scaledMass;
      Real rM2 = 1 / app->topology->atoms[a2].scaledMass;

      // now lets compute the lambdas.
      // compute the current bond vector
      Vector3D rab = app->positions[a1] - app->positions[a2];
      Real rabsq = rab.normSquared();

      // compute the current velocity vector
      Vector3D vab = app->velocities[a1] - app->velocities[a2];

      // dot product of distance and velocity vectors
      Real rvab = rab * vab;

      // compute the change in lambda
      Real gab = -rvab / (dt * (rM1 + rM2) * rabsq);
      Vector3D dp = rab * gab;

      // move the velocities based upon the multiplier
      app->velocities[a1] += dp * dt * rM1;
      app->velocities[a2] -= dp * dt * rM2;

      // the constraint adds a force to each atom since their positions
      // had to be changed.  This constraint force therefore contributes
      // to the atomic virial.  Note that the molecular virial is independent of
      // any intramolecular constraint forces.
      if (app->energies.virial()) app->energies.addVirial(dp * 2, rab);
    }

    // compute the error in all the velocity constraints after this RATTLE
    // iteration
    error = calcError();
    iter++;
    if (iter > myMaxIter) {
      report << warning << "maxIter = " << myMaxIter
             << " reached, but still not converged ... error is " << error <<
      endr;
      break;
    }
  }
}
Example #19
0
void
PlaneGeometry::InitializeStandardPlane( mitk::ScalarType width,
  ScalarType height, const Vector3D &rightVector, const Vector3D &downVector,
  const Vector3D *spacing )
{
  InitializeStandardPlane(
    width, height,
    rightVector.GetVnlVector(), downVector.GetVnlVector(),
    spacing );
}
Example #20
0
//obtains the orientation matrix based on the unitary vector x, 
//the vector vv corrspondent to y. z is cw defined, and vv corrected
OrientationMatrix::OrientationMatrix(Vector3D vu, Vector3D vv)
{
	vu.normalize();
	Vector3D vw=vu.cross(vv);
	vw.normalize();
	vv=vw.cross(vu);
	mat[0][0]=vu[0];mat[1][0]=vu[1];mat[2][0]=vu[2];
	mat[0][1]=vv[0];mat[1][1]=vv[1];mat[2][1]=vv[2];
	mat[0][2]=vw[0];mat[1][2]=vw[1];mat[2][2]=vw[2];
}
  //
  // Static methods
  //
  static Vector3D<T> add(Vector3D<T> v1, Vector3D<T> v2)
  {
    Vector3D<T> result = Vector3D<T>(v1._x, v1._y, v1._z);

    result._x += v2.getX();
    result._y += v2.getY();
    result._z += v2.getZ();

    return result;
  }
  static Vector3D<T> subtract(Vector3D<T> v1, Vector3D<T> v2)
  {
    Vector3D<T> result = Vector3D<T>(v1._x, v1._y, v1._z);

    result._x -= v2.getX();
    result._y -= v2.getY();
    result._z -= v2.getZ();

    return result;
  }
Example #23
0
double CMesh::GetEdgeLen(UINT iEdge)
{
	CVertex* pVertex[2];
	pVertex[0]=&(m_pVertex[m_pEdge[iEdge].m_iVertex[0]]);
	pVertex[1]=&(m_pVertex[m_pEdge[iEdge].m_iVertex[1]]);
		
	//get the vector
	Vector3D v = pVertex[0]->m_vPosition-pVertex[1]->m_vPosition;
	return v.length();
}
Example #24
0
bool UnitSphere::intersect( Ray3D& ray, const Matrix4x4& worldToModel,
		const Matrix4x4& modelToWorld ) {
	// TODO: implement intersection code for UnitSphere, which is centred 
	// on the origin.  
	//
	// Your goal here is to fill ray.intersection with correct values
	// should an intersection occur.  This includes intersection.point, 
	// intersection.normal, intersection.none, intersection.t_value.   
	//
	// HINT: Remember to first transform the ray into object space  
	// to simplify the intersection test.
	Point3D world_origin(0, 0, 0);
	
	double lambda;
	
	Vector3D d = worldToModel * ray.dir;
	Point3D a = worldToModel * ray.origin;
	Point3D c(0, 0, 0);
	Vector3D nmb = a - c;
	
	double A = d.dot(d);
	double B = nmb.dot(d);
	double C = nmb.dot(nmb) - 1;
	
	double D = (B * B) - (A * C);
	
	if (D < 0){
		return false;
	}
	else if(D == 0){
		lambda = - (B / A);
	}
	else{
		double lambda1 = - (B / A) + (sqrt(D) / A);
		double lambda2 = - (B / A) - (sqrt(D) / A);
		lambda = std::min(lambda1, lambda2);
		if (lambda < 0){
			lambda = std::max(lambda1, lambda2);
			if (lambda < 0){
				return false;
			}
		}
	}
	Point3D intersect_point = a + (lambda * d);
    Vector3D normal_vector = intersect_point - c;
    normal_vector.normalize();
    
	ray.intersection.t_value = lambda;
    ray.intersection.normal = transNorm(worldToModel, normal_vector);
    ray.intersection.normal.normalize();
    ray.intersection.point = modelToWorld * intersect_point;
    ray.intersection.none = false;
	return true;
}
Example #25
0
mitk::Vector3D
  mitk::SlicedGeometry3D::AdjustNormal( const mitk::Vector3D &normal ) const
{
  TransformType::Pointer inverse = TransformType::New();
  m_ReferenceGeometry->GetIndexToWorldTransform()->GetInverse( inverse );

  Vector3D transformedNormal = inverse->TransformVector( normal );

  transformedNormal.Normalize();
  return transformedNormal;
}
Example #26
0
void
  mitk::SlicedGeometry3D
  ::SetDirectionVector( const mitk::Vector3D& directionVector )
{
  Vector3D newDir = directionVector;
  newDir.Normalize();
  if ( newDir != m_DirectionVector )
  {
    m_DirectionVector = newDir;
    this->Modified();
  }
}
Example #27
0
///// paintGL /////////////////////////////////////////////////////////////////
void GLView::paintGL()
/// Overridden from QGlWidget::paintGL(). Does the drawing of the OpenGL scene.
{
  if(staticUpdateIndex != updateIndex)
    updateGLSettings();

  ///// build a quaternion from the user's changes
  Quaternion<float> changeQuaternion(xRot, yRot, zRot);
  ///// multiply it with the current quaternion
  Quaternion<float> tempQuaternion = *orientationQuaternion;
  *orientationQuaternion = tempQuaternion*changeQuaternion;  // no *= operator implemented yet => calling default constructor?
  ///// generate an axis-angle representation for OpenGL
  Vector3D<float> axis;
  float angle;
  orientationQuaternion->getAxisAngle(axis, angle);

  if(!animation)
  {
    ///// reset the changes
    xRot = 0.0f;
    yRot = 0.0f;
    zRot = 0.0f;
  }

  //if(baseParameters.antialias)
  //{
  //  glClear(GL_COLOR_BUFFER_BIT);
  //}
  //else
  //{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  //}

  glLoadIdentity();
  //qDebug("GlView::xPos = %f, yPos = %f, zPos = %f", xPos, yPos, zPos);
  //qDebug("GlView::orientationQuaternion = (%f, %f, %f, %f)",orientationQuaternion->x(),orientationQuaternion->y(),orientationQuaternion->z(),orientationQuaternion->w());
  ///// camera setup
  if(baseParameters.perspectiveProjection)
    gluLookAt(0.0f, 0.0f, zPos, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
  else
    resizeGL(width(), height());
  glPushMatrix();
  glTranslatef(xPos, yPos, 0.0f);
  glRotatef(angle, axis.x(), axis.y(), axis.z());

  drawScene(); // pure virtual

  glPopMatrix();
  glFlush(); // drawing is complete => send for execution
  if(animation)
    timer->start(redrawWait);
}
Example #28
0
void ExtendoHand::getHeading(Vector3D &m) {
    if (nineAxis) {
#ifdef ENABLE_MAGNETOMETER
        int16_t mx, my, mz;
        magnet.getHeading(&mx, &my, &mz);
        m.set(mx, my, mz);
#else
        m.set(0, 0, 0);
#endif // ENABLE_MAGNETOMETER
    } else {
        m.set(0, 0, 0);
    }
}
Example #29
0
void ExtendoHand::getRotation(Vector3D &g) {
    if (nineAxis) {
#ifdef ENABLE_GYRO
        int16_t gx, gy, gz;
        gyro.getRotation(&gx, &gy, &gz);
        g.set(gx, gy, gz);
#else
        g.set(0, 0, 0);
#endif // ENABLE_GYRO
    } else {
        g.set(0, 0, 0);
    }
}
Example #30
0
/**
 * Diffuse Shading
 */
void PointLight::shade_diffuse( Ray3D& ray ) {
	Intersection intPoint = ray.intersection;

	// construct vectors
	Vector3D n = intPoint.normal;
	Vector3D s = get_position() - intPoint.point;

	// normalize
	n.normalize();
	s.normalize();

	do_diffuse(s, n, ray);
}