<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {ROISpot5.png}, {ROISpot5Moving.png}
//    OUTPUTS: {SIFTResampling.png}
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// This example demonstrates the use of the
// \doxygen{otb}{KeyPointSetsMatchingFilter} for disparity map
// estimation. The idea here is to match SIFTs extracted from both the
// fixed and the moving images. The use of SIFTs is demonstrated in
// section \ref{sec:SIFTDetector}. The
// \doxygen{itk}{DeformationFieldSource} will be used
// to generate a deformation field by using
// interpolation on the deformation values from the point set. More
// advanced methods for deformation field interpolation are also
// available.
//
// The first step toward the use of these filters is to include the
// appropriate header files.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

#include "otbKeyPointSetsMatchingFilter.h"
//#include "otbSiftFastImageFilter.h"
#include "otbImageToSIFTKeyPointSetFilter.h"

// Disabling deprecation warning if on visual
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4996)
#endif
#include "itkDeformationFieldSource.h"
// Enabling remaining deprecation warning
#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "itkWarpImageFilter.h"

// Software Guide : EndCodeSnippet

#include "otbImage.h"
#include "otbMacro.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkPointSet.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbLeastSquareAffineTransformEstimator.h"
#include "itkResampleImageFilter.h"

int main (int argc, char* argv[])
{
  if (argc!= 9)
  {
    std::cerr <<"Usage: "<<argv[0];
    std::cerr<<"fixedFileName movingFileName resamplingImageFileName octaves scales threshold ratio secondOrderThreshold" << std::endl;
    return EXIT_FAILURE;
  }

  const char * fixedfname = argv[1];
  const char * movingfname = argv[2];
  const char * outputImageFilename = argv[3];

  const unsigned int octaves = atoi(argv[4]);
  const unsigned int scales = atoi(argv[5]);
  float threshold = atof(argv[6]);
  float ratio = atof(argv[7]);
  const double secondOrderThreshold = atof(argv[8]);

  const unsigned int Dimension = 2;

  // Software Guide : BeginLatex
  //
  // Then we must decide what pixel type to use for the image. We choose to do
  // all the computations in floating point precision and rescale the results
  // between 0 and 255 in order to export PNG images.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef double        RealType;
  typedef unsigned char OutputPixelType;

  typedef otb::Image<RealType,Dimension> ImageType;
  typedef otb::Image<OutputPixelType,Dimension> OutputImageType;

  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // The SIFTs obtained for the matching will be stored in vector
  // form inside a point set. So we need the following types:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef itk::VariableLengthVector<RealType> RealVectorType;
  typedef itk::PointSet<RealVectorType,Dimension> PointSetType;

  // Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // The filter for computing the SIFTs has a type defined as follows:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  //typedef otb::SiftFastImageFilter<ImageType,PointSetType>
  //ImageToSIFTKeyPointSetFilterType;
  typedef otb::ImageToSIFTKeyPointSetFilter<ImageType,PointSetType>
  ImageToSIFTKeyPointSetFilterType;

  // Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // Although many choices for evaluating the distances during the
  // matching procedure exist, we choose here to use a simple
  // Euclidean distance. We can then define the type for the matching filter.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef itk::Statistics::EuclideanDistance<RealVectorType> DistanceType;
  typedef otb::KeyPointSetsMatchingFilter<PointSetType, DistanceType>
  EuclideanDistanceMatchingFilterType;
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // The following types are needed for dealing with the matched points.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef PointSetType::PointType PointType;
  typedef std::pair<PointType,PointType> MatchType;
  typedef std::vector<MatchType> MatchVectorType;
  typedef EuclideanDistanceMatchingFilterType::LandmarkListType
  LandmarkListType;

  typedef PointSetType::PointsContainer PointsContainerType;
  typedef PointsContainerType::Iterator PointsIteratorType;
  typedef PointSetType::PointDataContainer PointDataContainerType;
  typedef PointDataContainerType::Iterator PointDataIteratorType;

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We define the type for the image reader.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef otb::ImageFileReader<ImageType> ReaderType;

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Two readers are instantiated : one for the fixed image, and one
  // for the moving image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  ReaderType::Pointer fixedReader = ReaderType::New();
  ReaderType::Pointer movingReader = ReaderType::New();

  fixedReader->SetFileName(fixedfname);
  movingReader->SetFileName(movingfname);
  fixedReader->UpdateOutputInformation();
  movingReader->UpdateOutputInformation();

  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We will now instantiate the 2 SIFT filters and the filter used
  // for the matching of the points.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  ImageToSIFTKeyPointSetFilterType::Pointer filter1 =
    ImageToSIFTKeyPointSetFilterType::New();
  ImageToSIFTKeyPointSetFilterType::Pointer filter2 =
    ImageToSIFTKeyPointSetFilterType::New();
  EuclideanDistanceMatchingFilterType::Pointer euclideanMatcher =
    EuclideanDistanceMatchingFilterType::New();

  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We plug the pipeline and set the parameters.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  bool useBackMatching = 0;

  filter1->SetInput( fixedReader->GetOutput() );
  //filter1->SetScalesNumber(3);
  filter2->SetInput( movingReader->GetOutput() );
  //filter2->SetScalesNumber(3);

  // Software Guide : BeginCodeSnippet
  filter1->SetOctavesNumber(octaves);
  filter1->SetScalesNumber(scales);

  filter1->SetDoGThreshold(threshold);
  filter1->SetEdgeThreshold(ratio);

  filter2->SetOctavesNumber(octaves);
  filter2->SetScalesNumber(scales);

  filter2->SetDoGThreshold(threshold);
  filter2->SetEdgeThreshold(ratio);
// Software Guide : EndCodeSnippet

  std::cout << "SIFT process fixed image" << std::endl;
  filter1->Update();
  std::cout << "SIFT process moving image" << std::endl;
  filter2->Update();

  //filter1->SetNumberOfThreads(1);
  //filter2->SetNumberOfThreads(1);

  //Take the minimum point set to compute euclidian diff (vector lengths must be equal)
  PointSetType::Pointer ptSet1 = filter1->GetOutput();
  PointSetType::Pointer ptSet2 = filter2->GetOutput();

  typedef PointSetType::PointsContainer PointsContainer;
  PointsContainer::Pointer              ptContainer1,ptContainer2;

  //Save point container to extract 2 points container with size = min (container1, container2)
  //TODO simplify subset selection in this itk::PointSet
  ptContainer1 = ptSet1->GetPoints();
  ptContainer2 = ptSet2->GetPoints();
  if ( ptSet1->GetNumberOfPoints() > ptSet2->GetNumberOfPoints() )
  {
 	ptContainer1 = ptSet2->GetPoints();
  	ptContainer2 = ptSet1->GetPoints();
  }

  PointsContainer::Pointer ptContainerRes =   PointsContainer::New();
  typedef PointsContainer::Iterator           PointsIterator;
  PointsIterator     pointsIterator =         ptContainer2->Begin();

  //Construct new point container (subset of input pointset)
  for (unsigned int id=0;id < ptContainer1->Size();++id)
  {
  	ptContainerRes->InsertElement(id, pointsIterator->Value());
	++pointsIterator;
  }

  if ( ptSet1->GetNumberOfPoints() > ptSet2->GetNumberOfPoints() )
  {
        ptSet1->SetPoints(ptContainerRes);
  }
  else
  {
  	ptSet2->SetPoints(ptContainerRes);
  }

  std::cout << "SIFT points size" << std::endl;
  std::cout << ptSet1->GetNumberOfPoints() << std::endl;
  std::cout << ptSet2->GetNumberOfPoints() << std::endl;

  //euclideanMatcher->SetInput1(ptSet1);
  //euclideanMatcher->SetInput2(ptSet2);
  euclideanMatcher->SetInput1(filter1->GetOutput());
  euclideanMatcher->SetInput2(filter2->GetOutput());

  euclideanMatcher->SetDistanceThreshold(secondOrderThreshold);
  euclideanMatcher->SetUseBackMatching(useBackMatching);
  std::cout << "Update euclidian distance" << std::endl;
  euclideanMatcher->Update();

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The matched points will be stored into a landmark list.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  LandmarkListType::Pointer landmarkList;
  landmarkList = euclideanMatcher->GetOutput();
  std::cout << "Get landmark" << std::endl;
  // Software Guide : EndCodeSnippet

 // Software Guide : BeginLatex
  //
  // Apply Mean square algorithm
  //
  // Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
  typedef itk::Point<double,2>                                 MyPointType;
  typedef otb::LeastSquareAffineTransformEstimator<MyPointType> EstimatorType;

  // instantiation
  EstimatorType::Pointer estimator = EstimatorType::New();
  std::cout << "landmark list size " << landmarkList->Size() << std::endl;
  for (LandmarkListType::Iterator it = landmarkList->Begin();
     it != landmarkList->End(); ++it)
  {
        //otbMsgDevMacro(<<"landmark1" << it.Get()->GetPoint1() );
        //otbMsgDevMacro(<<"landmark2" << it.Get()->GetPoint2() );
        std::cout << "landmark1" << it.Get()->GetPoint1() << std::endl;
        std::cout << "landmark2" << it.Get()->GetPoint2() << std::endl;
        estimator->AddTiePoints(it.Get()->GetPoint1(),it.Get()->GetPoint2());
  }

  // Trigger computation
  estimator->Compute();
  // meanSquarestimator->SetInput(euclideanMatcher->GetOutput());
// Software Guide : EndCodeSnippet

 // Software Guide : BeginLatex
  //
  // Resample the initial image with the transformation evaluated
  //
  // Software Guide : EndLatex
//  Software Guide : BeginLatex
  //
  //  It is common, as the last step of a registration task, to use
  //  the resulting transform to map the moving image into the fixed
  //  image space.  This is easily done with the
  //  \doxygen{itk}{ResampleImageFilter}. First, a ResampleImageFilter
  //  type is instantiated using the image types. It is convenient to
  //  use the fixed image type as the output type since it is likely
  //  that the transformed moving image will be compared with the
  //  fixed image.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::ResampleImageFilter<
  ImageType,
  OutputImageType >    ResampleFilterType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  A resampling filter is created and the moving image is connected as
  //  its input.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  ResampleFilterType::Pointer resampler = ResampleFilterType::New();
  resampler->SetInput( movingReader->GetOutput() );

  //typedef itk::ImageRegistrationMethod<
  //ImageType,
  //ImageType >    RegistrationType;

  //RegistrationType::Pointer   registration  = RegistrationType::New();

  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The Transform that is produced as output need to be inversed to
  //  We apply here the resampling algorithm to the "fixed" image
  // to produce the moving image. Or apply to the moving image
  //
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  // Get the output transform
  typedef EstimatorType::AffineTransformType AffineTransformType;
  AffineTransformType::Pointer transform = AffineTransformType::New();
  transform->GetInverse( estimator->GetAffineTransform() );

  resampler->SetTransform( transform );
  resampler->SetSize( fixedReader->GetOutput()->GetLargestPossibleRegion().GetSize() );
  resampler->SetOutputOrigin( fixedReader->GetOutput()->GetOrigin() );
  resampler->SetOutputSpacing( fixedReader->GetOutput()->GetSpacing() );
  resampler->SetDefaultPixelValue( 100 );

  // Software Guide : EndCodeSnippet

  typedef otb::ImageFileWriter< OutputImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();

  writer->SetInput( resampler->GetOutput() );
  writer->SetFileName( outputImageFilename );
  writer->Update();

  return EXIT_SUCCESS;
}

<commit_msg>DOC:sift example<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {ROISpot5.png}, {ROISpot5Moving.png}
//    OUTPUTS: {SIFTResampling.png}
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// This example demonstrates the use of the
// \doxygen{otb}{KeyPointSetsMatchingFilter} for transformation
// estimation between 2 images. The idea here is to match SIFTs extracted from both the
// fixed and the moving images. The use of SIFTs is demonstrated in
// section \ref{sec:SIFTDetector}. The
// \doxygen{otb}{LeastSquareAffineTransformEstimator} will be used
// to generate a transformation field by using
// mean square optimisation to estimate
// an affine transfrom from the point set.
//
// The first step toward the use of these filters is to include the
// appropriate header files.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

#include "otbKeyPointSetsMatchingFilter.h"
#include "otbImageToSIFTKeyPointSetFilter.h"

// Disabling deprecation warning if on visual
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4996)
#endif
#include "itkDeformationFieldSource.h"
// Enabling remaining deprecation warning
#ifdef _MSC_VER
#pragma warning(pop)
#endif

// Software Guide : EndCodeSnippet

#include "otbImage.h"
#include "otbMacro.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkPointSet.h"
#include "otbLeastSquareAffineTransformEstimator.h"
#include "itkResampleImageFilter.h"

int main (int argc, char* argv[])
{
  if (argc!= 9)
  {
    std::cerr <<"Usage: "<<argv[0];
    std::cerr<<"fixedFileName movingFileName resamplingImageFileName octaves scales threshold ratio secondOrderThreshold" << std::endl;
    return EXIT_FAILURE;
  }

  const char * fixedfname = argv[1];
  const char * movingfname = argv[2];
  const char * outputImageFilename = argv[3];

  const unsigned int octaves = atoi(argv[4]);
  const unsigned int scales = atoi(argv[5]);
  float threshold = atof(argv[6]);
  float ratio = atof(argv[7]);
  const double secondOrderThreshold = atof(argv[8]);

  const unsigned int Dimension = 2;

  // Software Guide : BeginLatex
  //
  // Then we must decide what pixel type to use for the image. We choose to do
  // all the computations in floating point precision and rescale the results
  // between 0 and 255 in order to export PNG images.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef double        RealType;
  typedef unsigned char OutputPixelType;

  typedef otb::Image<RealType,Dimension> ImageType;
  typedef otb::Image<OutputPixelType,Dimension> OutputImageType;

  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // The SIFTs obtained for the matching will be stored in vector
  // form inside a point set. So we need the following types:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef itk::VariableLengthVector<RealType> RealVectorType;
  typedef itk::PointSet<RealVectorType,Dimension> PointSetType;

  // Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // The filter for computing the SIFTs has a type defined as follows:
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  //typedef otb::SiftFastImageFilter<ImageType,PointSetType>
  //ImageToSIFTKeyPointSetFilterType;
  typedef otb::ImageToSIFTKeyPointSetFilter<ImageType,PointSetType>
  ImageToSIFTKeyPointSetFilterType;

  // Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // Although many choices for evaluating the distances during the
  // matching procedure exist, we choose here to use a simple
  // Euclidean distance. We can then define the type for the matching filter.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef itk::Statistics::EuclideanDistance<RealVectorType> DistanceType;
  typedef otb::KeyPointSetsMatchingFilter<PointSetType, DistanceType>
  EuclideanDistanceMatchingFilterType;
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // The following types are needed for dealing with the matched points.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef PointSetType::PointType PointType;
  typedef std::pair<PointType,PointType> MatchType;
  typedef std::vector<MatchType> MatchVectorType;
  typedef EuclideanDistanceMatchingFilterType::LandmarkListType
  LandmarkListType;

  typedef PointSetType::PointsContainer PointsContainerType;
  typedef PointsContainerType::Iterator PointsIteratorType;
  typedef PointSetType::PointDataContainer PointDataContainerType;
  typedef PointDataContainerType::Iterator PointDataIteratorType;

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We define the type for the image reader.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef otb::ImageFileReader<ImageType> ReaderType;

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Two readers are instantiated : one for the fixed image, and one
  // for the moving image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  ReaderType::Pointer fixedReader = ReaderType::New();
  ReaderType::Pointer movingReader = ReaderType::New();

  fixedReader->SetFileName(fixedfname);
  movingReader->SetFileName(movingfname);
  fixedReader->UpdateOutputInformation();
  movingReader->UpdateOutputInformation();

  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We will now instantiate the 2 SIFT filters and the filter used
  // for the matching of the points.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  ImageToSIFTKeyPointSetFilterType::Pointer filter1 =
    ImageToSIFTKeyPointSetFilterType::New();
  ImageToSIFTKeyPointSetFilterType::Pointer filter2 =
    ImageToSIFTKeyPointSetFilterType::New();
  EuclideanDistanceMatchingFilterType::Pointer euclideanMatcher =
    EuclideanDistanceMatchingFilterType::New();

  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We plug the pipeline and set the parameters.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  filter1->SetInput( fixedReader->GetOutput() );
  filter2->SetInput( movingReader->GetOutput() );

  filter1->SetOctavesNumber(octaves);
  filter1->SetScalesNumber(scales);

  filter1->SetDoGThreshold(threshold);
  filter1->SetEdgeThreshold(ratio);

  filter2->SetOctavesNumber(octaves);
  filter2->SetScalesNumber(scales);

  filter2->SetDoGThreshold(threshold);
  filter2->SetEdgeThreshold(ratio);
// Software Guide : EndCodeSnippet

  std::cout << "SIFT process fixed image" << std::endl;
  filter1->Update();
  std::cout << "SIFT process moving image" << std::endl;
  filter2->Update();

  //filter1->SetNumberOfThreads(1);
  //filter2->SetNumberOfThreads(1);

  //Take the minimum point set to compute euclidian diff (vector lengths must be equal)
  PointSetType::Pointer ptSet1 = filter1->GetOutput();
  PointSetType::Pointer ptSet2 = filter2->GetOutput();

  typedef PointSetType::PointsContainer PointsContainer;
  PointsContainer::Pointer              ptContainer1,ptContainer2;

  //Save point container to extract 2 points container with size = min (container1, container2)
  //TODO simplify subset selection in this itk::PointSet
  ptContainer1 = ptSet1->GetPoints();
  ptContainer2 = ptSet2->GetPoints();
  if ( ptSet1->GetNumberOfPoints() > ptSet2->GetNumberOfPoints() )
  {
 	ptContainer1 = ptSet2->GetPoints();
  	ptContainer2 = ptSet1->GetPoints();
  }

  PointsContainer::Pointer ptContainerRes =   PointsContainer::New();
  typedef PointsContainer::Iterator           PointsIterator;
  PointsIterator     pointsIterator =         ptContainer2->Begin();

  //Construct new point container (subset of input pointset)
  for (unsigned int id=0;id < ptContainer1->Size();++id)
  {
  	ptContainerRes->InsertElement(id, pointsIterator->Value());
	++pointsIterator;
  }

  if ( ptSet1->GetNumberOfPoints() > ptSet2->GetNumberOfPoints() )
  {
        ptSet1->SetPoints(ptContainerRes);
  }
  else
  {
  	ptSet2->SetPoints(ptContainerRes);
  }

  std::cout << "SIFT points size" << std::endl;
  std::cout << ptSet1->GetNumberOfPoints() << std::endl;
  std::cout << ptSet2->GetNumberOfPoints() << std::endl;

  // Software Guide : BeginLatex
  //
  // We use a simple Euclidean distance to select
  // matched points.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  //TODO use SIFT filters outputs or subset of pointset???
  //euclideanMatcher->SetInput1(ptSet1);
  //euclideanMatcher->SetInput2(ptSet2);
  euclideanMatcher->SetInput1(filter1->GetOutput());
  euclideanMatcher->SetInput2(filter2->GetOutput());

  bool useBackMatching = 0;

  euclideanMatcher->SetDistanceThreshold(secondOrderThreshold);
  euclideanMatcher->SetUseBackMatching(useBackMatching);
  std::cout << "Update euclidian distance" << std::endl;
  euclideanMatcher->Update();

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The matched points will be stored into a landmark list.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  LandmarkListType::Pointer landmarkList;
  landmarkList = euclideanMatcher->GetOutput();
  std::cout << "Get landmarkList" << std::endl;
  // Software Guide : EndCodeSnippet

 // Software Guide : BeginLatex
  //
  // Apply Mean square algorithm
  //
  // Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
  typedef itk::Point<double,2>                                 MyPointType;
  typedef otb::LeastSquareAffineTransformEstimator<MyPointType> EstimatorType;

  // instantiation
  EstimatorType::Pointer estimator = EstimatorType::New();
  std::cout << "landmark list size " << landmarkList->Size() << std::endl;
  for (LandmarkListType::Iterator it = landmarkList->Begin();
     it != landmarkList->End(); ++it)
  {
        std::cout << "landmark1" << it.Get()->GetPoint1() << std::endl;
        std::cout << "landmark2" << it.Get()->GetPoint2() << std::endl;
        estimator->AddTiePoints(it.Get()->GetPoint1(),it.Get()->GetPoint2());
  }

  // Trigger computation
  estimator->Compute();
  // meanSquarestimator->SetInput(euclideanMatcher->GetOutput());
// Software Guide : EndCodeSnippet

 // Software Guide : BeginLatex
  //
  // Resample the initial image with the transformation evaluated
  //
  // Software Guide : EndLatex
//  Software Guide : BeginLatex
  //
  //  It is common, as the last step of a registration task, to use
  //  the resulting transform to map the moving image into the fixed
  //  image space.  This is easily done with the
  //  \doxygen{itk}{ResampleImageFilter}. First, a ResampleImageFilter
  //  type is instantiated using the image types. It is convenient to
  //  use the fixed image type as the output type since it is likely
  //  that the transformed moving image will be compared with the
  //  fixed image.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::ResampleImageFilter<
  ImageType,
  OutputImageType >    ResampleFilterType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  A resampling filter is created and the moving image is connected as
  //  its input.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  ResampleFilterType::Pointer resampler = ResampleFilterType::New();
  resampler->SetInput( movingReader->GetOutput() );

  //typedef itk::ImageRegistrationMethod<
  //ImageType,
  //ImageType >    RegistrationType;

  //RegistrationType::Pointer   registration  = RegistrationType::New();

  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The Transform that is produced as output need to be inversed to
  //  We apply here the resampling algorithm to the "fixed" image
  // to produce the moving image. Or apply to the moving image
  //
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  // Get the output transform
  typedef EstimatorType::AffineTransformType AffineTransformType;
  AffineTransformType::Pointer transform = AffineTransformType::New();
  transform->GetInverse( estimator->GetAffineTransform() );

  resampler->SetTransform( transform );
  resampler->SetSize( fixedReader->GetOutput()->GetLargestPossibleRegion().GetSize() );
  resampler->SetOutputOrigin( fixedReader->GetOutput()->GetOrigin() );
  resampler->SetOutputSpacing( fixedReader->GetOutput()->GetSpacing() );
  resampler->SetDefaultPixelValue( 100 );

  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Write resampled image
  //
  //  Software Guide : EndLatex
  typedef otb::ImageFileWriter< OutputImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();

  writer->SetInput( resampler->GetOutput() );
  writer->SetFileName( outputImageFilename );
  writer->Update();

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>// $Id: patch_recovery_error_estimator.C,v 1.2 2004-06-02 20:55:17 jwpeterson Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2004  Benjamin S. Kirk, John W. Peterson

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes
#include <algorithm> // for std::fill
#include <math.h>    // for sqrt

// Local Includes
#include "libmesh_common.h"
#include "patch_recovery_error_estimator.h"
#include "dof_map.h"
#include "fe.h"
#include "dense_matrix.h"
#include "dense_vector.h"
#include "quadrature_gauss.h"
#include "libmesh_logging.h"

//-----------------------------------------------------------------
// ErrorEstimator implementations
void PatchRecoveryErrorEstimator::estimate_error (const SteadySystem& system,
						  std::vector<float>& error_per_cell)
{
  START_LOG("estimate_error()", "PatchRecoveryErrorEstimator");

  // The current mesh
  const Mesh& mesh = system.get_mesh();

  // The dimensionality of the mesh
  const unsigned int dim = mesh.mesh_dimension();

  // The number of variables in the system
  const unsigned int n_vars = system.n_vars();

  // The DofMap for this system
  const DofMap& dof_map = system.get_dof_map();

  // Resize the error_per_cell vector to be
  // the number of elements, initialize it to 0.
  error_per_cell.resize (mesh.n_elem());
  std::fill (error_per_cell.begin(), error_per_cell.end(), 0.);

  // Check for a valid component_mask
  if (!component_mask.empty())
    if (component_mask.size() != n_vars)
      {
	std::cerr << "ERROR: component_mask is the wrong size:"
		  << std::endl
		  << " component_mask.size()=" << component_mask.size()
		  << std::endl
		  << ", n_vars=" << n_vars
		  << std::endl;
	error();
      }

  //------------------------------------------------------------
  // Iterate over all the active elements in the mesh
  // that live on this processor.
  const_active_local_elem_iterator       elem_it (mesh.elements_begin());
  const const_active_local_elem_iterator elem_end(mesh.elements_end());

  for (; elem_it != elem_end; ++elem_it)
    {
      // elem is necessarily an active element on the local processor
      const Elem* elem = *elem_it;

      // Build a patch containing the current element
      // and its neighbors on the local processor
      std::set<const Elem*> patch;

      this->build_patch_from_local_neighbors (elem, patch);

      //------------------------------------------------------------
      // Process each variable in the system using the current patch
      for (unsigned int var=0; var<n_vars; var++)
	{
	  // Possibly skip this variable
	  if (!component_mask.empty())
	    if (component_mask[var] == false) continue;

	  // The type of finite element to use for this variable
	  const FEType& fe_type = dof_map.variable_type (var);

	  // Finite element object for use in this patch
	  AutoPtr<FEBase> fe (FEBase::build (dim, fe_type));

	  // Build an appropriate Gaussian quadrature rule
	  QGauss qrule (dim, fe_type.default_quadrature_order());

	  // Tell the finite element about the quadrature rule.
	  fe->attach_quadrature_rule (&qrule);

	  // Get Jacobian values, etc..
	  const std::vector<Real>&                       JxW     = fe->get_JxW();
	  const std::vector<Point>&                      q_point = fe->get_xyz();
	  const std::vector<std::vector<Real> >&         phi     = fe->get_phi();
	  const std::vector<std::vector<RealGradient> >& dphi    = fe->get_dphi();

	  // global DOF indices
	  std::vector<unsigned int> dof_indices;

	  // Dense matrix and vectors for patch projection.
	  // THE SIZES OF THESE NEED TO GET SMARTER!
	  DenseMatrix<Number> Kp(dim+1,dim+1);
	  DenseVector<Number>
	    Fx(dim+1), Pu_x_h(dim+1),
	    Fy(dim+1), Pu_y_h(dim+1),
	    Fz(dim+1), Pu_z_h(dim+1);

	  //------------------------------------------------------
	  // Loop over each element in the patch and compute their
	  // contribution to the patch gradient projection.
	  std::set<const Elem*>::const_iterator        patch_it  = patch.begin();
	  const std::set<const Elem*>::const_iterator  patch_end = patch.end();

	  for (; patch_it != patch_end; ++patch_it)
	    {
	      // The pth element in the patch
	      const Elem* e_p = *patch_it;

	      // Reinitialize the finite element data for this element
	      fe->reinit (e_p);

	      // Get the global DOF indices for the current variable
	      // in the current element
	      dof_map.dof_indices (e_p, dof_indices, var);

	      // Huh? Something is horribly WRONG!
	      assert (dof_indices.size() == phi.size());

	      const unsigned int n_dofs = dof_indices.size();
	      const unsigned int n_qp   = qrule.n_points();

	      // Compute the projection components from this cell.
	      // \int_{Omega_e} \psi_i \psi_j = \int_{Omega_e} du_h/dx_k \psi_i
	      for (unsigned int qp=0; qp<n_qp; qp++)
		{
		  // The x,y,z location of the current quadrature point
		  const Real
		    x = q_point[qp](0),
		    y = q_point[qp](1),
		    z = q_point[qp](2);

		  // Compute the gradient on the current patch element
		  // at the quadrature point
		  Gradient grad_u_h;

		  for (unsigned int i=0; i<n_dofs; i++)
		    grad_u_h += dphi[i][qp]*system.current_solution(dof_indices[i]);

		  // Construct the shape function values for the patch projection
		  std::vector<Real> psi;
		  {
		    psi.reserve (dim+1);

		    psi.push_back(1);
		    psi.push_back(x);
		    psi.push_back(y);

		    if (dim == 3)
		      psi.push_back(z);
		  }

		  // Patch matrix contribution
		  for (unsigned int i=0; i<Kp.m(); i++)
		    for (unsigned int j=0; j<Kp.n(); j++)
		      Kp(i,j) += JxW[qp]*psi[i]*psi[j];

		  // Patch RHS contributions
		  for (unsigned int i=0; i<psi.size(); i++)
		    {
		      Fx(i) += JxW[qp]*grad_u_h(0)*psi[i];
		      Fy(i) += JxW[qp]*grad_u_h(1)*psi[i];
		      Fz(i) += JxW[qp]*grad_u_h(2)*psi[i];
		    }

		} // end quadrature loop
	    } // end patch loop

	  //--------------------------------------------------
	  // Now we have fully assembled the projection system
	  // for this patch.  Project the gradient components.
	  // MAY NEED TO USE PARTIAL PIVOTING!
	  Kp.lu_solve (Fx, Pu_x_h);
	  Kp.lu_solve (Fy, Pu_y_h);
	  Kp.lu_solve (Fz, Pu_z_h);

	  //--------------------------------------------------
	  // Finally, estimate the error in the current variable
	  // for the current element by computing ||Pgrad_u_h - grad_u_h||
	  error();

	} // end variable loop
    } // end element loop

  // Each processor has now computed the error contribuions
  // for its local elements.  We need to sum the vector
  this->reduce_error(error_per_cell);

  STOP_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
}

void PatchRecoveryErrorEstimator::build_patch_from_local_neighbors (const Elem* e0,
								    std::set<const Elem*> patch,
								    const unsigned int target_patch_size)
{
  START_LOG("build_patch_from_local_neighbors()", "PatchRecoveryErrorEstimator");

  // Make sure we are building a patch for an active, local element.
  // (Are these restrictions necessary?)
  assert (e0 != NULL);
  assert (e0->processor_id() == libMesh::processor_id());
  assert (e0->active());

  // First add the element of interest.
  patch.insert (e0);

  // Repeatedly add the neighbors of the elements in the patch until
  // the target patch size is met
  while (patch.size() < target_patch_size)
    {
      // It is possible that the target patch size is larger than the number
      // of active elements in the mesh.  Since we don't have access to the
      // Mesh object here the only way we can detect this case is by detecting
      // a "stagnant patch," i.e. a patch whose size does not increase after adding
      // face neighbors
      const unsigned int old_patch_size = patch.size();

      // Loop over all the elements in the patch
      std::set<const Elem*>::const_iterator       it  = patch.begin();
      const std::set<const Elem*>::const_iterator end = patch.end();

      for (; (it != end) && (patch.size() < target_patch_size); ++it)
	{
	  // Convenience.  Keep the syntax simple.
	  const Elem* elem = *it;

	  for (unsigned int s=0; s<elem->n_sides(); s++)
	    if (elem->neighbor(s) != NULL)        // we have a neighbor on this side
	      {
		const Elem* neighbor = elem->neighbor(s);

		if (neighbor->active())           // ... and that neighbor is active
		  if (neighbor->processor_id() ==
		      libMesh::processor_id())    // ... and belongs to this processor
		    patch.insert (neighbor);      // ... then add it to the patch

		else                              // ... the neighbor is *not* active,
		  {                               // ... so add *all* its active, local children to the patch
		    std::vector<const Elem*> active_children;

		    neighbor->active_family_tree (active_children);

		    for (unsigned int c=0; c<active_children.size(); c++)
		      if (active_children[c]->processor_id() == libMesh::processor_id())
			patch.insert (active_children[c]);
		  }
	      }
	}

      // Check for a "stagnant" patch
      if (patch.size() == old_patch_size)
	{
	  std::cerr << "ERROR: stagnant patch of "
		    << patch.size() << " elements."
		    << std::endl
		    << "Does your target patch size exceed the number of elements?"
		    << std::endl;
	  here();
	  break;
	}
    } // end while loop

  // make sure all the elements in the patch are active and local
  // if we are in debug mode
#ifdef DEBUG
  {
    std::set<const Elem*>::const_iterator       it  = patch.begin();
    const std::set<const Elem*>::const_iterator end = patch.end();

    for (; it != end; ++it)
      {
	// Convenience.  Keep the syntax simple.
	const Elem* elem = *it;

	assert (elem->active());
	assert (elem->processor_id() == libMesh::processor_id());
      }
  }
#endif

  STOP_LOG("build_patch_from_local_neighbors()", "PatchRecoveryErrorEstimator");
}
<commit_msg>changes for complex.<commit_after>// $Id: patch_recovery_error_estimator.C,v 1.3 2004-06-08 14:45:50 spetersen Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2004  Benjamin S. Kirk, John W. Peterson

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes
#include <algorithm> // for std::fill
#include <math.h>    // for sqrt

// Local Includes
#include "libmesh_common.h"
#include "patch_recovery_error_estimator.h"
#include "dof_map.h"
#include "fe.h"
#include "dense_matrix.h"
#include "dense_vector.h"
#include "quadrature_gauss.h"
#include "libmesh_logging.h"

//-----------------------------------------------------------------
// ErrorEstimator implementations
void PatchRecoveryErrorEstimator::estimate_error (const SteadySystem& system,
						  std::vector<float>& error_per_cell)
{
  START_LOG("estimate_error()", "PatchRecoveryErrorEstimator");

  // The current mesh
  const Mesh& mesh = system.get_mesh();

  // The dimensionality of the mesh
  const unsigned int dim = mesh.mesh_dimension();

  // The number of variables in the system
  const unsigned int n_vars = system.n_vars();

  // The DofMap for this system
  const DofMap& dof_map = system.get_dof_map();

  // Resize the error_per_cell vector to be
  // the number of elements, initialize it to 0.
  error_per_cell.resize (mesh.n_elem());
  std::fill (error_per_cell.begin(), error_per_cell.end(), 0.);

  // Check for a valid component_mask
  if (!component_mask.empty())
    if (component_mask.size() != n_vars)
      {
	std::cerr << "ERROR: component_mask is the wrong size:"
		  << std::endl
		  << " component_mask.size()=" << component_mask.size()
		  << std::endl
		  << ", n_vars=" << n_vars
		  << std::endl;
	error();
      }

  //------------------------------------------------------------
  // Iterate over all the active elements in the mesh
  // that live on this processor.
  const_active_local_elem_iterator       elem_it (mesh.elements_begin());
  const const_active_local_elem_iterator elem_end(mesh.elements_end());

  for (; elem_it != elem_end; ++elem_it)
    {
      // elem is necessarily an active element on the local processor
      const Elem* elem = *elem_it;

      // Build a patch containing the current element
      // and its neighbors on the local processor
      std::set<const Elem*> patch;

      this->build_patch_from_local_neighbors (elem, patch);

      //------------------------------------------------------------
      // Process each variable in the system using the current patch
      for (unsigned int var=0; var<n_vars; var++)
	{
	  // Possibly skip this variable
	  if (!component_mask.empty())
	    if (component_mask[var] == false) continue;

	  // The type of finite element to use for this variable
	  const FEType& fe_type = dof_map.variable_type (var);

	  // Finite element object for use in this patch
	  AutoPtr<FEBase> fe (FEBase::build (dim, fe_type));

	  // Build an appropriate Gaussian quadrature rule
	  QGauss qrule (dim, fe_type.default_quadrature_order());

	  // Tell the finite element about the quadrature rule.
	  fe->attach_quadrature_rule (&qrule);

	  // Get Jacobian values, etc..
	  const std::vector<Real>&                       JxW     = fe->get_JxW();
	  const std::vector<Point>&                      q_point = fe->get_xyz();
	  const std::vector<std::vector<Real> >&         phi     = fe->get_phi();
	  const std::vector<std::vector<RealGradient> >& dphi    = fe->get_dphi();

	  // global DOF indices
	  std::vector<unsigned int> dof_indices;

	  // Dense matrix and vectors for patch projection.
	  // THE SIZES OF THESE NEED TO GET SMARTER!
	  DenseMatrix<Number> Kp(dim+1,dim+1);
	  DenseVector<Number>
	    Fx(dim+1), Pu_x_h(dim+1),
	    Fy(dim+1), Pu_y_h(dim+1),
	    Fz(dim+1), Pu_z_h(dim+1);

	  //------------------------------------------------------
	  // Loop over each element in the patch and compute their
	  // contribution to the patch gradient projection.
	  std::set<const Elem*>::const_iterator        patch_it  = patch.begin();
	  const std::set<const Elem*>::const_iterator  patch_end = patch.end();

	  for (; patch_it != patch_end; ++patch_it)
	    {
	      // The pth element in the patch
	      const Elem* e_p = *patch_it;

	      // Reinitialize the finite element data for this element
	      fe->reinit (e_p);

	      // Get the global DOF indices for the current variable
	      // in the current element
	      dof_map.dof_indices (e_p, dof_indices, var);

	      // Huh? Something is horribly WRONG!
	      assert (dof_indices.size() == phi.size());

	      const unsigned int n_dofs = dof_indices.size();
	      const unsigned int n_qp   = qrule.n_points();

	      // Compute the projection components from this cell.
	      // \int_{Omega_e} \psi_i \psi_j = \int_{Omega_e} du_h/dx_k \psi_i
	      for (unsigned int qp=0; qp<n_qp; qp++)
		{
		  // The x,y,z location of the current quadrature point
		  const Real
		    x = q_point[qp](0),
		    y = q_point[qp](1),
		    z = q_point[qp](2);

		  // Compute the gradient on the current patch element
		  // at the quadrature point
		  Gradient grad_u_h;

		  for (unsigned int i=0; i<n_dofs; i++)
		    // grad_u_h += dphi[i][qp]*system.current_solution(dof_indices[i]);
		    grad_u_h.add_scaled (dphi[i][qp],
				       system.current_solution(dof_indices[i]));

		  // Construct the shape function values for the patch projection
		  std::vector<Real> psi;
		  {
		    psi.reserve (dim+1);

		    psi.push_back(1);
		    psi.push_back(x);
		    psi.push_back(y);

		    if (dim == 3)
		      psi.push_back(z);
		  }

		  // Patch matrix contribution
		  for (unsigned int i=0; i<Kp.m(); i++)
		    for (unsigned int j=0; j<Kp.n(); j++)
		      Kp(i,j) += JxW[qp]*psi[i]*psi[j];

		  // Patch RHS contributions
		  for (unsigned int i=0; i<psi.size(); i++)
		    {
		      Fx(i) += JxW[qp]*grad_u_h(0)*psi[i];
		      Fy(i) += JxW[qp]*grad_u_h(1)*psi[i];
		      Fz(i) += JxW[qp]*grad_u_h(2)*psi[i];
		    }

		} // end quadrature loop
	    } // end patch loop

	  //--------------------------------------------------
	  // Now we have fully assembled the projection system
	  // for this patch.  Project the gradient components.
	  // MAY NEED TO USE PARTIAL PIVOTING!
	  Kp.lu_solve (Fx, Pu_x_h);
	  Kp.lu_solve (Fy, Pu_y_h);
	  Kp.lu_solve (Fz, Pu_z_h);

	  //--------------------------------------------------
	  // Finally, estimate the error in the current variable
	  // for the current element by computing ||Pgrad_u_h - grad_u_h||
	  error();

	} // end variable loop
    } // end element loop

  // Each processor has now computed the error contribuions
  // for its local elements.  We need to sum the vector
  this->reduce_error(error_per_cell);

  STOP_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
}

void PatchRecoveryErrorEstimator::build_patch_from_local_neighbors (const Elem* e0,
								    std::set<const Elem*> patch,
								    const unsigned int target_patch_size)
{
  START_LOG("build_patch_from_local_neighbors()", "PatchRecoveryErrorEstimator");

  // Make sure we are building a patch for an active, local element.
  // (Are these restrictions necessary?)
  assert (e0 != NULL);
  assert (e0->processor_id() == libMesh::processor_id());
  assert (e0->active());

  // First add the element of interest.
  patch.insert (e0);

  // Repeatedly add the neighbors of the elements in the patch until
  // the target patch size is met
  while (patch.size() < target_patch_size)
    {
      // It is possible that the target patch size is larger than the number
      // of active elements in the mesh.  Since we don't have access to the
      // Mesh object here the only way we can detect this case is by detecting
      // a "stagnant patch," i.e. a patch whose size does not increase after adding
      // face neighbors
      const unsigned int old_patch_size = patch.size();

      // Loop over all the elements in the patch
      std::set<const Elem*>::const_iterator       it  = patch.begin();
      const std::set<const Elem*>::const_iterator end = patch.end();

      for (; (it != end) && (patch.size() < target_patch_size); ++it)
	{
	  // Convenience.  Keep the syntax simple.
	  const Elem* elem = *it;

	  for (unsigned int s=0; s<elem->n_sides(); s++)
	    if (elem->neighbor(s) != NULL)        // we have a neighbor on this side
	      {
		const Elem* neighbor = elem->neighbor(s);

		if (neighbor->active())           // ... and that neighbor is active
		  if (neighbor->processor_id() ==
		      libMesh::processor_id())    // ... and belongs to this processor
		    patch.insert (neighbor);      // ... then add it to the patch

		else                              // ... the neighbor is *not* active,
		  {                               // ... so add *all* its active, local children to the patch
		    std::vector<const Elem*> active_children;

		    neighbor->active_family_tree (active_children);

		    for (unsigned int c=0; c<active_children.size(); c++)
		      if (active_children[c]->processor_id() == libMesh::processor_id())
			patch.insert (active_children[c]);
		  }
	      }
	}

      // Check for a "stagnant" patch
      if (patch.size() == old_patch_size)
	{
	  std::cerr << "ERROR: stagnant patch of "
		    << patch.size() << " elements."
		    << std::endl
		    << "Does your target patch size exceed the number of elements?"
		    << std::endl;
	  here();
	  break;
	}
    } // end while loop

  // make sure all the elements in the patch are active and local
  // if we are in debug mode
#ifdef DEBUG
  {
    std::set<const Elem*>::const_iterator       it  = patch.begin();
    const std::set<const Elem*>::const_iterator end = patch.end();

    for (; it != end; ++it)
      {
	// Convenience.  Keep the syntax simple.
	const Elem* elem = *it;

	assert (elem->active());
	assert (elem->processor_id() == libMesh::processor_id());
      }
  }
#endif

  STOP_LOG("build_patch_from_local_neighbors()", "PatchRecoveryErrorEstimator");
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: monst.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:30:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <stdlib.h>
#include "monst.hxx"
#include "invader.hrc"
#include "expl.hxx"
#include "shapes.hxx"

#ifndef _SV_OUTDEV_HXX //autogen
#include <vcl/outdev.hxx>
#endif

#ifndef _TOOLS_TIME_HXX //autogen
#include <tools/time.hxx>
#endif

Gegner::Gegner(Fighter* pFig, Bombe* pBom, ResMgr* pRes) :
            pFighter(pFig),
            GegnerListe(0,0),
            bDown(FALSE),
            bLeft(TRUE),
            bAuseMode(FALSE),
            pBombe(pBom),
            pBitMonst1(0L),
            pBitMonst2(0L),
            pBitMonst3(0L),
            pBitMonst4(0L),
            pBitMonst1b(0L),
            pBitMonst2b(0L),
            pBitMonst3b(0L),
            pBitMonst4b(0L),
            pBitMonst5(0L),
            pBitMonst5a(0L),
            pBitMonst5b(0L),
            nDown(MOVEY)
{
    pBitMonst1  = ImplLoadImage( MONSTER1, pRes );
    pBitMonst2  = ImplLoadImage( MONSTER2, pRes );
    pBitMonst3  = ImplLoadImage( MONSTER3, pRes );
    pBitMonst4  = ImplLoadImage( MONSTER4, pRes );
    pBitMonst1b = ImplLoadImage( MONSTER1B, pRes );
    pBitMonst2b = ImplLoadImage( MONSTER2B, pRes );
    pBitMonst3b = ImplLoadImage( MONSTER3B, pRes );
    pBitMonst4b = ImplLoadImage( MONSTER4B, pRes );
    pBitMonst5  = ImplLoadImage( MONSTER5, pRes );
    pBitMonst5a = ImplLoadImage( MONSTER5A, pRes );
    pBitMonst5b = ImplLoadImage( MONSTER5B, pRes );

    aOutSize = pBitMonst1->GetSizePixel();

    nRandWert = 200;
}

Gegner::~Gegner()
{
    ClearAll();

    delete pBitMonst1;
    delete pBitMonst2;
    delete pBitMonst3;
    delete pBitMonst4;
    delete pBitMonst1b;
    delete pBitMonst2b;
    delete pBitMonst3b;
    delete pBitMonst4b;
    delete pBitMonst5;
    delete pBitMonst5a;
    delete pBitMonst5b;
}

void Gegner::InsertGegner(USHORT nType, USHORT x, USHORT y)
{
    Gegner_Impl* pWork = new Gegner_Impl();

    pWork->aType = (enum GegnerType)nType;
    pWork->aMode = MOVE1;
    pWork->aXY   = Point(x,y);
    pWork->aX    = x;
    pWork->nHits = 0;
    switch(pWork->aType)
    {
        case GEGNER1:
            pWork->nPoints = 50;
            pWork->nMaxHits = 1;
            break;
        case GEGNER2:
            pWork->nPoints = 75;
            pWork->nMaxHits = 2;
            break;
        case GEGNER3:
            pWork->nPoints = 150;
            pWork->nMaxHits = 3;
            break;
        case GEGNER4:
            pWork->nPoints = 225;
            pWork->nMaxHits = 5;
            break;
        case GEGNER5:
            pWork->nPoints = 500;
            pWork->nMaxHits = 3;
            pWork->aMode = HIDE;
            break;
    }

    Insert(pWork);
}

void Gegner::Move()
{
    BOOL bNextDown = FALSE;

    for(long i=0; i<Count(); i++)
    {
        if(bDown)
        {
            SetGegnerPos(i,Point(GegnerX(i),GegnerY(i)+nDown));

        }
        else if(bLeft)
        {
            SetGegnerPos(i,Point(GegnerX(i)+MOVEX,GegnerY(i)));
            if(GegnerX(i)+MOVEX+aOutSize.Width() > nMaxX)
                bNextDown = TRUE;
        }
        else
        {
            SetGegnerPos(i,Point(GegnerX(i)-MOVEX,GegnerY(i)));
            if(GegnerX(i)-MOVEX <= 0)
                bNextDown = TRUE;
        }

    }

    if(bDown)
    {
        if(bLeft)
            bLeft = FALSE;
        else
            bLeft = TRUE;
    }

    bDown = FALSE;
    if(bNextDown)
        bDown = TRUE;
}

void Gegner::DrawGegner(OutputDevice* pDev,Point* pStart)
{

    Time aTime;
    srand(aTime.GetTime() % 1000);

    nMaxX = pDev->GetOutputSizePixel().Width()-pStart->X();

    for(long i=0; i<Count();i++)
    {
        switch(GegType(i))
        {
            case GEGNER1:
                if(GegMode(i) == MOVE1)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst1);
                    SetMode(i,MOVE2);
                }
                else if(GegMode(i) == MOVE2)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst1b);
                    SetMode(i,MOVE1);
                }
                break;
            case GEGNER2:
                if(GegMode(i) == MOVE1)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst2);
                    SetMode(i,MOVE2);
                }
                else if(GegMode(i) == MOVE2)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst2b);
                    SetMode(i,MOVE1);
                }
                break;
            case GEGNER3:
                if(GegMode(i) == MOVE1)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst3);
                    SetMode(i,MOVE2);
                }
                else if(GegMode(i) == MOVE2)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst3b);
                    SetMode(i,MOVE1);
                }
                break;
            case GEGNER4:
                if(GegMode(i) == MOVE1)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst4);
                    SetMode(i,MOVE2);
                }
                else if(GegMode(i) == MOVE2)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst4b);
                    SetMode(i,MOVE1);
                }
                break;
            case GEGNER5:
                if(GegMode(i) == MOVE1)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst5);
                    DecDelay(i);
                    if(!GetDelay(i))
                    {
                        SetDelay(i);
                        SetMode(i,MOVE2);
                    }
                }
                if(GegMode(i) == MOVE2)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst5a);
                    DecDelay(i);
                    if(!GetDelay(i))
                    {
                        SetDelay(i);
                        SetMode(i,MOVE3);
                    }
                }
                if(GegMode(i) == MOVE3)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst5b);
                    DecDelay(i);
                    if(!GetDelay(i))
                    {
                        pBombe->InsertBombe(Point(GegnerX(i)+aOutSize.Width()/2,
                                                GegnerY(i)+aOutSize.Height()));
                        SetDelay(i);
                        SetMode(i,MOVE4);
                    }
                }
                if(GegMode(i) == MOVE4)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst5a);
                    DecDelay(i);
                    if(!GetDelay(i))
                    {
                        SetDelay(i);
                        SetMode(i,MOVE5);
                    }
                }
                if(GegMode(i) == MOVE5)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst5);
                    DecDelay(i);
                    if(!GetDelay(i))
                        SetMode(i,HIDE);
                }
                break;

        }

        SetKoll(i,Rectangle(Point(GegnerX(i)+KOLLXY,GegnerY(i)+KOLLXY),
                        Point(GegnerX(i)+aOutSize.Width()-KOLLXY,
                            GegnerY(i)+aOutSize.Height()-KOLLXY)));

        if(bAuseMode && GegMode(i) == MOVE1)
        {
            if(GegnerX(i) < pFighter->GetHalf() &&
                        GegnerX(i)+aOutSize.Width() > pFighter->GetHalf())
                    pBombe->InsertBombe(Point(pFighter->GetPoint().X(),
                                            GegnerY(i)+aOutSize.Height()));
        }
        else
        {
            int ran = rand();

            if(ran < nRandWert)
            {
                if(GegType(i) != GEGNER5)
                    pBombe->InsertBombe(Point(GegnerX(i)+aOutSize.Width()/2,
                                            GegnerY(i)+aOutSize.Height()));
                else if(GegMode(i) == HIDE)
                {
                    SetMode(i,MOVE1);
                    SetDelay(i);
                }
            }
        }
    }

    Move();
}

long Gegner::Kollision(Rectangle& rRect, Explosion* pExpl)
{
    long nWert = -1;

    Rectangle aWork;

    for(long i=0; i<Count();i++)
    {
        aWork = GegnerKoll(i);
        if((aWork.Left() <= rRect.Left() &&  aWork.Right() >= rRect.Right()) &&
            (aWork.Top() <= rRect.Top() && aWork.Bottom() >= rRect.Bottom()) &&
                GegMode(i) != DELETED)
        {
            nWert = 0;
            if(GegnerDest(i))
            {
                SetMode(i,DELETED);
                if(nWert == -1)
                    nWert = GegnerPoints(i);
                else
                    nWert += GegnerPoints(i);
            }

            pExpl->InsertExpl(GegnerPos(i));

        }
    }

    return nWert;
}

BOOL Gegner::GegnerDest(long nWert)
{
    GegnerHit(nWert);
    if(GetObject(nWert)->nHits >= GetObject(nWert)->nMaxHits)
        return TRUE;

    return FALSE;
}

Rectangle Gegner::GetKoll(long nWert)
{
    return Rectangle(Point(GegnerX(nWert)+aOutSize.Width()/2,
                            GegnerY(nWert)+aOutSize.Height()),
                     Point(GegnerX(nWert)+aOutSize.Width()/2,
                            GegnerY(nWert)+aOutSize.Height()));
}

BOOL Gegner::RemoveGegner()
{
    for(long i=Count()-1; i>=0; i--)
    {
        Gegner_Impl* pWork = GetObject(i);

        if(pWork->aMode == DELETED)
        {
            Remove(pWork);
            delete pWork;
        }
    }
    if(Count())
        return FALSE;
    else
        return TRUE;
}

void Gegner::ClearAll()
{
    for(long i=0; i<Count(); i++)
        delete GetObject(i);

    Clear();
}
<commit_msg>INTEGRATION: CWS pj17 (1.1.1.1.264); FILE MERGED 2005/02/10 10:45:33 gh 1.1.1.1.264.3: more tuning to make it work nicely under windows too 2005/02/09 09:29:37 gh 1.1.1.1.264.2: finetuning 2005/02/07 17:05:49 gh 1.1.1.1.264.1: some fixes for 32 bit random numbers + enhanced invisible<commit_after>/*************************************************************************
 *
 *  $RCSfile: monst.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2005-02-11 19:30:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <stdlib.h>
#include "monst.hxx"
#include "invader.hrc"
#include "expl.hxx"
#include "shapes.hxx"

#ifndef _SV_OUTDEV_HXX //autogen
#include <vcl/outdev.hxx>
#endif

#ifndef _TOOLS_TIME_HXX //autogen
#include <tools/time.hxx>
#endif

Gegner::Gegner(Fighter* pFig, Bombe* pBom, ResMgr* pRes) :
            pFighter(pFig),
            GegnerListe(0,0),
            bDown(FALSE),
            bLeft(TRUE),
            bAuseMode(FALSE),
            pBombe(pBom),
            pBitMonst1(0L),
            pBitMonst2(0L),
            pBitMonst3(0L),
            pBitMonst4(0L),
            pBitMonst1b(0L),
            pBitMonst2b(0L),
            pBitMonst3b(0L),
            pBitMonst4b(0L),
            pBitMonst5(0L),
            pBitMonst5a(0L),
            pBitMonst5b(0L),
            nDown(MOVEY)
{
    pBitMonst1  = ImplLoadImage( MONSTER1, pRes );
    pBitMonst2  = ImplLoadImage( MONSTER2, pRes );
    pBitMonst3  = ImplLoadImage( MONSTER3, pRes );
    pBitMonst4  = ImplLoadImage( MONSTER4, pRes );
    pBitMonst1b = ImplLoadImage( MONSTER1B, pRes );
    pBitMonst2b = ImplLoadImage( MONSTER2B, pRes );
    pBitMonst3b = ImplLoadImage( MONSTER3B, pRes );
    pBitMonst4b = ImplLoadImage( MONSTER4B, pRes );
    pBitMonst5  = ImplLoadImage( MONSTER5, pRes );
    pBitMonst5a = ImplLoadImage( MONSTER5A, pRes );
    pBitMonst5b = ImplLoadImage( MONSTER5B, pRes );

    aOutSize = pBitMonst1->GetSizePixel();

    SetRandWert( 100 );
}

Gegner::~Gegner()
{
    ClearAll();

    delete pBitMonst1;
    delete pBitMonst2;
    delete pBitMonst3;
    delete pBitMonst4;
    delete pBitMonst1b;
    delete pBitMonst2b;
    delete pBitMonst3b;
    delete pBitMonst4b;
    delete pBitMonst5;
    delete pBitMonst5a;
    delete pBitMonst5b;
}

void Gegner::InsertGegner(USHORT nType, USHORT x, USHORT y)
{
    Gegner_Impl* pWork = new Gegner_Impl();

    pWork->aType = (enum GegnerType)nType;
    pWork->aMode = MOVE1;
    pWork->aXY   = Point(x,y);
    pWork->aX    = x;
    pWork->nHits = 0;
    switch(pWork->aType)
    {
        case GEGNER1:
            pWork->nPoints = 50;
            pWork->nMaxHits = 1;
            break;
        case GEGNER2:
            pWork->nPoints = 75;
            pWork->nMaxHits = 2;
            break;
        case GEGNER3:
            pWork->nPoints = 150;
            pWork->nMaxHits = 3;
            break;
        case GEGNER4:
            pWork->nPoints = 225;
            pWork->nMaxHits = 5;
            break;
        case GEGNER5:
            pWork->nPoints = 500;
            pWork->nMaxHits = 3;
            pWork->aMode = HIDE;
            break;
    }

    Insert(pWork);
}

void Gegner::Move()
{
    BOOL bNextDown = FALSE;

    for(long i=0; i<Count(); i++)
    {
        if(bDown)
        {
            SetGegnerPos(i,Point(GegnerX(i),GegnerY(i)+nDown));

        }
        else if(bLeft)
        {
            SetGegnerPos(i,Point(GegnerX(i)+MOVEX,GegnerY(i)));
            if(GegnerX(i)+MOVEX+aOutSize.Width() > nMaxX)
                bNextDown = TRUE;
        }
        else
        {
            SetGegnerPos(i,Point(GegnerX(i)-MOVEX,GegnerY(i)));
            if(GegnerX(i)-MOVEX <= 0)
                bNextDown = TRUE;
        }

    }

    if(bDown)
    {
        if(bLeft)
            bLeft = FALSE;
        else
            bLeft = TRUE;
    }

    bDown = FALSE;
    if(bNextDown)
        bDown = TRUE;
}

void Gegner::DrawGegner(OutputDevice* pDev,Point* pStart)
{

    Time aTime;
    srand(aTime.GetTime() % 1000);

    nMaxX = pDev->GetOutputSizePixel().Width()-pStart->X();

    for(long i=0; i<Count();i++)
    {
        switch(GegType(i))
        {
            case GEGNER1:
                if(GegMode(i) == MOVE1)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst1);
                    SetMode(i,MOVE2);
                }
                else if(GegMode(i) == MOVE2)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst1b);
                    SetMode(i,MOVE1);
                }
                break;
            case GEGNER2:
                if(GegMode(i) == MOVE1)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst2);
                    SetMode(i,MOVE2);
                }
                else if(GegMode(i) == MOVE2)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst2b);
                    SetMode(i,MOVE1);
                }
                break;
            case GEGNER3:
                if(GegMode(i) == MOVE1)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst3);
                    SetMode(i,MOVE2);
                }
                else if(GegMode(i) == MOVE2)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst3b);
                    SetMode(i,MOVE1);
                }
                break;
            case GEGNER4:
                if(GegMode(i) == MOVE1)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst4);
                    SetMode(i,MOVE2);
                }
                else if(GegMode(i) == MOVE2)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst4b);
                    SetMode(i,MOVE1);
                }
                break;
            case GEGNER5:
                if(GegMode(i) == MOVE1)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst5);
                    DecDelay(i);
                    if(!GetDelay(i))
                    {
                        SetDelay(i);
                        SetMode(i,MOVE2);
                    }
                }
                if(GegMode(i) == MOVE2)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst5a);
                    DecDelay(i);
                    if(!GetDelay(i))
                    {
                        SetDelay(i);
                        SetMode(i,MOVE3);
                    }
                }
                if(GegMode(i) == MOVE3)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst5b);
                    DecDelay(i);
                    pBombe->InsertBombe(Point(GegnerX(i),
                                            GegnerY(i)+aOutSize.Height()/2));
                    if(!GetDelay(i))
                    {
                        SetDelay(i);
                        SetMode(i,MOVE4);
                    }
                }
                if(GegMode(i) == MOVE4)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst5a);
                    DecDelay(i);
                    if(!GetDelay(i))
                    {
                        SetDelay(i);
                        if ( rand() % 5 < 2 )
                            SetMode(i,MOVE3);
                        else
                            SetMode(i,MOVE5);
                    }
                }
                if(GegMode(i) == MOVE5)
                {
                    pDev->DrawImage(Point(pStart->X()+GegnerX(i),
                            pStart->Y()+GegnerY(i)),*pBitMonst5);
                    DecDelay(i);
                    if(!GetDelay(i))
                    {
                        if ( rand() % 5 < 2 )
                        {
                            SetMode(i,MOVE1);
                            SetDelay(i);
                        }
                        else
                            SetMode(i,HIDE);
                    }
                }
                break;

        }

        SetKoll(i,Rectangle(Point(GegnerX(i)+KOLLXY,GegnerY(i)+KOLLXY),
                        Point(GegnerX(i)+aOutSize.Width()-KOLLXY,
                            GegnerY(i)+aOutSize.Height()-KOLLXY)));

        if(bAuseMode && GegMode(i) == MOVE1)
        {
            if(GegnerX(i) < pFighter->GetHalf() &&
                        GegnerX(i)+aOutSize.Width() > pFighter->GetHalf())
                    pBombe->InsertBombe(Point(pFighter->GetPoint().X(),
                                            GegnerY(i)+aOutSize.Height()/2));
        }
        else
        {
            int ran = rand();

            int nScaledLimit;
            // NOTE: the two expressions are the same in floatingpoint but not in integer
            if ( RAND_MAX < 32767 )
                nScaledLimit = GetRandWert() / (32767 / RAND_MAX);
            else
                nScaledLimit = GetRandWert() * (RAND_MAX / 32767);

            if(GegType(i) != GEGNER5)
            {
                if(ran < nScaledLimit )
                    pBombe->InsertBombe(Point(GegnerX(i),
                                            GegnerY(i)+aOutSize.Height()/2));
            }
            else if(GegMode(i) == HIDE)
            {
                if(ran < (nScaledLimit *3) /2)
                {
                    SetMode(i,MOVE1);
                    SetDelay(i);
                }
            }
        }
    }

    Move();
}

long Gegner::Kollision(Rectangle& rRect, Explosion* pExpl)
{
    long nWert = -1;

    Rectangle aWork;

    for(long i=0; i<Count();i++)
    {
        aWork = GegnerKoll(i);
        if((aWork.Left() <= rRect.Left() &&  aWork.Right() >= rRect.Right()) &&
            (aWork.Top() <= rRect.Top() && aWork.Bottom() >= rRect.Bottom()) &&
                GegMode(i) != DELETED)
        {
            nWert = 0;
            if(GegnerDest(i))
            {
                SetMode(i,DELETED);
                if(nWert == -1)
                    nWert = GegnerPoints(i);
                else
                    nWert += GegnerPoints(i);
            }

            pExpl->InsertExpl(GegnerPos(i));

        }
    }

    return nWert;
}

BOOL Gegner::GegnerDest(long nWert)
{
    GegnerHit(nWert);
    if(GetObject(nWert)->nHits >= GetObject(nWert)->nMaxHits)
        return TRUE;

    return FALSE;
}

Rectangle Gegner::GetKoll(long nWert)
{
    return Rectangle(Point(GegnerX(nWert)+aOutSize.Width()/2,
                            GegnerY(nWert)+aOutSize.Height()),
                     Point(GegnerX(nWert)+aOutSize.Width()/2,
                            GegnerY(nWert)+aOutSize.Height()));
}

BOOL Gegner::RemoveGegner()
{
    for(long i=Count()-1; i>=0; i--)
    {
        Gegner_Impl* pWork = GetObject(i);

        if(pWork->aMode == DELETED)
        {
            Remove(pWork);
            delete pWork;
        }
    }
    if(Count())
        return FALSE;
    else
        return TRUE;
}

void Gegner::ClearAll()
{
    for(long i=0; i<Count(); i++)
        delete GetObject(i);

    Clear();
}
<|endoftext|>


<commit_before>// Tests trace pc guard coverage collection.
//
// REQUIRES: has_sancovcc
// XFAIL: tsan
//
// RUN: DIR=%t_workdir
// RUN: CLANG_ARGS="-O0 -fsanitize-coverage=trace-pc-guard"
// RUN: rm -rf $DIR
// RUN: mkdir -p $DIR
// RUN: cd $DIR
// RUN: %clangxx -DSHARED1 $CLANG_ARGS -shared %s -o %t_1.so -fPIC
// RUN: %clangxx -DSHARED2 $CLANG_ARGS -shared %s -o %t_2.so -fPIC
// RUN: %clangxx -DMAIN $CLANG_ARGS %s -o %t %t_1.so %t_2.so
// RUN: %env_tool_opts=coverage=1 %t 2>&1 | FileCheck %s
// RUN: %sancovcc  -covered-functions -strip_path_prefix=TestCases/ *.sancov \
// RUN:            %t %t_1.so %t_2.so 2>&1 | \
// RUN:   FileCheck --check-prefix=CHECK-SANCOV %s
// RUN: rm -rf $DIR

#include <stdio.h>

extern "C" {
  int bar();
  int baz();
}

#ifdef MAIN

int foo() {
  fprintf(stderr, "foo\n");
  return 1;
}

int main() {
  fprintf(stderr, "main\n");
  foo();
  bar();
  baz();
}

#endif // MAIN

extern "C" {

#ifdef SHARED1
int bar() {
  fprintf(stderr, "bar\n");
  return 1;
}
#endif

#ifdef SHARED2
int baz() {
  fprintf(stderr, "baz\n");
  return 1;
}
#endif

} // extern "C"

// CHECK: main
// CHECK-NEXT: foo
// CHECK-NEXT: bar
// CHECK-NEXT: baz
// CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}.sancov 2 PCs written
// CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}_2.so.{{.*}}.sancov 1 PCs written
// CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}_1.so.{{.*}}.sancov 1 PCs written
//
// CHECK-SANCOV: Ignoring {{.*}}_1.so and its coverage because __sanitizer_cov* functions were not found.
// CHECK-SANCOV: Ignoring {{.*}}_2.so and its coverage because __sanitizer_cov* functions were not found.
// CHECK-SANCOV-NEXT: sanitizer_coverage_trace_pc_guard-dso.cc:29 foo
// CHECK-SANCOV-NEXT: sanitizer_coverage_trace_pc_guard-dso.cc:34 main
<commit_msg>[sanitizers] disabling dso test as well where appropriate<commit_after>// Tests trace pc guard coverage collection.
//
// REQUIRES: has_sancovcc
// XFAIL: tsan,arm,aarch64,darwin
//
// RUN: DIR=%t_workdir
// RUN: CLANG_ARGS="-O0 -fsanitize-coverage=trace-pc-guard"
// RUN: rm -rf $DIR
// RUN: mkdir -p $DIR
// RUN: cd $DIR
// RUN: %clangxx -DSHARED1 $CLANG_ARGS -shared %s -o %t_1.so -fPIC
// RUN: %clangxx -DSHARED2 $CLANG_ARGS -shared %s -o %t_2.so -fPIC
// RUN: %clangxx -DMAIN $CLANG_ARGS %s -o %t %t_1.so %t_2.so
// RUN: %env_tool_opts=coverage=1 %t 2>&1 | FileCheck %s
// RUN: %sancovcc  -covered-functions -strip_path_prefix=TestCases/ *.sancov \
// RUN:            %t %t_1.so %t_2.so 2>&1 | \
// RUN:   FileCheck --check-prefix=CHECK-SANCOV %s
// RUN: rm -rf $DIR

#include <stdio.h>

extern "C" {
  int bar();
  int baz();
}

#ifdef MAIN

int foo() {
  fprintf(stderr, "foo\n");
  return 1;
}

int main() {
  fprintf(stderr, "main\n");
  foo();
  bar();
  baz();
}

#endif // MAIN

extern "C" {

#ifdef SHARED1
int bar() {
  fprintf(stderr, "bar\n");
  return 1;
}
#endif

#ifdef SHARED2
int baz() {
  fprintf(stderr, "baz\n");
  return 1;
}
#endif

} // extern "C"

// CHECK: main
// CHECK-NEXT: foo
// CHECK-NEXT: bar
// CHECK-NEXT: baz
// CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}.sancov 2 PCs written
// CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}_2.so.{{.*}}.sancov 1 PCs written
// CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}_1.so.{{.*}}.sancov 1 PCs written
//
// CHECK-SANCOV: Ignoring {{.*}}_1.so and its coverage because __sanitizer_cov* functions were not found.
// CHECK-SANCOV: Ignoring {{.*}}_2.so and its coverage because __sanitizer_cov* functions were not found.
// CHECK-SANCOV-NEXT: sanitizer_coverage_trace_pc_guard-dso.cc:29 foo
// CHECK-SANCOV-NEXT: sanitizer_coverage_trace_pc_guard-dso.cc:34 main
<|endoftext|>


<commit_before>
#ifndef __SHUTDOWNICON_HXX__
#define __SHUTDOWNICON_HXX__

#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _RTL_STRING_HXX
#include <rtl/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _SFX_SFXUNO_HXX
#include <sfx2/sfxuno.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif

class ResMgr;

typedef ::cppu::WeakComponentImplHelper3<
    ::com::sun::star::lang::XInitialization,
    ::com::sun::star::frame::XTerminateListener,
    ::com::sun::star::lang::XServiceInfo > ShutdownIconServiceBase;

class ShutdownIcon :    public ShutdownIconServiceBase
{
        ::osl::Mutex    m_aMutex;
        bool            m_bVeto;
        ResMgr          *m_pResMgr;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;

        static ShutdownIcon *pShutdownIcon; // one instance

#ifdef WNT
        void initSystray();
        void deInitSystray();
        static void SetAutostartW32( const ::rtl::OUString& aShortcutName, bool bActivate );
        static bool GetAutostartW32( const ::rtl::OUString& aShortcutName );
#endif

    public:
        ShutdownIcon( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > aSMgr );

        virtual ~ShutdownIcon();

        SFX_DECL_XSERVICEINFO

        static ShutdownIcon* getInstance();
        static void terminateDesktop();
        static void addTerminateListener();

        static void FileOpen();
        static void OpenURL( ::rtl::OUString& aURL );
        static void FromTemplate();

        static void SetAutostart( bool bActivate );
        static bool GetAutostart();

        static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >
                    GetWrapperFactory( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSMgr );
        static ::rtl::OUString  GetImplementationName_static();

        ::rtl::OUString GetResString( int id );
        ::rtl::OUString GetUrlDescription( const ::rtl::OUString& aUrl );

        void SetVeto( bool bVeto )  { m_bVeto = bVeto;}
        bool GetVeto()              { return m_bVeto; }

        // Component Helper - force override
        virtual void SAL_CALL disposing();

        // XEventListener
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
            throw(::com::sun::star::uno::RuntimeException);

        // XTerminateListener
        virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent )
            throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent )
            throw(::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
            throw( ::com::sun::star::uno::Exception );

        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDesktop > m_xDesktop;
};

#endif
<commit_msg>#87576# include fixed<commit_after>
#ifndef __SHUTDOWNICON_HXX__
#define __SHUTDOWNICON_HXX__

#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _RTL_STRING_HXX
#include <rtl/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _SFX_SFXUNO_HXX
#include <sfxuno.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif

class ResMgr;

typedef ::cppu::WeakComponentImplHelper3<
    ::com::sun::star::lang::XInitialization,
    ::com::sun::star::frame::XTerminateListener,
    ::com::sun::star::lang::XServiceInfo > ShutdownIconServiceBase;

class ShutdownIcon :    public ShutdownIconServiceBase
{
        ::osl::Mutex    m_aMutex;
        bool            m_bVeto;
        ResMgr          *m_pResMgr;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;

        static ShutdownIcon *pShutdownIcon; // one instance

#ifdef WNT
        void initSystray();
        void deInitSystray();
        static void SetAutostartW32( const ::rtl::OUString& aShortcutName, bool bActivate );
        static bool GetAutostartW32( const ::rtl::OUString& aShortcutName );
#endif

    public:
        ShutdownIcon( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > aSMgr );

        virtual ~ShutdownIcon();

        SFX_DECL_XSERVICEINFO

        static ShutdownIcon* getInstance();
        static void terminateDesktop();
        static void addTerminateListener();

        static void FileOpen();
        static void OpenURL( ::rtl::OUString& aURL );
        static void FromTemplate();

        static void SetAutostart( bool bActivate );
        static bool GetAutostart();

        static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >
                    GetWrapperFactory( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSMgr );
        static ::rtl::OUString  GetImplementationName_static();

        ::rtl::OUString GetResString( int id );
        ::rtl::OUString GetUrlDescription( const ::rtl::OUString& aUrl );

        void SetVeto( bool bVeto )  { m_bVeto = bVeto;}
        bool GetVeto()              { return m_bVeto; }

        // Component Helper - force override
        virtual void SAL_CALL disposing();

        // XEventListener
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
            throw(::com::sun::star::uno::RuntimeException);

        // XTerminateListener
        virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent )
            throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent )
            throw(::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
            throw( ::com::sun::star::uno::Exception );

        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDesktop > m_xDesktop;
};

#endif
<|endoftext|>