Example #1
0
bool ChangeUpDirection::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   ProgressTracker progress(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()),
      "Rotating data.", "app", "{11adadb9-c133-49de-8cf5-a16372da2578}");

   RasterElement* pData = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pData == NULL)
   {
      progress.report("No data element specified.", 0, ERRORS, true);
      return false;
   }
   bool display = false;
   if (!pInArgList->getPlugInArgValue("Display Results", display))
   {
      progress.report("Unsure if results should be displayed. Invalid argument.", 0, ERRORS, true);
      return false;
   }
   double rotation = 0.0;
   SpatialDataView* pOrigView = NULL;
   if (isBatch())
   {
      if (!pInArgList->getPlugInArgValue("Rotation", rotation))
      {
         progress.report("No rotation specified.", 0, ERRORS, true);
         return false;
      }
   }
   else
   {
      pOrigView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg());
      if (pOrigView == NULL)
      {
         progress.report("No view specified.", 0, ERRORS, true);
         return false;
      }
      GraphicLayer* pLayer = dynamic_cast<GraphicLayer*>(pOrigView->getActiveLayer());
      if (pLayer == NULL)
      {
         pLayer = dynamic_cast<GraphicLayer*>(pOrigView->getTopMostLayer(ANNOTATION));
      }
      GraphicObject* pArrow = NULL;
      if (pLayer != NULL)
      {
         std::list<GraphicObject*> objects;
         pLayer->getObjects(ARROW_OBJECT, objects);
         if (!objects.empty())
         {
            pArrow = objects.back();
         }
         if (objects.size() > 1)
         {
            progress.report("Multiple arrow objects found. Using the most recently added one.", 0, WARNING, true);
         }
      }
      if (pArrow == NULL)
      {
         progress.report("Unable to locate up direction. Add an arrow annotation and re-run this plugin.",
            0, ERRORS, true);
         return false;
      }
      LocationType ur = pArrow->getUrCorner();
      LocationType ll = pArrow->getLlCorner();
      double xlen = ur.mX - ll.mX;
      double ylen = ur.mY - ll.mY;

      // Initial rotatation value. The 90 degrees is due to the difference
      // in the "0 point" (right vs. up). Also account for explicit rotation
      // of the annotation object. Convert this to radians.
      rotation = GeoConversions::convertDegToRad(90 + pArrow->getRotation());

      // Determine a rotation adjustment based on the bounding box
      rotation += atan2(ylen, xlen);
   }

   progress.report("Rotating data.", 10, NORMAL);
   ModelResource<RasterElement> pRotated(pData->copyShallow(pData->getName() + "_rotated", pData->getParent()));
   if (pRotated.get() == NULL)
   {
      progress.report("Unable to create destination raster element.", 0, ERRORS, true);
      return false;
   }

   int defaultBadValue(0);  // the rotate method will handle setting the default bad values into the rotated raster
   if (!RasterUtilities::rotate(pRotated.get(), pData, rotation, defaultBadValue,
      INTERP_NEAREST_NEIGHBOR, progress.getCurrentProgress(), &mAbort))
   {
      // error message already reported by rotate()
      return false;
   }
   pOutArgList->setPlugInArgValue("Rotated Element", pRotated.get());

   if (display)
   {
      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(
         Service<DesktopServices>()->createWindow(pRotated->getName(), SPATIAL_DATA_WINDOW));
      SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL)
      {
         Service<DesktopServices>()->deleteWindow(pWindow);
         progress.report("Unable to create view.", 0, ERRORS, true);
         return false;
      }
      pView->setPrimaryRasterElement(pRotated.get());

      RasterLayer* pLayer = NULL;
      { // scope
         UndoLock lock(pView);
         pLayer = static_cast<RasterLayer*>(pView->createLayer(RASTER, pRotated.get()));
      }
      if (pLayer == NULL)
      {
//#pragma message(__FILE__ "(" STRING(__LINE__) ") : warning : This would be cleaner with a WindowResource. If one " \
//                                              "becomes available, use it instead. (tclarke)")
         Service<DesktopServices>()->deleteWindow(pWindow);
         progress.report("Unable to create layer.", 0, ERRORS, true);
         return false;
      }
      pOutArgList->setPlugInArgValue("View", pView);
   }

   pRotated.release();
   progress.report("Rotation complete.", 100, NORMAL);
   progress.upALevel();
   return true;
}
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();
}
/**
 * Move a layer to a new position in the layer list.
 *
 * @param[in] [1]
 *            The name of the layer to move.
 * @param[in] INDEX
 *            The new 0 based index for the layer.
 * @param[in] WINDOW @opt
 *            The name of the window. Defaults to the active window.
 * @rsof
 * @usage print,set_layer_position("data.tif", INDEX=0)
 * @endusage
 */
IDL_VPTR set_layer_position(int argc, IDL_VPTR pArgv[], char* pArgk)
{
   IDL_VPTR idlPtr;
   typedef struct
   {
      IDL_KW_RESULT_FIRST_FIELD;
      int windowExists;
      IDL_STRING windowName;
      int indexExists;
      IDL_LONG index;
   } 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,
      {"INDEX", IDL_TYP_LONG, 1, 0, reinterpret_cast<int*>(IDL_KW_OFFSETOF(indexExists)),
         reinterpret_cast<char*>(IDL_KW_OFFSETOF(index))},
      {"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;
   int index = -1;
   std::string name;

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

   if (argc < 2)
   {
      IDL_Message(IDL_M_GENERIC, IDL_MSG_RET, "set_layer_position takes a layer name as a parameter with a "
         "window as an optional keyword.  A keyword 'index' is needed to specify the position.");
      return IDL_StrToSTRING("failure");
   }
   //the name of the layer to set the posisiton of
   name = IDL_VarGetString(pArgv[0]);
   bool bSuccess = false;
   SpatialDataView* pView = dynamic_cast<SpatialDataView*>(IdlFunctions::getViewByWindowName(windowName));
   if (pView != NULL)
   {
      Layer* pLayer = IdlFunctions::getLayerByName(windowName, name, false);
      if (pLayer != NULL)
      {
         pView->setLayerDisplayIndex(pLayer, index);
         bSuccess = true;
      }
   }
   if (bSuccess)
   {
      idlPtr = IDL_StrToSTRING("success");
   }
   else
   {
      idlPtr = IDL_StrToSTRING("failure");
   }
   return idlPtr;
}
Example #4
0
void ChippingWindow::createView()
{
   if (mpChippingWidget == NULL)
   {
      return;
   }

   RasterElement* pRaster = getRasterElement();
   if (pRaster == NULL)
   {
      return;
   }

   // Create the new raster element from the primary element of the source.
   // Note that this does not chip displayed elements if they differ from the primary element.
   // This causes a special case below where the stretch values are being applied to the chipped layer.
   RasterElement* pRasterChip = pRaster->createChip(pRaster->getParent(), "_chip",
      mpChippingWidget->getChipRows(), mpChippingWidget->getChipColumns(), mpChippingWidget->getChipBands());
   if (pRasterChip == NULL)
   {
      QMessageBox::critical(this, windowTitle(), "Unable to create a new cube!");
      return;
   }

   const RasterDataDescriptor* pDescriptor =
      dynamic_cast<const RasterDataDescriptor*>(pRasterChip->getDataDescriptor());
   VERIFYNRV(pDescriptor != NULL);

   // Create a view for the new chip
   SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(
      Service<DesktopServices>()->createWindow(pRasterChip->getName(), SPATIAL_DATA_WINDOW));
   if (pWindow == NULL)
   {
      return;
   }

   SpatialDataView* pView = pWindow->getSpatialDataView();
   if (pView == NULL)
   {
      Service<DesktopServices>()->deleteWindow(pWindow);
      return;
   }

   UndoLock lock(pView);
   if (pView->setPrimaryRasterElement(pRasterChip) == false)
   {
      Service<DesktopServices>()->deleteWindow(pWindow);
      return;
   }

   // RasterLayerImp is needed for the call to setCurrentStretchAsOriginalStretch().
   RasterLayerImp* pLayer = dynamic_cast<RasterLayerImp*>(pView->createLayer(RASTER, pRasterChip));
   if (pLayer == NULL)
   {
      Service<DesktopServices>()->deleteWindow(pWindow);
      return;
   }

   string origName = pRaster->getName();

   SpatialDataWindow* pOrigWindow = dynamic_cast<SpatialDataWindow*>(
      Service<DesktopServices>()->getWindow(origName, SPATIAL_DATA_WINDOW));
   if (pOrigWindow != NULL)
   {
      SpatialDataView* pOrigView = pOrigWindow->getSpatialDataView();
      if (pOrigView != NULL)
      {
         LayerList* pLayerList = pOrigView->getLayerList();
         if (pLayerList != NULL)
         {
            RasterLayer* pOrigLayer = static_cast<RasterLayer*>(pLayerList->getLayer(RASTER, pRaster));
            if (pOrigLayer != NULL)
            {
               // Set the stretch type first so that stretch values are interpreted correctly.
               pLayer->setStretchType(GRAYSCALE_MODE, pOrigLayer->getStretchType(GRAYSCALE_MODE));
               pLayer->setStretchType(RGB_MODE, pOrigLayer->getStretchType(RGB_MODE));
               pLayer->setDisplayMode(pOrigLayer->getDisplayMode());

               // Set the properties of the cube layer in the new view.
               // For each channel, display the first band if the previously displayed band was chipped.
               vector<RasterChannelType> channels = StringUtilities::getAllEnumValues<RasterChannelType>();
               for (vector<RasterChannelType>::const_iterator iter = channels.begin(); iter != channels.end(); ++iter)
               {
                  bool bandCopied = true;
                  DimensionDescriptor newBand;
                  DimensionDescriptor oldBand = pOrigLayer->getDisplayedBand(*iter);
                  if (oldBand.isOriginalNumberValid() == true)
                  {
                     newBand = pDescriptor->getOriginalBand(oldBand.getOriginalNumber());
                  }

                  if (newBand.isValid() == false)
                  {
                     bandCopied = false;
                     newBand = pDescriptor->getBands().front();
                  }

                  // No need to explicitly set the RasterElement here since the new view only has one RasterElement.
                  pLayer->setDisplayedBand(*iter, newBand);

                  // Use the default stretch properties if the displayed band was removed from the view or
                  // if the non-primary raster element was displayed. Otherwise, copy the stretch properties.
                  if (bandCopied && pRaster == pOrigLayer->getDisplayedRasterElement(*iter))
                  {
                     // Set the stretch units first so that stretch values are interpreted correctly.
                     pLayer->setStretchUnits(*iter, pOrigLayer->getStretchUnits(*iter));

                     double lower;
                     double upper;
                     pOrigLayer->getStretchValues(*iter, lower, upper);
                     pLayer->setStretchValues(*iter, lower, upper);
                  }
               }

               pLayer->setCurrentStretchAsOriginalStretch();
               pView->refresh();
            }
         }
      }
   }

   // Create a GCP layer
   if (pRaster->isGeoreferenced() == true)
   {
      const vector<DimensionDescriptor>& rows = mpChippingWidget->getChipRows();
      const vector<DimensionDescriptor>& columns = mpChippingWidget->getChipColumns();
      if ((rows.empty() == false) && (columns.empty() == false))
      {
         // Get the geocoordinates at the chip corners
         VERIFYNRV(rows.front().isActiveNumberValid() == true);
         VERIFYNRV(rows.back().isActiveNumberValid() == true);
         VERIFYNRV(columns.front().isActiveNumberValid() == true);
         VERIFYNRV(columns.back().isActiveNumberValid() == true);

         unsigned int startRow = rows.front().getActiveNumber();
         unsigned int endRow = rows.back().getActiveNumber();
         unsigned int startCol = columns.front().getActiveNumber();
         unsigned int endCol = columns.back().getActiveNumber();

         GcpPoint ulPoint;
         ulPoint.mPixel = LocationType(startCol, startRow);
         ulPoint.mCoordinate = pRaster->convertPixelToGeocoord(ulPoint.mPixel);

         GcpPoint urPoint;
         urPoint.mPixel = LocationType(endCol, startRow);
         urPoint.mCoordinate = pRaster->convertPixelToGeocoord(urPoint.mPixel);

         GcpPoint llPoint;
         llPoint.mPixel = LocationType(startCol, endRow);
         llPoint.mCoordinate = pRaster->convertPixelToGeocoord(llPoint.mPixel);

         GcpPoint lrPoint;
         lrPoint.mPixel = LocationType(endCol, endRow);
         lrPoint.mCoordinate = pRaster->convertPixelToGeocoord(lrPoint.mPixel);

         GcpPoint centerPoint;
         centerPoint.mPixel = LocationType((startCol + endCol) / 2, (startRow + endRow) / 2);
         centerPoint.mCoordinate = pRaster->convertPixelToGeocoord(centerPoint.mPixel);

         // Reset the coordinates to be in active numbers relative to the chip
         const vector<DimensionDescriptor>& chipRows = pDescriptor->getRows();
         const vector<DimensionDescriptor>& chipColumns = pDescriptor->getColumns();

         VERIFYNRV(chipRows.front().isActiveNumberValid() == true);
         VERIFYNRV(chipRows.back().isActiveNumberValid() == true);
         VERIFYNRV(chipColumns.front().isActiveNumberValid() == true);
         VERIFYNRV(chipColumns.back().isActiveNumberValid() == true);

         unsigned int chipStartRow = chipRows.front().getActiveNumber();
         unsigned int chipEndRow = chipRows.back().getActiveNumber();
         unsigned int chipStartCol = chipColumns.front().getActiveNumber();
         unsigned int chipEndCol = chipColumns.back().getActiveNumber();
         ulPoint.mPixel = LocationType(chipStartCol, chipStartRow);
         urPoint.mPixel = LocationType(chipEndCol, chipStartRow);
         llPoint.mPixel = LocationType(chipStartCol, chipEndRow);
         lrPoint.mPixel = LocationType(chipEndCol, chipEndRow);
         centerPoint.mPixel = LocationType((chipStartCol + chipEndCol) / 2, (chipStartRow + chipEndRow) / 2);

         // Create the GCP list
         Service<ModelServices> pModel;

         GcpList* pGcpList = static_cast<GcpList*>(pModel->createElement("Corner Coordinates",
            TypeConverter::toString<GcpList>(), pRasterChip));
         if (pGcpList != NULL)
         {
            list<GcpPoint> gcps;
            gcps.push_back(ulPoint);
            gcps.push_back(urPoint);
            gcps.push_back(llPoint);
            gcps.push_back(lrPoint);
            gcps.push_back(centerPoint);

            pGcpList->addPoints(gcps);

            // Create the layer
            if (pView->createLayer(GCP_LAYER, pGcpList) == NULL)
            {
               QMessageBox::warning(this, windowTitle(), "Could not create a GCP layer.");
            }
         }
         else
         {
            QMessageBox::warning(this, windowTitle(), "Could not create a GCP list.");
         }
      }
   }
}
bool MultiLayerMovie::setupAnimations()
{
   // Create the controller
   Service<AnimationServices> pServices;

   AnimationController* pController = pServices->getAnimationController("MultiLayerMovie");
   if (pController != NULL)
   {
      pServices->destroyAnimationController(pController);
   }

   pController = pServices->createAnimationController("MultiLayerMovie", FRAME_TIME);
   if (pController == NULL)
   {
      return false;
   }
   pController->setCanDropFrames(false);

   // Set the controller into each of the views
   SpatialDataView* pView = dynamic_cast<SpatialDataView*>(mpWindow->getView());
   if (pView == NULL)
   {
      pServices->destroyAnimationController(pController);
      return false;
   }

   pView->setAnimationController(pController);

   // Create the animations for each layer
   Animation* pAnimation1 = pController->createAnimation("MultiLayerMovie1");
   Animation* pAnimation2 = pController->createAnimation("MultiLayerMovie2");
   Animation* pAnimation3 = pController->createAnimation("MultiLayerMovie3");
   if (pAnimation1 == NULL || pAnimation2 == NULL || pAnimation3 == NULL)
   {
      pServices->destroyAnimationController(pController);
      return false;
   }

   // Set up the frames for each animation
   const int timeOffset = mNumBands/4;
   vector<AnimationFrame> frames1;
   vector<AnimationFrame> frames2;
   vector<AnimationFrame> frames3;
   for (int i = 0; i < mNumBands; ++i)
   {
      AnimationFrame frame1("frame", i, static_cast<double>(i)/mNumBands);
      AnimationFrame frame2("frame", i, static_cast<double>(i+timeOffset)/(mNumBands+timeOffset));
      AnimationFrame frame3("frame", i, static_cast<double>(i+2*timeOffset)/(mNumBands+timeOffset));
      frames1.push_back(frame1);
      frames2.push_back(frame2);
      frames3.push_back(frame3);
   }

   // Set the frames into the animations
   pAnimation1->setFrames(frames1);
   pAnimation2->setFrames(frames2);
   pAnimation3->setFrames(frames3);

   // Assign the animations to the layers
   mpLayer1->setAnimation(pAnimation1);
   mpLayer2->setAnimation(pAnimation2);
   mpLayer3->setAnimation(pAnimation3);

   return true;
}
bool Deconvolution::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Deconvolution Sharpening", "app", "619F3C8A-FB70-44E0-B211-B116E604EDDA");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == 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());

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Deconvolution_Sharpening_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;
   }
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());

   Service<DesktopServices> pDesktop;
   DeconvolutionDlg dlg(pDesktop->getMainWidget());
   int stat = dlg.exec();
   if (stat != QDialog::Accepted)
   {
	   return true;
   }

   double minGrayValue;
   double maxGrayValue;
   double deltaValue = 0.0;

   int nFilterType = dlg.getCurrentFilterType();
   int windowSize = dlg.getCurrentWindowSize();
   double sigmaVal = dlg.getSigmaValue();
   double gamaVal = dlg.getGamaValue();
   windowSize = (windowSize-1)/2;
   
   if (NULL != pOriginalImage)
   {
	   free(pOriginalImage);
   }
   pOriginalImage = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount());
   
   double *OrigData = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount());
   double *NewData  = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount());
   double *ConvoData = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount());
   double *pTempData;

   InitializeData(pSrcAcc, pOriginalImage, OrigData, pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType());
   GetGrayScale(&minGrayValue, &maxGrayValue, pDesc->getDataType());
   
   //Perform deconvolution iteratively
   for (int num = 0; num < MAX_ITERATION_NUMBER; num++)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Deconvolution process", num*100/MAX_ITERATION_NUMBER, NORMAL);
      }
      if (isAborted())
      {
         std::string msg = getName() + " has been aborted.";
         pStep->finalize(Message::Abort, msg);
         if (pProgress != NULL)
         {
            pProgress->updateProgress(msg, 0, ABORT);
         }
         
         free(OrigData);
         free(NewData);
         free(ConvoData);
         
         return false;
      }
      
      deltaValue = DeconvolutionFunc(OrigData, pOriginalImage, NewData, ConvoData, sigmaVal, gamaVal, 
                                     windowSize, pDesc->getRowCount(), pDesc->getColumnCount(), nFilterType, maxGrayValue, minGrayValue);


      pTempData = OrigData;
      OrigData = NewData;
      NewData = pTempData;

	  double errorRate = deltaValue/(maxGrayValue-minGrayValue);
	  if (errorRate < CONVERGENCE_THRESHOLD)
	  {
		  break;
	  }
   }
   
   free(NewData);
   free(ConvoData);


   //Output result
   unsigned int nCount = 0;
   for (int i = 0; i < pDesc->getRowCount(); i++)
   {
       for (int j = 0; j < pDesc->getColumnCount(); j++)		   
	   {		   
		   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);       
			   }   
			   free(OrigData);                  
			   return false;              
		   }
			   
		   pDestAcc->toPixel(i, j);	
		   switchOnEncoding(ResultType, restoreImageValue, pDestAcc->getColumn(), (OrigData+nCount));
		   nCount++;

	   }
   }
   
   free(OrigData);  


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

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Deconvolution enhancement is complete.", 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("Deconvolution enhancement Result", pResultCube.release());

   pStep->finalize();


   return true;
}
Example #7
0
bool ImageHandler::getSessionItemImage(SessionItem* pItem, QBuffer& buffer, const QString& format, int band, int* pBbox)
{
   if (format.isEmpty())
   {
      return false;
   }
   bool success = true;
   QImage image;
   Layer* pLayer = dynamic_cast<Layer*>(pItem);
   View* pView = dynamic_cast<View*>(pItem);
   if (pLayer != NULL)
   {
      SpatialDataView* pSDView = dynamic_cast<SpatialDataView*>(pLayer->getView());
      if (pSDView != NULL)
      {
         UndoLock ulock(pSDView);
         DimensionDescriptor cur;
         DisplayMode mode;
         RasterLayer* pRasterLayer = dynamic_cast<RasterLayer*>(pLayer);
         if (band >= 0 && pRasterLayer != NULL)
         {
            RasterElement* pRaster = pRasterLayer->getDisplayedRasterElement(GRAY);
            DimensionDescriptor bandDesc =
               static_cast<RasterDataDescriptor*>(pRaster->getDataDescriptor())->getActiveBand(band);
            cur = pRasterLayer->getDisplayedBand(GRAY);
            mode = pRasterLayer->getDisplayMode();
            pRasterLayer->setDisplayedBand(GRAY, bandDesc);
            pRasterLayer->setDisplayMode(GRAYSCALE_MODE);
         }
         int bbox[4] = {0, 0, 0, 0};
         ColorType transparent(255, 255, 254);
         success = pSDView->getLayerImage(pLayer, image, transparent, bbox);
         if (pBbox != NULL)
         {
            memcpy(pBbox, bbox, sizeof(bbox));
         }
         QImage alphaChannel(image.size(), QImage::Format_Indexed8);
         if (image.hasAlphaChannel())
         {
            alphaChannel = image.alphaChannel();
         }
         else
         {
            alphaChannel.fill(0xff);
         }
         QRgb transColor = COLORTYPE_TO_QCOLOR(transparent).rgb();
         for (int y = 0; y < image.height(); y++)
         {
            for (int x = 0; x < image.width(); x++)
            {
               if (image.pixel(x, y) == transColor)
               {
                  alphaChannel.setPixel(x, y, 0x00);
               }
            }
         }
         image.setAlphaChannel(alphaChannel);
         if (mode.isValid())
         {
            pRasterLayer->setDisplayedBand(GRAY, cur);
            pRasterLayer->setDisplayMode(mode);
         }
      }
   }
   else if (pView != NULL)
   {
      success = pView->getCurrentImage(image);
   }
   else
   {
      success = false;
   }
   if (success)
   {
      buffer.open(QIODevice::WriteOnly);
      QImageWriter writer(&buffer, format.toAscii());
      success = writer.write(image);
   }
   return success;
}
Example #8
0
bool pagauss::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Tutorial 5", "app", "5EA0CC75-9E0B-4c3d-BA23-6DB7157BBD54");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == 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);
   if (pDesc->getDataType() == INT4SCOMPLEX || pDesc->getDataType() == FLT8COMPLEX)
   {
      std::string msg = "Edge detection cannot be performed on complex types.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }

   


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

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Edge_Detection_Result", pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType()));
   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;
   }
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());
   

   for (long signed int row = 0; row < pDesc->getRowCount(); ++row)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Calculating result", 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;
      }
      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;
      }
      for (long signed int col = 0; col < pDesc->getColumnCount(); ++col)
      {
         switchOnEncoding(pDesc->getDataType(), gauss, pDestAcc->getColumn(), pSrcAcc, row, col,
            pDesc->getRowCount(), pDesc->getColumnCount());
         pDestAcc->nextColumn();
      }

      pDestAcc->nextRow();
   }

   

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

   if (pProgress != NULL)
   {
      pProgress->updateProgress("pagauss is compete.", 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("pagauss_Result", pResultCube.release());

   pStep->finalize();
   return true;
}
QWidget* RasterElementImporterShell::getPreview(const DataDescriptor* pDescriptor, Progress* pProgress)
{
   if (pDescriptor == NULL)
   {
      return NULL;
   }

   // Create a copy of the descriptor to change the loading parameters
   string previewName = string("Preview: ") + pDescriptor->getName();

   RasterDataDescriptor* pLoadDescriptor = dynamic_cast<RasterDataDescriptor*>(pDescriptor->copy(previewName, NULL));
   if (pLoadDescriptor == NULL)
   {
      return NULL;
   }

   // Set the active row and column numbers
   vector<DimensionDescriptor> newRows = pLoadDescriptor->getRows();
   for (unsigned int i = 0; i < newRows.size(); ++i)
   {
      newRows[i].setActiveNumber(i);
   }
   pLoadDescriptor->setRows(newRows);

   vector<DimensionDescriptor> newColumns = pLoadDescriptor->getColumns();
   for (unsigned int i = 0; i < newColumns.size(); ++i)
   {
      newColumns[i].setActiveNumber(i);
   }
   pLoadDescriptor->setColumns(newColumns);

   // Set the bands to load to just the first band and display it in grayscale mode
   const vector<DimensionDescriptor>& bands = pLoadDescriptor->getBands();
   if (bands.empty() == false)
   {
      DimensionDescriptor displayBand = bands.front();
      displayBand.setActiveNumber(0);

      vector<DimensionDescriptor> newBands;
      newBands.push_back(displayBand);

      pLoadDescriptor->setBands(newBands);
      pLoadDescriptor->setDisplayMode(GRAYSCALE_MODE);
      pLoadDescriptor->setDisplayBand(GRAY, displayBand);
   }

   // Set the processing location to load on-disk read-only
   pLoadDescriptor->setProcessingLocation(ON_DISK_READ_ONLY);

   // Do not georeference
   GeoreferenceDescriptor* pLoadGeorefDescriptor = pLoadDescriptor->getGeoreferenceDescriptor();
   if (pLoadGeorefDescriptor != NULL)
   {
      pLoadGeorefDescriptor->setGeoreferenceOnImport(false);
   }

   // Validate the preview
   string errorMessage;
   bool bValidPreview = validate(pLoadDescriptor, vector<const DataDescriptor*>(), errorMessage);
   if (bValidPreview == false)
   {
      // Try an in-memory preview
      pLoadDescriptor->setProcessingLocation(IN_MEMORY);
      bValidPreview = validate(pLoadDescriptor, vector<const DataDescriptor*>(), errorMessage);
   }

   QWidget* pPreviewWidget = NULL;
   if (bValidPreview == true)
   {
      // Create the model element
      RasterElement* pRasterElement = static_cast<RasterElement*>(mpModel->createElement(pLoadDescriptor));
      if (pRasterElement != NULL)
      {
         // Add the progress and raster element to an input arg list
         PlugInArgList* pInArgList = NULL;
         bool bSuccess = getInputSpecification(pInArgList);
         if ((bSuccess == true) && (pInArgList != NULL))
         {
            bSuccess = pInArgList->setPlugInArgValue(Executable::ProgressArg(), pProgress);
            if (bSuccess)
            {
               bSuccess = pInArgList->setPlugInArgValue(Importer::ImportElementArg(), pRasterElement);
            }
         }

         // Load the data in batch mode
         bool bBatch = isBatch();
         setBatch();

         bSuccess = execute(pInArgList, NULL);

         // Restore to interactive mode if necessary
         if (bBatch == false)
         {
            setInteractive();
         }

         // Create the spatial data view
         if (bSuccess == true)
         {
            string name = pRasterElement->getName();

            SpatialDataView* pView = static_cast<SpatialDataView*>(mpDesktop->createView(name, SPATIAL_DATA_VIEW));
            if (pView != NULL)
            {
               // Set the spatial data in the view
               pView->setPrimaryRasterElement(pRasterElement);

               // Add the cube layer
               RasterLayer* pLayer = static_cast<RasterLayer*>(pView->createLayer(RASTER, pRasterElement));
               if (pLayer != NULL)
               {
                  // Get the widget from the view
                  pPreviewWidget = pView->getWidget();
               }
               else
               {
                  string message = "Could not create the cube layer!";
                  if (pProgress != NULL)
                  {
                     pProgress->updateProgress(message, 0, ERRORS);
                  }

                  mpModel->destroyElement(pRasterElement);
               }
            }
            else
            {
               string message = "Could not create the view!";
               if (pProgress != NULL)
               {
                  pProgress->updateProgress(message, 0, ERRORS);
               }

               mpModel->destroyElement(pRasterElement);
            }
         }
         else
         {
            mpModel->destroyElement(pRasterElement);
         }
      }
   }

   // Delete the data descriptor copy
   mpModel->destroyDataDescriptor(pLoadDescriptor);

   return pPreviewWidget;
}
Example #10
0
bool SaveLayer::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "DCBBB270-9360-4c96-8CE9-A9D414FC68EE");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (!extractInputArgs(pInArgList))
   {
      reportError("Unable to extract input arguments.", "CE17C3AD-05BD-4624-A9AD-9694430E1A6C");
      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!", "2682BD10-8A8E-4aed-B2D8-7F7B4CC857A4");
      return false;
   }

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

   if (mpElement == NULL)
   {
      reportError("The data element input value is invalid!", "CC2017C8-FB19-43c0-B1C6-C70625BFE611");
      return false;
   }

   DataElement* pParent = mpElement->getParent();
   if (mpStep != NULL)
   {
      if (pParent != NULL)
      {
         mpStep->addProperty("dataSet", pParent->getName());
      }
      else
      {
         mpStep->addProperty("dataSet", mpElement->getName());
      }
   }

   // Get the Layer
   Layer* pLayer = NULL;

   vector<Window*> windows;
   Service<DesktopServices> pDesktop;
   VERIFY(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)
            {
               vector<Layer*> layers;
               pLayerList->getLayers(layers);
               vector<Layer*>::iterator layerIter;
               for (layerIter = layers.begin(); layerIter != layers.end(); ++layerIter)
               {
                  Layer* pCurrentLayer = *layerIter;
                  if (pCurrentLayer != NULL)
                  {
                     if (pCurrentLayer->getDataElement() == mpElement)
                     {
                        pLayer = pCurrentLayer;
                        break;
                     }
                  }
               }
            }
         }
      }
   }

   if (pLayer == NULL)
   {
      reportError("Could not get the layer to save!", "37EBD88F-9752-4b52-8A8A-F1BD9A98E608");
      return false;
   }

   // Get the layer type
   LayerType eType = getLayerType();

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

   if (!bSaved)
   {
      reportError("Could not save the layer to the file: " + filename, "E2F6878E-E462-409b-AE8A-6E1555198316");
      return false;
   }

   reportComplete();
   return true;
}
Example #11
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;
}
Example #12
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;
}
Example #13
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;
}
Example #14
0
bool ShapeFileExporter::extractInputs(const PlugInArgList* pInArgList, string& message)
{
   if (pInArgList == NULL)
   {
      message = "Invalid argument list.";
      return false;
   }

   FileDescriptor* pFileDescriptor = pInArgList->getPlugInArgValue<FileDescriptor>(Exporter::ExportDescriptorArg());
   if (pFileDescriptor == NULL)
   {
      message = "No file specified.";
      return false;
   }
   mShapefile.setFilename(pFileDescriptor->getFilename().getFullPathAndName());

   if (isBatch())
   {
      mpAoi = pInArgList->getPlugInArgValue<AoiElement>("AoiElement");
      mpGeoref = pInArgList->getPlugInArgValue<RasterElement>("RasterElement");
   }
   else
   {
      AoiLayer* pLayer = pInArgList->getPlugInArgValue<AoiLayer>(Exporter::ExportItemArg());
      if (pLayer == NULL)
      {
         message = "Input argument list did not include anything to export.";
         return false;
      }

      mpAoi = dynamic_cast<AoiElement*>(pLayer->getDataElement());
      SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pLayer->getView());
      if (pView != NULL)
      {
         mpLayers = pView->getLayerList();
         if (mpLayers != NULL)
         {
            mpGeoref = mpLayers->getPrimaryRasterElement();
         }
      }
   }

   if (mpAoi == NULL)
   {
      message = "Could not identify the data element to export.";
      return false;
   }

   // The BitMaskIterator does not support negative extents and
   // the BitMask does not correctly handle the outside flag so
   // the BitMaskIterator is used for cases when the outside flag is true and
   // the BitMask is used for cases when the outside flag is false.
   // This is the case when the outside flag is false. The case where the
   // outside flag is true for this condition is handled in
   // ShapeFile::addFeatures()
   const BitMask* pMask = mpAoi->getSelectedPoints();
   if (mpAoi->getGroup()->getObjects().empty() == true && 
      pMask->isOutsideSelected() == false)
   {
      message = "The AOI does not contain any points to export.";
      return false;
   }

   if (mpGeoref == NULL)
   {
      message = "Could not identify the georeference to use for export.";
      return false;
   }

   //add aoi to shape file
   mShapefile.setShape(ShapefileTypes::MULTIPOINT_SHAPE);
   string err;
   mShapefile.addFeatures(mpAoi, mpGeoref, err);

   return true;
}
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;
}
SpatialDataView* RasterElementImporterShell::createView() const
{
   if (mpRasterElement == NULL)
   {
      return NULL;
   }

   StepResource pStep("Create view", "app", "F41DCDE3-A5C9-4CE7-B9D4-7DF5A9063840");
   if (mpProgress != NULL)
   {
      mpProgress->updateProgress("Creating view...", 99, NORMAL);
   }

   // Get the data set name
   const string& name = mpRasterElement->getName();
   if (name.empty() == true)
   {
      string message = "The data set name is invalid!  A view cannot be created.";
      if (mpProgress != NULL)
      {
         mpProgress->updateProgress(message, 0, ERRORS);
      }

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

   // Create the spatial data window
   SpatialDataView* pView = NULL;

   SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(mpDesktop->createWindow(name, SPATIAL_DATA_WINDOW));
   if (pWindow != NULL)
   {
      pView = pWindow->getSpatialDataView();
   }

   if (pView == NULL)
   {
      string message = "Could not create the view window!";
      if (mpProgress != NULL)
      {
         mpProgress->updateProgress(message, 0, ERRORS);
      }

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

   // Set the spatial data in the view
   pView->setPrimaryRasterElement(mpRasterElement);

   // Create the layers
   {
      UndoLock lock(pView);
      createRasterLayer(pView, pStep.get());
      createGcpLayer(pView, pStep.get());

      const RasterDataDescriptor* pRasterDescriptor =
         dynamic_cast<const RasterDataDescriptor*>(mpRasterElement->getDataDescriptor());
      if (pRasterDescriptor != NULL)
      {
         const GeoreferenceDescriptor* pGeorefDescriptor = pRasterDescriptor->getGeoreferenceDescriptor();
         if ((pGeorefDescriptor != NULL) && (pGeorefDescriptor->getCreateLayer() == true))
         {
            createLatLonLayer(pView, pStep.get());
         }
      }
   }

   // Check for at least one layer in the view
   LayerList* pLayerList = pView->getLayerList();
   VERIFYRV(pLayerList != NULL, NULL);

   if (pLayerList->getNumLayers() == 0)
   {
      mpDesktop->deleteWindow(pWindow);

      string message = "The view contains no layers, so it will not be created.";
      if (mpProgress != NULL)
      {
         mpProgress->updateProgress(message, 0, ERRORS);
      }

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

   pStep->finalize(Message::Success);
   return pView;
}
void MeasurementObjectImp::draw(double zoomFactor) const
{
   const_cast<MeasurementObjectImp*>(this)->updateGeoreferenceAttachment();

   // Verify that factor values are valid
   if ((mArrowRelStartLoc < 0.0) || (mArrowRelStartLoc > mArrowRelEndLoc) || (mArrowRelStartLoc > 1.0) ||
      (mArrowRelEndLoc < 0.0) || (mArrowRelEndLoc > 1.0) || (mBarEndLength < 0))
   {
      return;
   }
    
   // Draw the main line
   LineObjectImp::draw(zoomFactor);
   
   // Get the current view 
   SpatialDataView* pView = NULL;

   MeasurementLayerImp* pLayer = dynamic_cast<MeasurementLayerImp*>(getLayer());
   if (pLayer != NULL)
   {
      pView = dynamic_cast<SpatialDataView*>(pLayer->getView());
   }

   if (pView == NULL)
   {
      return;
   }

   // Misc Variables
   LocationType junkLocation;    // junk variable used to call methods that require unneeded parameters
   double startPerc = 0.0;       // The relative start location along a line to start drawing
   double lineLength = 0;        // The length of the main line
   double pixelSize = 0;         // The number of screen pixels in a scene pixel
   double lineWidth = 0;         // The width of the main line
   double sqrtLineWidth = 0;     // The square root of the line width
   LocationType llCorner;        // lower left corner of annotation bounding box
   LocationType urCorner;        // upper right corner of annotation bounding box
   ColorType textColor;          // The color to draw the text
   ColorType lineColor;          // The color to draw the line
   ColorType fillColor;          // The color to draw the stippled line

   // Misc Calculations
   pixelSize = DrawUtil::getPixelSize(junkLocation.mX, junkLocation.mY, junkLocation.mX, junkLocation.mY);
   llCorner = getLlCorner();
   urCorner = getUrCorner();
   lineWidth = getLineWidth();
   sqrtLineWidth = sqrt(lineWidth);
   textColor = getTextColor();
   lineLength = sqrt(pow(abs(urCorner.mX - llCorner.mX), 2) + pow(abs(urCorner.mY - llCorner.mY), 2));
   lineColor = getLineColor();
   fillColor = getFillColor();

   // Get text font info (used for all text, set to italic if using inaccurate extrapolation)
   QFont font = getFont();
   font.setItalic(mUsingInaccurateGeocoords);

   // Calculate arrow info (line only)
   LocationType arrowStartPoint; // The start point of the arrow line
   LocationType arrowEndPoint;   // The end point of the arrow line
   double arrowOffset = 0;       // Normal offset from main line to arrow
   double arrowLength = 0;       // The length of the arrow line (in pixels)
   arrowOffset = (pixelSize == 0.0) ? 0.0 : mArrowOffset * sqrtLineWidth / pixelSize;
   DrawUtil::getParallelLine(llCorner, urCorner, arrowOffset, mArrowRelStartLoc, mArrowRelEndLoc,
      arrowStartPoint, arrowEndPoint);
   arrowLength = sqrt(pow(abs(arrowEndPoint.mX - arrowStartPoint.mX), 2) + 
      pow(abs(arrowEndPoint.mY - arrowStartPoint.mY), 2));

   // Calculate arrow head info (Only half arrow head is drawn)
   LocationType arrowHeadBasePoint; // Location of arrow head base point
   double arrowHeadOffset = 0;      // Perpendicular offset from arrow line to arrow head base
   arrowHeadOffset = (pixelSize == 0.0) ? 0.0 : (mArrowHeadOffset * sqrtLineWidth) / pixelSize;
   
   // Adjust arrow head size if arrow length becomes smaller then arrow head length.
   while (arrowHeadOffset > arrowLength)
   {  // Since arrow head is at 45 degree angle, arrowHeadOffset is same as arrow head length

      // Adjust size of arrow head
      if (arrowHeadOffset >= 1)
      {
         arrowHeadOffset -= 1;
      }
      else if (arrowHeadOffset > .2)
      {
         arrowHeadOffset = arrowHeadOffset - .1;
      }
      else
      {
         break;
      }
      arrowHeadOffset = (arrowHeadOffset < 0) ? 0.0 : arrowHeadOffset;
   }
   
   // Get arrow head base point coordinates from calculated arrow head info
   startPerc = (arrowLength == 0.0) ? 0.0 : 1 - (arrowHeadOffset/arrowLength);
   startPerc = (startPerc < 0.0) ? 0.0 : startPerc;
   startPerc = (startPerc > 1.0) ? 1.0 : startPerc;
   DrawUtil::getParallelLine(arrowStartPoint, arrowEndPoint, arrowHeadOffset, startPerc, 1.0f,
                             arrowHeadBasePoint, junkLocation);

   // End bar coordinates
   LocationType barStartPoint1;
   LocationType barStartPoint2;     // The points that make up the start bar-end (ll corner)
   LocationType barEndPoint1;
   LocationType barEndPoint2;       // The points that make up the end bar-end (ur corner)
   double barLength = 0;            // Bar-ends length
   barLength = (pixelSize == 0.0) ? 0.0 : (mBarEndLength * sqrtLineWidth) / pixelSize;
   DrawUtil::getPerpendicularLine(llCorner, urCorner, barLength, barStartPoint1, barStartPoint2);
   DrawUtil::getPerpendicularLine(urCorner, llCorner, barLength, barEndPoint1, barEndPoint2);

   // Calculate text info
   double textOffset = 0;     // Perpendicular offset from text to text anchor
   int maxTextureSize = 0;    // The max allowable texture size
   textOffset = (pixelSize == 0.0) ? 0.0 : (mTextOffset * sqrtLineWidth) / pixelSize;
   glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
   QFontMetrics ftMetrics(font);
  
   double viewRotation = pView->getRotation();
   viewRotation = GeoConversions::convertDegToRad(viewRotation);

   if (mDrawnDistanceUnit != pLayer->getDistanceUnits() ||
      mDrawnGeocoord != pLayer->getGeocoordType() ||
      mDrawnDmsFormat != pLayer->getGeoFormat())
   {
      refreshGeoInformation(); // only modifies cache stuff
   }

   if (pLayer->getDisplayEndPoints())
   {
      // Calculate start and end text info
      bool startLocDrawTop = false; // Whether to draw the start lat/lon text on the top of the specified point
      bool endLocDrawTop = true;    // Whether to draw the end lat/lon text on the top of the specified point
      if (urCorner.mY < llCorner.mY)
      {
         startLocDrawTop = true;
         endLocDrawTop = false;
      }

      // Calculate start and end location text info
      LocationType startLocPoint;   // The location to display the "start location" text
      LocationType endLocPoint;     // The location to display the "end location" text
      startLocPoint = llCorner;
      endLocPoint = urCorner;
      startLocPoint.mY += textOffset;
      endLocPoint.mY += textOffset;

      if (!mStartLocText.isEmpty())
      {
         DrawUtil::drawRotatedText(mStartLocTextTexture, mStartLocText, font,
            textColor, startLocPoint, viewRotation, startLocDrawTop);
      }
      if (!mEndLocText.isEmpty())
      {
         DrawUtil::drawRotatedText(mEndLocTextTexture, mEndLocText, font,
            textColor, endLocPoint, viewRotation, endLocDrawTop);
      }
   }
   
   if (pLayer->getDisplayBearing())
   {
      // Calculate bearing text info
      LocationType bearingTextStartPoint; // The location to display the bearing text
      LocationType bearingTextEndPoint;   // The pseudo end location of the baring text (only used to calculate angle)
      double bearingTextTheta = 0;        // Angle (in radians) of bearing text
      bool bearingDrawTop = false;        // The vertical origin to draw text from (True = top, False = bottom)
      QRect bearingTextBoundingBox;       // Bounding box surrounding the bearing text
      bearingTextBoundingBox = ftMetrics.boundingRect(0, 0, maxTextureSize, maxTextureSize, 
         Qt::AlignLeft | Qt::TextWordWrap, mBearingText);
      if (arrowEndPoint.mX < arrowStartPoint.mX)   // To the left of the origin (text underneath line)
      {
         startPerc = ((pixelSize == 0.0) || (arrowLength == 0.0)) ? 0.0 :
            1.0 - (bearingTextBoundingBox.width()/pixelSize)/arrowLength;
         startPerc = (startPerc < 0.0) ? 0.0 : startPerc;
         startPerc = (startPerc > 1.0) ? 1.0 : startPerc;
         DrawUtil::getParallelLine(arrowEndPoint, arrowStartPoint, (-1) * textOffset, startPerc, 1.0f,
            bearingTextStartPoint, bearingTextEndPoint);
         bearingDrawTop = true;
      } 
      else   // To the right of the origin (text on top of the line)
      {
         DrawUtil::getParallelLine(arrowStartPoint, arrowEndPoint, textOffset, 0.0f, 1.0f,
            bearingTextStartPoint, bearingTextEndPoint);
         bearingDrawTop = false;
      }
      bearingTextTheta = ((bearingTextEndPoint.mX - bearingTextStartPoint.mX) == 0.0) ? 0.0 :
         atan((bearingTextEndPoint.mY - bearingTextStartPoint.mY) /
         (bearingTextEndPoint.mX - bearingTextStartPoint.mX));

      if (!mBearingText.isEmpty())
      {
         DrawUtil::drawRotatedText(mBearingTextTexture, mBearingText, font,
            textColor, bearingTextStartPoint, bearingTextTheta, bearingDrawTop);
      }  
   }
   
   if (pLayer->getDisplayDistance())
   {
      // Calculate distance text info
      LocationType distanceTextStartPoint;   // The location to display the distance text
      LocationType distanceTextEndPoint;     // The pseudo end location of the distance text (only used to calculate
                                             // angle)
      double distanceTextTheta = 0;          // Angle (in radians) of distnace text
      bool distanceDrawTop = false;          // The vertical origin to draw text from (True = top, False = bottom)
      double distanceTextWidth = 0;          // The width of the ditance text bounding box (in screen pixels)
      QRect distanceTextBoundingBox;         // Bounding box that surrounds the distance text
      distanceTextBoundingBox = ftMetrics.boundingRect(0, 0, maxTextureSize, maxTextureSize, 
         Qt::AlignLeft | Qt::TextWordWrap, mDistanceText);
      distanceTextWidth = distanceTextBoundingBox.width();
      if ((pixelSize == 0.0) || (lineLength == 0.0))
      {
         startPerc = 0.0;
      } 
      else
      {
         if (urCorner.mX < llCorner.mX)
         {
            startPerc = .5 + (distanceTextWidth/pixelSize/2)/lineLength;
            distanceDrawTop = false;
         }
         else
         {
            startPerc = .5 - (distanceTextWidth/pixelSize/2)/lineLength;
            distanceDrawTop = true;
         }
      }
      startPerc = (startPerc < 0.0) ? 0.0 : startPerc;
      startPerc = (startPerc > 1.0) ? 1.0 : startPerc;
      DrawUtil::getParallelLine(llCorner, urCorner, (-1) * textOffset, startPerc, 1.0f, distanceTextStartPoint,
         distanceTextEndPoint);
      if (lineLength < (distanceTextBoundingBox.width()/pixelSize))
      {
         if (urCorner.mX < llCorner.mX)
         {
            DrawUtil::getParallelLine(llCorner, urCorner, (-1) * textOffset, 0.0f, 1.0f, distanceTextEndPoint,
               distanceTextStartPoint);
         } 
         else
         {
            DrawUtil::getParallelLine(llCorner, urCorner, (-1) * textOffset, 0.0f, 1.0f, distanceTextStartPoint,
               distanceTextEndPoint);
         }

      }
      distanceTextTheta = ((distanceTextEndPoint.mX - distanceTextStartPoint.mX) == 0.0) ? 0.0 :
         atan((distanceTextEndPoint.mY - distanceTextStartPoint.mY) /
         (distanceTextEndPoint.mX - distanceTextStartPoint.mX));

      if (!mDistanceText.isEmpty())
      {
         DrawUtil::drawRotatedText(mDistanceTextTexture, mDistanceText, font,
            textColor, distanceTextStartPoint, distanceTextTheta, distanceDrawTop);
      }
   }

   // GL options
   glLineWidth(lineWidth);
   #if defined(WIN_API)
      glEnable(GL_LINE_SMOOTH);
   #else
      if (lineWidth == 1.0)
      {
         glEnable(GL_LINE_SMOOTH);
      }
      else
      {
         glDisable(GL_LINE_SMOOTH);
      }
   #endif
   glEnable(GL_BLEND);
   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
   glColor3ub(lineColor.mRed, lineColor.mGreen, lineColor.mBlue);
   
   // Draw the end bar
   glBegin(GL_LINE_STRIP);
   glVertex2d(barEndPoint1.mX, barEndPoint1.mY);
   glVertex2d(barEndPoint2.mX, barEndPoint2.mY);
   glEnd();

   // Draw the start bar
   glBegin(GL_LINE_STRIP);
   glVertex2d(barStartPoint1.mX, barStartPoint1.mY);
   glVertex2d(barStartPoint2.mX, barStartPoint2.mY);
   glEnd();

   // Draw the arrow if bearing is displayed
   if (pLayer->getDisplayBearing())
   {
      glBegin(GL_LINE_STRIP);
      glVertex2d(arrowStartPoint.mX, arrowStartPoint.mY);
      glVertex2d(arrowEndPoint.mX, arrowEndPoint.mY);
      glVertex2d(arrowHeadBasePoint.mX, arrowHeadBasePoint.mY);
      glEnd();
   }

   // Set GL options to draw stippled line (Main line)
   glEnable(GL_LINE_STIPPLE);
   glLineStipple(3, 0xf0f0);
   glColor3ub(fillColor.mRed, fillColor.mGreen, fillColor.mBlue);

   // Draw the stippled line (on top of regular line)
   glBegin(GL_LINE_STRIP);
   glVertex2d(llCorner.mX, llCorner.mY);
   glVertex2d(urCorner.mX, urCorner.mY);
   glEnd();

   // Reset GL options
   glDisable(GL_BLEND);
   glDisable(GL_TEXTURE_2D);
   glDisable(GL_LINE_SMOOTH);
   glDisable(GL_LINE_STIPPLE);
   glLineWidth(1);
}
Example #18
0
bool MovieExporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   FileDescriptor* pFileDescriptor(NULL);
   string filename;
   View* pView(NULL);
   AnimationController* pController(NULL);
   FrameType eType;
   AVOutputFormat* pOutFormat(NULL);
   int resolutionX(-1);
   int resolutionY(-1);
   rational<int> framerate(0);
   unsigned int bitrate(0);
   double startExport(0.0);
   double stopExport(0.0);
   bool fullResolution(false);

   mpProgress = NULL;
   mpStep = StepResource("Export movie", "app", "2233BFC9-9C51-4e31-A8C5-2512925CBE6D");

   // get input arguments and log some useful info about them
   { // scope the MessageResource
      MessageResource pMsg("Input arguments", "app", "4551F478-E182-4b56-B88F-6682F0E3A2CF");

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

      pFileDescriptor = pInArgList->getPlugInArgValue<FileDescriptor>(Exporter::ExportDescriptorArg());
      if (pFileDescriptor == NULL)
      {
         log_error("No file specified");
         return false;
      }
      pMsg->addProperty("Destination", pFileDescriptor->getFilename());
      filename = pFileDescriptor->getFilename().getFullPathAndName();

      pView = pInArgList->getPlugInArgValue<View>(Exporter::ExportItemArg());
      if (pView == NULL)
      {
         log_error("No view specified");
         return false;
      }

      pController = pView->getAnimationController();
      if (pController == NULL)
      {
         log_error("No animation controller specified");
         return false;
      }
      pMsg->addProperty("Animation Controller Name", pController->getName());

      pOutFormat = getOutputFormat();
      if (pOutFormat == NULL)
      {
         log_error("Can't determine output format or format not supported.");
         return false;
      }
      pMsg->addProperty("Format", pOutFormat->long_name);

      bool resolutionFromInputArgs(false);
      if (!pInArgList->getPlugInArgValue("Resolution X", resolutionX) ||
         !pInArgList->getPlugInArgValue("Resolution Y", resolutionY))
      {
         if (mpOptionWidget.get() != NULL)
         {
            ViewResolutionWidget* pResolutionWidget = mpOptionWidget->getResolutionWidget();
            VERIFY(pResolutionWidget != NULL);

            switch(pResolutionWidget->getResolutionType())
            {
            case OptionsMovieExporter::VIEW_RESOLUTION:
               resolutionX = -1;
               resolutionY = -1;
               fullResolution = false;
               break;
            case OptionsMovieExporter::FULL_RESOLUTION:
               resolutionX = -1;
               resolutionY = -1;
               fullResolution = true;
               break;
            case OptionsMovieExporter::FIXED_RESOLUTION:
            {
               QSize resolution = pResolutionWidget->getResolution();
               resolutionX = resolution.width();
               resolutionY = resolution.height();
               fullResolution = false;
               break;
            }
            default:
               break; // nothing
            }
         }
         else
         {
            switch(StringUtilities::fromXmlString<OptionsMovieExporter::ResolutionType>(
               OptionsMovieExporter::getSettingResolutionType()))
            {
            case OptionsMovieExporter::VIEW_RESOLUTION:
               resolutionX = -1;
               resolutionY = -1;
               fullResolution = false;
               break;
            case OptionsMovieExporter::FULL_RESOLUTION:
               resolutionX = -1;
               resolutionY = -1;
               fullResolution = true;
               break;
            case OptionsMovieExporter::FIXED_RESOLUTION:
               resolutionX = OptionsMovieExporter::getSettingWidth();
               resolutionY = OptionsMovieExporter::getSettingHeight();
               fullResolution = false;
               break;
            default:
               break; // nothing
            }
         }
      }
      else
      {
         resolutionFromInputArgs = true;
      }

      if (resolutionX <= 0 || resolutionY <= 0)
      {
         QWidget* pWidget = pView->getWidget();
         if (pWidget != NULL)
         {
            resolutionX = pWidget->width();
            resolutionY = pWidget->height();
            resolutionFromInputArgs = false;
            if (fullResolution)
            {
               PerspectiveView* pPersp = dynamic_cast<PerspectiveView*>(pView);
               if (pPersp != NULL && pPersp->getZoomPercentage() > 100.)
               {
                  fullResolution = false;
                  if (mpProgress != NULL)
                  {
                     mpProgress->updateProgress("Full resolution export will be smaller than "
                        "view export, changing export resolution to current view size.", 0, WARNING);
                  }
               }
               else
               {
                  // translate to data coordinate
                  double x1 = 0.0;
                  double y1 = 0.0;
                  double x2 = 0.0;
                  double y2 = 0.0;
                  pView->translateScreenToWorld(0.0, 0.0, x1, y1);
                  pView->translateScreenToWorld(resolutionX, resolutionY, x2, y2);
                  resolutionX = (x2 > x1) ? (x2 - x1 + 0.5) : (x1 - x2 + 0.5);
                  resolutionY = (y2 > y1) ? (y2 - y1 + 0.5) : (y1 - y2 + 0.5);
               }
            }
         }
         else
         {
            log_error("Can't determine output resolution.");
            return false;
         }
      }

      int oldResX = resolutionX;
      int oldResY = resolutionY;
      if (!convertToValidResolution(resolutionX, resolutionY) ||
            (resolutionFromInputArgs && (resolutionX != oldResX || resolutionY != oldResY)))
      {
         stringstream msg;
         msg << "The export resolution does not meet the requirements of the the selected CODEC. "
                "The input arguments were X resolution of "
             << oldResX << " and Y resolution of " << oldResY << "."
             << "The adjusted resolution was (" << resolutionX << ", " << resolutionY << ")";
         log_error(msg.str());
         return false;
      }

      pMsg->addProperty("Resolution", QString("%1 x %2").arg(resolutionX).arg(resolutionY).toStdString());

      int framerateNum = 0;
      int framerateDen = 0;
      // first, get the framerate from the arg list
      // next, try the option widget
      // next, get from the animation controller
      if (pInArgList->getPlugInArgValue("Framerate Numerator", framerateNum) &&
         pInArgList->getPlugInArgValue("Framerate Denominator", framerateDen))
      {
         try
         {
            framerate.assign(framerateNum, framerateDen);
         }
         catch (const boost::bad_rational&)
         {
            // Do nothing; the code below handles this case
         }
      }
      if (framerate == 0)
      {
         if (mpOptionWidget.get() != NULL)
         {
            FramerateWidget* pFramerateWidget = mpOptionWidget->getFramerateWidget();
            VERIFY(pFramerateWidget != NULL);

            framerate = pFramerateWidget->getFramerate();
         }
         else
         {
            framerate = getFrameRate(pController);
         }
      }

      if (framerate == 0)
      {
         log_error("No framerate specified");
         return false;
      }

      // Validate the framerate
      boost::rational<int> validFrameRate = convertToValidFrameRate(framerate);
      if (validFrameRate != framerate)
      {
         QString msg = QString("The selected animation frame rate (%1/%2 fps) can not be represented in the "
                               "selected movie format. A frame rate of %3/%4 fps is being used instead.")
                              .arg(framerate.numerator())
                              .arg(framerate.denominator())
                              .arg(validFrameRate.numerator())
                              .arg(validFrameRate.denominator());
         mpProgress->updateProgress(msg.toStdString(), 0, WARNING);

         framerate = validFrameRate;
      }

      pMsg->addProperty("Framerate",
         QString("%1/%2").arg(framerate.numerator()).arg(framerate.denominator()).toStdString());

      if (!pInArgList->getPlugInArgValue("Bitrate", bitrate))
      {
         if (mpOptionWidget.get() != NULL)
         {
            BitrateWidget* pBitrateWidget = mpOptionWidget->getBitrateWidget();
            VERIFY(pBitrateWidget != NULL);

            bitrate = pBitrateWidget->getBitrate();
         }
         else
         {
            bitrate = OptionsMovieExporter::getSettingBitrate();
         }
      }
      pMsg->addProperty("Bitrate", QString::number(bitrate).toStdString());

      eType = pController->getFrameType();
      if (!pInArgList->getPlugInArgValue("Start Export", startExport))
      {
         if (mpOptionWidget.get() != NULL)
         {
            AnimationFrameSubsetWidget* pSubsetWidget = mpOptionWidget->getSubsetWidget();
            VERIFY(pSubsetWidget != NULL);

            startExport = pSubsetWidget->getStartFrame();
         }
         else
         {
            if (pController->getBumpersEnabled())
            {
               startExport = pController->getStartBumper();
            }
            else
            {
               startExport = pController->getStartFrame();
            }
         }
      }
      else
      {
         // adjust to 0-based since the input arg uses 1-based
         --startExport;
      }

      if (!pInArgList->getPlugInArgValue("Stop Export", stopExport))
      {
         if (mpOptionWidget.get() != NULL)
         {
            AnimationFrameSubsetWidget* pSubsetWidget = mpOptionWidget->getSubsetWidget();
            VERIFY(pSubsetWidget != NULL);

            stopExport = pSubsetWidget->getStopFrame();
         }
         else
         {
            if (pController->getBumpersEnabled())
            {
               stopExport = pController->getStopBumper();
            }
            else
            {
               stopExport = pController->getStopFrame();
            }
         }
      }
      else
      {
         // adjust to 0-based since the input arg users 1-based
         --stopExport;
      }
      string valueType("Time");
      if (eType == FRAME_ID)
      {
         valueType = "Frame";
      }

      pMsg->addProperty("Start "+valueType, QString::number(startExport).toStdString());
      pMsg->addProperty("Stop "+valueType, QString::number(stopExport).toStdString());
   }

   AvFormatContextResource pFormat(pOutFormat);
   VERIFY(pFormat != NULL);
   snprintf(pFormat->filename, sizeof(pFormat->filename), "%s", filename.c_str());
   AvStreamResource pVideoStream(pFormat, pOutFormat->video_codec);
   if (pVideoStream == NULL)
   {
      log_error("Unable to create video stream.");
      return false;
   }

   /**
    * allow changing of:
    *    dia_size/
    */
   AVCodecContext* pCodecContext = pVideoStream->codec;
   if (!setAvCodecOptions(pCodecContext))
   {
      log_error("Unable to initialize CODEC options");
      return false;
   }
   // set time_base, width, height, and bitrate here since
   // they can be passed in via the input args
   pCodecContext->width = resolutionX;
   pCodecContext->height = resolutionY;
   pCodecContext->bit_rate = bitrate * 1000;
   // the AVCodecContext wants a time_base which is
   // the inverse of fps.
   pCodecContext->time_base.num = framerate.denominator();
   pCodecContext->time_base.den = framerate.numerator();

   if (av_set_parameters(pFormat, NULL) < 0)
   {
      log_error("Invalid output format parameters.");
      return false;
   }
   if (!open_video(pFormat, pVideoStream))
   {
      log_error("Unable to initialize video stream.");
      return false;
   }
   if (url_fopen(&pFormat->pb, filename.c_str(), URL_WRONLY) < 0)
   {
      log_error("Could not open the output file. Ensure the destination directory is writable.");
      return false;
   }
   av_write_header(pFormat);

   // calculate time interval
   if ((framerate < getFrameRate(pController)) && (mpProgress != NULL))
   {
      mpProgress->updateProgress("The selected output frame rate may not encode all the frames in the movie.  "
                                 "Frames may be dropped.", 0, WARNING);
   }

   // do not use the boost::rational<int> overloaded operator '/' since it truncates type double to int
   double interval = pController->getIntervalMultiplier() * framerate.denominator() / framerate.numerator();

   // export the frames
   AVFrame* pTmpPicture = alloc_picture(PIX_FMT_RGBA32, pCodecContext->width, pCodecContext->height);
   if (pTmpPicture == NULL)
   {
      QString msg("Unable to allocate frame buffer of size %1 x %2");
      log_error(msg.arg(pCodecContext->width).arg(pCodecContext->height).toStdString());
      return false;
   }
   QImage image(pTmpPicture->data[0], pCodecContext->width, pCodecContext->height, QImage::Format_ARGB32);

   // For frame id based animation, each band of the data set fills one second of animation. 
   // If the requested frame rate for export is 15 fps, then each band is replicated 15 times. The execution
   // loop uses a pseudo time value, video_pts, to walk through the animation. The interval between 
   // exported frames is the inverse of the frame rate, e.g., for 15 fps the interval is 0.06667.
   // To fully export the last requested frame, we need to add just under an extra pseudo second to
   // the end time - stopExport. If we added a full extra second, we would export one video frame of the band past
   // the last requested frame - could cause crash if the last request frame was the last band.
   if (eType == FRAME_ID)
   {
      stopExport += 0.99;
   }

   bool drawClassMarkings = fullResolution &&
      Service<ConfigurationSettings>()->getSettingDisplayClassificationMarkings();
   QString classText;
   QFont classFont;
   QColor classColor;
   QPoint classPositionTop;
   QPoint classPositionBottom;
   const int shadowOffset = 2;
   if (drawClassMarkings)
   {
      const int topMargin = 1;
      const int bottomMargin = 4;
      const int leftMargin = 5;
      const int rightMargin = 5;

      classText = QString::fromStdString(pView->getClassificationText());
      classColor = COLORTYPE_TO_QCOLOR(pView->getClassificationColor());
      pView->getClassificationFont(classFont);
      QFontMetrics fontMetrics(classFont);
      int classWidth = fontMetrics.width(classText);
      int classHeight = fontMetrics.ascent();
      int topX((pCodecContext->width / 2) - (classWidth / 2) + shadowOffset);
      int bottomX((pCodecContext->width / 2) - (classWidth / 2));
      // determine the classification position
      switch (pView->getClassificationPosition())
      {
      case TOP_LEFT_BOTTOM_LEFT:
         topX = leftMargin + shadowOffset;
         bottomX = leftMargin + shadowOffset;
         break;
      case TOP_LEFT_BOTTOM_RIGHT:
         topX = leftMargin + shadowOffset;
         bottomX = pCodecContext->width - rightMargin - classWidth + shadowOffset;
         break;
      case TOP_RIGHT_BOTTOM_LEFT:
         topX = pCodecContext->width - rightMargin - classWidth + shadowOffset;
         bottomX = leftMargin + shadowOffset;
         break;
      case TOP_RIGHT_BOTTOM_RIGHT:
         topX = pCodecContext->width - rightMargin - classWidth + shadowOffset;
         bottomX = pCodecContext->width - rightMargin - classWidth + shadowOffset;
         break;
      default:
         // nothing to do, markings centered by default
         break;
      }
      int screenY = 1 + classHeight;
      classPositionTop = QPoint(topX, 1 + classHeight);
      classPositionBottom = QPoint(bottomX, pCodecContext->height - 1);
   }

   // make sure controller is not running prior to export. Save current state and restore after export finished
   AnimationState savedAnimationState = pController->getAnimationState();
   pController->setAnimationState(STOP);

   for (double video_pts = startExport; video_pts <= stopExport; video_pts += interval)
   {
      if (isAborted() == true)
      {
         // reset resources to close output file so it can be deleted
         pVideoStream = AvStreamResource();
         pFormat = AvFormatContextResource(NULL);
         mpPicture = NULL;
         free(mpVideoOutbuf);
         mpVideoOutbuf = NULL;
         remove(filename.c_str());

         if (mpProgress != NULL)
         {
            mpProgress->updateProgress("Export aborted", 0, ABORT);
         }
         pController->setAnimationState(savedAnimationState);
         mpStep->finalize(Message::Abort);
         return false;
      }

      // generate the next frame
      pController->setCurrentFrame(video_pts);
      if (mpProgress != NULL)
      {
         double progressValue = (video_pts - startExport) / (stopExport - startExport) * 100.0;
         mpProgress->updateProgress("Saving movie", static_cast<int>(progressValue), NORMAL);
      }
      if (fullResolution)
      {
         QSize totalSize(pCodecContext->width, pCodecContext->height);
         QSize subImageSize(pView->getWidget()->width(), pView->getWidget()->height());
         // Make sure that the sub-image and the main image have the same aspect ratio to
         // minimize wasted tile space
         if (pCodecContext->width > pCodecContext->height)
         {
            subImageSize.setWidth(
               totalSize.width() / static_cast<float>(totalSize.height()) * subImageSize.height() + 0.5);
         }
         else
         {
            subImageSize.setHeight(
               totalSize.height() / static_cast<float>(totalSize.width()) * subImageSize.width() + 0.5);
         }
         // Remove pan and zoom limits so they don't interfere with the subimage grab
         // and restore them when done
         SpatialDataView* pSdv = dynamic_cast<SpatialDataView*>(pView);
         PanLimitType panLimit;
         if (pSdv != NULL)
         {
            panLimit = pSdv->getPanLimit();
            pSdv->setPanLimit(NO_LIMIT);
         }
         View::SubImageIterator* pSubImage(pView->getSubImageIterator(totalSize, subImageSize));
         if (pSubImage == NULL)
         {
            if (pSdv != NULL)
            {
               pSdv->setPanLimit(panLimit);
            }
            if (mpProgress != NULL)
            {
               mpProgress->updateProgress("Unable to render full scale data", 0, ERRORS);
            }
            pController->setAnimationState(savedAnimationState);
            mpStep->finalize(Message::Failure);
            return false;
         }
         QPainter outPainter(&image);
         QPoint origin(0, image.height() - subImageSize.height());
         while (pSubImage->hasNext())
         {
            QImage subImage;
            if (!pSubImage->next(subImage))
            {
               if (pSdv != NULL)
               {
                  pSdv->setPanLimit(panLimit);
               }
               if (mpProgress != NULL)
               {
                  mpProgress->updateProgress("An error occurred when generating the image", 0, ERRORS);
               }
               pController->setAnimationState(savedAnimationState);
               mpStep->finalize(Message::Failure);
               delete pSubImage;
               return false;
            }
            // copy this subimage to the output buffer
            outPainter.drawImage(origin, subImage);

            int newX = origin.x() + subImage.width();
            int newY = origin.y();
            if (newX >= totalSize.width())
            {
               newY -= subImage.height();
               newX = 0;
            }
            origin = QPoint(newX, newY);
         }
         delete pSubImage;
         if (drawClassMarkings)
         {
            outPainter.setFont(classFont);
            outPainter.setPen(Qt::black);
            outPainter.drawText(classPositionTop, classText);
            outPainter.drawText(classPositionBottom, classText);
            outPainter.setPen(classColor);
            outPainter.drawText(classPositionTop - QPoint(shadowOffset, shadowOffset), classText);
            outPainter.drawText(classPositionBottom - QPoint(shadowOffset, shadowOffset), classText);
         }
         if (pSdv != NULL)
         {
            pSdv->setPanLimit(panLimit);
         }
      }
      else
      {
         pView->getCurrentImage(image);
      }
      img_convert(reinterpret_cast<AVPicture*>(mpPicture),
         pCodecContext->pix_fmt,
         reinterpret_cast<AVPicture*>(pTmpPicture),
         PIX_FMT_RGBA32,
         pCodecContext->width,
         pCodecContext->height);
      if (!write_video_frame(pFormat, pVideoStream))
      {
         // reset resources to close output file so it can be deleted
         pVideoStream = AvStreamResource();
         pFormat = AvFormatContextResource(NULL);
         mpPicture = NULL;
         free(mpVideoOutbuf);
         mpVideoOutbuf = NULL;
         remove(filename.c_str());
         string msg = "Can't write frame.";
         log_error(msg.c_str());
         pController->setAnimationState(savedAnimationState);
         return false;
      }
   }
   for (int frame = 0; frame < pCodecContext->delay; ++frame)
   {
      write_video_frame(pFormat, pVideoStream);
   }

   av_write_trailer(pFormat);

   if (mpProgress != NULL)
   {
      mpProgress->updateProgress("Finished saving movie", 100, NORMAL);
   }

   free(mpVideoOutbuf);
   mpVideoOutbuf = NULL;
   pController->setAnimationState(savedAnimationState);
   mpStep->finalize(Message::Success);
   return true;
}
bool Orthorectification::process(int type, RasterElement *pDSM, GRID DSMGrid, double Geoid_Offset, int DSM_resampling)
{
	StepResource pStep("Orthorectification Process", "app", "B4D426EC-E06D-11E1-83C8-42E56088709B");
	pStep->addStep("Start","app", "B4D426EC-E06D-11E1-83C8-42E56088709B");
	boxsize=0;

	res_type = type;

	if (res_type == 0) 
	{
		boxsize=0;	
	}
	else if (res_type == 1)
	{
		boxsize=1;		
	}
	else if (res_type == 2)
	{
		boxsize=2;		
	}
	else if (res_type == 3)
	{
		boxsize=3;	
	}

    ProgressResource pResource("ProgressBar");

	Progress *pProgress=pResource.get(); 

	pProgress->setSettingAutoClose(false);

	RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(Image->getDataDescriptor());
    
    FactoryResource<DataRequest> pRequest;
    DataAccessor pSrcAcc = Image->getDataAccessor(pRequest.release());

    RasterDataDescriptor* pDescDSM = static_cast<RasterDataDescriptor*>(pDSM->getDataDescriptor());

	FactoryResource<DataRequest> pRequestDSM;
    DataAccessor pDSMAcc = pDSM->getDataAccessor(pRequestDSM.release());

 
	unsigned int N_Row = int(OrthoGrid.Y_Dim)+1;
	unsigned int N_Col = int(OrthoGrid.X_Dim)+1;

	// Check name of raster element //
	Service<ModelServices> pModel;
    vector<string> mCubeNames = pModel->getElementNames("RasterElement");

	int NameIndex = 0, control=0;
	stringstream out;
	string OutputName=Image->getName();
	string OutputName1 = OutputName.substr(0,OutputName.find_last_of("."));

	while (control == 0)
	{
		control = 1;
		OutputName = OutputName1+"_ortho_";

		out << NameIndex;
		OutputName.append(out.str()+".tiff");		
		
		for (unsigned int k=0; k<mCubeNames.size(); k++)
		{
		if (OutputName.compare(mCubeNames[k]) == 0) control = 0;
		}

		NameIndex++;
		out.str("");
		out.clear();

	}

	// Create output raster element and assoiciated descriptor and accessor //
	
	ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(OutputName,N_Row ,N_Col, FLT4BYTES));

	RasterDataDescriptor* pResultDesc = static_cast<RasterDataDescriptor*> (pResultCube->getDataDescriptor());

    FactoryResource<DataRequest> pResultRequest;
    pResultRequest->setWritable(true);
    DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());

    double NodeLat, NodeLon, H_IJ=0;
	//int DSM_I, DSM_J;

    for (unsigned int row = 0; row < N_Row; ++row)
    {
	  if (pProgress != NULL)
	  {
      pProgress->updateProgress("Calculating result", row * 100 / N_Row, NORMAL);
	  }

      if (!pDestAcc.isValid())
      {
         std::string msg = "Unable to access the cube data.";
         pProgress->updateProgress(msg, 0, ERRORS);
		 pStep->finalize(Message::Failure, msg);
         return false;
      }

      for (unsigned int col = 0; col < N_Col; ++col)
      {

		  NodeLat = OrthoGrid.Lat_Min+row*OrthoGrid.Lat_Step;
		  NodeLon = OrthoGrid.Lon_Min+col*OrthoGrid.Lon_Step;

		  // RETRIEVE HEIGHT VALUE FROM DSM 

		  if (DSM_resampling == 0) 
		  {
		  int DSM_I = int((NodeLon - DSMGrid.Lon_Min)/DSMGrid.Lon_Step);
		  int DSM_J = pDescDSM->getRowCount() - int((NodeLat - DSMGrid.Lat_Min)/DSMGrid.Lat_Step);		  
          pDSMAcc->toPixel(DSM_J,DSM_I);
	      VERIFY(pDSMAcc.isValid());
          H_IJ = (pDSMAcc->getColumnAsDouble());
		  }
		  else
		  {
		  double DSM_I = ((NodeLon - DSMGrid.Lon_Min)/DSMGrid.Lon_Step);
		  double DSM_J = pDescDSM->getRowCount() - ((NodeLat - DSMGrid.Lat_Min)/DSMGrid.Lat_Step);
		  H_IJ = bilinear_height(pDSMAcc,DSM_I,DSM_J);
		  }

		  P_COORD NodeImage = Model->SAR_GroundToImage(NodeLon,NodeLat,H_IJ+Geoid_Offset);

		  if ((NodeImage.I>1 && NodeImage.I< Model->Metadata.Width-1) && (NodeImage.J>1 && NodeImage.J< Model->Metadata.Height-1))
		  {
			switchOnEncoding(pResultDesc->getDataType(), copypixel3, pDestAcc->getColumn(), pSrcAcc, int(NodeImage.I), int(NodeImage.J),boxsize, H_IJ);		
		  }		  
		  pDestAcc->nextColumn();
      }

      pDestAcc->nextRow();
    }

   Service<DesktopServices> pDesktop;

   Service<ModelServices> pMod;

   GcpList* GcpL = static_cast<GcpList*>(pMod->createElement("corner coordinate","GcpList",pResultCube.get()));
   
   // Update GCPs Information: to account for Opticks reading gcp lat&lon values the opposite way around, 
   // here it is necessary to switch the value to assign lat to gcp.mCoordinate.mX  and lon to gcp.mCoordinate.mY 

   GcpPoint Punto;

   Punto.mCoordinate.mX = OrthoGrid.Lat_Min;
   Punto.mCoordinate.mY = OrthoGrid.Lon_Min;
   Punto.mCoordinate.mZ = 0.0;
   Punto.mPixel.mX = 0.0;
   Punto.mPixel.mY = 0.0;

   GcpL->addPoint(Punto);

   Punto.mCoordinate.mX = OrthoGrid.Lat_Max;
   Punto.mCoordinate.mY = OrthoGrid.Lon_Min;
   Punto.mCoordinate.mZ = 0.0;
   Punto.mPixel.mX = 0.0;
   Punto.mPixel.mY = OrthoGrid.Y_Dim;
   
   GcpL->addPoint(Punto);

   Punto.mCoordinate.mX = OrthoGrid.Lat_Min;
   Punto.mCoordinate.mY = OrthoGrid.Lon_Max;
   Punto.mCoordinate.mZ = 0.0;
   Punto.mPixel.mX = OrthoGrid.X_Dim;
   Punto.mPixel.mY = 0.0;
   
   GcpL->addPoint(Punto);

   Punto.mCoordinate.mX = OrthoGrid.Lat_Max;
   Punto.mCoordinate.mY = OrthoGrid.Lon_Max;
   Punto.mCoordinate.mZ = 0.0;
   Punto.mPixel.mX = OrthoGrid.X_Dim;
   Punto.mPixel.mY = OrthoGrid.Y_Dim;
   
   GcpL->addPoint(Punto); 

   SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(),
         SPATIAL_DATA_WINDOW));
 
   SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();  

   pView->setPrimaryRasterElement(pResultCube.get());

   pView->createLayer(RASTER, pResultCube.get());
   
   pView->createLayer(GCP_LAYER,GcpL,"GCP");

   pView->setDataOrigin(LOWER_LEFT);

   pResultCube.release();

   pProgress->updateProgress("Orthorectification is complete.", 100, NORMAL);
   pStep->addStep("End","app", "B4D426EC-E06D-11E1-83C8-42E56088709B");
   pStep->finalize();

   return true;
   
}
bool adaptive_median::execute(PlugInArgList * pInArgList,
							  PlugInArgList * pOutArgList)
{
	StepResource pStep("adap_median", "noise",
					   "5EA0CC75-9E0B-4c3d-BA23-6DB7157BBD55");
	if (pInArgList == NULL || pOutArgList == NULL)
	{
		return false;
	}

	std::string msg = "Noise Reduction by Adaptive Median Filter ";
	Progress *pProgress =
		pInArgList->getPlugInArgValue < Progress > (Executable::ProgressArg());
	RasterElement *pCube =
		pInArgList->getPlugInArgValue < RasterElement >
		(Executable::DataElementArg());

	if (pCube == 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);
	if (pDesc->getDataType() == INT4SCOMPLEX
		|| pDesc->getDataType() == FLT8COMPLEX)
	{
		std::string msg =
			"Noise Reduction cannot be performed on complex types.";
		pStep->finalize(Message::Failure, msg);
		if (pProgress != NULL)
		{
			pProgress->updateProgress(msg, 0, ERRORS);
		}
		return false;
	}

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

	RasterElement *dRas =
		RasterUtilities::createRasterElement(pCube->getName() +
											 "Noise_reduction_Median_filter",
											 pDesc->getRowCount(),
											 pDesc->getColumnCount(), 3,
											 pDesc->getDataType(), BSQ);

	pProgress->updateProgress(msg, 50, NORMAL);

	copyImage4(pCube, dRas, 0, pProgress);
	pProgress->updateProgress(msg + "RED complete", 60, NORMAL);

	copyImage4(pCube, dRas, 1, pProgress);
	pProgress->updateProgress(msg + "GREEN complete", 70, NORMAL);

	copyImage4(pCube, dRas, 2, pProgress);
	pProgress->updateProgress(msg + "BLUE complete", 80, NORMAL);

	// new model resource
	RasterDataDescriptor *rDesc =
		dynamic_cast < RasterDataDescriptor * >(dRas->getDataDescriptor());
	rDesc->setDisplayMode(RGB_MODE);	// enable color mode
	rDesc->setDisplayBand(RED, rDesc->getActiveBand(0));
	rDesc->setDisplayBand(GREEN, rDesc->getActiveBand(1));
	rDesc->setDisplayBand(BLUE, rDesc->getActiveBand(2));

	ModelResource < RasterElement > pResultCube(dRas);

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

	pProgress->updateProgress("Final", 100, NORMAL);

	pProgress->updateProgress(msg, 100, NORMAL);

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

	if (pProgress != NULL)
	{
		pProgress->updateProgress("adaptive_median is compete.", 100, NORMAL);
	}

	pOutArgList->setPlugInArgValue("adaptive_median_Result", pResultCube.release());	// saving 
																						// data

	pStep->finalize();
	return true;
}
Example #21
0
string TextObjectImp::getSubstitutedText()
{
   string txt = getText();

   DataElement* pParent = getElement();
   pParent = (pParent == NULL) ? NULL : pParent->getParent();
   DataDescriptor* pParentDesc = (pParent == NULL) ? NULL : pParent->getDataDescriptor();
   DynamicObject* pParentMetadata = (pParentDesc == NULL) ? NULL : pParentDesc->getMetadata();
   for (int i = 0; i < 50; ++i)
   {
      //each pass does replacement of $M(a) currently in the string.
      //do 50 passes to perform sub-expansion at most fifty times, ie. prevent infinite loop
      //for non-terminating recursive expansion
      string::size_type pos = txt.find("$");
      while (pos != string::npos)
      {
         if (pos + 1 >= txt.size())
         {
            break;
         }
         string type = txt.substr(pos+1, 1);
         if (type != "$") //ie. not $$, the escape sequence so continue
         {
            bool replaced = false;
            if (pos+4 < txt.size()) //ie. $M(a)
            {
               if (txt[pos+2] == '(')
               {
                  string::size_type closeParen = txt.find(')', pos+2);
                  if (closeParen == string::npos)
                  {
                     closeParen = txt.size();
                  }
                  string variableName = txt.substr(pos+3, closeParen-(pos+2)-1);
                  string replacementString;
                  if (type == "M" || type == "S")
                  {
                     DataElement* pElmnt = pParent;
                     DynamicObject* pMetadata = pParentMetadata;
                     if (variableName.substr(0, 2) == "//")
                     {
                        string::size_type endNamePos = variableName.find("//", 2);
                        if (endNamePos != string::npos)
                        {
                           string elementName = variableName.substr(2, endNamePos - 2);
                           variableName = variableName.substr(endNamePos + 2);
                           if (!variableName.empty())
                           {
                              if (elementName[0] == '[' && elementName[elementName.size() - 1] == ']')
                              {
                                 elementName = elementName.substr(1, elementName.size() - 2);
                                 std::list<GraphicObject*> objects;
                                 getLayer()->getObjects(VIEW_OBJECT, objects);
                                 for (std::list<GraphicObject*>::iterator object = objects.begin();
                                    object != objects.end(); ++object)
                                 {
                                    GraphicObject* pObj = *object;
                                    if (pObj->getName() == elementName)
                                    {
                                       SpatialDataView* pSdv = dynamic_cast<SpatialDataView*>(pObj->getObjectView());
                                       if (pSdv != NULL)
                                       {
                                          pElmnt = pSdv->getLayerList()->getPrimaryRasterElement();
                                          DataDescriptor* pDesc =
                                             (pElmnt == NULL) ? NULL : pElmnt->getDataDescriptor();
                                          pMetadata = (pDesc == NULL) ? NULL : pDesc->getMetadata();
                                       }
                                       break;
                                    }
                                 }
                              }
                              else
                              {
                                 pElmnt = Service<ModelServices>()->getElement(elementName,
                                    TypeConverter::toString<RasterElement>(), NULL);
                                 DataDescriptor* pDesc = (pElmnt == NULL) ? NULL : pElmnt->getDataDescriptor();
                                 pMetadata = (pDesc == NULL) ? NULL : pDesc->getMetadata();
                              }
                           }
                           else
                           {
                              pElmnt = NULL;
                              pMetadata = NULL;
                           }
                        }
                     }
                     bool success = false;
                     if (type == "M" && pMetadata != NULL)
                     {
                        DataVariant var = pMetadata->getAttributeByPath(variableName);
                        if (var.isValid())
                        {
                           DataVariant::Status status;
                           replacementString = var.toDisplayString(&status);
                           success = (status == DataVariant::SUCCESS);
                           if (mMetadataObjects.find(pMetadata) == mMetadataObjects.end())
                           {
                              mMetadataObjects.insert(make_pair(pMetadata, new AttachmentPtr<DynamicObject>(
                                 pMetadata, SIGNAL_NAME(Subject, Modified),
                                 Slot(this, &TextObjectImp::invalidateTexture))));
                           }
                        }
                     }
                     else if (type == "S" && pElmnt != NULL && variableName == "CLASSIFICATION")
                     {
                        Classification* pClass = pElmnt->getDataDescriptor()->getClassification();
                        pClass->getClassificationText(replacementString);
                        success = true;
                        if (mClassificationObjects.find(pClass) == mClassificationObjects.end())
                        {
                           mClassificationObjects.insert(make_pair(pClass, new AttachmentPtr<Classification>(
                              pClass, SIGNAL_NAME(Subject, Modified),
                              Slot(this, &TextObjectImp::invalidateTexture))));
                        }
                     }
                     if (!success)
                     {
                        replacementString = "Error!";
                     }
                     replaced = true;
                  }
                  if (replaced)
                  {
                     txt.replace(pos, closeParen-pos+1, replacementString);
                     pos = txt.find("$", pos+replacementString.size());
                  }
               }
            }
            if (!replaced)
            {
               pos = txt.find("$", pos+1);
            }
         }
         else
         {
            pos = txt.find("$", pos+2);
         }
      }
   }
   string::size_type pos = txt.find("$$");
   while (pos != string::npos)
   {
      txt.replace(pos, 2, "$");
      pos = txt.find("$$");
   }

   return txt;
}
bool TextureSegmentation::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("SAR image segmentation", "app", "CC430C1A-9D8C-4bb5-9254-FCF7EECAFA3C");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == 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 = INT1UBYTE;


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

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Segmentation_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;
   }
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());

   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 (NULL != pBuffer)
   {
	   free(pBuffer);
   }
   pBuffer = (float *)malloc(sizeof(float)*pDesc->getRowCount()*pDesc->getColumnCount());
  
   MakeSegmentation(pSrcAcc, pBuffer, pBuffer, pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType());

   //Output the value 
   unsigned int nCount = 0;
   for (unsigned int j = 0; j < pDesc->getColumnCount(); j++)
   {
       for (unsigned int i = 0; i < pDesc->getRowCount(); i++)		   
	   {		   
		   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;              
		   }
			   
		   pDestAcc->toPixel(i, j);		   
		   switchOnEncoding(ResultType, restoreSegmentationValue, pDestAcc->getColumn(), (pBuffer+nCount));
		   nCount++;
	   }
   }

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

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Image segmentation is compete.", 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("Image segmentation result", pResultCube.release());

   pStep->finalize();
   return true;
}
Example #23
0
ChippingWindow::ChippingWindow(SpatialDataView* pView, QWidget* parent) :
   QDialog(parent),
   mpView(pView),
   mpChippingWidget(NULL),
   mpWindowRadio(NULL),
   mpFileRadio(NULL)
{
   // View widget
   SpatialDataView* pChipView = createChipView();
   pChipView->getWidget()->installEventFilter(this);
   mpChippingWidget = new ChippingWidget(pChipView, NULL, this);
   mpChippingWidget->setExportMode(true);

   // Chip mode
   QGroupBox* pModeGroup = new QGroupBox("Chipping Mode", this);
   mpWindowRadio = new QRadioButton("Create new window", pModeGroup);
   mpFileRadio = new QRadioButton("Export to file", pModeGroup);

   // Horizontal line
   QFrame* pHLine = new QFrame(this);
   pHLine->setFrameStyle(QFrame::HLine | QFrame::Sunken);

   // Buttons
   QPushButton* pOkButton = new QPushButton("&OK", this);
   QPushButton* pCancelButton = new QPushButton("&Cancel", this);

   // Layout
   QVBoxLayout* pModeLayout = new QVBoxLayout(pModeGroup);
   pModeLayout->setMargin(10);
   pModeLayout->setSpacing(5);
   pModeLayout->addWidget(mpWindowRadio);
   pModeLayout->addWidget(mpFileRadio);

   QHBoxLayout* pButtonLayout = new QHBoxLayout();
   pButtonLayout->setMargin(0);
   pButtonLayout->setSpacing(5);
   pButtonLayout->addStretch(10);
   pButtonLayout->addWidget(pOkButton);
   pButtonLayout->addWidget(pCancelButton);

   QVBoxLayout* pLayout = new QVBoxLayout(this);
   pLayout->setMargin(10);
   pLayout->setSpacing(10);
   pLayout->addWidget(mpChippingWidget, 10);
   pLayout->addWidget(pModeGroup, 0, Qt::AlignLeft);
   pLayout->addWidget(pHLine);
   pLayout->addLayout(pButtonLayout);

   // Initialization
   setModal(true);
   resize(400, 200);
   mpWindowRadio->setChecked(true);

   // Set the window icon
   setWindowIcon(QIcon(":/icon/ChipImage"));

   // Set the caption of the dialog
   QString strCaption = "Create Image Chip";
   if (mpView != NULL)
   {
      string viewName = mpView->getName();
      if (viewName.empty() == false)
      {
         QFileInfo fileInfo(QString::fromStdString(viewName));
         QString strFilename = fileInfo.fileName();
         if (strFilename.isEmpty() == false)
         {
            strCaption += ": " + strFilename;
         }
      }
   }

   setWindowTitle(strCaption);

   // Connections
   connect(pOkButton, SIGNAL(clicked()), this, SLOT(accept()));
   connect(pCancelButton, SIGNAL(clicked()), this, SLOT(reject()));
}
Example #24
0
bool RasterTimingTest::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   if (isBatch())
   {
      VERIFY(pOutArgList != NULL);
   }
   Service<DesktopServices> pDesktop;
   SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pDesktop->getCurrentWorkspaceWindowView());
   if (pView)
   {
      UndoLock lock(pView);

      RasterElement* pElement = pView->getLayerList()->getPrimaryRasterElement();
      RasterDataDescriptor* pDesc = dynamic_cast<RasterDataDescriptor*>(pElement->getDataDescriptor());
      int bands = pDesc->getBandCount();
      int frameNumber = 0;
      RasterLayer* pLayer = NULL;
      vector<Layer*> layers;
      pView->getLayerList()->getLayers(RASTER, layers);
      for (vector<Layer*>::iterator iter = layers.begin(); iter != layers.end(); ++iter)
      {
         RasterLayer* pRasterLayer = static_cast<RasterLayer*>(*iter);
         if (pRasterLayer != NULL)
         {
            RasterElement* pCurrentRasterElement = dynamic_cast<RasterElement*>(pRasterLayer->getDataElement());
            if (pCurrentRasterElement == pElement)
            {
               pLayer = pRasterLayer;
               break;
            }
         }
      }
      for (int i = 0; i < bands; ++i)
      {
         pElement->getStatistics(pDesc->getActiveBand(i))->getMin();
      }
      // set grayscale display mode
      DisplayMode initialDisplayMode = pLayer->getDisplayMode();
      pLayer->setDisplayMode(GRAYSCALE_MODE);
      const int frameiterations = 10000;
      clock_t startTime = clock();
      QWidget* pWidget = pView->getWidget();
      int i = 0;
      for (i = 0; i < frameiterations; ++i, ++frameNumber)
      {
         if (frameNumber >= bands)
         {
            frameNumber = 0;
         }

         pLayer->setDisplayedBand(GRAY, pDesc->getActiveBand(frameNumber));
         if (pWidget)
         {
            pWidget->repaint();
         }

         if ((i + 1) % (frameiterations / 100) == 0)
         {
            QString message = QString("Frame ") + QString::number(i+1) + QString(" of ") +
               QString::number(frameiterations);
            pDesktop->setStatusBarMessage(message.toStdString());
         }
         if ((i + 1) % 20 == 0)
         {
            clock_t stopTime = clock();
            double elapsedTime = static_cast<double>(stopTime - startTime) / CLOCKS_PER_SEC;
            if (elapsedTime > 30)
            {
               ++i;
               break;
            }
         }
      }
      clock_t stopTime = clock();
      double framesPerSec = i / (static_cast<double>(stopTime - startTime) / CLOCKS_PER_SEC);

      // restore display mode
      pLayer->setDisplayMode(initialDisplayMode);

      if (isBatch())
      {
         pOutArgList->setPlugInArgValue<double>("Framerate", &framesPerSec);
      }
      else
      {
         QMessageBox::information(pDesktop->getMainWidget(), "Frame Rate", 
            QString("The number of frames per second was: %1\nGPU Acceleration was%2 enabled\n").arg(framesPerSec)
                     .arg(pLayer->isGpuImageEnabled() ? "" : " not"));
      }

      return true;
   }

   return false;
}
Example #25
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;
}
Example #26
0
bool EdgeDetector::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Edge Detector", "app", "37C57772-DD49-4532-8BC6-9CFB8587D0C9");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == 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 = INT1UBYTE;

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

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Edge_Detect_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;
   }
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());

   Service<DesktopServices> pDesktop;
   EdgeRatioThresholdDlg dlg(pDesktop->getMainWidget(), SMALL_WINDOW_THRESHOLD, MEDIAN_WINDOW_THRESHOLD, LARGE_WINDOW_THRESHOLD);
   int stat = dlg.exec();
   if (stat == QDialog::Accepted)
   {
      for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("Edge detect ", 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;
         }
         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;
         }
         for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
         {
            switchOnEncoding(ResultType, EdgeDetectSAR, pDestAcc->getColumn(), pSrcAcc, row, col,
                             pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), 
			                 dlg.getSmallThreshold(), dlg.getMedianThreshold(), dlg.getLargeThreshold());
            pDestAcc->nextColumn();
         }

         pDestAcc->nextRow();
      }

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

      if (pProgress != NULL)
      {
         pProgress->updateProgress("Edge detect compete.", 100, NORMAL);
      }

      pOutArgList->setPlugInArgValue("Edge detect result", pResultCube.release());

      pStep->finalize();
   }
   return true;
}
/**
 * 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;
}
bool bilinear_bayer::execute(PlugInArgList * pInArgList,
							 PlugInArgList * pOutArgList)
{


	StepResource pStep("bilinear_bayer", "pratik",
					   "27170298-10CE-4E6C-AD7A-97E8058C29FF");
	if (pInArgList == NULL || pOutArgList == NULL)
	{
		return false;
	}

	Progress *pProgress =
		pInArgList->getPlugInArgValue < Progress > (Executable::ProgressArg());

	RasterElement *pCube = pInArgList->getPlugInArgValue < RasterElement > (Executable::DataElementArg());	// pCube

	if (pCube == 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;
	}

	pProgress->updateProgress("Starting calculations", 10, NORMAL);
	RasterDataDescriptor *pDesc =
		static_cast < RasterDataDescriptor * >(pCube->getDataDescriptor());
	VERIFY(pDesc != NULL);


	std::string msg = "De-bayerize by bilinear interpolation \n";
	pProgress->updateProgress(msg, 20, NORMAL);	// show initial R,G and B
												// values

	RasterElement *dRas =
		RasterUtilities::createRasterElement(pCube->getName() + "RGB",
											 pDesc->getRowCount(),
											 pDesc->getColumnCount(), 3,
											 pDesc->getDataType(), BSQ);

	// request

	pProgress->updateProgress(msg, 50, NORMAL);

	copyImage(pCube, dRas, 0, pProgress);
	pProgress->updateProgress(msg + "RED complete", 60, NORMAL);

	copyImage(pCube, dRas, 1, pProgress);
	pProgress->updateProgress(msg + "GREEN complete", 70, NORMAL);

	copyImage(pCube, dRas, 2, pProgress);
	pProgress->updateProgress(msg + "BLUE complete", 80, NORMAL);



	// new model resource
	RasterDataDescriptor *rDesc =
		dynamic_cast < RasterDataDescriptor * >(dRas->getDataDescriptor());
	rDesc->setDisplayMode(RGB_MODE);	// enable color mode
	rDesc->setDisplayBand(RED, rDesc->getActiveBand(0));
	rDesc->setDisplayBand(GREEN, rDesc->getActiveBand(1));
	rDesc->setDisplayBand(BLUE, rDesc->getActiveBand(2));
	ModelResource < RasterElement > pResultCube(dRas);


	pProgress->updateProgress("Final", 100, NORMAL);

	// create window

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

	}
	pOutArgList->setPlugInArgValue("bilinear_bayer_Result", pResultCube.release());	// for 
																					// saving 
																					// data

	pStep->finalize();
	return true;
}
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;
}
bool SampleGeoref::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
    // Do any kind of setup we need before converting coordinates.
    // In this case, get our X and Y factors.

    StepResource pStep("Run Sample Georef", "app", "CFCB8AA9-D504-42e9-86F0-547DF9B4798A");
    Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());

    FAIL_IF(!isBatch(), "Interactive mode is not supported.", return false);

    // Default values
    bool animated = false;

    // get factors from pInArgList
    pInArgList->getPlugInArgValue("XSize", mXSize);
    pInArgList->getPlugInArgValue("YSize", mYSize);
    pInArgList->getPlugInArgValue("Extrapolate", mExtrapolate);
    pInArgList->getPlugInArgValue("Animated", animated);
    pInArgList->getPlugInArgValue("Rotate", mRotate);

    View* pView = pInArgList->getPlugInArgValue<View>(Executable::ViewArg());
    mpRaster = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
    FAIL_IF(mpRaster == NULL, "Could not find raster element", return false);

    if (mpGui != NULL)
    {
        mXSize = mpGui->getXSize();
        mYSize = mpGui->getYSize();
        animated = mpGui->getAnimated();
        mRotate = mpGui->getRotate();
        mExtrapolate = mpGui->getExtrapolate();
    }

    if (animated)
    {
        SpatialDataView* pSpatialView = dynamic_cast<SpatialDataView*>(pView);
        FAIL_IF(pSpatialView == NULL, "Could not find spatial data view.", return false);

        LayerList* pLayerList = pSpatialView->getLayerList();
        FAIL_IF(pLayerList == NULL, "Could not find layer list.", return false);

        RasterLayer* pLayer = dynamic_cast<RasterLayer*>(pLayerList->getLayer(RASTER, mpRaster));
        FAIL_IF(pLayer == NULL, "Could not find raster layer", return false);

        Animation* pAnim = pLayer->getAnimation();
        FAIL_IF(pAnim == NULL, "Could not find animation", return false);

        const std::vector<AnimationFrame>& frames = pAnim->getFrames();
        FAIL_IF(frames.empty(), "No frames in animation.", return false);

        mpAnimation.reset(pAnim);
        mFrames = frames.size();
        mCurrentFrame = 0;
    }

    RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(mpRaster->getDataDescriptor());
    FAIL_IF(pDescriptor == NULL, "Could not get data descriptor.", return false);

    unsigned int rows = pDescriptor->getRowCount();
    unsigned int cols = pDescriptor->getColumnCount();
    unsigned int bands = pDescriptor->getBandCount();

    mXScale = static_cast<double>(mXSize) / rows;
    mYScale = static_cast<double>(mYSize) / cols;

    mpRaster->setGeoreferencePlugin(this);

    mpGui = NULL; // Pointer not guaranteed to be valid after execute() is called
    return true;
}