Example #1
0
void Qualitative::drawBox(Point3D a, Point3D b) {
  double min_x, min_y, min_z, max_x, max_y, max_z;
  if (a.x() > b.x()) {
    max_x = a.x(); min_x = b.x();
  } else {
    max_x = b.x(); min_x = a.x();
  }
  if (a.y() > b.y()) {
    max_y = a.y(); min_y = b.y();
  } else {
    max_y = b.y(); min_y = a.y();
  }
  if (a.z() > b.z()) {
    max_z = a.z(); min_z = b.z();
  } else {
    max_z = b.z(); min_z = a.z();
  }
  glBegin(GL_QUADS);
  // X-Y faces
  glVertex3d( min_x, min_y, min_z );
  glVertex3d( max_x, min_y, min_z );
  glVertex3d( max_x, max_y, min_z );
  glVertex3d( min_x, max_y, min_z );
  glVertex3d( min_x, min_y, max_z );
  glVertex3d( max_x, min_y, max_z );
  glVertex3d( max_x, max_y, max_z );
  glVertex3d( min_x, max_y, max_z );
  // X-Z faces
  glVertex3d( min_x, min_y, min_z );
  glVertex3d( max_x, min_y, min_z );
  glVertex3d( max_x, min_y, max_z );
  glVertex3d( min_x, min_y, max_z );
  glVertex3d( min_x, max_y, min_z );
  glVertex3d( max_x, max_y, min_z );
  glVertex3d( max_x, max_y, max_z );
  glVertex3d( min_x, max_y, max_z );
  // Y-Z faces
  glVertex3d( min_x, min_y, min_z );
  glVertex3d( min_x, max_y, min_z );
  glVertex3d( min_x, max_y, max_z );
  glVertex3d( min_x, min_y, max_z );
  glVertex3d( max_x, min_y, min_z );
  glVertex3d( max_x, max_y, min_z );
  glVertex3d( max_x, max_y, max_z );
  glVertex3d( max_x, min_y, max_z );
  glEnd();
  //cout << "draw box" << endl;
}
/** Aims at an object.
 *
 * This function should be called multiple frames consecutively in order
 * to actually aim at the object. The gun barrel has a rotation time,
 * and this function takes care of moving the virtual barrel to where it
 * needs to be. This will take care of predicting where the target will
 * be based on its current velocity.
 *
 * @param dt time difference since last frame, for gun turning.
 * @return Whether or not the ship is ready to fire.
 */
bool ShootingAI::aimAt(double dt, Object3D* target) {
   Vector3D wouldHit;
   Vector3D randomVariation;
   double ang = 0;

   //------------------------------
   // Add a random variation to the aim.
   // randomVariation is between <-1, -1, -1> and <1, 1, 1>
   randomVariation.randomMagnitude();

   /* maxDifficulty - difficulty ensures that high difficulty means very 
    * little is added onto the randomVariation. Low difficulty means that
    * a large number is added onto the randomVariation.
    * The accuracy scales exponentially. Even a max difficulty AI will have
    * some small randomIAVariationAmount per weapon.
    */
   //randomVariation.scalarMultiplyUpdate(chosenWeapon->randomAIVariationAmount + (maxDifficulty - difficulty)/((float)difficulty / 2));
   randomVariation.scalarMultiplyUpdate(chosenWeapon->randomAIVariationAmount + ((maxDifficulty - difficulty)*(maxDifficulty - difficulty)/15));
   //aim.addUpdate(randomVariation);
   //-----------------------------

   Point3D aim = lastShotPos;
   Point3D targetPos = chosenWeapon->project(target, randomVariation);
   Vector3D targetDir = (targetPos - ship->shotOrigin).getNormalized();


   // This section of code does angle interpolation.
   // Find the angle between our vector and where we want to be.
   ang = acos(aim * targetDir);

   // Get our axis of rotation.
   wouldHit = (aim ^ targetDir);
   wouldHit.normalize();

   if (ang > (gunRotSpeed * dt)) {
      Quaternion q;
      q.FromAxis(wouldHit, gunRotSpeed * dt);

      aim = q * aim;
      // Normalize the vector.
      aim.normalize();
   }
   else {
      aim = targetDir;
   }


   // The aiming should be clamped within a radius
   //double forwardDotAim = aim.dot(*ship->forward);
   double forwardDotAim = targetDir.dot(*ship->forward);
   /*
   double upDotAim = aim.dot(*ship->up);
   double rightDotAim = aim.dot(*ship->right);
   */
   // (Root 2)/2 radians
   const double minForwardAimAmount = 0.707;

   ship->updateShotDirection(aim);
   lastShotPos = aim;

   bool shouldFire = !chosenWeapon->isOverheated() && 
    chosenWeapon->shouldFire(&targetPos, &aim);


   /* If the cursor is going outside of the allowable range, choose a new target.
    * Make sure we don't fire.
    */
   if(forwardDotAim < minForwardAimAmount) {
      needToChooseTarget = true;
      shouldFire = false;
   }
   return shouldFire;
}
SolidPolygon3D SolidPolygon3D::moveResult(Point3D delta){
	return moveResult(delta.getX(), delta.getY(), delta.getZ());
}
float squareDistance(const Point3D & u, const Point3D & v)
{
    return (sqr(u.x() - v.x()) + sqr(u.y() - v.y()) + sqr(u.z() - v.z()));
}
void mitk::Geometry2DDataToSurfaceFilter::GenerateOutputInformation()
{
  mitk::Geometry2DData::ConstPointer input = this->GetInput();
  mitk::Surface::Pointer output = this->GetOutput();

  if ( input.IsNull() || (input->GetGeometry2D() == NULL)
    || (input->GetGeometry2D()->IsValid() == false)
    || (m_UseBoundingBox && (m_BoundingBox.IsNull() || (m_BoundingBox->GetDiagonalLength2() < mitk::eps))) )
  {
    return;
  }

  Point3D origin;
  Point3D right, bottom;

  vtkPolyData *planeSurface = NULL;


  // Does the Geometry2DData contain a PlaneGeometry?
  if ( dynamic_cast< PlaneGeometry * >( input->GetGeometry2D() ) != NULL )
  {
    mitk::PlaneGeometry *planeGeometry =
      dynamic_cast< PlaneGeometry * >( input->GetGeometry2D() );

    if ( m_PlaceByGeometry )
    {
      // Let the output use the input geometry to appropriately transform the
      // coordinate system.
      mitk::Geometry3D::TransformType *affineTransform =
        planeGeometry->GetIndexToWorldTransform();

      TimeGeometry *timeGeometry = output->GetTimeGeometry();
      Geometry3D *geometrie3d = timeGeometry->GetGeometryForTimeStep( 0 );
      geometrie3d->SetIndexToWorldTransform( affineTransform );
    }

    if ( !m_UseBoundingBox)
    {
      // We do not have a bounding box, so no clipping is required.

      if ( m_PlaceByGeometry )
      {
        // Derive coordinate axes and origin from input geometry extent
        origin.Fill( 0.0 );
        FillVector3D( right,  planeGeometry->GetExtent(0), 0.0, 0.0 );
        FillVector3D( bottom, 0.0, planeGeometry->GetExtent(1), 0.0 );
      }
      else
      {
        // Take the coordinate axes and origin directly from the input geometry.
        origin = planeGeometry->GetOrigin();
        right = planeGeometry->GetCornerPoint( false, true );
        bottom = planeGeometry->GetCornerPoint( true, false );
      }

      // Since the plane is planar, there is no need to subdivide the grid
      // (cf. AbstractTransformGeometry case)
      m_PlaneSource->SetXResolution( 1 );
      m_PlaneSource->SetYResolution( 1 );

      m_PlaneSource->SetOrigin( origin[0], origin[1], origin[2] );
      m_PlaneSource->SetPoint1( right[0], right[1], right[2] );
      m_PlaneSource->SetPoint2( bottom[0], bottom[1], bottom[2] );

      m_PlaneSource->Update();
      planeSurface = m_PlaneSource->GetOutput();

    }
    else
    {
      // Set up a cube with the extent and origin of the bounding box. This
      // cube will be clipped by a plane later on. The intersection of the
      // cube and the plane will be the surface we are interested in. Note
      // that the bounding box needs to be explicitly specified by the user
      // of this class, since it is not necessarily clear from the data
      // available herein which bounding box to use. In most cases, this
      // would be the bounding box of the input geometry's reference
      // geometry, but this is not an inevitable requirement.
      mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum();
      mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum();
      mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter();

      m_CubeSource->SetXLength( boundingBoxMax[0] - boundingBoxMin[0] );
      m_CubeSource->SetYLength( boundingBoxMax[1] - boundingBoxMin[1] );
      m_CubeSource->SetZLength( boundingBoxMax[2] - boundingBoxMin[2] );
      m_CubeSource->SetCenter(
        boundingBoxCenter[0],
        boundingBoxCenter[1],
        boundingBoxCenter[2] );


      // Now we have to transform the cube, so that it will cut our plane
      // appropriately. (As can be seen below, the plane corresponds to the
      // z-plane in the coordinate system and is *not* transformed.) Therefore,
      // we get the inverse of the plane geometry's transform and concatenate
      // it with the transform of the reference geometry, if available.
      m_Transform->Identity();
      m_Transform->Concatenate(
        planeGeometry->GetVtkTransform()->GetLinearInverse()
      );

      Geometry3D *referenceGeometry = planeGeometry->GetReferenceGeometry();
      if ( referenceGeometry )
      {
        m_Transform->Concatenate(
          referenceGeometry->GetVtkTransform()
        );
      }

      // Transform the cube accordingly (s.a.)
      m_PolyDataTransformer->SetInputConnection( m_CubeSource->GetOutputPort() );
      m_PolyDataTransformer->SetTransform( m_Transform );

      // Initialize the plane to clip the cube with, as lying on the z-plane
      m_Plane->SetOrigin( 0.0, 0.0, 0.0 );
      m_Plane->SetNormal( 0.0, 0.0, 1.0 );

      // Cut the plane with the cube.
      m_PlaneCutter->SetInputConnection( m_PolyDataTransformer->GetOutputPort() );
      m_PlaneCutter->SetCutFunction( m_Plane );

      // The output of the cutter must be converted into appropriate poly data.
      m_PlaneStripper->SetInputConnection( m_PlaneCutter->GetOutputPort() );
      m_PlaneStripper->Update();

      if ( m_PlaneStripper->GetOutput()->GetNumberOfPoints() < 3 )
      {
        return;
      }

      m_PlanePolyData->SetPoints( m_PlaneStripper->GetOutput()->GetPoints() );
      m_PlanePolyData->SetPolys( m_PlaneStripper->GetOutput()->GetLines() );

      m_PlaneTriangler->SetInputData( m_PlanePolyData );


      // Get bounds of the resulting surface and use it to generate the texture
      // mapping information
      m_PlaneTriangler->Update();
      m_PlaneTriangler->GetOutput()->ComputeBounds();
      double *surfaceBounds =
        m_PlaneTriangler->GetOutput()->GetBounds();

      origin[0] = surfaceBounds[0];
      origin[1] = surfaceBounds[2];
      origin[2] = surfaceBounds[4];

      right[0] = surfaceBounds[1];
      right[1] = surfaceBounds[2];
      right[2] = surfaceBounds[4];

      bottom[0] = surfaceBounds[0];
      bottom[1] = surfaceBounds[3];
      bottom[2] = surfaceBounds[4];

      // Now we tell the data how it shall be textured afterwards;
      // description see above.
      m_TextureMapToPlane->SetInputConnection( m_PlaneTriangler->GetOutputPort() );
      m_TextureMapToPlane->AutomaticPlaneGenerationOn();
      m_TextureMapToPlane->SetOrigin( origin[0], origin[1], origin[2] );
      m_TextureMapToPlane->SetPoint1( right[0], right[1], right[2] );
      m_TextureMapToPlane->SetPoint2( bottom[0], bottom[1], bottom[2] );

      // Need to call update so that output data and bounds are immediately
      // available
      m_TextureMapToPlane->Update();


      // Return the output of this generation process
      planeSurface = dynamic_cast< vtkPolyData * >(
        m_TextureMapToPlane->GetOutput()
      );
    }
  }

  // Does the Geometry2DData contain an AbstractTransformGeometry?
  else if ( mitk::AbstractTransformGeometry *abstractGeometry =
    dynamic_cast< AbstractTransformGeometry * >( input->GetGeometry2D() ) )
  {
    // In the case of an AbstractTransformGeometry (which holds a possibly
    // non-rigid transform), we proceed slightly differently: since the
    // plane can be arbitrarily deformed, we need to transform it by the
    // abstract transform before clipping it. The setup for this is partially
    // done in the constructor.
    origin = abstractGeometry->GetPlane()->GetOrigin();
    right = origin + abstractGeometry->GetPlane()->GetAxisVector( 0 );
    bottom = origin + abstractGeometry->GetPlane()->GetAxisVector( 1 );

    // Define the plane
    m_PlaneSource->SetOrigin( origin[0], origin[1], origin[2] );
    m_PlaneSource->SetPoint1( right[0], right[1], right[2] );
    m_PlaneSource->SetPoint2( bottom[0], bottom[1], bottom[2] );

    // Set the plane's resolution (unlike for non-deformable planes, the plane
    // grid needs to have a certain resolution so that the deformation has the
    // desired effect).
    if ( m_UseGeometryParametricBounds )
    {
      m_PlaneSource->SetXResolution(
        (int)abstractGeometry->GetParametricExtent(0)
      );
      m_PlaneSource->SetYResolution(
        (int)abstractGeometry->GetParametricExtent(1)
      );
    }
    else
    {
      m_PlaneSource->SetXResolution( m_XResolution );
      m_PlaneSource->SetYResolution( m_YResolution );
    }
    if ( m_PlaceByGeometry )
    {
      // Let the output use the input geometry to appropriately transform the
      // coordinate system.
      mitk::Geometry3D::TransformType *affineTransform =
        abstractGeometry->GetIndexToWorldTransform();

      TimeGeometry *timeGeometry = output->GetTimeGeometry();
      Geometry3D *g3d = timeGeometry->GetGeometryForTimeStep( 0 );
      g3d->SetIndexToWorldTransform( affineTransform );

      vtkGeneralTransform *composedResliceTransform = vtkGeneralTransform::New();
      composedResliceTransform->Identity();
      composedResliceTransform->Concatenate(
        abstractGeometry->GetVtkTransform()->GetLinearInverse() );
      composedResliceTransform->Concatenate(
        abstractGeometry->GetVtkAbstractTransform()
        );
      // Use the non-rigid transform for transforming the plane.
      m_VtkTransformPlaneFilter->SetTransform(
        composedResliceTransform
      );
    }
    else
    {
      // Use the non-rigid transform for transforming the plane.
      m_VtkTransformPlaneFilter->SetTransform(
        abstractGeometry->GetVtkAbstractTransform()
      );
    }

    if ( m_UseBoundingBox )
    {
      mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum();
      mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum();
      //mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter();

      m_Box->SetXMin( boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2] );
      m_Box->SetXMax( boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2] );
    }
    else
    {
      // Plane will not be clipped
      m_Box->SetXMin( -10000.0, -10000.0, -10000.0 );
      m_Box->SetXMax( 10000.0, 10000.0, 10000.0 );
    }

    m_Transform->Identity();
    m_Transform->Concatenate( input->GetGeometry2D()->GetVtkTransform() );
    m_Transform->PreMultiply();

    m_Box->SetTransform( m_Transform );

    m_PlaneClipper->SetInputConnection(m_VtkTransformPlaneFilter->GetOutputPort() );
    m_PlaneClipper->SetClipFunction( m_Box );
    m_PlaneClipper->GenerateClippedOutputOff(); // important to NOT generate normals data for clipped part
    m_PlaneClipper->InsideOutOn();
    m_PlaneClipper->SetValue( 0.0 );
    m_PlaneClipper->Update();

    planeSurface = m_PlaneClipper->GetOutput();
  }

  m_NormalsUpdater->SetInputData( planeSurface );
  m_NormalsUpdater->AutoOrientNormalsOn(); // that's the trick! Brings consistency between
                                          //  normals direction and front/back faces direction (see bug 1440)
  m_NormalsUpdater->ComputePointNormalsOn();
  m_NormalsUpdater->Update();

  output->SetVtkPolyData( m_NormalsUpdater->GetOutput() );
  output->CalculateBoundingBox();
}
Point3D Point3D::operator- ( Point3D rhs ) const {
	return Point3D( getX() - rhs.getX(), getY() - rhs.getY(), getZ() - rhs.getZ() );
}
Example #7
0
mitk::InteractionEvent::Pointer mitk::EventFactory::CreateEvent(PropertyList::Pointer list)
{
  //
  std::string eventClass, eventVariant;
  list->GetStringProperty(InteractionEventConst::xmlParameterEventClass().c_str(), eventClass);
  list->GetStringProperty(InteractionEventConst::xmlParameterEventVariant().c_str(), eventVariant);

  // Query all possible attributes, if they are not present, set their default values.
  // Position Events & Key Events
  std::string strModifiers;
  InteractionEvent::ModifierKeys modifiers = InteractionEvent::NoKey;
  std::string strEventButton;
  InteractionEvent::MouseButtons eventButton = InteractionEvent::NoButton;
  std::string strButtonState;
  InteractionEvent::MouseButtons buttonState = InteractionEvent::NoButton;
  std::string strKey;
  std::string key;
  std::string strWheelDelta;
  int wheelDelta;
  std::string strSignalName = "";

  Point2D pos;
  pos.Fill(0);
  std::string strPos;

  // Position on screen
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyPositionOnScreen().c_str(), strPos))
  {
    // split comma separated string
    int commaPos;
    commaPos = strPos.find_first_of(',');

    pos[0] = static_cast<mitk::ScalarType>(std::atof(strPos.substr(0, commaPos).c_str()));
    pos[1] = static_cast<mitk::ScalarType>(std::atof(strPos.substr(commaPos + 1, strPos.length()).c_str()));
  }

  std::string strWorld;
  Point3D worldPos;
  worldPos.Fill(0);
  // Position in world coordinates
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyPositionInWorld().c_str(), strWorld))
  {
    const std::vector<std::string> coords = split(strWorld, ',');
    int i = 0;
    for (std::vector<std::string>::const_iterator it = coords.cbegin(); it != coords.cend(); ++it, ++i)
    {
      worldPos[i] = atof((*it).c_str());
    }
  }

  // Parse modifier information
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyModifier().c_str(), strModifiers))
  {
    std::vector<std::string> mods = split(strModifiers, ',');
    for (std::vector<std::string>::iterator it = mods.begin(); it != mods.end(); ++it)
    {
      std::transform((*it).cbegin(), (*it).cend(), (*it).begin(), ::toupper);
      if (*it == "CTRL")
      {
        modifiers = modifiers | InteractionEvent::ControlKey;
      }
      else if (*it == "ALT")
      {
        modifiers = modifiers | InteractionEvent::AltKey;
      }
      else if (*it == "SHIFT")
      {
        modifiers = modifiers | InteractionEvent::ShiftKey;
      }
      else
      {
        MITK_WARN << "mitkEventFactory: Invalid event modifier in config file :" << (*it);
      }
    }
  }

  // Set EventButton
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyEventButton().c_str(), strEventButton))
  {
    std::transform(strEventButton.cbegin(), strEventButton.cend(), strEventButton.begin(), ::toupper);
    if (strEventButton == "MIDDLEMOUSEBUTTON")
    {
      eventButton = InteractionEvent::MiddleMouseButton;
    }
    else if (strEventButton == "LEFTMOUSEBUTTON")
    {
      eventButton = InteractionEvent::LeftMouseButton;
    }
    else if (strEventButton == "RIGHTMOUSEBUTTON")
    {
      eventButton = InteractionEvent::RightMouseButton;
    }
    else
    {
      MITK_WARN << "mitkEventFactory: Invalid event button in config file: " << strEventButton;
    }
  }

  // Parse ButtonStates
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyButtonState().c_str(), strButtonState))
  {
    std::vector<std::string> mods = split(strButtonState, ',');
    for (std::vector<std::string>::iterator it = mods.begin(); it != mods.end(); ++it)
    {
      std::transform((*it).cbegin(), (*it).cend(), (*it).begin(), ::toupper);
      if (*it == "MIDDLEMOUSEBUTTON")
      {
        buttonState = buttonState | InteractionEvent::MiddleMouseButton;
      }
      else if (*it == "LEFTMOUSEBUTTON")
      {
        buttonState = buttonState | InteractionEvent::LeftMouseButton;
      }
      else if (*it == "RIGHTMOUSEBUTTON")
      {
        buttonState = buttonState | InteractionEvent::RightMouseButton;
      }
      else
      {
        MITK_WARN << "mitkEventFactory: Invalid event buttonstate in config file:" << (*it);
      }
    }
  }

  // Key
  if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyKey().c_str(), strKey))
  {
    key = "";
  }
  else
  {
    key = strKey;
  }
  // WheelDelta
  if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyScrollDirection().c_str(), strWheelDelta))
  {
    wheelDelta = 0;
  }
  else
  {
    std::transform(strWheelDelta.cbegin(), strWheelDelta.cend(), strWheelDelta.begin(), ::toupper);
    if (strWheelDelta == "DOWN")
    {
      wheelDelta = -1;
    }
    else
    {
      wheelDelta = 1;
    }
  }
  // Internal Signals Name
  list->GetStringProperty(InteractionEventConst::xmlEventPropertySignalName().c_str(), strSignalName);

  // Get BaseRenderer by name
  mitk::BaseRenderer *renderer = nullptr;
  std::string strRenderer;

  // only search for a renderer if there is at least one renderer registered
  if (mitk::BaseRenderer::baseRendererMap.size() > 0)
  {
    if (list->GetStringProperty(mitk::InteractionEventConst::xmlEventPropertyRendererName().c_str(), strRenderer))
    {
      // look up for renderer registered with the name in xml file
      renderer = mitk::BaseRenderer::GetByName(strRenderer);
    }

    // if not found always use first registered renderer
    if (renderer == nullptr)
      renderer = (*(mitk::BaseRenderer::baseRendererMap.cbegin())).second;
  }

  /*
   * Here the objects are created
   */

  mitk::InteractionEvent::Pointer event;
  std::transform(eventClass.cbegin(), eventClass.cend(), eventClass.begin(), ::toupper);

  if (eventClass == "MOUSEPRESSEVENT")
  {
    // buttonstates incorporate the event button (as in Qt)
    buttonState = buttonState | eventButton;
    event = MousePressEvent::New(renderer, pos, buttonState, modifiers, eventButton);
  }
  else if (eventClass == "MOUSEDOUBLECLICKEVENT")
  {
    buttonState = buttonState | eventButton;
    event = MouseDoubleClickEvent::New(renderer, pos, buttonState, modifiers, eventButton);
  }
  else if (eventClass == "MOUSEMOVEEVENT")
  {
    event = MouseMoveEvent::New(renderer, pos, buttonState, modifiers);
  }
  else if (eventClass == "MOUSERELEASEEVENT")
  {
    event = MouseReleaseEvent::New(renderer, pos, buttonState, modifiers, eventButton);
  }
  else if (eventClass == "INTERACTIONKEYEVENT")
  {
    event = InteractionKeyEvent::New(renderer, key, modifiers);
  }
  else if (eventClass == "MOUSEWHEELEVENT")
  {
    event = MouseWheelEvent::New(renderer, pos, buttonState, modifiers, wheelDelta);
  }
  else if (eventClass == "INTERACTIONPOSITIONEVENT")
  {
    event = InteractionPositionEvent::New(renderer, pos);
  }
  else if (eventClass == "INTERNALEVENT")
  {
    event = InternalEvent::New(renderer, nullptr, strSignalName);
  }
  else if (eventClass == "INTERACTIONEVENT")
  {
    event = InteractionEvent::New(renderer);
  }
  if (event.IsNull())
  {
    MITK_WARN << "Event couldn't be constructed. Please check your StateMachine patterns and config files\n for the "
                 "following event class, which is not valid: "
              << eventClass;
    return nullptr;
  }
  return event;
}
Example #8
0
/** Override : the equality operator.*/
bool Point3D::operator==(Point3D otherPt) {
    return (xCoor == otherPt.x()
	    && yCoor == otherPt.y()
	    && zCoor == otherPt.z());
}
Example #9
0
/** Override : the - operator.
 *  Returns the result of VECTOR SUBTRACTION of 2 points.
 *  e.g.: (1, 2, 3) - (3, 4, 5)  = (-2, -2, -2)--> this is returned.*/
Point3D Point3D::operator-(Point3D pt) {
    Point3D result(xCoor - pt.x(), yCoor - pt.y(), zCoor - pt.z());
    return result;
}
Example #10
0
/** Returns the dot product of 2 points.
 *  e.g. : (1,2,3).dot((3,4,5)) = 1*3 + 2*4 + 3*5= 26.*/
double Point3D::dot(Point3D pt) {
    double result = xCoor*pt.x() + yCoor*pt.y() + zCoor*pt.z();
    return result;
}
Example #11
0
/** Returns the cross (vector) product of 2 points.*/
Point3D Point3D::cross(Point3D pt) {
    Point3D result(yCoor*pt.z() - zCoor*pt.y(),
		   zCoor*pt.x() - xCoor*pt.z(),
		   xCoor*pt.y() - yCoor*pt.x());
    return result;
}
Example #12
0
void Vector3D::SetValues(Point3D p1, Point3D p2)
{
	x = p2.GetX() - p1.GetX();
	y = p2.GetY() - p1.GetY();
	z = p2.GetZ() - p1.GetZ();
}
Example #13
0
 bool operator()(const Pose& pose, const Point3D& point3d, double (&res) [2]) const
 {
 	res[0] = pose.norm() + point3d.norm();
 	res[1] = pose.squaredNorm() + point3d.squaredNorm();
 	return true;
 }
Example #14
0
double Point3D::GetDistance(const Point3D& point1)
{
	return sqrt((point1.GetX()-m_fX)*(point1.GetX()-m_fX)+
				(point1.GetY()-m_fY)*(point1.GetY()-m_fY)+
				(point1.GetZ()-m_fZ)*(point1.GetZ()-m_fZ));
}
Example #15
0
void Point3D::rotate(float t, const Point3D& cp, char axis){
	rotate(t,cp.getX(),cp.getY(),cp.getZ(),axis);
}
Example #16
0
Point3D operator*(double k, Point3D pt) {
    Point3D result(k * pt.x(), k * pt.y(), k * pt.z());
    return result;
}
MasterConfigurationDialog::MasterConfigurationDialog(DataEntry* obj) :
	ConfigurationDialog(obj, "Master Configuration Dialog", WIDTH, HEIGHT) {
	
	end();
	
	moreDialog = NULL;
	
	// initialize the object
	object = dynamic_cast<bz2object*>( obj );
	if( !object )
		return;
	
	// get information from the object that can be put into the widgets
	string objectStr = object->get();
	
	// read position
	Point3D position = Point3D(object->getPos());
	
	// read rotation
	float rotation = (object->getRotation().z());
	
	// read size
	Point3D size = Point3D(object->getSize());
	
	// read transformations
	vector< osg::ref_ptr<BZTransform> > transforms = (object->getTransformations());
	
	// find out the supported transformations and determine their field format
	supportedTransformations = string("");
	transformationFormat = string("");
	
	if(object->isKey("shift")) {
		supportedTransformations += "<shift>";
		transformationFormat += "<shift:|along x|along y|along z|>";	
	}
	if(object->isKey("shear")) {
		supportedTransformations += "<shear>";
		transformationFormat += "<shear:|dx|dy|dz|>";
	}
	if(object->isKey("spin")) {
		supportedTransformations += "<spin>";
		transformationFormat += "<spin:|Angle|dx|dy|dz|>";
	}
	if(object->isKey("scale")) {
		supportedTransformations += "<scale>";
		transformationFormat += "<scale:|x multiplier|y multiplier|z multiplier|>";
	}	
	
	// initialize widgets
	
	// position
	if( object->isKey("position") )
		positionLabel = new QuickLabel("Position", 5, 15);
	else if( object->isKey("shift") )	// "shift" can emulate "position"
		positionLabel = new QuickLabel("Shift", 5, 15);
		
	positionXField = new Fl_Float_Input(5 + 100, 15, 100, DEFAULT_TEXTSIZE + 6, "X");
	positionYField = new Fl_Float_Input(5 + 100 + 120, 15, 100, DEFAULT_TEXTSIZE + 6, "Y");
	positionZField = new Fl_Float_Input(5 + 100 + 120 + 120, 15, 100, DEFAULT_TEXTSIZE + 6, "Z");
	
	if(!(object->isKey("position") || object->isKey("shift")) ) {
		positionXField->deactivate();
		positionYField->deactivate();
		positionZField->deactivate();	
	}
	else {
		positionXField->value(ftoa(position.x()).c_str());
		positionYField->value(ftoa(position.y()).c_str());
		positionZField->value(ftoa(position.z()).c_str());	
	}
	
	// rotation
	rotationLabel = new QuickLabel("Rotation", 5, 45);
	rotationField = new Fl_Float_Input(5 + 100, 45, 100, DEFAULT_TEXTSIZE + 6, "degrees");
	rotationField->align(FL_ALIGN_RIGHT);
	
	if(!object->isKey("rotation") || object->isKey("spin")) {
		rotationField->deactivate();	// objects supporting "spin" ignore "rotation"
		rotationLabel->deactivate();
	}
	else {
		rotationField->value(ftoa(rotation).c_str());	
	}
	
	// size
	if( object->isKey("size") )
		sizeLabel = new QuickLabel("Size", 5, 75);
	else if( object->isKey("scale") )
		sizeLabel = new QuickLabel("Scale", 5, 75);
		
	sizeXField = new Fl_Float_Input(5 + 100, 75, 100, DEFAULT_TEXTSIZE + 6, "dx");
	sizeYField = new Fl_Float_Input(5 + 100 + 120, 75, 100, DEFAULT_TEXTSIZE + 6, "dy");
	sizeZField = new Fl_Float_Input(5 + 100 + 120 + 120, 75, 100, DEFAULT_TEXTSIZE + 6, "dz");
	
	if(!(object->isKey("size") || object->isKey("scale")) ) {
		sizeXField->deactivate();
		sizeYField->deactivate();
		sizeZField->deactivate();	
	}
	else {
		sizeXField->value(ftoa(size.x()).c_str());
		sizeYField->value(ftoa(size.y()).c_str());
		sizeZField->value(ftoa(size.z()).c_str());	
	}
	
	// spin (BZW 2.0 objects only)
	spinLabel = new QuickLabel("Spin", 5, 105);
	spinXField = new Fl_Float_Input(5 + 100, 105, 100, DEFAULT_TEXTSIZE + 6, "rx");
	spinYField = new Fl_Float_Input(5 + 100 + 120, 105, 100, DEFAULT_TEXTSIZE + 6, "ry");
	spinZField = new Fl_Float_Input(5 + 100 + 120 + 120, 105, 100, DEFAULT_TEXTSIZE + 6, "rz");
	
	if( !object->isKey("spin") ) {
		spinXField->deactivate();
		spinYField->deactivate();
		spinZField->deactivate();
		spinLabel->deactivate();
	}
	else {
		spinXField->value(ftoa(object->getRotation().x()).c_str());
		spinYField->value(ftoa(object->getRotation().y()).c_str());
		spinZField->value(ftoa(object->getRotation().z()).c_str());	
	}
	
	// transformation scroll area
	transformationLabel = new QuickLabel("Transformations (order matters)", 5, 145);
	transformationScrollArea = new Fl_Scroll(5, 175, WIDTH - 10, 200);
	transformationScrollArea->end();
	transformationScrollArea->box(FL_UP_BOX);
	transformationScrollArea->type(Fl_Scroll::VERTICAL_ALWAYS);
	// add the transformations if they exist and are supported
	if(transformationFormat.length() > 0 && transforms.size() > 0) {
		
		// add the transforms
		for(vector< osg::ref_ptr<BZTransform> >::iterator i = transforms.end() - 1; i != transforms.begin() - 1; i--) {
			// don't include transformations that won't be written
			if( !(*i)->isApplied() )
				continue;
			
			// next transform widget (the dimensions of which shall be calculated in the addTransformCallback_real method
			TransformWidget* nextTransform = new TransformWidget(0, 0, transformationScrollArea->w(), 3*DEFAULT_TEXTSIZE, transformationFormat.c_str(), false);
			
			nextTransform->setTransformationType( (*i)->getName().c_str() );
			nextTransform->setFields( (*i)->getData() );
			
			this->addTransformCallback_real(nextTransform);	
		}
	}
	
	// add transformation button
	addTransformationButton = new Fl_Button(15, 385, 90, DEFAULT_TEXTSIZE + 6, "Add");
	addTransformationButton->callback(addTransformCallback, this);
	addTransformationButton->when(FL_WHEN_RELEASE);
	if(transformationFormat.length() == 0)
		addTransformationButton->deactivate();	// don't add transformations if none are supported
	
	// remove transformation button
	removeTransformationButton = new Fl_Button(110, 385, 90, DEFAULT_TEXTSIZE + 6, "Remove");
	removeTransformationButton->callback(removeTransformCallback, this);
	removeTransformationButton->when(FL_WHEN_RELEASE);
	if(transformationFormat.length() == 0)
		removeTransformationButton->deactivate(); // don't remove transformations if none can be added
	
	// more button
	moreButton = new Fl_Button(WIDTH - 10 - 95 - 95 - 95, 385, 90, DEFAULT_TEXTSIZE + 6, "More...");
	moreButton->callback(moreCallback, this);
	moreButton->when(FL_WHEN_RELEASE);
	moreButton->deactivate();		// will be re-activated upon a successfull call to setAdditionalConfiguration()
	
	// edit button
	editTextButton = new Fl_Button(WIDTH - 10 - 95 - 95, 385, 90, DEFAULT_TEXTSIZE + 6, "Edit BZW");
	editTextButton->callback(editTextCallback, this);
	editTextButton->when(FL_WHEN_RELEASE);
	
	// advanced button
	advancedButton = new Fl_Button(WIDTH - 10 - 95, 385, 90, DEFAULT_TEXTSIZE + 6, "Advanced...");
	advancedButton->callback(advancedCallback, this);
	advancedButton->when(FL_WHEN_RELEASE);
	
	// add default OK/Cancel callbacks
	setOKEventHandler(OKButtonCallback, this);
	setCancelEventHandler(CancelButtonCallback, this);
	
	// add widgets
	add(positionLabel);
	add(positionXField);
	add(positionYField);
	add(positionZField);
	add(rotationLabel);
	add(rotationField);
	add(sizeLabel);
	add(sizeXField);
	add(sizeYField);
	add(sizeZField);
	add(spinLabel);
	add(spinXField);
	add(spinYField);
	add(spinZField);
	add(transformationLabel);
	add(transformationScrollArea);
	add(addTransformationButton);
	add(removeTransformationButton);
	add(moreButton);
	add(editTextButton);
	add(advancedButton);
	
}
WFMath::CoordType squareDistance(const Point3D & u, const Point3D & v)
{
    return (sqr(u.x() - v.x()) + sqr(u.y() - v.y()) + sqr(u.z() - v.z()));
}
Example #19
0
std::vector<BaseData::Pointer> ItkImageIO::Read()
{
  std::vector<BaseData::Pointer> result;

  const std::string& locale = "C";
  const std::string& currLocale = setlocale( LC_ALL, NULL );

  if ( locale.compare(currLocale)!=0 )
  {
    try
    {
      setlocale(LC_ALL, locale.c_str());
    }
    catch(...)
    {
      MITK_INFO << "Could not set locale " << locale;
    }
  }

  Image::Pointer image = Image::New();

  const unsigned int MINDIM = 2;
  const unsigned int MAXDIM = 4;

  const std::string path = this->GetLocalFileName();

  MITK_INFO << "loading " << path << " via itk::ImageIOFactory... " << std::endl;

  // Check to see if we can read the file given the name or prefix
  if (path.empty())
  {
    mitkThrow() << "Empty filename in mitk::ItkImageIO ";
  }

  // Got to allocate space for the image. Determine the characteristics of
  // the image.
  m_ImageIO->SetFileName( path );
  m_ImageIO->ReadImageInformation();

  unsigned int ndim = m_ImageIO->GetNumberOfDimensions();
  if ( ndim < MINDIM || ndim > MAXDIM )
  {
    MITK_WARN << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D.";
    ndim = MAXDIM;
  }

  itk::ImageIORegion ioRegion( ndim );
  itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize();
  itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex();

  unsigned int dimensions[ MAXDIM ];
  dimensions[ 0 ] = 0;
  dimensions[ 1 ] = 0;
  dimensions[ 2 ] = 0;
  dimensions[ 3 ] = 0;

  ScalarType spacing[ MAXDIM ];
  spacing[ 0 ] = 1.0f;
  spacing[ 1 ] = 1.0f;
  spacing[ 2 ] = 1.0f;
  spacing[ 3 ] = 1.0f;

  Point3D origin;
  origin.Fill(0);

  unsigned int i;
  for ( i = 0; i < ndim ; ++i )
  {
    ioStart[ i ] = 0;
    ioSize[ i ] = m_ImageIO->GetDimensions( i );
    if(i<MAXDIM)
    {
      dimensions[ i ] = m_ImageIO->GetDimensions( i );
      spacing[ i ] = m_ImageIO->GetSpacing( i );
      if(spacing[ i ] <= 0)
        spacing[ i ] = 1.0f;
    }
    if(i<3)
    {
      origin[ i ] = m_ImageIO->GetOrigin( i );
    }
  }

  ioRegion.SetSize( ioSize );
  ioRegion.SetIndex( ioStart );

  MITK_INFO << "ioRegion: " << ioRegion << std::endl;
  m_ImageIO->SetIORegion( ioRegion );
  void* buffer = new unsigned char[m_ImageIO->GetImageSizeInBytes()];
  m_ImageIO->Read( buffer );

  image->Initialize( MakePixelType(m_ImageIO), ndim, dimensions );
  image->SetImportChannel( buffer, 0, Image::ManageMemory );

  // access direction of itk::Image and include spacing
  mitk::Matrix3D matrix;
  matrix.SetIdentity();
  unsigned int j, itkDimMax3 = (ndim >= 3? 3 : ndim);
  for ( i=0; i < itkDimMax3; ++i)
    for( j=0; j < itkDimMax3; ++j )
      matrix[i][j] = m_ImageIO->GetDirection(j)[i];

  // re-initialize PlaneGeometry with origin and direction
  PlaneGeometry* planeGeometry = image->GetSlicedGeometry(0)->GetPlaneGeometry(0);
  planeGeometry->SetOrigin(origin);
  planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix);

  // re-initialize SlicedGeometry3D
  SlicedGeometry3D* slicedGeometry = image->GetSlicedGeometry(0);
  slicedGeometry->InitializeEvenlySpaced(planeGeometry, image->GetDimension(2));
  slicedGeometry->SetSpacing(spacing);

  MITK_INFO << slicedGeometry->GetCornerPoint(false,false,false);
  MITK_INFO << slicedGeometry->GetCornerPoint(true,true,true);

  // re-initialize TimeGeometry
  ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New();
  timeGeometry->Initialize(slicedGeometry, image->GetDimension(3));
  image->SetTimeGeometry(timeGeometry);

  buffer = NULL;
  MITK_INFO << "number of image components: "<< image->GetPixelType().GetNumberOfComponents() << std::endl;

  const itk::MetaDataDictionary& dictionary = m_ImageIO->GetMetaDataDictionary();
  for (itk::MetaDataDictionary::ConstIterator iter = dictionary.Begin(), iterEnd = dictionary.End();
       iter != iterEnd; ++iter)
  {
    std::string key = std::string("meta.") + iter->first;
    if (iter->second->GetMetaDataObjectTypeInfo() == typeid(std::string))
    {
      std::string value = dynamic_cast<itk::MetaDataObject<std::string>*>(iter->second.GetPointer())->GetMetaDataObjectValue();
      image->SetProperty(key.c_str(), mitk::StringProperty::New(value));
    }
  }

  MITK_INFO << "...finished!" << std::endl;

  try
  {
    setlocale(LC_ALL, currLocale.c_str());
  }
  catch(...)
  {
    MITK_INFO << "Could not reset locale " << currLocale;
  }

  result.push_back(image.GetPointer());
  return result;
}
Example #20
0
  void
  PlaneGeometry::InitializeStandardPlane( mitk::ScalarType width, mitk::ScalarType height,
                                          const AffineTransform3D* transform /* = nullptr */,
                                          PlaneGeometry::PlaneOrientation planeorientation /* = Axial */,
                                          mitk::ScalarType zPosition /* = 0 */,
                                          bool frontside /* = true */,
                                          bool rotated /* = false */ )
  {
    Superclass::Initialize();

    /// construct standard view.

    // We define at the moment "frontside" as: axial from above,
    // coronal from front (nose), saggital from right.
    // TODO: Double check with medicals doctors or radiologists [ ].

    // We define the orientation in patient's view, e.g. LAI is in a axial cut
    // (parallel to the triangle ear-ear-nose):
    // first axis: To the left ear of the patient
    // seecond axis: To the nose of the patient
    // third axis: To the legs of the patient.

    // Options are: L/R left/right; A/P anterior/posterior; I/S inferior/superior
    // (AKA caudal/cranial).
    // We note on all cases in the following switch block r.h. for right handed
    // or l.h. for left handed to describe the different cases.
    // However, which system is chosen is defined at the end of the switch block.

    // CAVE / be careful: the vectors right and bottom are relative to the plane
    // and do NOT describe e.g. the right side of the patient.

    Point3D origin;
    /** Bottom means downwards, DV means Direction Vector. Both relative to the image! */
    VnlVector rightDV(3), bottomDV(3);
    /** Origin of this plane is by default a zero vector and implicitly in the top-left corner: */
    origin.Fill(0);
    /** This is different to all definitions in MITK, except the QT mouse clicks.
    *   But it is like this here and we don't want to change a running system.
    *   Just be aware, that IN THIS FUNCTION we define the origin at the top left (e.g. your screen). */

    /** NormalDirection defines which axis (i.e. column index in the transform matrix)
    * is perpendicular to the plane: */
    int normalDirection;

    switch(planeorientation) // Switch through our limited choice of standard planes:
    {
      case None:
        /** Orientation 'None' shall be done like the axial plane orientation,
         *  for whatever reasons. */
      case Axial:
        if(frontside) // Radiologist's view from below. A cut along the triangle ear-ear-nose.
        {
          if(rotated==false)
            /** Origin in the top-left corner, x=[1; 0; 0], y=[0; 1; 0], z=[0; 0; 1],
            *   origin=[0,0,zpos]: LAI (r.h.)
            *
            *  0---rightDV---->                            |
            *  |                                           |
            *  |  Picture of a finite, rectangular plane   |
            *  |  ( insert LOLCAT-scan here ^_^ )          |
            *  |                                           |
            *  v  _________________________________________|
            *
            */
          {
            FillVector3D(origin,   0,  0, zPosition);
            FillVector3D(rightDV,  1,  0,         0);
            FillVector3D(bottomDV, 0,  1,         0);
          }
          else  // Origin rotated to the bottom-right corner, x=[-1; 0; 0], y=[0; -1; 0], z=[0; 0; 1],
               // origin=[w,h,zpos]: RPI (r.h.)
          {   // Caveat emptor:  Still  using  top-left  as  origin  of  index  coordinate  system!
            FillVector3D(origin,   width,  height, zPosition);
            FillVector3D(rightDV,     -1,       0,         0);
            FillVector3D(bottomDV,     0,      -1,         0);
          }
        }
        else // 'Backside, not frontside.' Neuro-Surgeons's view from above patient.
        {
          if(rotated==false) // x=[-1; 0; 0], y=[0; 1; 0], z=[0; 0; 1], origin=[w,0,zpos]:  RAS (r.h.)
          {
            FillVector3D(origin,   width,  0, zPosition);
            FillVector3D(rightDV,     -1,  0,         0);
            FillVector3D(bottomDV,     0,  1,         0);
          }
          else // Origin in the bottom-left corner, x=[1; 0; 0], y=[0; -1; 0], z=[0; 0; 1],
              // origin=[0,h,zpos]:  LPS (r.h.)
          {
            FillVector3D(origin,   0,  height, zPosition);
            FillVector3D(rightDV,  1,       0,         0);
            FillVector3D(bottomDV, 0,      -1,         0);
          }
        }
        normalDirection = 2; // That is S=Superior=z=third_axis=middlefinger in righthanded LPS-system.
      break;

      // Frontal is known as Coronal in mitk. Plane cuts through patient's ear-ear-heel-heel:
      case Frontal:
        if(frontside)
        {
          if(rotated==false) // x=[1; 0; 0], y=[0; 0; 1], z=[0; 1; 0], origin=[0,zpos,0]: LAI (r.h.)
          {
            FillVector3D(origin,   0, zPosition, 0);
            FillVector3D(rightDV,  1, 0,         0);
            FillVector3D(bottomDV, 0, 0,         1);
          }
          else // x=[-1;0;0], y=[0;0;-1], z=[0;1;0], origin=[w,zpos,h]:  RAS  (r.h.)
          {
            FillVector3D(origin,   width, zPosition, height);
            FillVector3D(rightDV,     -1,         0,      0);
            FillVector3D(bottomDV,     0,         0,     -1);
          }
        }
        else
        {
          if(rotated==false) //  x=[-1;0;0], y=[0;0;1], z=[0;1;0], origin=[w,zpos,0]: RPI (r.h.)
          {
            FillVector3D(origin,    width, zPosition,  0);
            FillVector3D(rightDV,      -1,         0,  0);
            FillVector3D(bottomDV,      0,         0,  1);
          }
          else //  x=[1;0;0], y=[0;1;0], z=[0;0;-1], origin=[0,zpos,h]: LPS (r.h.)
          {
            FillVector3D(origin,   0, zPosition,  height);
            FillVector3D(rightDV,  1,         0,       0);
            FillVector3D(bottomDV, 0,         0,      -1);
          }
        }
        normalDirection = 1; // Normal vector = posterior direction.
      break;

      case Sagittal: // Sagittal=Medial plane, the symmetry-plane mirroring your face.
        if(frontside)
        {
          if(rotated==false) //  x=[0;1;0], y=[0;0;1], z=[1;0;0], origin=[zpos,0,0]:  LAI (r.h.)
          {
            FillVector3D(origin,   zPosition, 0, 0);
            FillVector3D(rightDV,  0,         1, 0);
            FillVector3D(bottomDV, 0,         0, 1);
          }
          else //  x=[0;-1;0], y=[0;0;-1], z=[1;0;0], origin=[zpos,w,h]:  LPS (r.h.)
          {
            FillVector3D(origin,   zPosition, width, height);
            FillVector3D(rightDV,          0,    -1,      0);
            FillVector3D(bottomDV,         0,     0,     -1);
          }
        }
        else
        {
          if(rotated==false) //  x=[0;-1;0], y=[0;0;1], z=[1;0;0], origin=[zpos,w,0]:  RPI (r.h.)
          {
            FillVector3D(origin,   zPosition,  width, 0);
            FillVector3D(rightDV,          0,     -1, 0);
            FillVector3D(bottomDV,         0,      0, 1);
          }
          else //  x=[0;1;0], y=[0;0;-1], z=[1;0;0], origin=[zpos,0,h]:  RAS (r.h.)
          {
            FillVector3D(origin,   zPosition,  0, height);
            FillVector3D(rightDV,          0,  1,      0);
            FillVector3D(bottomDV,         0,  0,     -1);
          }
        }
        normalDirection = 0; // Normal vector = Lateral direction: Left in a LPS-system.
      break;

      default:
        itkExceptionMacro("unknown PlaneOrientation");
    }

    /// Checking if lefthanded or righthanded:
    mitk::ScalarType lhOrRhSign=(+1);
    if ( transform != nullptr )
    {
      lhOrRhSign = ( (0 < vnl_determinant( transform->GetMatrix().GetVnlMatrix() )) ? (+1) : (-1) );

      MITK_DEBUG << "mitk::PlaneGeometry::InitializeStandardPlane(): lhOrRhSign, normalDirection, NameOfClass, ObjectName = "
                 << lhOrRhSign << ", " << normalDirection << ", " << transform->GetNameOfClass()
                 << ", " << transform->GetObjectName() << ".";

      origin = transform->TransformPoint( origin );
      rightDV = transform->TransformVector( rightDV );
      bottomDV = transform->TransformVector( bottomDV );

      /// Signing normal vector according to l.h./r.h. coordinate system:
      this->SetMatrixByVectors( rightDV,
                                bottomDV,
                                transform->GetMatrix().GetVnlMatrix().get_column(normalDirection).two_norm() * lhOrRhSign );
    }
    else if ( transform == nullptr )
    {
      this->SetMatrixByVectors( rightDV, bottomDV );
    }

    ScalarType bounds[6]= { 0, width, 0, height, 0, 1 };

    this->SetBounds( bounds );

    this->SetOrigin( origin );
  }
Example #21
0
void GL_render()
{
    glClear( GL_COLOR_BUFFER_BIT );
    
    // For each pixel,
    for( int i = 0; i < WINDOW_WIDTH; ++i )
    {
      for( int j = 0; j < WINDOW_HEIGHT; ++j )
      {
		//cout << i << " " << j << " ";
		// Check if there is an intersection between ray and a triangle
		int which_triangle = pixelOn( i, 800 - j );
	
		if( which_triangle >= 0 )
		{
		  Point3D viewer(i, j, 1.0);
	  
		  // We now find the illumination
		  float sum = 0;
	  
		  // For all light sources
		  for( int x = 0; x < 1; ++x )
		  {
		    // We determine if there is a shadow. If so, only add ambient light
		    
		    // If there isn't, add diffuse and specular as well
		    
		    // Phong Illumination Model
		    // L = kd * Ld * cos(theta) + ks * Ls * cos( phi ) + ka * La
		    // cos( theta ) = N * l / (||N|| || L || ), where N = normal vector, L = light
		    
		    // First we find the normal vector of that triangle
		    Point3D p1 = cartesian_points.at( triangles.at( which_triangle ).p1 );  // Get x, y, z
		    Point3D p2 = cartesian_points.at( triangles.at( which_triangle ).p2 );
		    Point3D p3 = cartesian_points.at( triangles.at( which_triangle ).p3 );
		    
		    Point3D vector1 = Point3D(p1.x - p2.x, p1.y - p2.y, p1.z - p2.z);       // Get 2 vectors from pts
		    Point3D vector2 = Point3D(p1.x - p3.x, p1.y - p3.y, p1.z - p3.z);
		    
		    Point3D normal = vector1.cross( vector2 );                        // Find normal from cross
		    
		    // Using the normal, we calculate the diffuse component as Kd * Ld * ( N * l )/(|N||L|)
		    float diffuse = (normal.dot( lights[x] ) / ( normal.magnitude() * lights[x].magnitude() ))*Kd*Ld;
		    
		    // We then find our specular component using the reflected vector from the light source
		    Point3D reflector = normal * 2 * ( normal.dot( (lights[x] / lights[x].magnitude()) ) ) - lights[x];
		    float specular = (reflector.dot( viewer ) / ( reflector.magnitude() * viewer.magnitude() ))*Ks*Ls;
		    
		    // Finally, the ambient component
		    float ambient = Ka * La;
		    
		    // Find the total illumination
		    sum += diffuse + specular + ambient;
	
		  }
	  
	  	// After looping through all light sources, we then render the pixel
	    clr colour = triangles.at( which_triangle ).Color;	  	  
	    renderPixel( i, 800 - j,/*colour.R**/sum, /*colour.G**/sum, /*colour.B**/sum);

	}
      
      }
    }

    // Project 1 way of rendering triangles
    /*// Traverse through points in all polygons
    for( int i = 0; i < triangles.size(); ++i )
    {
        // Grab the 2D projected points and push them to points container
        Point3D temp;
        temp = cartesian_points[ triangles[i].p1 ]; // First point
        points.push_back( Point2D( temp.x, temp.y ) );
        
        temp = cartesian_points[ triangles[i].p2 ]; // Second point
        points.push_back( Point2D( temp.x, temp.y ) );
        
        temp = cartesian_points[ triangles[i].p3 ]; // Third point
        points.push_back( Point2D( temp.x, temp.y ) );
    }
    
    // Go through points container and output pixels
    for( int i = 0; i < points.size()/3; ++i)
    renderTPolygon(i); // Render triangle polygons, based on zbuffer depth as well*/
    
    glutSwapBuffers();
}
bool mitk::SurfaceDeformationDataInteractor3D::DeformObject (StateMachineAction*, InteractionEvent* interactionEvent)
{
  const InteractionPositionEvent* positionEvent = dynamic_cast<const InteractionPositionEvent*>(interactionEvent);
  if(positionEvent == NULL)
    return false;

  int timeStep = interactionEvent->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
  vtkPolyData* polyData = m_Surface->GetVtkPolyData(timeStep);
  Geometry3D::Pointer geometry = this->GetDataNode()->GetData()->GetGeometry(timeStep);

  Point3D currentPickedPoint = positionEvent->GetPositionInWorld();

  // Calculate mouse move in 3D space
  Vector3D interactionMove;
  interactionMove[0] = currentPickedPoint[0] - m_InitialPickedPoint[0];
  interactionMove[1] = currentPickedPoint[1] - m_InitialPickedPoint[1];
  interactionMove[2] = currentPickedPoint[2] - m_InitialPickedPoint[2];

  // Transform mouse move into geometry space
  this->GetDataNode()->GetData()->UpdateOutputInformation();// make sure that the Geometry is up-to-date
  Vector3D interactionMoveIndex;
  geometry->WorldToIndex(interactionMove, interactionMoveIndex);

  // Get picked point and transform into local coordinates
  Point3D pickedPoint;
  geometry->WorldToIndex(m_InitialPickedPoint, pickedPoint);

  Vector3D v1 = pickedPoint.GetVectorFromOrigin();

  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);
  }

  Vector3D v2 = m_ObjectNormal * (interactionMoveIndex * m_ObjectNormal);

  vtkPoints* originalPoints = m_OriginalPolyData->GetPoints();
  vtkPoints* deformedPoints = polyData->GetPoints();

  double denom = m_GaussSigma * m_GaussSigma * 2;
  double point[3];
  for (unsigned int i = 0; i < deformedPoints->GetNumberOfPoints(); ++i)
  {
    // Get original point
    double* originalPoint = originalPoints->GetPoint( i );

    Vector3D v0;
    v0[0] = originalPoint[0];
    v0[1] = originalPoint[1];
    v0[2] = originalPoint[2];

    // Calculate distance of this point from line through picked point
    double d = itk::CrossProduct(m_ObjectNormal, (v1 - v0)).GetNorm();

    Vector3D t = v2 * exp(- d * d / denom);

    point[0] = originalPoint[0] + t[0];
    point[1] = originalPoint[1] + t[1];
    point[2] = originalPoint[2] + t[2];
    deformedPoints->SetPoint(i, point);
  }

  // Make sure that surface is colorized at initial picked position as long as we are in deformation state
  m_SurfaceColorizationCenter = m_InitialPickedPoint;

  polyData->Modified();
  m_Surface->Modified();

  interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll();
  return true;
}
Example #23
0
float sqrMag(const Point3D & p)
{
    return p.x() * p.x() + p.y() * p.y() + p.z() * p.z();
}
bool mitk::SurfaceDeformationDataInteractor3D::ColorizeSurface(vtkPolyData* polyData, int timeStep, const Point3D &pickedPoint, int mode, double scalar)
{
  if (polyData == NULL)
    return false;

  vtkPoints* points = polyData->GetPoints();
  vtkPointData* pointData = polyData->GetPointData();
  if ( pointData == NULL )
    return false;

  vtkDataArray* scalars = pointData->GetScalars();
  if (scalars == NULL)
    return false;

  if (mode == COLORIZATION_GAUSS)
  {
    // Get picked point and transform into local coordinates
    Point3D localPickedPoint;
    Geometry3D::Pointer geometry = this->GetDataNode()->GetData()->GetGeometry(timeStep);
    geometry->WorldToIndex( pickedPoint, localPickedPoint );

    Vector3D v1 = localPickedPoint.GetVectorFromOrigin();

    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);
    }

    double denom = m_GaussSigma * m_GaussSigma * 2;
    for (unsigned int i = 0; i < points->GetNumberOfPoints(); ++i)
    {
      // Get original point
      double* point = points->GetPoint(i);
      Vector3D v0;
      v0[0] = point[0];
      v0[1] = point[1];
      v0[2] = point[2];

      // Calculate distance of this point from line through picked point
      double d = itk::CrossProduct(m_ObjectNormal, (v1 - v0)).GetNorm();
      double t = exp(- d * d / denom);

      scalars->SetComponent(i, 0, t);
    }
  }
  else if (mode == COLORIZATION_CONSTANT)
  {
    for (unsigned int i = 0; i < pointData->GetNumberOfTuples(); ++i)
    {
      scalars->SetComponent(i, 0, scalar);
    }
  }

  polyData->Modified();
  pointData->Update();

  return true;
}
void mitk::_InternalComputeClippedImage(itk::Image<TPixel, VImageDimension>* inputItkImage, mitk::GeometryClipImageFilter* geometryClipper, const mitk::Geometry2D* clippingGeometry2D)
{
  typedef itk::Image<TPixel, VImageDimension> ItkInputImageType;
  typedef itk::Image<TPixel, VImageDimension> ItkOutputImageType;

  typedef itk::ImageRegionConstIteratorWithIndex< ItkInputImageType > ItkInputImageIteratorType;
  typedef itk::ImageRegionIteratorWithIndex< ItkOutputImageType > ItkOutputImageIteratorType;

  typename mitk::ImageToItk<ItkOutputImageType>::Pointer outputimagetoitk = mitk::ImageToItk<ItkOutputImageType>::New();
  outputimagetoitk->SetInput(geometryClipper->m_OutputTimeSelector->GetOutput());
  outputimagetoitk->Update();
  typename ItkOutputImageType::Pointer outputItkImage = outputimagetoitk->GetOutput();

  // create the iterators
  typename ItkInputImageType::RegionType inputRegionOfInterest = inputItkImage->GetLargestPossibleRegion();
  ItkInputImageIteratorType  inputIt( inputItkImage, inputRegionOfInterest );
  ItkOutputImageIteratorType outputIt( outputItkImage, inputRegionOfInterest );

  typename ItkOutputImageType::PixelType outsideValue;
  if(geometryClipper->m_AutoOutsideValue)
    outsideValue = itk::NumericTraits<typename ItkOutputImageType::PixelType>::min();
  else
    outsideValue = (typename ItkOutputImageType::PixelType) geometryClipper->m_OutsideValue;

  mitk::Geometry3D* inputGeometry = geometryClipper->m_InputTimeSelector->GetOutput()->GetGeometry();
  typedef itk::Index<VImageDimension> IndexType;
  Point3D indexPt; indexPt.Fill(0);
  int i, dim=IndexType::GetIndexDimension();
  Point3D pointInMM;
  bool above = geometryClipper->m_ClipPartAboveGeometry;
  bool labelBothSides = geometryClipper->GetLabelBothSides();

  if (geometryClipper->GetAutoOrientLabels())
  {
    Point3D leftMostPoint;
    leftMostPoint.Fill( std::numeric_limits<float>::min() / 2.0 );
    if(clippingGeometry2D->IsAbove(pointInMM) != above)
      {
      // invert meaning of above --> left is always the "above" side
      above = !above;
    MITK_INFO << leftMostPoint << " is BELOW geometry. Inverting meaning of above" << std::endl;
    }
    else
    MITK_INFO << leftMostPoint << " is above geometry" << std::endl;
  }

  typename ItkOutputImageType::PixelType aboveLabel = (typename ItkOutputImageType::PixelType)geometryClipper->GetAboveGeometryLabel();
  typename ItkOutputImageType::PixelType belowLabel = (typename ItkOutputImageType::PixelType)geometryClipper->GetBelowGeometryLabel();

  for ( inputIt.GoToBegin(), outputIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt, ++outputIt)
  {
    if((typename ItkOutputImageType::PixelType)inputIt.Get() == outsideValue)
    {
      outputIt.Set(outsideValue);
    }
    else
    {
      for(i=0;i<dim;++i)
        indexPt[i]=(mitk::ScalarType)inputIt.GetIndex()[i];
      inputGeometry->IndexToWorld(indexPt, pointInMM);
      if(clippingGeometry2D->IsAbove(pointInMM) == above)
      {
        if ( labelBothSides )
          outputIt.Set( aboveLabel );
        else
          outputIt.Set( outsideValue );
      }
      else
      {
        if ( labelBothSides)
          outputIt.Set( belowLabel );
        else
          outputIt.Set( inputIt.Get() );
      }
    }
  }
}
Example #26
0
Point3D Point3D::mirrorResult() const{
	Point3D p;
	p.setXYZ(-x,-y,-z);	
	return p;
}
Example #27
0
// http://algolist.manual.ru/graphics/3dfaq/articles/33.php
// здесь я использую тот факт, что w = 1 / (dist + z),
// где dist - расстояние от наблюдателя до картинной плоскости
// z - расстояние от точки до той же плоскости
// так вот w - зависит в пределах грани линейно от sx, sy - экранных координат
// то есть зная w в вершинах треугольника можно найти и w для любой точки на экране внутри проекции этого треугольника
// и вместо z-буффера использовать w-буффер
void Scene3D::DrawTriangle(const Point3D &A, const Point3D &B, const Point3D &C, const Color& color)
{
	// ---------------------------------------------------------------------------------------
	// вспомогательные вычисления
	// нормаль
	const Vector3D& n = (B - A) ^ (C - A);

	if(n.Length() ==  0)
		return; // вырожденный треугольник

	// центр треугольника
	const Point3D& medium = (A + B + C) / 3.0;
	// вектор к зрителю
	const Vector3D SpectatorV = SpectatorPosition - medium;

	// ---------------------------------------------------------------------------------------
	// проверить угол между нормалью к треугольнику и направлением к зрителю
	// и если треугольник повернут "задом" то его не рисовать
	if(n * SpectatorV < 0)
	{
		return;
	}

	// ---------------------------------------------------------------------------------------
	// рассчитаем освещенность грани (считая что она освещена равномерно)
	// освещенность это сумма рассеянного освещения (ambient)
	// плюс сумма мощностей источников света, умноженных на косинусы углов падения света на грань
	// и в конце нормирую эту сумму, чтобы вместе с ambient она могла дать максимум 1.0
	const double ambient = 0.6;
	const size_t nlight = Light.size(); // количество источников
	double sumpower = 0; // сумма мощностей
	double lightness = 0; // освещенность, без учета ambient и не нормированная

	for(unsigned int i = 0; i < nlight; ++i)
	{
		const double power = Light[i].second;
		const Point3D position = Light[i].first;
		const Point3D l = position - medium;
		const double cosphi = n * l / n.Length() / l.Length();

		sumpower += power;
		lightness += power * cosphi;
	}

	// итоговая освещенность
	const double light = ambient + (sumpower == 0 ? 0 : lightness / sumpower * 0.4);
	assert(light >= 0.0 && light <= 1.0);

	// на основе освещенности рассчитываем новый цвет грани
	const Color realcolor = static_cast<RealColor>(color) * light;

	// ---------------------------------------------------------------------------------------
	// проекция
	const Projection::Matrix projector = Projection::PerspectiveProjection<1>(SpectatorPosition);

	// вершины треугольника, спрецированные на экранную плоскость
	const Point2D a = Projection::GetXZ(projector * A);
	const Point2D b = Projection::GetXZ(projector * B);
	const Point2D c = Projection::GetXZ(projector * C);

	// соответствующие им w
	const double wa = W(A);
	const double wb = W(B);
	const double wc = W(C);

	// Отсортировав вершины треугольника по y, вместе с их значениями w
	std::vector<Point> v;
	v.push_back(Point(a, wa));
	v.push_back(Point(b, wb));
	v.push_back(Point(c, wc));
	std::sort(v.begin(), v.end());

	const Point p = v[0], q = v[1], r = v[2];

	// можно закрасить его верхнюю и нижнюю половину
	if(VectorMultiplication2D(q.p - p.p, r.p - p.p) < 0) // делаю чтобы первый сегмент был левее второго
	{
		Util::FillInside(Segment(p, q), Segment(p, r), realcolor, app, this);
		Util::FillInside(Segment(q, r), Segment(p, r), realcolor, app, this);
	}
	else
	{
		Util::FillInside(Segment(p, r), Segment(p, q), realcolor, app, this);
		Util::FillInside(Segment(p, r), Segment(q, r), realcolor, app, this);
	}
}
Example #28
0
void Point3D::scale(float s, Point3D& cp) {
	scale(s,cp.getX(),cp.getY(),cp.getZ());
}
SolidPolygon3D SolidPolygon3D::rotationResult(float deltaDegree, Point3D poros, char axis){
	SolidPolygon3D tmp1 = moveResult(poros.mirrorResult());
	SolidPolygon3D tmp2 = tmp1.rotationResult(deltaDegree, axis);
	return tmp2.moveResult(poros);
}
Example #30
0
void Qualitative::drawCylinder(Point3D a, Point3D b, double bradius, 
			     double tradius)
{
  GLUquadric *q1;
  q1 = gluNewQuadric();

  bool capped=false;
  double l;

  if (tradius < 0.0) { capped = true; tradius = -tradius; }

  glPushMatrix();

  glTranslated(a.x(), a.y(), a.z() );

  double dx = b.x() - a.x();
  double dy = b.y() - a.y();
  double dz = b.z() - a.z();
  l = sqrt(dx*dx + dy*dy + dz*dz);

  if (l < 0.001) return;

#define DEGREES(rad) ((rad)*180.0/3.14159265358979323846)
  if (fabs( a.y() - b.y() ) < 0.000001 &&
      fabs( b.x() - a.x() ) < 0.000001) {
    if ( b.z() - a.z() < 0.0) glRotated(180.0,1.0,0.0,0.0);
  } else {
    glRotated(DEGREES(acos(( b.z() - a.z() ) / l)),
              a.y() - b.y(), b.x() - a.x(), 0.0);
  }

  gluCylinder(q1, bradius, tradius, l, 16, 1);

  if (capped) {
    glPushMatrix();
    glRotated(180.0, 0.0, 1.0, 0.0);
    gluDisk(q1, 0.0, bradius, 8, 1);
    glPopMatrix();
    glPushMatrix();
    glTranslated(0.0, 0.0, l);
    gluDisk(q1, 0.0, tradius, 8, 1);
    glPopMatrix();
  }

  glPopMatrix();
}