Ejemplo n.º 1
0
bool GetPrimaryRasterLayer::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "5D20DF72-1C71-4a5d-9B1A-398A91154EBD");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (pInArgList == NULL || pOutArgList == NULL)
   {
      reportError("Invalid Plug-In Arg List specified.", "8161F92F-124F-4118-8E24-532187A442AA");
      return false;
   }

   if (extractInputArgs(pInArgList) == false)
   {
      return false;
   }

   LayerList* pLayerList = mpSpatialDataView->getLayerList();
   VERIFY(pLayerList != NULL);

   RasterElement* pElement = pLayerList->getPrimaryRasterElement();
   RasterLayer* pLayer = dynamic_cast<RasterLayer*>(pLayerList->getLayer(RASTER, pElement));
   if (pOutArgList->setPlugInArgValue(Executable::LayerArg(), pLayer) == false)
   {
      reportError("Unable to set output argument.", "B4DE1827-3B96-4a96-89BB-62431B6E81CF");
      return false;
   }

   reportComplete();
   return true;
}
Ejemplo n.º 2
0
void MeasurementObjectImp::updateGeoreferenceAttachment()
{
   if (mpGeoreference.get() != NULL)
   {
      return;
   }

   RasterElement* pGeoreference = NULL;

   // Must find Georeference through the view, since the GraphicElement is a root element.
   GraphicLayer* pLayer = getLayer();
   if (pLayer != NULL)
   {
      SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pLayer->getView());
      if (pView != NULL)
      {
         LayerList* pLayerList = pView->getLayerList();
         VERIFYNRV(pLayerList != NULL);
         pGeoreference = pLayerList->getPrimaryRasterElement();
      }
   }

   if (pGeoreference != NULL && pGeoreference->isGeoreferenced())
   {
      mpGeoreference.reset(pGeoreference);
      enableGeo();
      generateGeoStrings();
   }
}
Ejemplo n.º 3
0
bool PrintView::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "4EA89098-57C8-4b93-B04F-3197C59B0D58");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (!extractInputArgs(pInArgList))
   {
      reportError("Unable to extract input arguments.", "9FC540AC-4BCF-4041-9E8E-484A494AF6AD");
      return false;
   }

   // Get the window
   SpatialDataWindow* pWindow = NULL;

   vector<Window*> windows;
   Service<DesktopServices> pDesktop;
   if (pDesktop.get() != NULL)
   {
      pDesktop->getWindows(SPATIAL_DATA_WINDOW, windows);
   }

   for (vector<Window*>::iterator iter = windows.begin(); iter != windows.end(); ++iter)
   {
      SpatialDataWindow* pCurrentWindow = static_cast<SpatialDataWindow*>(*iter);
      if (pCurrentWindow != NULL)
      {
         SpatialDataView* pView = pCurrentWindow->getSpatialDataView();
         if (pView != NULL)
         {
            LayerList* pLayerList = pView->getLayerList();
            if (pLayerList != NULL)
            {
               RasterElement* pRasterElement = pLayerList->getPrimaryRasterElement();
               if (pRasterElement != NULL && pRasterElement == mpRasterElement)
               {
                  pWindow = pCurrentWindow;
                  break;
               }
            }
         }
      }
   }

   if (pWindow == NULL)
   {
      reportError("Could not get the window for the data set!", "28355746-8AE3-44a4-9253-58684E1964C1");
      return false;
   }

   // Print the view
   pWindow->print(mbPrintDialog);

   reportComplete();
   return true;
}
Ejemplo n.º 4
0
void OverviewWindow::updateSelectionBox()
{
   if ((mpView == NULL) || (mpSelectionWidget == NULL))
   {
      return;
   }

   // Get the pixel coordinates at the view corners
   LocationType lowerLeft;
   LocationType upperLeft;
   LocationType upperRight;
   LocationType lowerRight;
   mpView->getVisibleCorners(lowerLeft, upperLeft, upperRight, lowerRight);

   // Disconnect the signal to update the view since the values are obtained from the view
   disconnect(mpSelectionWidget, SIGNAL(selectionChanged(const std::vector<LocationType>&)), this,
      SLOT(updateView(const std::vector<LocationType>&)));

   LayerList* pLayerList = mpView->getLayerList();
   VERIFYNRV(pLayerList != NULL);
   Layer* pLayer = pLayerList->getLayer(RASTER, pLayerList->getPrimaryRasterElement());
   VERIFYNRV(pLayer != NULL);

   // Set the selection area
   vector<LocationType> selectionArea;
   LocationType dataCoord;
   pLayer->translateWorldToData(lowerLeft.mX, lowerLeft.mY, dataCoord.mX, dataCoord.mY);
   selectionArea.push_back(dataCoord);
   pLayer->translateWorldToData(lowerRight.mX, lowerRight.mY, dataCoord.mX, dataCoord.mY);
   selectionArea.push_back(dataCoord);
   pLayer->translateWorldToData(upperRight.mX, upperRight.mY, dataCoord.mX, dataCoord.mY);
   selectionArea.push_back(dataCoord);
   pLayer->translateWorldToData(upperLeft.mX, upperLeft.mY, dataCoord.mX, dataCoord.mY);
   selectionArea.push_back(dataCoord);

   // update snail trail if zoom factor greater than or equal zoom threshold
   if ((mpTrail != NULL) && (static_cast<int>(mpView->getZoomPercentage() + 0.5) >= mZoomThreshold))
   {
      // Translate each point into a screen location
      if (mpOverview != NULL)
      {
         mpOverview->translateWorldToScreen(lowerLeft.mX, lowerLeft.mY, lowerLeft.mX, lowerLeft.mY);
         mpOverview->translateWorldToScreen(lowerRight.mX, lowerRight.mY, lowerRight.mX, lowerRight.mY);
         mpOverview->translateWorldToScreen(upperLeft.mX, upperLeft.mY, upperLeft.mX, upperLeft.mY);
         mpOverview->translateWorldToScreen(upperRight.mX, upperRight.mY, upperRight.mX, upperRight.mY);

         mpTrail->addToStencil(lowerLeft, lowerRight, upperLeft, upperRight);
      }
   }

   mpSelectionWidget->setSelection(selectionArea);

   // Reconnect the signal to update the view
   connect(mpSelectionWidget, SIGNAL(selectionChanged(const std::vector<LocationType>&)), this,
      SLOT(updateView(const std::vector<LocationType>&)));
}
Ejemplo n.º 5
0
RasterElement* ChippingWindow::getRasterElement() const
{
   LayerList* pLayerList = mpView->getLayerList();
   if (pLayerList == NULL)
   {
      return NULL;
   }

   return pLayerList->getPrimaryRasterElement();
}
Ejemplo n.º 6
0
    Image(SpatialDataView* iPView) : pView(iPView) {
        LayerList* pLayerList = pView->getLayerList(); VERIFYNRV(pLayerList != NULL);
        pRaster = dynamic_cast<RasterElement*>(pLayerList->getPrimaryRasterElement()); VERIFYNRV(pRaster != NULL);
        pDataDescriptor = dynamic_cast<const RasterDataDescriptor*>(pRaster->getDataDescriptor()); VERIFYNR(pDataDescriptor != NULL);
/*        Service<DesktopServices> pDesktop;
        VERIFYNRV(pDesktop.get() != NULL);
        SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(pDesktop->getWindow(pRaster->getName(), SPATIAL_DATA_WINDOW));
        VERIFYNRV(pWindow != NULL);
        VERIFYNRV(pDesktop->setCurrentWorkspaceWindow(pWindow));*/
    }
Ejemplo n.º 7
0
SpatialDataViewImp* OverviewWindow::createOverview()
{
   SpatialDataViewImp* pOverview = NULL;
   if (mpView != NULL)
   {
      pOverview = dynamic_cast<SpatialDataViewImp*>(mpView->copy());
      VERIFYRV(pOverview != NULL, NULL);
      pOverview->installEventFilter(this);

      LayerList* pLayerList = NULL;
      pLayerList = pOverview->getLayerList();
      if (pLayerList != NULL)
      {
         // get primary raster layer from data view
         LayerList* pSDVlist = mpView->getLayerList();
         VERIFYRV(pSDVlist != NULL, NULL);
         DataElement* pPrimElem = pSDVlist->getPrimaryRasterElement();
         VERIFYRV(pPrimElem != NULL, NULL);
         Layer* pPrimLayer = pSDVlist->getLayer(RASTER, pPrimElem);
         VERIFYRV(pPrimLayer != NULL, NULL);
         string primName(pPrimLayer->getName());

         vector<Layer*> layers;
         pLayerList->getLayers(layers);
         for (unsigned int i = 0; i < layers.size(); i++)
         {
            Layer* pLayer = NULL;
            pLayer = layers.at(i);
            string layerName(pLayer->getName());
            if (pLayer->getLayerType()==RASTER && layerName==primName)
            {
               pPrimLayer->linkLayer(pLayer);

               // reset the scale to what is in the model
               DataElement* pElement = pLayer->getDataElement();
               VERIFYRV(pElement != NULL, NULL);

               const RasterDataDescriptor* pDescriptor =
                  dynamic_cast<const RasterDataDescriptor*>(pElement->getDataDescriptor());
               VERIFYRV(pDescriptor != NULL, NULL);

               pLayer->setYScaleFactor(pDescriptor->getYPixelSize());
               pLayer->setXScaleFactor(pDescriptor->getXPixelSize());
            }
            else
            {
               pOverview->deleteLayer(pLayer);
            }
         }
         pOverview->resetOrientation();
      }
   }

   return pOverview;
}
Ejemplo n.º 8
0
bool GeocoordLinkFunctor::initialize()
{
   if (mInitialized)
   {
      return true;
   }

   if (mpSrcView != NULL)
   {
      LayerList* pSrcLayerList = mpSrcView->getLayerList();
      if (pSrcLayerList == NULL)
      {
         return false;
      }

      mpSrcGeo = pSrcLayerList->getPrimaryRasterElement();
      if (mpSrcGeo == NULL || !mpSrcGeo->isGeoreferenced())
      {
         return false;
      }

      mpSrcLayer = pSrcLayerList->getLayer(RASTER, mpSrcGeo);
      if (mpSrcLayer == NULL)
      {
         return false;
      }

      LocationType srcWorldCenter(mpSrcView->getVisibleCenter());

      LocationType srcScreenCenter;
      mpSrcView->translateWorldToScreen(srcWorldCenter.mX, srcWorldCenter.mY, 
         srcScreenCenter.mX, srcScreenCenter.mY);
      mSrcScreenCenter = complex<double>(srcScreenCenter.mX, srcScreenCenter.mY);

      LocationType srcDataCenter;
      mpSrcLayer->translateWorldToData(srcWorldCenter.mX, srcWorldCenter.mY, 
         srcDataCenter.mX, srcDataCenter.mY);
      mCenterGeocoord = mpSrcGeo->convertPixelToGeocoord(srcDataCenter);

      mTightness = findResolution(mpSrcGeo, mpSrcLayer, mCenterGeocoord) * LINK_TIGHTNESS;

      mInitialized = true;
      return true;
   }

   return false;
}
Ejemplo n.º 9
0
void OverviewWindow::updateView(const vector<LocationType>& selectionArea)
{
   if ((mpView == NULL) || (selectionArea.size() != 4))
   {
      return;
   }

   LayerList* pLayerList = mpView->getLayerList();
   VERIFYNRV(pLayerList != NULL);
   Layer* pLayer = pLayerList->getLayer(RASTER, pLayerList->getPrimaryRasterElement());
   VERIFYNRV(pLayer != NULL);
   LocationType worldLl;
   LocationType worldUr;
   pLayer->translateDataToWorld(selectionArea[0].mX, selectionArea[0].mY, worldLl.mX, worldLl.mY);
   pLayer->translateDataToWorld(selectionArea[2].mX, selectionArea[2].mY, worldUr.mX, worldUr.mY);
   
   // Update the view
   mpView->zoomToBox(worldLl, worldUr);
   mpView->repaint();
}
Ejemplo n.º 10
0
bool LayerImporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   Layer* pLayer = NULL;
   Progress* pProgress = NULL;
   DataElement* pElement = NULL;
   SpatialDataView* pView = NULL;
   StepResource pStep("Import layer", "app", "DF24688A-6B34-4244-98FF-5FFE2063AC05");

   // get input arguments and log some useful info about them
   { // scope the MessageResource
      MessageResource pMsg("Input arguments", "app", "C0A532DE-0E19-44D3-837C-16ABD267B2C1");

      pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
      pMsg->addBooleanProperty("Progress Present", (pProgress != NULL));

      pElement = pInArgList->getPlugInArgValue<DataElement>(Importer::ImportElementArg());
      if (pElement == NULL)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("No data element", 100, ERRORS);
         }
         pStep->finalize(Message::Failure, "No data element");
         return false;
      }
      pMsg->addProperty("Element name", pElement->getName());
      pView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg());
      if (pView != NULL)
      {
         pMsg->addProperty("View name", pView->getName());
      }
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress((string("Read and parse file ") + pElement->getFilename()),
         20, NORMAL);
   }

   // parse the xml
   XmlReader xml(Service<MessageLogMgr>()->getLog());

   XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDomDocument = xml.parse(pElement->getFilename());
   if (pDomDocument == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Unable to parse the file", 100, ERRORS);
      }
      pStep->finalize(Message::Failure, "Unable to parse the file");
      return false;
   }

   DOMElement* pRootElement = pDomDocument->getDocumentElement();
   VERIFY(pRootElement != NULL);

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Create the layer", 40, NORMAL);
   }

   string name(A(pRootElement->getAttribute(X("name"))));
   string type(A(pRootElement->getAttribute(X("type"))));
   unsigned int formatVersion = atoi(A(pRootElement->getAttribute(X("version"))));

   { // scope the MessageResource
      MessageResource pMsg("Layer information", "app", "AA358F7A-107E-456E-8D11-36DDBE5B1645");
      pMsg->addProperty("name", name);
      pMsg->addProperty("type", type);
      pMsg->addProperty("format version", formatVersion);
   }


   // If user requested pixel coordinates be used.
   bool usePixelCoords = false;
   DataDescriptor* pDesc = pElement->getDataDescriptor();
   VERIFY( pDesc );
   pDesc->getMetadata()->getAttributeByPath( "Layer/Import Options/Use Pixel Coordinates" ).getValue( usePixelCoords );
   if (usePixelCoords)
   {
      // Remove geoVertices and geoBox elements.
      removeGeoNodes(pRootElement);
   }

   if (pView == NULL)
   {
      //no view provided, so find current view
      SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(mpDesktop->getCurrentWorkspaceWindow());
      if (pWindow != NULL)
      {
         pView = pWindow->getSpatialDataView();
      }
   }

   if (pView == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Could not access the view to create the layer.", 100, ERRORS);
      }

      pStep->finalize(Message::Failure, "Could not access the view to create the layer.");
      return false;
   }

   bool error = false;
   LayerType layerType = StringUtilities::fromXmlString<LayerType>(type, &error);
   if (error == true)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("The layer type is invalid.", 100, ERRORS);
      }

      pStep->finalize(Message::Failure, "The layer type is invalid.");
      return false;
   }

   LayerList* pLayerList = pView->getLayerList();
   if (pLayerList != NULL)
   {
      RasterElement* pNewParentElement = pLayerList->getPrimaryRasterElement();
      if (pNewParentElement != NULL)
      {
         Service<ModelServices> pModel;
         if (pModel->setElementParent(pElement, pNewParentElement) == false)
         {
            pProgress->updateProgress("The layer already exists.", 100, ERRORS);
            pStep->finalize(Message::Failure, "The layer already exists.");
            return false;
         }
      }
   }

   UndoGroup group(pView, "Import " + StringUtilities::toDisplayString(layerType) + " Layer");

   pLayer = pView->createLayer(layerType, pElement);
   if (pLayer == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Unable to create the layer", 100, ERRORS);
      }
      pStep->finalize(Message::Failure, "Unable to create the layer");
      return false;
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Build the layer", 60, NORMAL);
   }

   // deserialize the layer
   try
   {
      if (pLayer->fromXml(pRootElement, formatVersion) == false)
      {
         pProgress->updateProgress("Problem with layer file.", 100, ERRORS);
         pStep->finalize(Message::Failure, "Problem with layer file.");
         return false;
      }
   }
   catch (XmlReader::DomParseException&)
   {
      return false;
   }

   pStep->finalize(Message::Success);
   if (pProgress != NULL)
   {
      pProgress->updateProgress("Finished loading the layer", 100, NORMAL);
   }

   // Add the layer to the view
   pView->addLayer(pLayer);
   pView->setActiveLayer(pLayer);
   pView->setMouseMode("LayerMode");

   if (pOutArgList != NULL)
   {
      // set the output arguments
      pOutArgList->setPlugInArgValue("Layer", pLayer);
   }

   return true;
}
Ejemplo n.º 11
0
bool CgmImporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   Progress* pProgress = NULL;
   DataElement* pElement = NULL;
   StepResource pStep("Import cgm element", "app", "8D5522FE-4A89-44cb-9735-6920A3BFC903");

   // get input arguments and log some useful info about them
   { // scope the MessageResource
      MessageResource pMsg("Input arguments", "app", "A1735AC7-C182-45e6-826F-690DBA15D84A");

      pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
      pMsg->addBooleanProperty("Progress Present", (pProgress != NULL));
      
      pElement = pInArgList->getPlugInArgValue<DataElement>(Importer::ImportElementArg());
      if (pElement == NULL)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("No data element", 0, ERRORS);
         }
         pStep->finalize(Message::Failure, "No data element");
         return false;
      }
      pMsg->addProperty("Element name", pElement->getName());
   }
   if (pProgress != NULL)
   {
      pProgress->updateProgress((string("Read and parse file ") + pElement->getFilename()), 20, NORMAL);
   }

   // Create a new annotation layer for a spatial data view or get the layout layer for a product view
   if (pProgress != NULL)
   {
      pProgress->updateProgress("Create a new layer", 30, NORMAL);
   }

   View* pView = mpDesktop->getCurrentWorkspaceWindowView();
   if (pView == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Could not access the current view.", 0, ERRORS);
      }

      pStep->finalize(Message::Failure, "Could not access the current view.");
      return false;
   }

   UndoGroup undoGroup(pView, "Import CGM");
   AnnotationLayer* pLayer = NULL;

   SpatialDataView* pSpatialDataView = dynamic_cast<SpatialDataView*>(pView);
   if (pSpatialDataView != NULL)
   {
      // Set the parent element of the annotation element to the primary raster element
      LayerList* pLayerList = pSpatialDataView->getLayerList();
      if (pLayerList != NULL)
      {
         RasterElement* pNewParentElement = pLayerList->getPrimaryRasterElement();
         if (pNewParentElement != NULL)
         {
            Service<ModelServices> pModel;
            pModel->setElementParent(pElement, pNewParentElement);
         }
      }

      pLayer = dynamic_cast<AnnotationLayer*>(pSpatialDataView->createLayer(ANNOTATION, pElement));
   }
   else
   {
      ProductView* pProductView = dynamic_cast<ProductView*>(mpDesktop->getCurrentWorkspaceWindowView());
      if (pProductView != NULL)
      {
         pLayer = pProductView->getLayoutLayer();
      }
   }

   if (pLayer == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Unable to get the annotation layer", 0, ERRORS);
      }

      pStep->finalize(Message::Failure, "Unable to get the annotation layer");
      return false;
   }

   // add the CGM object
   if (pProgress != NULL)
   {
      pProgress->updateProgress("Create the CGM object", 60, NORMAL);
   }
   CgmObject* pCgmObject = dynamic_cast<CgmObject*>(pLayer->addObject(CGM_OBJECT));
   if (pCgmObject == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Unable to create the CGM object", 0, ERRORS);
      }
      pStep->finalize(Message::Failure, "Unable to create the CGM object");
      return false;
   }

   // load the CGM file
   if (pProgress != NULL)
   {
      pProgress->updateProgress("Load the CGM file", 90, NORMAL);
   }
   string fname = pElement->getDataDescriptor()->getFileDescriptor()->getFilename().getFullPathAndName();
   if (!pCgmObject->deserializeCgm(fname))
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Error loading the CGM element", 0, ERRORS);
      }
      pStep->finalize(Message::Failure, "Unable to parse the CGM file.");
      return false;
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Successfully loaded the CGM file", 100, NORMAL);
   }
   pStep->finalize(Message::Success);
   return true;
}
Ejemplo n.º 12
0
/**
 * Get the names of all the data elements which are children of the primary raster element.
 *
 * @param[in] WINDOW @opt
 *            The name of the window. Defaults to the active window.
 * @return An array of data element names or the string "failure" if an error occurred.
 * @usage names = get_data_element_names()
 * @endusage
 */
IDL_VPTR get_data_element_names(int argc, IDL_VPTR pArgv[], char* pArgk)
{
   typedef struct
   {
      IDL_KW_RESULT_FIRST_FIELD;
      int windowExists;
      IDL_STRING windowName;
   } KW_RESULT;

   //IDL_KW_FAST_SCAN is the type of scan we are using, following it is the
   //name of the keyword, followed by the type, the mask(which should be 1),
   //flags, a boolean whether the value was populated and finally the value itself
   static IDL_KW_PAR kw_pars[] = {
      IDL_KW_FAST_SCAN,
      {"WINDOW", IDL_TYP_STRING, 1, 0, reinterpret_cast<int*>(IDL_KW_OFFSETOF(windowExists)),
         reinterpret_cast<char*>(IDL_KW_OFFSETOF(windowName))},
      {NULL}
   };

   IdlFunctions::IdlKwResource<KW_RESULT> kw(argc, pArgv, pArgk, kw_pars, 0, 1);
   std::string windowName;
   std::string name;
   bool bSuccess = false;
   IDL_VPTR idlPtr;
   unsigned int total = 0;
   IDL_STRING* pStrarr = NULL;

   if (kw->windowExists)
   {
      windowName = IDL_STRING_STR(&kw->windowName);
   }

   SpatialDataWindow* pWindow = NULL;
   if (windowName.empty())
   {
      pWindow = dynamic_cast<SpatialDataWindow*>(Service<DesktopServices>()->getCurrentWorkspaceWindow());
   }
   else
   {
      pWindow = dynamic_cast<SpatialDataWindow*>(
         Service<DesktopServices>()->getWindow(windowName, SPATIAL_DATA_WINDOW));
   }
   if (pWindow != NULL)
   {
      SpatialDataView* pView = pWindow->getSpatialDataView();
      if (pView != NULL)
      {
         LayerList* pList = pView->getLayerList();
         if (pList != NULL)
         {
            RasterElement* pElement = pList->getPrimaryRasterElement();
            if (pElement != NULL)
            {
               std::vector<std::string> names = Service<ModelServices>()->getElementNames(pElement, "");
               total = names.size();
               if (total > 0)
               {
                  pStrarr = reinterpret_cast<IDL_STRING*>(malloc(total * sizeof(IDL_STRING)));
                  for (unsigned int i=0; i < total; ++i)
                  {
                     IDL_StrStore(&(pStrarr[i]), const_cast<char*>(names[i].c_str()));
                  }
                  bSuccess = true;
               }
            }
         }
      }
   }
   else if (windowName == "all")
   {
      std::vector<std::string> names = Service<ModelServices>()->getElementNames("RasterElement");
      total = names.size();
      if (total > 0)
      {
         pStrarr = reinterpret_cast<IDL_STRING*>(malloc(total* sizeof(IDL_STRING)));
         for (unsigned int i=0; i < total; ++i)
         {
            IDL_StrStore(&(pStrarr[i]), const_cast<char*>(names[i].c_str()));
         }
         bSuccess = true;
      }
   }
   if (!bSuccess)
   {
      IDL_Message(IDL_M_GENERIC, IDL_MSG_RET, "No elements matched.");
      return IDL_StrToSTRING("failure");
   }
   IDL_MEMINT dims[] = {total};
   idlPtr = IDL_ImportArray(1, dims, IDL_TYP_STRING, reinterpret_cast<UCHAR*>(pStrarr),
      reinterpret_cast<IDL_ARRAY_FREE_CB>(free), NULL);
   return idlPtr;
}
Ejemplo n.º 13
0
bool SetDataSetWavelengths::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   if (pInArgList == NULL)
   {
      return false;
   }

   StepResource pStep(string("Execute ") + getName(), "Spectral", "863CB0EE-5BC0-4A49-8FCB-FBC385F1AD2D");

   // Extract the input args
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(ProgressArg());

   RasterElement* pDataset = pInArgList->getPlugInArgValue<RasterElement>(DataElementArg());
   if ((pDataset == NULL) && (isBatch() == false))
   {
      SpatialDataView* pView = pInArgList->getPlugInArgValue<SpatialDataView>(ViewArg());
      if (pView != NULL)
      {
         LayerList* pLayerList = pView->getLayerList();
         if (pLayerList != NULL)
         {
            pDataset = pLayerList->getPrimaryRasterElement();
         }
      }
   }

   if (pDataset == NULL)
   {
      string message = "The data set input value is invalid.";
      if (pProgress != NULL)
      {
         pProgress->updateProgress(message, 0, ERRORS);
      }

      pStep->finalize(Message::Failure, message);
      return false;
   }

   DynamicObject* pWavelengthData = pInArgList->getPlugInArgValue<DynamicObject>(Wavelengths::WavelengthsArg());
   if (pWavelengthData == NULL)
   {
      string message = "The " + Wavelengths::WavelengthsArg() + " input value is invalid.";
      if (pProgress != NULL)
      {
         pProgress->updateProgress(message, 0, ERRORS);
      }

      pStep->finalize(Message::Failure, message);
      return false;
   }

   // Apply the wavelength data to the data set
   Wavelengths wavelengths(pWavelengthData);
   if (wavelengths.applyToDataset(pDataset) == false)
   {
      string message = "The wavelengths could not be applied to the data set.  The number of wavelength values "
         "may not match the number of bands in the data set.";
      if (pProgress != NULL)
      {
         pProgress->updateProgress(message, 0, ERRORS);
      }

      pStep->finalize(Message::Failure, message);
      return false;
   }

   pStep->finalize(Message::Success);
   return true;
}
Ejemplo n.º 14
0
bool SaveLayerFromDataSet::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "A1205468-4950-4c8f-9821-60063CC4B31B");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (!extractInputArgs(pInArgList))
   {
      reportError("Unable to extract input arguments.", "9A496CD9-5068-4b12-A4C4-AB561CD49523");
      return false;
   }

   // Check for valid input values
   string filename;
   if (mpOutputFilename != NULL)
   {
      filename = mpOutputFilename->getFullPathAndName();
   }

   if (filename.empty())
   {
      reportError(" The filename input value is invalid!", "DA76EB21-7E5A-45aa-A60D-0B99C72585EC");
      return false;
   }

   if (mpStep != NULL)
   {
      mpStep->addProperty("filename", filename);
   }

   if (mpRasterElement == NULL)
   {
      reportError("The data set input value is invalid!", "E11D0EC5-97E6-41a5-8F1F-937290CA102F");
      return false;
   }

   if (mpStep != NULL)
   {
      mpStep->addProperty("dataSet", mpRasterElement->getName());
   }

   if (mLayerName.empty())
   {
      reportError("The layer name input value is invalid!", "0DF331B8-05FF-4178-82D3-9A9CF2851DCF");
      return false;
   }

   if (mpStep != NULL)
   {
      mpStep->addProperty("layerName", mLayerName);
   }

   // Get the view
   SpatialDataView* pView = NULL;

   vector<Window*> windows;
   Service<DesktopServices> pDesktop;
   if (pDesktop.get() != NULL)
   {
      pDesktop->getWindows(SPATIAL_DATA_WINDOW, windows);
   }

   for (vector<Window*>::iterator iter = windows.begin(); iter != windows.end(); ++iter)
   {
      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(*iter);
      if (pWindow != NULL)
      {
         SpatialDataView* pCurrentView = pWindow->getSpatialDataView();
         if (pCurrentView != NULL)
         {
            LayerList* pLayerList = pCurrentView->getLayerList();
            if (pLayerList != NULL)
            {
               RasterElement* pRasterElement = pLayerList->getPrimaryRasterElement();
               if (pRasterElement == mpRasterElement)
               {
                  pView = pCurrentView;
                  break;
               }
            }
         }
      }
   }

   if (pView == NULL)
   {
      reportError("Could not get the view!", "830E3C55-561A-4c49-8269-06E1E04B1BFA");
      return false;
   }

   // Get the spectral element
   LayerType eType = getLayerType();
   string modelType = getModelType(eType);

   DataElement* pElement = NULL;
   Service<ModelServices> pModel;
   if ((pModel.get() != NULL) && !modelType.empty())
   {
      pElement = pModel->getElement(mLayerName, modelType, mpRasterElement);
   }

   // Save the layer
   bool bSaved = false;

   LayerList* pLayerList = pView->getLayerList();
   if (pLayerList != NULL)
   {
      Layer* pLayer = pLayerList->getLayer(eType, pElement, mLayerName.c_str());
      if (pLayer == NULL)
      {
         reportError("Could not get the layer to save!", "02F03D56-7CA8-4052-894D-BFDDFC3A814F");
         return false;
      }

      FactoryResource<FileDescriptor> pFileDescriptor;
      VERIFY(pFileDescriptor.get() != NULL);
      pFileDescriptor->setFilename(filename);
      ExporterResource exporter("Layer Exporter", pLayer, pFileDescriptor.get());
      VERIFY(exporter->getPlugIn() != NULL);
      bSaved = exporter->execute();
   }

   if (!bSaved)
   {
      reportError("Could not save the layer to the file: " + filename, "CAFF2CD5-E6CB-4e90-80E7-87E094F2CB1C");
      return false;
   }

   reportComplete();
   return true;
}
Ejemplo n.º 15
0
bool TiffDetails::addGeoKeys(TIFF* pOut, int width, int height, const SessionItem *pItem)
{
   if ((pOut == NULL) || (width == 0) || (height == 0))
   {
      return false;
   }

   const View* pInputView = dynamic_cast<const View*>(pItem);
   if (pInputView == NULL)
   {
      return false;
   }

   RasterElement* pGeoreferencedRaster = NULL; // First raster element we find with georeferencing information
   const ProductView* pView = dynamic_cast<const ProductView*>(pInputView);
   if (pView != NULL)
   {
      AnnotationLayer* pAnno = pView->getLayoutLayer();
      if (pAnno == NULL)
      {
         return false;
      }

      /* NOTE: If we find more than one SpatialDataView with a georeferenced RasterElement, we will only provide
      geo-data for the FIRST one - because two views could theoretically screw up the
      geo-data if one is in Australia and the other in Canada.
      */

      // get all the view objects
      std::list<GraphicObject*> objs;
      pAnno->getObjects(VIEW_OBJECT, objs);

      // for every object, find the data set with a geocoord matrix
      for (std::list<GraphicObject*>::iterator it = objs.begin(); it != objs.end(); ++it)
      {
         GraphicObject* pObj = *it;
         if (pObj != NULL)
         {
            SpatialDataView* pSpView = dynamic_cast<SpatialDataView*>(pObj->getObjectView());
            if (pSpView != NULL)
            {
               LayerList* pLayerList = pSpView->getLayerList();
               if (pLayerList != NULL)
               {
                  RasterElement* pRaster = pLayerList->getPrimaryRasterElement();
                  if (pRaster != NULL && pRaster->isGeoreferenced())
                  {
                     pGeoreferencedRaster = pRaster;
                     break;
                  }
               }
            }
         }
      }
   }

   const SpatialDataView* pSpView = dynamic_cast<const SpatialDataView*>(pInputView);
   if (pSpView != NULL)
   {
      LayerList* pLayerList = pSpView->getLayerList();
      if (pLayerList != NULL)
      {
         RasterElement* pRaster = pLayerList->getPrimaryRasterElement();
         if (pRaster != NULL && pRaster->isGeoreferenced())
         {
            pGeoreferencedRaster = pRaster;
         }
      }
   }

   if (pGeoreferencedRaster == NULL)
   {
      return false;
   }

   GTIF* pGtif = GTIFNew(pOut);
   if (pGtif == NULL)
   {
      return false;
   }

   LocationType lowerLeft;
   LocationType upperLeft;
   LocationType upperRight;
   LocationType lowerRight;
   pInputView->getVisibleCorners(lowerLeft, upperLeft, upperRight, lowerRight);

   LocationType latLong;
   //get the lat/long's (0,0)
   latLong = pGeoreferencedRaster->convertPixelToGeocoord(upperLeft);
   double ll1y = latLong.mY;               //delta long
   double ll1x = latLong.mX;               //delta lat

   latLong = pGeoreferencedRaster->convertPixelToGeocoord(upperRight);
   double ll2y = latLong.mY;               //long
   double ll2x = latLong.mX;               //lat

   latLong = pGeoreferencedRaster->convertPixelToGeocoord(lowerLeft);
   double ll3y = latLong.mY;               //long
   double ll3x = latLong.mX;               //lat

   //compute transformation Matrix values
   //added slight modification, must divide by magnitude
   double a = (ll2y - ll1y) / width;
   double b = (ll3y - ll1y) / height;
   double d = (ll1y);
   double e = (ll2x - ll1x) / width;
   double f = (ll3x - ll1x) / height;
   double h = (ll1x);

   double tMatrix[16] =
   {
      a,   b,   0.0, d,
      e,   f,   0.0, h,
      0.0, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 1.0
   };

   TIFFSetField(pOut, GTIFF_TRANSMATRIX, 16, tMatrix);

   GTIFKeySet(pGtif, GTRasterTypeGeoKey, TYPE_SHORT, 1, RasterPixelIsArea);
   GTIFKeySet(pGtif, GTModelTypeGeoKey, TYPE_SHORT, 1, ModelGeographic);
   GTIFKeySet(pGtif, GeographicTypeGeoKey, TYPE_SHORT, 1, GCS_WGS_84);

   // Here we violate the GTIF abstraction to retarget on another file.
   // We should just have a function for copying tags from one GTIF object
   // to another.
   pGtif->gt_tif = pOut;
   pGtif->gt_flags |= FLAG_FILE_MODIFIED;

   // Install keys and tags
   GTIFWriteKeys(pGtif);
   GTIFFree(pGtif);
   return true;
}
Ejemplo n.º 16
0
 Layer* getLayer(const char* pName, const char* pType)
 {
    Layer* pLayer = NULL;
    const std::string name(pName == NULL ? std::string() : pName);
    const std::string type(pType == NULL ? std::string() : pType);
    SessionItem* pSessionItem = Service<SessionManager>()->getSessionItem(name);
    if (pSessionItem != NULL)
    {
       pLayer = dynamic_cast<Layer*>(pSessionItem);
       if (pLayer == NULL || (!type.empty() && !pLayer->isKindOf(type)))
       {
          setLastError(SIMPLE_WRONG_TYPE);
          return NULL;
       }
    }
    else
    {
       std::vector<std::string> id = splitIdentifier(name);
       SpatialDataView* pView = static_cast<SpatialDataView*>(getView(id.size() == 0 ? NULL : id.front().c_str(),
          TypeConverter::toString<SpatialDataView>()));
       LayerList* pLayerList = (pView == NULL) ? NULL : pView->getLayerList();
       if (pLayerList == NULL)
       {
          setLastError(SIMPLE_NOT_FOUND);
          return NULL;
       }
       if (id.size() < 2)
       {
          if (!type.empty() && type == TypeConverter::toString<RasterLayer>())
          {
             pLayer = pLayerList->getLayer(RASTER, pLayerList->getPrimaryRasterElement());
          }
          else
          {
             pLayer = pView->getActiveLayer();
             if (pLayer != NULL && !type.empty() && !pLayer->isKindOf(type))
             {
                pLayer = NULL;
             }
             if (pLayer == NULL)
             {
                if (type.empty())
                {
                   pLayer = pView->getTopMostLayer();
                }
                else
                {
                   pLayer = pView->getTopMostLayer(StringUtilities::fromDisplayString<LayerType>(type));
                }
             }
          }
       }
       if (pLayer == NULL)
       {
          std::vector<Layer*> layers;
          pLayerList->getLayers(layers);
          for (std::vector<Layer*>::reverse_iterator layer = layers.rbegin();
             layer != layers.rend();
             ++layer)
          {
             if ((type.empty() || (*layer)->isKindOf(type)) && 
                (id.empty() || (*layer)->getName() == id.back() || (*layer)->getDisplayName() == id.back()))
             {
                pLayer = *layer;
                break;
             }
          }
       }
       if (pLayer == NULL)
       {
          setLastError(SIMPLE_NOT_FOUND);
          return NULL;
       }
    }
    setLastError(SIMPLE_NO_ERROR);
    return pLayer;
 }
Ejemplo n.º 17
0
void EastArrowObjectImp::orient()
{
   if (isOriented() == true)
   {
      return;
   }

   GraphicLayer* pLayer = NULL;
   pLayer = getLayer();
   if (pLayer == NULL)
   {
      return;
   }

   View* pView = NULL;
   pView = pLayer->getView();
   if (pView == NULL)
   {
      return;
   }

   SpatialDataView* pSpatialDataView = NULL;
   if (pView->isKindOf("SpatialDataView") == true)
   {
      pSpatialDataView = static_cast<SpatialDataView*> (pView);
   }
   else if (pView->isKindOf("ProductView") == true)
   {
      ProductView* pProductView = static_cast<ProductView*> (pView);

      GraphicLayer* pLayoutLayer = NULL;
      pLayoutLayer = pProductView->getLayoutLayer();
      if (pLayoutLayer == pLayer)
      {
         list<GraphicObject*> viewObjects;
         pLayoutLayer->getObjects(VIEW_OBJECT, viewObjects);

         list<GraphicObject*>::iterator iter = viewObjects.begin();
         while (iter != viewObjects.end())
         {
            GraphicObject* pObject = *iter;
            if (pObject != NULL)
            {
               View* pObjectView = pObject->getObjectView();
               if (pObjectView != NULL)
               {
                  if (pObjectView->isKindOf("SpatialDataView") == true)
                  {
                     pSpatialDataView = static_cast<SpatialDataView*> (pObjectView);
                  }
               }
            }

            ++iter;
         }
      }
   }

   if (pSpatialDataView == NULL)
   {
      return;
   }

   LayerList* pLayerList = pSpatialDataView->getLayerList();
   VERIFYNRV(pLayerList != NULL);
   RasterElement* pRaster = pLayerList->getPrimaryRasterElement();
   VERIFYNRV(pRaster != NULL);
   if (!pRaster->isGeoreferenced())
   {
      return;
   }

   // Calculate the angle of the object relative to the pixel coordinates
   updateHandles();

   LocationType pixelStart = mHandles[7];

   ProductView* pProductView = dynamic_cast<ProductView*> (pView);
   if (pProductView != NULL)
   {
      // Convert to the screen coordinate system
      double dScreenX = 0;
      double dScreenY = 0;
      pLayer->translateDataToWorld(pixelStart.mX, pixelStart.mY, pixelStart.mX, pixelStart.mY);
      pProductView->translateWorldToScreen(pixelStart.mX, pixelStart.mY, dScreenX, dScreenY);
      
      // Convert to the spatial data view coordinate system
      pSpatialDataView->translateScreenToWorld(dScreenX,
         dScreenY, pixelStart.mX, pixelStart.mY);
      pLayer->translateWorldToData(pixelStart.mX, pixelStart.mY, pixelStart.mX, pixelStart.mY);
   }

   double dAngle;
   if (GeoAlgorithms::getAngleToNorth(pRaster, dAngle, pixelStart) == false)
   {
      return;
   }

   // Update the angle if the object is in the layout layer
   if (pProductView != NULL)
   {
      // Rotation
      dAngle -= pSpatialDataView->getRotation();

      // Pitch
      double dPitch = pSpatialDataView->getPitch();
      if (dPitch > 0.0)
      {
         dAngle *= -1.0;
      }
   }

   // Rotate the object
   setRotation(dAngle);

   // Update the orientation flag
   DirectionalArrowObjectImp::orient();
}
Ejemplo n.º 18
0
void GeocoordLinkFunctor::operator()(ViewImp *pDestView) const
{
   // lazily prepare the functor with the source information
   if (!const_cast<GeocoordLinkFunctor*>(this)->initialize())
   {
      return;
   }

   SpatialDataViewImp* pDstViewSpatial = dynamic_cast<SpatialDataViewImp*>(pDestView);
   if (pDstViewSpatial == NULL)
   {
      return;
   }

   LayerList* pDstLayerList = pDstViewSpatial->getLayerList();
   if (pDstLayerList == NULL)
   {
      return;
   }

   RasterElement* pDstGeo = pDstLayerList->getPrimaryRasterElement();
   if (pDstGeo == NULL || !pDstGeo->isGeoreferenced())
   {
      return;
   }

   Layer* pDstLayer = pDstLayerList->getLayer(RASTER, pDstGeo);
   if (pDstLayer == NULL)
   {
      return;
   }

   pDstViewSpatial->setPanLimit(NO_LIMIT);
   pDstViewSpatial->setMinimumZoom(0);
   pDstViewSpatial->setMaximumZoom(0);

   LocationType dstDataCenter = pDstGeo->convertGeocoordToPixel(mCenterGeocoord);
   LocationType dstWorldCenter;
   pDstLayer->translateDataToWorld(dstDataCenter.mX, dstDataCenter.mY, 
      dstWorldCenter.mX, dstWorldCenter.mY);
   LocationType dstScreenCenter(pDstViewSpatial->width() / 2.0, pDstViewSpatial->height() / 2.0);

   // Determined zoom and rotation are relative to the view's current state.
   // Reset the zoom and rotation to prevent cascading rounding errors
   pDstViewSpatial->resetOrientation();
   if (pDstViewSpatial->getDataOrigin() == UPPER_LEFT)
   {
      pDstViewSpatial->flipVertical();
   }
   pDstViewSpatial->panTo(dstWorldCenter);
   pDstViewSpatial->zoomTo(100);

   double localTightness = mTightness / findResolution(pDstGeo, pDstLayer, mCenterGeocoord);

   vector<LocationType> dstScreen(NUM_POINTS);
   dstScreen[0] = dstScreenCenter + LocationType(0, localTightness);
   dstScreen[1] = dstScreenCenter + LocationType(0, -localTightness);
   dstScreen[2] = dstScreenCenter + LocationType(localTightness, 0);
   dstScreen[3] = dstScreenCenter + LocationType(-localTightness, 0);

   // (Desired screen offset) / (world offset) yields zoom (magnitude) and rotation (phase).
   vector<complex<double> > transformVec(NUM_POINTS);
   for (unsigned int i = 0; i < NUM_POINTS; ++i)
   {
      // dst: screen -> world -> data -> geo
      LocationType dstWorld;
      pDstViewSpatial->translateScreenToWorld(dstScreen[i].mX, dstScreen[i].mY, dstWorld.mX, dstWorld.mY);
      LocationType dstData;
      pDstLayer->translateWorldToData(dstWorld.mX, dstWorld.mY, dstData.mX, dstData.mY);
      LocationType dstGeo = pDstGeo->convertPixelToGeocoord(dstData);

      // src: geo -> data -> screen
      LocationType srcData = mpSrcGeo->convertGeocoordToPixel(dstGeo);
      LocationType srcScreen;
      mpSrcLayer->translateDataToScreen(srcData.mX, srcData.mY, srcScreen.mX, srcScreen.mY);
      complex<double> srcScreenOffset = complex<double>(srcScreen.mX, srcScreen.mY) - mSrcScreenCenter;
      LocationType dstDataOffset = dstWorld - dstWorldCenter;
      transformVec[i] = srcScreenOffset / complex<double>(dstDataOffset.mX, dstDataOffset.mY);
   }

   // find average zoom and rotation for each axis
   complex<double> vertical = (transformVec[0] + transformVec[1]) / complex<double>(2);
   complex<double> horizontal = (transformVec[2] + transformVec[3]) / complex<double>(2);

   // find the aspects from the relative zoom, and correct the
   // vector to get a better rotation and zoom
   double aspect = abs(horizontal) / abs(vertical);
   if (aspect > 1)
   {
      horizontal /= aspect;
   }
   else
   {
      vertical *= aspect;
   }

   complex<double> total = (horizontal + vertical) / complex<double>(2);
   complex<double> totalFlipped = (horizontal - vertical) / complex<double>(2);
   if (abs(totalFlipped) > abs(total))
   {
      total = conj(totalFlipped);
      pDstViewSpatial->flipVertical();
   }

   double zoom = 100 * abs(total);
   double rot = 360 - (arg(total) * 180/PI);

   pDstViewSpatial->rotateTo(fmod(rot, 360));
   pDstViewSpatial->zoomTo(zoom);
   pDstViewSpatial->setPixelAspect(aspect);

}
bool ResamplerPlugIn::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   VERIFY(pInArgList != NULL && pOutArgList != NULL);
   ProgressTracker progress(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()),
      "Executing Spectral Resampler.", "spectral", "{88CD3E49-A522-431A-AE2A-96A6B2EB4012}");

   Service<DesktopServices> pDesktop;

   const DataElement* pElement(NULL);
   std::string waveFilename;

   // get default resampling options from user config
   std::string resampleMethod = ResamplerOptions::getSettingResamplerMethod();
   double dropOutWindow = ResamplerOptions::getSettingDropOutWindow();
   double fwhm = ResamplerOptions::getSettingFullWidthHalfMax();
   bool useFillValue = ResamplerOptions::getSettingUseFillValue();
   double fillValue = ResamplerOptions::getSettingSignatureFillValue();

   std::vector<Signature*> originalSignatures;
   std::auto_ptr<std::vector<Signature*> > pResampledSignatures(new std::vector<Signature*>);
   std::string errorMsg;

   if (isBatch())
   {
      VERIFY(pInArgList->getPlugInArgValue("Signatures to resample", originalSignatures));
      if (originalSignatures.empty())
      {
         Signature* pSignature = pInArgList->getPlugInArgValue<Signature>("Signature to resample");
         if (pSignature != NULL)
         {
            originalSignatures.push_back(pSignature);
         }
      }
      if (originalSignatures.empty())
      {
         progress.report("No signatures are available to be resampled.", 0, ERRORS, true);
         return false;
      }
      pElement = pInArgList->getPlugInArgValue<DataElement>("Data element wavelength source");
      Filename* pWaveFilename = pInArgList->getPlugInArgValue<Filename>("Wavelengths Filename");
      if (pWaveFilename != NULL)
      {
         waveFilename = pWaveFilename->getFullPathAndName();
      }
      VERIFY(pInArgList->getPlugInArgValue("Resampling Method", resampleMethod));
      VERIFY(pInArgList->getPlugInArgValue("Drop out window", dropOutWindow));
      VERIFY(pInArgList->getPlugInArgValue("FWHM", fwhm));
      VERIFY(pInArgList->getPlugInArgValue("Use fill value", useFillValue));
      VERIFY(pInArgList->getPlugInArgValue("Fill value", fillValue));
   }
   else
   {
      ResamplerPlugInDlg dlg(pDesktop->getMainWidget());
      if (dlg.exec() == QDialog::Rejected)
      {
         progress.report("User canceled resampling.", 0, ABORT, true);
         progress.upALevel();
         return false;
      }
      originalSignatures = dlg.getSignaturesToResample();
      resampleMethod = dlg.getResamplingMethod();
      dropOutWindow = dlg.getDropOutWindow();
      fwhm = dlg.getFWHM();
      useFillValue = dlg.getUseFillValue();
      fillValue = dlg.getFillValue();
      pElement = dlg.getWavelengthsElement();
      waveFilename = dlg.getWavelengthsFilename();
   }

   std::string resampledTo;
   FactoryResource<Wavelengths> pWavelengths;
   if (pElement != NULL)  // try loading wavelengths from user specified data element
   {
      if (getWavelengthsFromElement(pElement, pWavelengths.get(), errorMsg) == false)
      {
         progress.report(errorMsg, 0, ERRORS, true);
         return false;
      }
      resampledTo = pElement->getName();
   }
   else if (waveFilename.empty() == false)  // if no user provided raster, look for a wavelengths file
   {
      if (QFile::exists(QString::fromStdString(waveFilename)))
      {
         if (getWavelengthsFromFile(waveFilename, pWavelengths.get(), errorMsg) == false)
         {
            progress.report(errorMsg, 0, ERRORS, true);
            return false;
         }
      }
      else
      {
         errorMsg = "The wavelengths file \"" + waveFilename + "\" could not be found.";
         progress.report(errorMsg, 0, ERRORS, true);
         return false;
      }
      resampledTo = waveFilename;
   }
   else  // if no wavelength source provided, look for raster in current active spatial data view
   {
      SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pDesktop->getCurrentWorkspaceWindowView());
      if (pView != NULL)
      {
         LayerList* pLayerList = pView->getLayerList();
         if (pLayerList != NULL)
         {
            pElement = pLayerList->getPrimaryRasterElement();
            pWavelengths->initializeFromDynamicObject(pElement->getMetadata(), false);
            if (pWavelengths->isEmpty())
            {
               progress.report("No target wavelengths are available for resampling the signatures.", 0, ERRORS, true);
               return false;
            }
            resampledTo = pElement->getName();
         }
      }
   }

   PlugInResource pPlugIn("Resampler");
   Resampler* pResampler = dynamic_cast<Resampler*>(pPlugIn.get());
   if (pResampler == NULL)
   {
      progress.report("The \"Resampler\" plug-in is not available so the signatures can not be resampled.",
         0, ERRORS, true);
      return false;
   }
   std::string dataName("Reflectance");
   std::string wavelengthName("Wavelength");

   // save user config settings - Resampler doesn't have interface to set them separately from user config
   std::string configMethod = ResamplerOptions::getSettingResamplerMethod();
   ResamplerOptions::setSettingResamplerMethod(resampleMethod);
   double configDropout = ResamplerOptions::getSettingDropOutWindow();
   ResamplerOptions::setSettingDropOutWindow(dropOutWindow);
   double configFwhm = ResamplerOptions::getSettingFullWidthHalfMax();
   ResamplerOptions::setSettingFullWidthHalfMax(fwhm);

   std::vector<double> toWavelengths = pWavelengths->getCenterValues();
   std::vector<double> toFwhm = pWavelengths->getFwhm();
   if (toFwhm.size() != toWavelengths.size())
   {
      toFwhm.clear();  // Resampler will use the default config setting fwhm if this vector is empty
   }

   unsigned int numSigs = originalSignatures.size();
   unsigned int numSigsResampled(0);
   progress.report("Begin resampling signatures...", 0, NORMAL);
   for (unsigned int index = 0; index < numSigs; ++index)
   {
      if (isAborted())
      {
         progress.report("Resampling aborted by user", 100 * index / numSigs, ABORT, true);
         return false;
      }
      if (originalSignatures[index] == NULL)
      {
         continue;
      }

      // check if signature has target wavelength centers and doesn't need to be resampled
      if (needToResample(originalSignatures[index], pWavelengths.get()) == false)
      {
         pResampledSignatures->push_back(originalSignatures[index]);
         ++numSigsResampled;
         continue;
      }

      DataVariant var = originalSignatures[index]->getData(dataName);
      if (var.isValid() == false)
      {
         continue;
      }
      std::vector<double> fromData;
      if (!var.getValue(fromData))
      {
         continue;
      }
      var = originalSignatures[index]->getData(wavelengthName);
      if (var.isValid() == false)
      {
         continue;
      }
      std::vector<double> fromWavelengths;
      if (!var.getValue(fromWavelengths))
      {
         continue;
      }
      std::string resampledSigName = originalSignatures[index]->getName() + "_resampled";
      int suffix(2);
      ModelResource<Signature> pSignature(resampledSigName, NULL);

      // probably not needed but just in case resampled name already used
      while (pSignature.get() == NULL)
      {
         pSignature = ModelResource<Signature>(resampledSigName + StringUtilities::toDisplayString(suffix), NULL);
         ++suffix;
      }
      if (resampledTo.empty() == false)
      {
         DynamicObject* pMetaData = pSignature->getMetadata();
         if (pMetaData != NULL)
         {
            pMetaData->setAttribute(CommonSignatureMetadataKeys::ResampledTo(), resampledTo);
         }
      }
      std::vector<double> toData;
      std::vector<int> toBands;
      if (pResampler->execute(fromData, toData, fromWavelengths, toWavelengths, toFwhm, toBands, errorMsg))
      {
         if (toWavelengths.size() != toBands.size())
         {
            if (toBands.size() < 2)  // no need to try if only one point
            {
               continue;
            }

            if (useFillValue)
            {
               std::vector<double> values(toWavelengths.size(), fillValue);
               for (unsigned int i = 0; i < toBands.size(); ++i)
               {
                  values[static_cast<unsigned int>(toBands[i])] = toData[i];
               }
               toData.swap(values);
               DynamicObject* pMetaData = pSignature->getMetadata();
               if (pMetaData != NULL)
               {
                  pMetaData->setAttribute(CommonSignatureMetadataKeys::FillValue(), fillValue);
               }
            }
            else
            {
               std::vector<double> wavelengths(toBands.size());
               for (unsigned int i = 0; i < toBands.size(); ++i)
               {
                  wavelengths[i] = toWavelengths[static_cast<unsigned int>(toBands[i])];
               }
               toWavelengths.swap(wavelengths);
            }
         }
         pSignature->setData(dataName, toData);
         pSignature->setData(wavelengthName, toWavelengths);
         SignatureDataDescriptor* pDesc = dynamic_cast<SignatureDataDescriptor*>(pSignature->getDataDescriptor());
         if (pDesc == NULL)
         {
            continue;
         }
         pDesc->setUnits(dataName, originalSignatures[index]->getUnits(dataName));
         pResampledSignatures->push_back(pSignature.release());
         ++numSigsResampled;
      }
      std::string progressStr =
         QString("Resampled signature %1 of %2 signatures").arg(index + 1).arg(numSigs).toStdString();
      progress.report(progressStr, (index + 1) * 100 / numSigs, NORMAL);
   }

   // reset config options
   ResamplerOptions::setSettingResamplerMethod(configMethod);
   ResamplerOptions::setSettingDropOutWindow(configDropout);
   ResamplerOptions::setSettingFullWidthHalfMax(configFwhm);

   if (numSigsResampled == numSigs)
   {
      progress.report("Complete", 100, NORMAL);
      progress.upALevel();
   }
   else
   {
      errorMsg = QString("Only %1 of the %2 signatures were successfully resampled.").arg(
         numSigsResampled).arg(numSigs).toStdString();
      progress.report(errorMsg, 100, WARNING, true);
   }

   VERIFY(pOutArgList->setPlugInArgValue("Resampled signatures", pResampledSignatures.release()));
   return true;
}
Ejemplo n.º 20
0
string MeasurementObjectImp::generateGeoStrings() const
{
   LocationType llCorner = getLlCorner();
   LocationType urCorner = getUrCorner();
   LocationType llCornerLatLon;
   LocationType urCornerLatLon;
   bool unitsValid = false;

   // Get lat lon coordinates and terrain raster
   const RasterElement* pTerrain = NULL;

   bool geoValid(false);
   if (mpGeoreference.get() != NULL)
   {
      GraphicLayer* pLayer = getLayer();
      if (pLayer != NULL)
      {
         SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pLayer->getView());
         if (pView != NULL)
         {
            LayerList* pLayerList = pView->getLayerList();
            VERIFYRV(pLayerList != NULL, "");
            VERIFYRV(pLayerList->getPrimaryRasterElement() == mpGeoreference.get(), "");

            pTerrain = mpGeoreference->getTerrain();

            Layer* pPrimaryRasterLayer = pLayerList->getLayer(RASTER, mpGeoreference.get());
            if (pPrimaryRasterLayer != NULL)
            {
               pPrimaryRasterLayer->translateWorldToData(llCorner.mX, llCorner.mY, llCorner.mX, llCorner.mY);
               pPrimaryRasterLayer->translateWorldToData(urCorner.mX, urCorner.mY, urCorner.mX, urCorner.mY);
            }
         }
      }

      if (mpGeoreference->isGeoreferenced())
      {
         bool llValid(false);
         bool urValid(false);
         llCornerLatLon = mpGeoreference->convertPixelToGeocoord(llCorner, false, &llValid);
         urCornerLatLon = mpGeoreference->convertPixelToGeocoord(urCorner, false, &urValid);
         geoValid = llValid && urValid;
      }
   }

   mUsingInaccurateGeocoords = !geoValid;
   unitsValid = geoValid;

   //String Variables
   string startLoc = "";
   string endLoc = "";
   string distance = "";
   string bearing = "";
   string distanceUnit = "";

   GeoAlgorithms algs;
   double distanceVal = 0;
   double azimuthVal = 0;

   // Create GeoPoint objects
   LatLonPoint startLlPoint = llCornerLatLon;
   LatLonPoint endLlPoint = urCornerLatLon;
   UtmPoint startUtmPoint = startLlPoint;
   UtmPoint endUtmPoint = endLlPoint;
   MgrsPoint startMgrsPoint = startLlPoint;
   MgrsPoint endMgrsPoint = endLlPoint;

   // find elevations
   double elevation1(0.0);
   double elevation2(0.0);
   if (pTerrain != NULL)
   {
      const RasterDataDescriptor* pDescriptor =
         dynamic_cast<const RasterDataDescriptor*>(pTerrain->getDataDescriptor());
      if (pDescriptor != NULL)
      {
         const vector<DimensionDescriptor>& activeRows = pDescriptor->getRows();
         const vector<DimensionDescriptor>& activeColumns = pDescriptor->getColumns();
         if ( llCorner.mY >= 0 && llCorner.mY < activeRows.size() &&
              llCorner.mX >= 0 && llCorner.mX < activeColumns.size() &&
              urCorner.mY >= 0 && urCorner.mY < activeRows.size() &&
              urCorner.mX >= 0 && urCorner.mX < activeColumns.size() )
         {
            DimensionDescriptor llRowDim(activeRows[llCorner.mY]);
            DimensionDescriptor llColumnDim(activeColumns[llCorner.mX]);
            DimensionDescriptor urRowDim(activeRows[urCorner.mY]);
            DimensionDescriptor urColumnDim(activeColumns[urCorner.mX]);
            elevation1 = pTerrain->getPixelValue(llColumnDim, llRowDim, DimensionDescriptor(), COMPLEX_MAGNITUDE);
            elevation2 = pTerrain->getPixelValue(urColumnDim, urRowDim, DimensionDescriptor(), COMPLEX_MAGNITUDE);
            const Units* pElevationUnits = pDescriptor->getUnits();
            if (pElevationUnits != NULL)
            {
               double scale = pElevationUnits->getScaleFromStandard();
               elevation1 *= scale;
               elevation2 *= scale;
            }
         }
      }
   }

   if (unitsValid == true)
   {
      // Calculate bearing and distance
      distanceVal = algs.getPythagoreanOrVincentyDistance(startLlPoint.getLatitude().getValue(),
         startLlPoint.getLongitude().getValue(), endLlPoint.getLatitude().getValue(),
         endLlPoint.getLongitude().getValue(), elevation1, elevation2);
      azimuthVal = algs.getVincentyAzimuth(startLlPoint.getLatitude().getValue(),
         startLlPoint.getLongitude().getValue(), endLlPoint.getLatitude().getValue(),
         endLlPoint.getLongitude().getValue());
      azimuthVal = GeoConversions::convertRadToDeg(azimuthVal);

      // Set distance text
      if (mDrawnDistanceUnit == KILOMETER)
      {
         distanceUnit = "km";
         distanceVal = distanceVal/1000;
      }
      else if (mDrawnDistanceUnit == MILE)
      {
         distanceUnit = "mi";
         distanceVal = GeoConversions::convertMetersToMiles(distanceVal);
      }
      else if (mDrawnDistanceUnit == NAUTICAL_MILE)
      {
         distanceUnit = "Nm";
         distanceVal = GeoConversions::convertMetersToNm(distanceVal);
      }
      else if (mDrawnDistanceUnit == METER)
      {
         distanceUnit = "m";
      }
      else if (mDrawnDistanceUnit == YARD)
      {
         distanceUnit = "yd";
         distanceVal = GeoConversions::convertMetersToFeet(distanceVal)/3;
      }
      else if (mDrawnDistanceUnit == FOOT)
      {
         distanceUnit = "ft";
         distanceVal = GeoConversions::convertMetersToFeet(distanceVal);
      }

      // set location text
      switch (mDrawnGeocoord)
      {
      case GEOCOORD_LATLON:
         startLoc = startLlPoint.getText(mDrawnDmsFormat, mEndPointsPrecision);
         endLoc = endLlPoint.getText(mDrawnDmsFormat, mEndPointsPrecision);
         break;

      case GEOCOORD_UTM:
         startLoc = startUtmPoint.getText();
         endLoc = endUtmPoint.getText();
         break;

      case GEOCOORD_MGRS:
         startLoc = startMgrsPoint.getText();
         endLoc = endMgrsPoint.getText();
         break;

      default:
         startLoc = "(" + QString::number(llCorner.mX, 'f', mEndPointsPrecision).toStdString() + ", " +
            QString::number(llCorner.mY, 'f', mEndPointsPrecision).toStdString() + ")";
         endLoc = "(" + QString::number(urCorner.mX, 'f', mEndPointsPrecision).toStdString() + ", " +
            QString::number(urCorner.mY, 'f', mEndPointsPrecision).toStdString() + ")";
         break;
      }
   }
   else
   {
      startLoc = "(" + QString::number(llCorner.mX, 'f', mEndPointsPrecision).toStdString() + ", " +
         QString::number(llCorner.mY, 'f', mEndPointsPrecision).toStdString() + ")";
      endLoc = "(" + QString::number(urCorner.mX, 'f', mEndPointsPrecision).toStdString() + ", " +
         QString::number(urCorner.mY, 'f', mEndPointsPrecision).toStdString() + ")";
      azimuthVal = algs.getPythagoreanAzimuth(llCorner.mX, llCorner.mY, urCorner.mX, urCorner.mY);
      azimuthVal = GeoConversions::convertRadToDeg(azimuthVal);
      distanceVal = algs.getPythagoreanDistance(urCorner.mX, urCorner.mY, llCorner.mX, llCorner.mY);
      distanceUnit = "pix";
   }

   bearing = QString::number(azimuthVal, 'f', mBearingPrecision).toStdString();
   distance = QString::number(distanceVal, 'f', mDistancePrecision).toStdString();

   QString bearingText = QString::fromStdString(bearing) + " deg";
   QString distanceText = QString::fromStdString(distance) + " " + QString::fromStdString(distanceUnit);
   QString startLocText = QString::fromStdString(startLoc);
   QString endLocText = QString::fromStdString(endLoc);

   // Final strings
   if (bearingText != mBearingText)
   {
      mBearingText = bearingText;
      mBearingTextTexture.invalidate();
   }

   if (distanceText != mDistanceText)
   {
      mDistanceText = distanceText;
      mDistanceTextTexture.invalidate();
   }
   if (startLocText != mStartLocText)
   {
      mStartLocText = startLocText;
      mStartLocTextTexture.invalidate();
   }
   if (endLocText != mEndLocText)
   {
      mEndLocText = endLocText;
      mEndLocTextTexture.invalidate();
   }

   string rtnVal = "DISTANCE: " + distanceText.toStdString() + " : LOCATION: " + startLoc + " to " +
      endLoc + " at " + bearingText.toStdString();
   return rtnVal;
}
LocateDialog::LocateDialog(const RasterElement* pRaster, QWidget* pParent) :
   QDialog(pParent, Qt::WindowCloseButtonHint),
   mpRaster(pRaster),
   mLayerNameBase("Spectral Library Match Locate Results - "),
   mpAlgCombo(NULL),
   mpThreshold(NULL),
   mpOutputLayerName(NULL),
   mpUseAoi(NULL),
   mpAoiCombo(NULL),
   mpSaveSettings(NULL)
{
   setWindowTitle("Locate Matched Signatures Settings");

   // layout
   QGridLayout* pGrid = new QGridLayout(this);
   pGrid->setSpacing(5);
   pGrid->setMargin(10);

   QLabel* pNameLabel = new QLabel("Dataset:", this);
   QLabel* pDataLabel = new QLabel(QString::fromStdString(pRaster->getDisplayName(true)), this);
   pDataLabel->setToolTip(QString::fromStdString(pRaster->getName()));
   QLabel* pAlgLabel = new QLabel("Algorithm:", this);
   mpAlgCombo = new QComboBox(this);
   QLabel* pThresLabel = new QLabel("Threshold:", this);
   mpThreshold = new QDoubleSpinBox(this);
   mpThreshold->setSingleStep(0.1);
   QLabel* pLayerLabel = new QLabel("Output Layer Name:", this);
   mpOutputLayerName = new QLineEdit(this);
   mpUseAoi = new QCheckBox("Area of Interest:", this);
   mpUseAoi->setToolTip("Check box to limit the Locate function to an AOI");
   mpAoiCombo = new QComboBox(this);
   mpAoiCombo->setEnabled(false);
   mpSaveSettings = new QCheckBox("Save the algorithm and threshold settings", this);
   QFrame* pLineSeparator = new QFrame(this);
   pLineSeparator->setFrameStyle(QFrame::HLine | QFrame::Sunken);
   QDialogButtonBox* pButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
      Qt::Horizontal, this);

   pGrid->addWidget(pNameLabel, 0, 0, Qt::AlignRight);
   pGrid->addWidget(pDataLabel, 0, 1);
   pGrid->addWidget(pAlgLabel, 1, 0, Qt::AlignRight);
   pGrid->addWidget(mpAlgCombo, 1, 1);
   pGrid->addWidget(pThresLabel, 2, 0, Qt::AlignRight);
   pGrid->addWidget(mpThreshold, 2, 1);
   pGrid->addWidget(pLayerLabel, 3, 0, Qt::AlignRight);
   pGrid->addWidget(mpOutputLayerName, 3, 1);
   pGrid->addWidget(mpUseAoi, 4, 0, Qt::AlignRight);
   pGrid->addWidget(mpAoiCombo, 4, 1);
   pGrid->addWidget(mpSaveSettings, 5, 1);
   pGrid->addWidget(pLineSeparator, 7, 0, 1, 2);
   pGrid->addWidget(pButtons, 8, 0, 1, 2, Qt::AlignRight);
   pGrid->setRowStretch(6, 10);
   pGrid->setColumnStretch(1, 10);

   // initialize algorithm combo
   std::vector<std::string> algNames =
      StringUtilities::getAllEnumValuesAsDisplayString<SpectralLibraryMatch::LocateAlgorithm>();
   for (std::vector<std::string>::const_iterator it = algNames.begin(); it != algNames.end(); ++it)
   {
      mpAlgCombo->addItem(QString::fromStdString(*it));
   }

   // set up algorithm threshold map
   std::vector<std::string> algorithmNames =
      StringUtilities::getAllEnumValuesAsDisplayString<SpectralLibraryMatch::LocateAlgorithm>();
   for (std::vector<std::string>::iterator it = algorithmNames.begin();
      it != algorithmNames.end(); ++it)
   {
      float threshold(0.0f);
      switch (StringUtilities::fromDisplayString<SpectralLibraryMatch::LocateAlgorithm>(*it))
      {
      case SpectralLibraryMatch::SLLA_CEM:
         threshold = SpectralLibraryMatchOptions::getSettingLocateCemThreshold();
         break;

      case SpectralLibraryMatch::SLLA_SAM:
         threshold = SpectralLibraryMatchOptions::getSettingLocateSamThreshold();
         break;

      case SpectralLibraryMatch::SLLA_WBI:
         threshold = SpectralLibraryMatchOptions::getSettingLocateWbiThreshold();
         break;

      default:
         threshold = 0.0f;
         break;
      }

      mLocateThresholds.insert(std::pair<std::string, float>(*it, threshold));
   }

   // load aoi combo
   std::vector<DataElement*> aois =
      Service<ModelServices>()->getElements(pRaster, TypeConverter::toString<AoiElement>());
   for (std::vector<DataElement*>::const_iterator it = aois.begin(); it != aois.end(); ++it)
   {
      mpAoiCombo->addItem(QString::fromStdString((*it)->getName()));
   }

   // try to determine the active aoi layer and set combo to the element for that layer
   std::vector<Window*> windows;
   SpatialDataView* pView(NULL);
   Service<DesktopServices>()->getWindows(SPATIAL_DATA_WINDOW, windows);
   for (std::vector<Window*>::iterator it = windows.begin(); it != windows.end(); ++it)
   {
      SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(*it);
      if (pWindow != NULL)
      {
         SpatialDataView* pTmpView = dynamic_cast<SpatialDataView*>(pWindow->getView());
         if (pTmpView != NULL)
         {
            LayerList* pLayerList = pTmpView->getLayerList();
            if (pLayerList != NULL)
            {
               if (pRaster == pLayerList->getPrimaryRasterElement())
               {
                  pView = pTmpView;
                  break;
               }
            }
         }
      }
   }

   if (pView != NULL)
   {
      Layer* pLayer = pView->getActiveLayer();
      if (pLayer != NULL)
      {
         DataElement* pElement = pLayer->getDataElement();
         if (pElement != NULL)
         {
            std::string elementName = pElement->getName();
            int index = mpAoiCombo->findText(QString::fromStdString(elementName));
            if (index != -1)
            {
               mpAoiCombo->setCurrentIndex(index);
            }
         }
      }
   }
   if (mpAoiCombo->count() == 0)
   {
      mpUseAoi->setEnabled(false);
   }

   // Initialize From Settings
   SpectralLibraryMatch::LocateAlgorithm locType =
      StringUtilities::fromXmlString<SpectralLibraryMatch::LocateAlgorithm>(
      SpectralLibraryMatchOptions::getSettingLocateAlgorithm());
   mpAlgCombo->setCurrentIndex(mpAlgCombo->findText(QString::fromStdString(
      StringUtilities::toDisplayString<SpectralLibraryMatch::LocateAlgorithm>(locType))));
   mpThreshold->setValue(mLocateThresholds[mpAlgCombo->currentText().toStdString()]);
   QString layerName = mLayerNameBase;
   switch (locType)
   {
   case SpectralLibraryMatch::SLLA_CEM:
      layerName += "CEM";
      break;

   case SpectralLibraryMatch::SLLA_SAM:
      layerName += "SAM";
      break;

   case SpectralLibraryMatch::SLLA_WBI:
      layerName += "WBI";
      break;

   default:
      layerName += "Unknown Algorithm";
      break;
   }
   mpOutputLayerName->setText(layerName);

   // connections
   VERIFYNR(connect(pButtons, SIGNAL(accepted()), this, SLOT(accept())));
   VERIFYNR(connect(pButtons, SIGNAL(rejected()), this, SLOT(reject())));
   VERIFYNR(connect(mpAlgCombo, SIGNAL(currentIndexChanged(const QString&)),
      this, SLOT(algorithmChanged(const QString&))));
   VERIFYNR(connect(mpThreshold, SIGNAL(valueChanged(double)),
      this, SLOT(thresholdChanged(double))));
   VERIFYNR(connect(mpUseAoi, SIGNAL(toggled(bool)), mpAoiCombo, SLOT(setEnabled(bool))));
}
bool ImageRegistration::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Image Registration", "app", "A2E0FC44-2A31-41EE-90F8-805773D01FCA");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   //RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());

   std::vector<Window*> windows;
   Service<DesktopServices>()->getWindows(SPATIAL_DATA_WINDOW, windows);
   std::vector<RasterElement*> elements;
   for (unsigned int i = 0; i < windows.size(); ++i)
   {
       SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(windows[i]);
       if (pWindow == NULL)
       {
           continue;
       }
       LayerList* pList = pWindow->getSpatialDataView()->getLayerList();
       elements.push_back(pList->getPrimaryRasterElement());
   }

   RasterElement* pCube = elements[0];
   RasterElement* pCubeRef = elements[1];
   if ((pCube == NULL) || (pCubeRef == NULL))
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);
   
   EncodingType ResultType = pDesc->getDataType();
   if (pDesc->getDataType() == INT4SCOMPLEX)
   {
      ResultType = INT4SBYTES;
   }
   else if (pDesc->getDataType() == FLT8COMPLEX)
   {
      ResultType = FLT8BYTES;
   }

   FactoryResource<DataRequest> pRequest;
   pRequest->setInterleaveFormat(BSQ);
   DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release());

   FactoryResource<DataRequest> pRequestRef;
   pRequestRef->setInterleaveFormat(BSQ);
   DataAccessor pSrcAccRef = pCubeRef->getDataAccessor(pRequestRef.release());

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Image_Registration_Result", pDesc->getRowCount(), pDesc->getColumnCount(), ResultType));
   if (pResultCube.get() == NULL)
   {
      std::string msg = "A raster cube could not be created.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }

   std::vector<int> badValues = pDesc->getBadValues();
   //badValues.push_back(0);
   RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(pResultCube->getDataDescriptor());
   Statistics* pStatistics = pResultCube->getStatistics(pDescriptor->getActiveBand(0));
   pStatistics->setBadValues(badValues);

   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());
   
   nCountMas = 0;
   nCountRef = 0;
   int windowSize = 6;
   double *pBuffer = (double *)calloc(pDesc->getRowCount()*pDesc->getColumnCount(), sizeof(double));

   GetGrayScale(pDesc->getDataType());

   
   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
	   if (pProgress != NULL)
       {
           pProgress->updateProgress("Image registration", row * 100 / pDesc->getRowCount(), NORMAL);
       }
       if (isAborted())
       {
          std::string msg = getName() + " has been aborted.";
          pStep->finalize(Message::Abort, msg);
          if (pProgress != NULL)
          {
             pProgress->updateProgress(msg, 0, ABORT);
          }
          return false;
       }
       for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
       {
	       locateAllStarPosition(pSrcAcc, pSrcAccRef, row, col, pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), windowSize, pBuffer);
       }
   }

   ModifyCenter(pSrcAcc, pDesc->getDataType(), windowSize, nCountMas, nStarPositionsMas);
   ModifyCenter(pSrcAccRef, pDesc->getDataType(), windowSize, nCountRef, nStarPositionsRef);

   GetAllNeighborStars();
   GetMatchingStars();
   
   GetParameters(pDesc->getRowCount(), pDesc->getColumnCount());
  
   DrawStars(pBuffer, pSrcAccRef, pDesc->getDataType(), matrixT, pDesc->getRowCount(), pDesc->getColumnCount());

   //Output the value 
      for (unsigned int m = 0; m < pDesc->getRowCount(); m++)
      {
	      for (unsigned int n = 0; n < pDesc->getColumnCount(); n++)
	      {
		      if (isAborted())
              {
                  std::string msg = getName() + " has been aborted.";
                  pStep->finalize(Message::Abort, msg);
                  if (pProgress != NULL)
                  {
                      pProgress->updateProgress(msg, 0, ABORT);
                  }
                  return false;
              }
				      
			  if (!pDestAcc.isValid())
              {
                  std::string msg = "Unable to access the cube data.";
                  pStep->finalize(Message::Failure, msg);
                  if (pProgress != NULL) 
                  {
                      pProgress->updateProgress(msg, 0, ERRORS);
                   }
                   return false;
               }

				       
			  switchOnEncoding(ResultType, updatePixel, pDestAcc->getColumn(), pBuffer, m, n, pDesc->getRowCount(), pDesc->getColumnCount());       
			  pDestAcc->nextColumn();
				   
		  }
				   
		  pDestAcc->nextRow();
		  
	  }
   free(pBuffer);
   


   if (!isBatch())
   {
      Service<DesktopServices> pDesktop;

      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(),
         SPATIAL_DATA_WINDOW));

      SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL)
      {
         std::string msg = "Unable to create view.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }

      pView->setPrimaryRasterElement(pResultCube.get());
      pView->createLayer(RASTER, pResultCube.get());
   }

   double theta = std::acos(matrixT[0][0])*180.0/3.1415926;

   std::string msg = "Image Registration is complete.\n Translation x = " +  StringUtilities::toDisplayString(round(shiftX)) + ", y = " + 
	                 StringUtilities::toDisplayString(round(shiftY)) + ", rotation = " + StringUtilities::toDisplayString(round(theta)) + " degree";
   if (pProgress != NULL)
   {
	   
       pProgress->updateProgress(msg, 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("Image Registration Result", pResultCube.release());

   pStep->finalize();


   return true;
}