<commit_before>// Fill out your copyright notice in the Description page of Project Settings.

#include "TransformTool.h"
#include "TransformToolPrivatePCH.h"
#include "MoveTool.h"

// Sets default values
AMoveTool::AMoveTool()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    CurrentStatus = EMoveToolStatusEnum::ES_NONE;

    AttachedCamera = nullptr;

    OverlookActor = nullptr;

    Center = CreateDefaultSubobject<USphereComponent>(TEXT("center"));
    RootComponent = Center;
    Center->SetSphereRadius(0.2f);

    InitAxis();

    InitBox();

    InitCombinationAxis();
}

// Called when the game starts or when spawned
void AMoveTool::BeginPlay()
{
    Super::BeginPlay();
}

// Called every frame
void AMoveTool::Tick( float DeltaTime )
{
    Super::Tick( DeltaTime );
}

void AMoveTool::AttachToCamera(class UCameraComponent* Camera)
{
    AttachedCamera = Camera;
}

void AMoveTool::SetOverlookActor(class AActor* Actor)
{
    OverlookActor = Actor;
}

void AMoveTool::InitAxis()
{
    AxisX = CreateAxis("AxisX", FColor(0xFF, 0x00, 0x00, 0xFF), FRotator(0.0f, 0.0f, 90.0f));

    AxisY = CreateAxis("AxisY", FColor(0x00, 0xFF, 0x00, 0xFF), FRotator(0.0f, 90.0f, 0.0f));

    AxisZ = CreateAxis("AxisZ", FColor(0x00, 0x00, 0xFF, 0xFF), FRotator(90.0f, 0.0f, 0.0f));
}

class UArrowComponent* AMoveTool::CreateAxis(FString Name, FColor Color, FRotator Rotation)
{
    UArrowComponent* pAxis = CreateDefaultSubobject<UArrowComponent>(*Name);

    pAxis->ArrowSize = 0.1f;
    pAxis->bHiddenInGame = false;
    pAxis->ArrowColor = Color;
    pAxis->RelativeRotation = Rotation;

    pAxis->AttachTo(Center);

    return pAxis;
}

void AMoveTool::InitBox()
{
    BoxX = CreateBox("BoxX", FVector(4.5f, 0.0f, 0.0f), FVector(0.1f, 0.015625f, 0.015625f));
    BoxX->OnClicked.AddDynamic(this, &AMoveTool::OnAxisXClicked);

    BoxY = CreateBox("BoxY", FVector(0.0f, 4.5f, 0.0f), FVector(0.015625f, 0.1f, 0.015625f));
    BoxY->OnClicked.AddDynamic(this, &AMoveTool::OnAxisYClicked);

    BoxZ = CreateBox("BoxZ", FVector(0.0f, 0.0f, 4.5f), FVector(0.015625f, 0.015625f, 0.1f));
    BoxZ->OnClicked.AddDynamic(this, &AMoveTool::OnAxisZClicked);
}

class UBoxComponent* AMoveTool::CreateBox(FString Name, FVector Location, FVector Scale3D)
{
    UBoxComponent* Box = CreateDefaultSubobject<UBoxComponent>(*Name);
    Box->SetCollisionProfileName(FName(TEXT("UI")));

    Box->RelativeLocation = Location;
    Box->RelativeScale3D = Scale3D;

    Box->OnReleased.AddDynamic(this, &AMoveTool::OnAxisReleased);
    Box->OnBeginCursorOver.AddDynamic(this, &AMoveTool::OnAxisBeginCursorOver);
    Box->OnEndCursorOver.AddDynamic(this, &AMoveTool::OnAxisEndCursorOver);

    Box->AttachTo(Center);

    return Box;
}

void AMoveTool::InitCombinationAxis()
{
    AxisXY = CreateCombinationAxis("AxisX&Y", FVector(1.4f, 1.4f, 0.0f), FVector(0.024f, 0.024f, 0.000244f));
    AxisXY->OnClicked.AddDynamic(this, &AMoveTool::OnAxisXYClicked);

    AxisXZ = CreateCombinationAxis("AxisX&Z", FVector(1.4f, 0.0f, 1.4f), FVector(0.024f, 0.000244f, 0.024f));
    AxisXZ->OnClicked.AddDynamic(this, &AMoveTool::OnAxisXZClicked);

    AxisYZ = CreateCombinationAxis("AxisY&Z", FVector(0.0f, 1.4f, 1.4f), FVector(0.000244f, 0.024f, 0.024f));
    AxisYZ->OnClicked.AddDynamic(this, &AMoveTool::OnAxisYZClicked);
}

class UStaticMeshComponent* AMoveTool::CreateCombinationAxis(FString Name, FVector Location, FVector Scale3D)
{
    UStaticMeshComponent* CombinationAxis = CreateDefaultSubobject<UStaticMeshComponent>(*Name);

    static ConstructorHelpers::FObjectFinder<UStaticMesh> MehFinder(TEXT("/Engine/BasicShapes/Cube"));
    static ConstructorHelpers::FObjectFinder<UMaterial> MatFinder(TEXT("/Engine/BasicShapes/BasicShapeMaterial"));

    CombinationAxis->StaticMesh = MehFinder.Object;
    CombinationAxis->SetMaterial(0, MatFinder.Object);

    CombinationAxis->SetCollisionProfileName(FName(TEXT("UI")));

    CombinationAxis->RelativeLocation = Location;
    CombinationAxis->RelativeScale3D = Scale3D;

    CombinationAxis->OnReleased.AddDynamic(this, &AMoveTool::OnAxisReleased);
    CombinationAxis->OnBeginCursorOver.AddDynamic(this, &AMoveTool::OnAxisBeginCursorOver);
    CombinationAxis->OnEndCursorOver.AddDynamic(this, &AMoveTool::OnAxisEndCursorOver);

    CombinationAxis->AttachTo(Center);

    return CombinationAxis;
}

void AMoveTool::UpdateMoveToolPosition()
{
    if (!IsValid(OverlookActor) || !IsValid(AttachedCamera))
    {
        return;
    }

    FRotator ViewRotation = AttachedCamera->GetComponentRotation();
    FVector ViewLocation = AttachedCamera->GetComponentLocation();

    FVector moveToolLocation = (OverlookActor->GetActorLocation() - ViewLocation).Rotation().RotateVector(FVector(61.0f, 0.0f, 0.0f));
    SetActorLocation(ViewLocation + moveToolLocation);
}

void AMoveTool::SetCurrentStatus(EMoveToolStatusEnum Status)
{
    CurrentStatus = Status;
}

class AActor* AMoveTool::GetOverLookActor()
{
    return OverlookActor;
}

EMoveToolStatusEnum AMoveTool::GetCurrentStatus()
{
    return CurrentStatus;
}

void AMoveTool::SwitchMouseCursor(EMouseCursor::Type type)
{
    UGameplayStatics::GetPlayerController(GetWorld(), 0)->CurrentMouseCursor = type;
}

void AMoveTool::OnAxisXClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisXClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISX);
}

void AMoveTool::OnAxisYClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisYClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISY);
}

void AMoveTool::OnAxisZClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisZClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISZ);
}

void AMoveTool::OnAxisXYClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisXYClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISXY);
}

void AMoveTool::OnAxisXZClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisXZClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISXZ);
}

void AMoveTool::OnAxisYZClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisYZClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISYZ);
}

void AMoveTool::OnAxisReleased(class UPrimitiveComponent* TouchedComponent)
{
    SetCurrentStatus(EMoveToolStatusEnum::ES_NONE);
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisReleased");
}

void AMoveTool::OnAxisBeginCursorOver(class UPrimitiveComponent* TouchedComponent)
{
    SwitchMouseCursor(EMouseCursor::Type::CardinalCross);
}

void AMoveTool::OnAxisEndCursorOver(class UPrimitiveComponent* TouchedComponent)
{
    SwitchMouseCursor(EMouseCursor::Type::Default);
}
<commit_msg>fix click self problem<commit_after>// Fill out your copyright notice in the Description page of Project Settings.

#include "TransformTool.h"
#include "TransformToolPrivatePCH.h"
#include "MoveTool.h"

// Sets default values
AMoveTool::AMoveTool()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    CurrentStatus = EMoveToolStatusEnum::ES_NONE;

    AttachedCamera = nullptr;

    OverlookActor = nullptr;

    Center = CreateDefaultSubobject<USphereComponent>(TEXT("center"));
    RootComponent = Center;
    Center->SetSphereRadius(0.2f);

    InitAxis();

    InitBox();

    InitCombinationAxis();
}

// Called when the game starts or when spawned
void AMoveTool::BeginPlay()
{
    Super::BeginPlay();
}

// Called every frame
void AMoveTool::Tick( float DeltaTime )
{
    Super::Tick( DeltaTime );
}

void AMoveTool::AttachToCamera(class UCameraComponent* Camera)
{
    AttachedCamera = Camera;
}

void AMoveTool::SetOverlookActor(class AActor* Actor)
{
    OverlookActor = (this == Actor) ? OverlookActor : Actor;
}

void AMoveTool::InitAxis()
{
    AxisX = CreateAxis("AxisX", FColor(0xFF, 0x00, 0x00, 0xFF), FRotator(0.0f, 0.0f, 90.0f));

    AxisY = CreateAxis("AxisY", FColor(0x00, 0xFF, 0x00, 0xFF), FRotator(0.0f, 90.0f, 0.0f));

    AxisZ = CreateAxis("AxisZ", FColor(0x00, 0x00, 0xFF, 0xFF), FRotator(90.0f, 0.0f, 0.0f));
}

class UArrowComponent* AMoveTool::CreateAxis(FString Name, FColor Color, FRotator Rotation)
{
    UArrowComponent* pAxis = CreateDefaultSubobject<UArrowComponent>(*Name);

    pAxis->ArrowSize = 0.1f;
    pAxis->bHiddenInGame = false;
    pAxis->ArrowColor = Color;
    pAxis->RelativeRotation = Rotation;

    pAxis->AttachTo(Center);

    return pAxis;
}

void AMoveTool::InitBox()
{
    BoxX = CreateBox("BoxX", FVector(4.5f, 0.0f, 0.0f), FVector(0.1f, 0.015625f, 0.015625f));
    BoxX->OnClicked.AddDynamic(this, &AMoveTool::OnAxisXClicked);

    BoxY = CreateBox("BoxY", FVector(0.0f, 4.5f, 0.0f), FVector(0.015625f, 0.1f, 0.015625f));
    BoxY->OnClicked.AddDynamic(this, &AMoveTool::OnAxisYClicked);

    BoxZ = CreateBox("BoxZ", FVector(0.0f, 0.0f, 4.5f), FVector(0.015625f, 0.015625f, 0.1f));
    BoxZ->OnClicked.AddDynamic(this, &AMoveTool::OnAxisZClicked);
}

class UBoxComponent* AMoveTool::CreateBox(FString Name, FVector Location, FVector Scale3D)
{
    UBoxComponent* Box = CreateDefaultSubobject<UBoxComponent>(*Name);
    Box->SetCollisionProfileName(FName(TEXT("UI")));

    Box->RelativeLocation = Location;
    Box->RelativeScale3D = Scale3D;

    Box->OnReleased.AddDynamic(this, &AMoveTool::OnAxisReleased);
    Box->OnBeginCursorOver.AddDynamic(this, &AMoveTool::OnAxisBeginCursorOver);
    Box->OnEndCursorOver.AddDynamic(this, &AMoveTool::OnAxisEndCursorOver);

    Box->AttachTo(Center);

    return Box;
}

void AMoveTool::InitCombinationAxis()
{
    AxisXY = CreateCombinationAxis("AxisX&Y", FVector(1.4f, 1.4f, 0.0f), FVector(0.024f, 0.024f, 0.000244f));
    AxisXY->OnClicked.AddDynamic(this, &AMoveTool::OnAxisXYClicked);

    AxisXZ = CreateCombinationAxis("AxisX&Z", FVector(1.4f, 0.0f, 1.4f), FVector(0.024f, 0.000244f, 0.024f));
    AxisXZ->OnClicked.AddDynamic(this, &AMoveTool::OnAxisXZClicked);

    AxisYZ = CreateCombinationAxis("AxisY&Z", FVector(0.0f, 1.4f, 1.4f), FVector(0.000244f, 0.024f, 0.024f));
    AxisYZ->OnClicked.AddDynamic(this, &AMoveTool::OnAxisYZClicked);
}

class UStaticMeshComponent* AMoveTool::CreateCombinationAxis(FString Name, FVector Location, FVector Scale3D)
{
    UStaticMeshComponent* CombinationAxis = CreateDefaultSubobject<UStaticMeshComponent>(*Name);

    static ConstructorHelpers::FObjectFinder<UStaticMesh> MehFinder(TEXT("/Engine/BasicShapes/Cube"));
    static ConstructorHelpers::FObjectFinder<UMaterial> MatFinder(TEXT("/Engine/BasicShapes/BasicShapeMaterial"));

    CombinationAxis->StaticMesh = MehFinder.Object;
    CombinationAxis->SetMaterial(0, MatFinder.Object);

    CombinationAxis->SetCollisionProfileName(FName(TEXT("UI")));

    CombinationAxis->RelativeLocation = Location;
    CombinationAxis->RelativeScale3D = Scale3D;

    CombinationAxis->OnReleased.AddDynamic(this, &AMoveTool::OnAxisReleased);
    CombinationAxis->OnBeginCursorOver.AddDynamic(this, &AMoveTool::OnAxisBeginCursorOver);
    CombinationAxis->OnEndCursorOver.AddDynamic(this, &AMoveTool::OnAxisEndCursorOver);

    CombinationAxis->AttachTo(Center);

    return CombinationAxis;
}

void AMoveTool::UpdateMoveToolPosition()
{
    if (!IsValid(OverlookActor) || !IsValid(AttachedCamera))
    {
        return;
    }

    FRotator ViewRotation = AttachedCamera->GetComponentRotation();
    FVector ViewLocation = AttachedCamera->GetComponentLocation();

    FVector moveToolLocation = (OverlookActor->GetActorLocation() - ViewLocation).Rotation().RotateVector(FVector(61.0f, 0.0f, 0.0f));
    SetActorLocation(ViewLocation + moveToolLocation);
}

void AMoveTool::SetCurrentStatus(EMoveToolStatusEnum Status)
{
    CurrentStatus = Status;
}

class AActor* AMoveTool::GetOverLookActor()
{
    return OverlookActor;
}

EMoveToolStatusEnum AMoveTool::GetCurrentStatus()
{
    return CurrentStatus;
}

void AMoveTool::SwitchMouseCursor(EMouseCursor::Type type)
{
    UGameplayStatics::GetPlayerController(GetWorld(), 0)->CurrentMouseCursor = type;
}

void AMoveTool::OnAxisXClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisXClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISX);
}

void AMoveTool::OnAxisYClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisYClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISY);
}

void AMoveTool::OnAxisZClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisZClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISZ);
}

void AMoveTool::OnAxisXYClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisXYClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISXY);
}

void AMoveTool::OnAxisXZClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisXZClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISXZ);
}

void AMoveTool::OnAxisYZClicked(class UPrimitiveComponent* TouchedComponent)
{
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisYZClicked");
    SetCurrentStatus(EMoveToolStatusEnum::ES_AXISYZ);
}

void AMoveTool::OnAxisReleased(class UPrimitiveComponent* TouchedComponent)
{
    SetCurrentStatus(EMoveToolStatusEnum::ES_NONE);
    GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, "OnAxisReleased");
}

void AMoveTool::OnAxisBeginCursorOver(class UPrimitiveComponent* TouchedComponent)
{
    SwitchMouseCursor(EMouseCursor::Type::CardinalCross);
}

void AMoveTool::OnAxisEndCursorOver(class UPrimitiveComponent* TouchedComponent)
{
    SwitchMouseCursor(EMouseCursor::Type::Default);
}
<|endoftext|>


<commit_before>#ifndef BOOK_SAUCER_HPP
#define BOOK_SAUCER_HPP

#include <SFML-Book/Enemy.hpp>

namespace book
{
    class Saucer : public Enemy
    {
        public:
            Saucer(const Saucer&) = delete;
            Saucer& operator=(const Saucer&) = delete;

            using Enemy::Enemy;

            virtual bool isCollide(const Entity& other)const;

            static void newSaucer(World& world);

            virtual void update(sf::Time deltaTime);

            virtual void onDestroy();
    };

    class BigSaucer : public Saucer
    {
        public:
            BigSaucer(World& world);
            virtual int getPoints()const;
    };

    class SmallSaucer : public Saucer
    {
        public :
            SmallSaucer(World& world);
            virtual int getPoints()const;
            virtual void update(sf::Time deltaTime);

        private:
            sf::Time            _timeSinceLastShoot;
    };

}
#endif
<commit_msg>Update Saucer.hpp (#10)<commit_after>#ifndef BOOK_SAUCER_HPP
#define BOOK_SAUCER_HPP

#include <SFML-Book/Enemy.hpp>

namespace book
{
    class Saucer : public Enemy
    {
        public:
            Saucer(const Saucer&) = delete;
            Saucer& operator=(const Saucer&) = delete;
            Saucer(Configuration::Textures textures, World& world);

            using Enemy::Enemy;

            virtual bool isCollide(const Entity& other)const;

            static void newSaucer(World& world);

            virtual void update(sf::Time deltaTime);

            virtual void onDestroy();
    };

    class BigSaucer : public Saucer
    {
        public:
            BigSaucer(World& world);
            virtual int getPoints()const;
    };

    class SmallSaucer : public Saucer
    {
        public :
            SmallSaucer(World& world);
            virtual int getPoints()const;
            virtual void update(sf::Time deltaTime);

        private:
            sf::Time            _timeSinceLastShoot;
    };

}
#endif
<|endoftext|>


<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.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbGenericRSResampleImageFilter.h"

#include "itkLinearInterpolateImageFunction.h"
#include "otbBCOInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"

#include "otbPleiadesImageMetadataInterface.h"

#include "itkScalableAffineTransform.h"

// Elevation handler
#include "otbWrapperElevationParametersHandler.h"

#include "otbDateTimeAdapter.h"
#include "otbStreamingResampleImageFilter.h"

namespace otb
{

enum
{
  Interpolator_BCO,
  Interpolator_NNeighbor,
  Interpolator_Linear
};

enum
{
  Mode_Default,
  Mode_PHR
};

namespace Wrapper
{

class Superimpose : public Application
{
public:
  /** Standard class typedefs. */
  typedef Superimpose         Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(Superimpose, Application);

  typedef unsigned short int PixelType;

  typedef itk::LinearInterpolateImageFunction
    <FloatVectorImageType,
     double>                                                      LinInterpolatorType;
  typedef itk::NearestNeighborInterpolateImageFunction
    <FloatVectorImageType,
     double>                                                      NNInterpolatorType;
  typedef otb::BCOInterpolateImageFunction
    <FloatVectorImageType>                                        BCOInterpolatorType;

  typedef otb::GenericRSResampleImageFilter<FloatVectorImageType,
                                            FloatVectorImageType>  ResamplerType;

  typedef itk::ScalableAffineTransform<double, 2>                 TransformType;

  typedef otb::ImageKeywordlist                                   ImageKeywordlistType;

  typedef otb::StreamingResampleImageFilter
    <FloatVectorImageType,
     FloatVectorImageType>                                        BasicResamplerType;

private:
  void DoInit()
  {
    SetName("Superimpose");
    SetDescription("Using available image metadata, project one image onto another one");

    // Documentation
    SetDocName("Superimpose sensor");
    SetDocLongDescription("This application performs the projection of an image into the geometry of another one.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Geometry);
    AddDocTag("Superimposition");

    AddParameter(ParameterType_InputImage,   "inr",   "Reference input");
    SetParameterDescription("inr","The input reference image.");
    AddParameter(ParameterType_InputImage,   "inm",   "The image to reproject");
    SetParameterDescription("inm","The image to reproject into the geometry of the reference input.");

    // Elevation
    ElevationParametersHandler::AddElevationParameters(this, "elev");

    AddParameter(ParameterType_Float,        "lms",   "Spacing of the deformation field");
    SetParameterDescription("lms","Generate a coarser deformation field with the given spacing");
    SetDefaultParameterFloat("lms", 4.);
    MandatoryOff("lms");

    AddParameter(ParameterType_OutputImage,  "out",   "Output image");
    SetParameterDescription("out","Output reprojected image.");

    // Superposition mode
    AddParameter(ParameterType_Choice,"mode", "Mode");
    SetParameterDescription("mode", "Superimposition mode");

    AddChoice("mode.default", "Default mode");
    SetParameterDescription("mode.default", "Default superimposition mode : "
      "uses any projection reference or sensor model found in the images");

    AddChoice("mode.phr", "Pleiades mode");
    SetParameterDescription("mode.phr", "Pleiades superimposition mode, "
      "designed for the case of a P+XS bundle in SENSOR geometry. It uses"
      " a simple transform : a scaling and a residual translation.");

    // Interpolators
    AddParameter(ParameterType_Choice,   "interpolator", "Interpolation");
    SetParameterDescription("interpolator","This group of parameters allows to define how the input image will be interpolated during resampling.");

    AddChoice("interpolator.bco",    "Bicubic interpolation");
    SetParameterDescription("interpolator.bco", "Bicubic interpolation leads to very good image quality but is slow.");

    AddParameter(ParameterType_Radius, "interpolator.bco.radius", "Radius for bicubic interpolation");
    SetParameterDescription("interpolator.bco.radius","This parameter allows to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.");
    SetDefaultParameterInt("interpolator.bco.radius", 2);

    AddChoice("interpolator.nn",     "Nearest Neighbor interpolation");
    SetParameterDescription("interpolator.nn","Nearest neighbor interpolation leads to poor image quality, but it is very fast.");

    AddChoice("interpolator.linear", "Linear interpolation");
    SetParameterDescription("interpolator.linear","Linear interpolation leads to average image quality but is quite fast");

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("inr", "QB_Toulouse_Ortho_PAN.tif");
    SetDocExampleParameterValue("inm", "QB_Toulouse_Ortho_XS.tif");
    SetDocExampleParameterValue("out", "SuperimposedXS_to_PAN.tif");
  }

  void DoUpdateParameters()
  {
    if (!HasUserValue("mode") &&
        HasValue("inr") &&
        HasValue("inm"))
      {
      FloatVectorImageType* refImage = GetParameterImage("inr");
      FloatVectorImageType* movingImage = GetParameterImage("inm");
      bool isRefPHR = false;
      bool isMovingPHR = false;

      otb::PleiadesImageMetadataInterface::Pointer phrIMI =
        otb::PleiadesImageMetadataInterface::New();
      phrIMI->SetMetaDataDictionary(refImage->GetMetaDataDictionary());
      isRefPHR = phrIMI->CanRead();

      phrIMI->SetMetaDataDictionary(movingImage->GetMetaDataDictionary());
      isMovingPHR = phrIMI->CanRead();

      if (isRefPHR && isMovingPHR)
        {
        ImageKeywordlistType kwlPan;
        ImageKeywordlistType kwlXS;

        itk::ExposeMetaData<ImageKeywordlistType>(
          refImage->GetMetaDataDictionary(),
          MetaDataKey::OSSIMKeywordlistKey,
          kwlPan);

        itk::ExposeMetaData<ImageKeywordlistType>(
          movingImage->GetMetaDataDictionary(),
          MetaDataKey::OSSIMKeywordlistKey,
          kwlXS);

        // Get geometric processing
        std::string panProcessing = kwlPan.GetMetadataByKey("support_data.processing_level");
        std::string xsProcessing = kwlXS.GetMetadataByKey("support_data.processing_level");

        if (panProcessing.compare("SENSOR") == 0 &&
            xsProcessing.compare("SENSOR") == 0)
          {
          SetParameterInt("mode",Mode_PHR);
          otbAppLogINFO("Enable the PHR mode");
          }
        }
      }
  }

  void DoExecute()
  {
    // Get the inputs
    FloatVectorImageType* refImage = GetParameterImage("inr");
    FloatVectorImageType* movingImage = GetParameterImage("inm");

    // Resample filter
    m_Resampler = ResamplerType::New();

    m_BasicResampler = BasicResamplerType::New();

    // Get Interpolator
    switch ( GetParameterInt("interpolator") )
      {
      case Interpolator_Linear:
      {
      LinInterpolatorType::Pointer interpolator = LinInterpolatorType::New();
      m_Resampler->SetInterpolator(interpolator);
      m_BasicResampler->SetInterpolator(interpolator);
      }
      break;
      case Interpolator_NNeighbor:
      {
      NNInterpolatorType::Pointer interpolator = NNInterpolatorType::New();
      m_Resampler->SetInterpolator(interpolator);
      m_BasicResampler->SetInterpolator(interpolator);
      }
      break;
      case Interpolator_BCO:
      {
      BCOInterpolatorType::Pointer interpolator = BCOInterpolatorType::New();
      interpolator->SetRadius(GetParameterInt("interpolator.bco.radius"));
      m_Resampler->SetInterpolator(interpolator);
      m_BasicResampler->SetInterpolator(interpolator);
      }
      break;
      }

    // Setup the DEM Handler
    otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");

    // Set up output image informations
    FloatVectorImageType::SpacingType spacing = refImage->GetSpacing();
    FloatVectorImageType::IndexType   start   = refImage->GetLargestPossibleRegion().GetIndex();
    FloatVectorImageType::SizeType    size    = refImage->GetLargestPossibleRegion().GetSize();
    FloatVectorImageType::PointType   origin  = refImage->GetOrigin();

    FloatVectorImageType::PixelType defaultValue;
    itk::NumericTraits<FloatVectorImageType::PixelType>::SetLength(defaultValue, movingImage->GetNumberOfComponentsPerPixel());

    switch ( GetParameterInt("mode") )
    {
    case Mode_Default:
      {
      if(IsParameterEnabled("lms"))
        {
        float defScalarSpacing = vcl_abs(GetParameterFloat("lms"));
        otbAppLogDEBUG("Generating coarse deformation field (spacing="<<defScalarSpacing<<")");
        FloatVectorImageType::SpacingType defSpacing;

        defSpacing[0] = defScalarSpacing;
        defSpacing[1] = defScalarSpacing;

        if (spacing[0]<0.0) defSpacing[0] *= -1.0;
        if (spacing[1]<0.0) defSpacing[1] *= -1.0;

        m_Resampler->SetDisplacementFieldSpacing(defSpacing);
        }

      // Setup transform through projRef and Keywordlist
      m_Resampler->SetInputKeywordList(movingImage->GetImageKeywordlist());
      m_Resampler->SetInputProjectionRef(movingImage->GetProjectionRef());

      m_Resampler->SetOutputKeywordList(refImage->GetImageKeywordlist());
      m_Resampler->SetOutputProjectionRef(refImage->GetProjectionRef());

      m_Resampler->SetInput(movingImage);

      m_Resampler->SetOutputOrigin(origin);
      m_Resampler->SetOutputSpacing(spacing);
      m_Resampler->SetOutputSize(size);
      m_Resampler->SetOutputStartIndex(start);

      m_Resampler->SetEdgePaddingValue(defaultValue);

      // Set the output image
      SetParameterOutputImage("out", m_Resampler->GetOutput());
      }
      break;
    case Mode_PHR:
      {
      // Setup a simple affine transform using PHR support data

      ImageKeywordlistType kwlPan;
      ImageKeywordlistType kwlXS;

      itk::ExposeMetaData<ImageKeywordlistType>(
        refImage->GetMetaDataDictionary(),
        MetaDataKey::OSSIMKeywordlistKey,
        kwlPan);

      itk::ExposeMetaData<ImageKeywordlistType>(
        movingImage->GetMetaDataDictionary(),
        MetaDataKey::OSSIMKeywordlistKey,
        kwlXS);

      // Compute time delta
      std::string strStartTimePan = kwlPan.GetMetadataByKey("support_data.time_range_start");
      std::string strStartTimeXS = kwlXS.GetMetadataByKey("support_data.time_range_start");

      DateTimeAdapter::Pointer startTimePan = DateTimeAdapter::New();
      DateTimeAdapter::Pointer startTimeXS = DateTimeAdapter::New();

      startTimePan->SetFromIso8601(strStartTimePan);
      startTimeXS->SetFromIso8601(strStartTimeXS);

      double timeDelta = startTimeXS->GetDeltaInSeconds(startTimePan);

      // Retrieve line period in Pan
      std::string tmpStr = kwlPan.GetMetadataByKey("support_data.line_period");
      double linePeriodPan = atof(tmpStr.c_str());

      // Retrieve column start
      tmpStr = kwlPan.GetMetadataByKey("support_data.swath_first_col");
      int colStartPan = atoi(tmpStr.c_str());
      tmpStr = kwlXS.GetMetadataByKey("support_data.swath_first_col");
      int colStartXS = atoi(tmpStr.c_str());

      // Compute shift between MS and P (in Pan pixels)
      int lineShift_MS_P =int(vcl_floor((timeDelta/(linePeriodPan/1000))  + 0.5));
      int colShift_MS_P = colStartXS*4 - colStartPan;

      // Apply the scaling
      TransformType::Pointer transform = TransformType::New();
      transform->Scale(4.0);

      // Resample filter assumes the origin is attached to the pixel center
      // in order to keep the top left corners unchanged, apply a 3/2 pixels
      // shift in each direction
      // TODO : clarify formula, the '-1.0' for columns is strange
      TransformType::OutputVectorType offset;
      offset[0] = 1.5 - (static_cast<double>(colShift_MS_P) - 1.0);
      offset[1] = 1.5 - static_cast<double>(lineShift_MS_P);
      transform->Translate(offset);

      // Invert the transform as the resampler filter expect an output-to-input
      // transform (we have computed the input-to-output transform)
      TransformType::Pointer realTransform = TransformType::New();
      transform->GetInverse(realTransform);
      m_BasicResampler->SetTransform(realTransform);

      m_BasicResampler->SetInput(movingImage);

      m_BasicResampler->SetOutputOrigin(origin);
      m_BasicResampler->SetOutputSpacing(spacing);
      m_BasicResampler->SetOutputSize(size);
      m_BasicResampler->SetOutputStartIndex(start);

      m_BasicResampler->SetEdgePaddingValue(defaultValue);

      // Set the output image
      SetParameterOutputImage("out", m_BasicResampler->GetOutput());

      // DEBUG
      otbAppLogINFO("Panchro start (in s) : "<< startTimePan->GetSeconds());
      otbAppLogINFO("MS start (in s)      : "<< startTimeXS->GetSeconds());
      otbAppLogINFO("Time delta (in s)    : "<< timeDelta);
      otbAppLogINFO("Line period P (in ms): "<< linePeriodPan);
      otbAppLogINFO("Line shift (in pix)  : "<< lineShift_MS_P);
      otbAppLogINFO("Col shift (in pix)   : "<< colShift_MS_P);
      }
      break;
    default:
      {
      otbAppLogWARNING("Unknown mode");
      }
      break;
    }

  }

  ResamplerType::Pointer           m_Resampler;

  BasicResamplerType::Pointer      m_BasicResampler;

};

} // end namespace Wrapper
} // end namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::Superimpose)

<commit_msg>ENH: OTB-626 : use same formula as in fusion_phr.py, clean code<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.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbGenericRSResampleImageFilter.h"

#include "itkLinearInterpolateImageFunction.h"
#include "otbBCOInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"

#include "otbPleiadesImageMetadataInterface.h"

#include "itkScalableAffineTransform.h"

// Elevation handler
#include "otbWrapperElevationParametersHandler.h"

#include "otbDateTimeAdapter.h"
#include "otbStreamingResampleImageFilter.h"

namespace otb
{

enum
{
  Interpolator_BCO,
  Interpolator_NNeighbor,
  Interpolator_Linear
};

enum
{
  Mode_Default,
  Mode_PHR
};

namespace Wrapper
{

class Superimpose : public Application
{
public:
  /** Standard class typedefs. */
  typedef Superimpose         Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(Superimpose, Application);

  typedef unsigned short int PixelType;

  typedef itk::LinearInterpolateImageFunction
    <FloatVectorImageType,
     double>                                                      LinInterpolatorType;
  typedef itk::NearestNeighborInterpolateImageFunction
    <FloatVectorImageType,
     double>                                                      NNInterpolatorType;
  typedef otb::BCOInterpolateImageFunction
    <FloatVectorImageType>                                        BCOInterpolatorType;

  typedef otb::GenericRSResampleImageFilter<FloatVectorImageType,
                                            FloatVectorImageType>  ResamplerType;

  typedef itk::ScalableAffineTransform<double, 2>                 TransformType;

  typedef otb::StreamingResampleImageFilter
    <FloatVectorImageType,
     FloatVectorImageType>                                        BasicResamplerType;

private:
  void DoInit()
  {
    SetName("Superimpose");
    SetDescription("Using available image metadata, project one image onto another one");

    // Documentation
    SetDocName("Superimpose sensor");
    SetDocLongDescription("This application performs the projection of an image into the geometry of another one.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Geometry);
    AddDocTag("Superimposition");

    AddParameter(ParameterType_InputImage,   "inr",   "Reference input");
    SetParameterDescription("inr","The input reference image.");
    AddParameter(ParameterType_InputImage,   "inm",   "The image to reproject");
    SetParameterDescription("inm","The image to reproject into the geometry of the reference input.");

    // Elevation
    ElevationParametersHandler::AddElevationParameters(this, "elev");

    AddParameter(ParameterType_Float,        "lms",   "Spacing of the deformation field");
    SetParameterDescription("lms","Generate a coarser deformation field with the given spacing");
    SetDefaultParameterFloat("lms", 4.);
    MandatoryOff("lms");

    AddParameter(ParameterType_OutputImage,  "out",   "Output image");
    SetParameterDescription("out","Output reprojected image.");

    // Superposition mode
    AddParameter(ParameterType_Choice,"mode", "Mode");
    SetParameterDescription("mode", "Superimposition mode");

    AddChoice("mode.default", "Default mode");
    SetParameterDescription("mode.default", "Default superimposition mode : "
      "uses any projection reference or sensor model found in the images");

    AddChoice("mode.phr", "Pleiades mode");
    SetParameterDescription("mode.phr", "Pleiades superimposition mode, "
      "designed for the case of a P+XS bundle in SENSOR geometry. It uses"
      " a simple transform : a scaling and a residual translation.");

    // Interpolators
    AddParameter(ParameterType_Choice,   "interpolator", "Interpolation");
    SetParameterDescription("interpolator","This group of parameters allows to define how the input image will be interpolated during resampling.");

    AddChoice("interpolator.bco",    "Bicubic interpolation");
    SetParameterDescription("interpolator.bco", "Bicubic interpolation leads to very good image quality but is slow.");

    AddParameter(ParameterType_Radius, "interpolator.bco.radius", "Radius for bicubic interpolation");
    SetParameterDescription("interpolator.bco.radius","This parameter allows to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.");
    SetDefaultParameterInt("interpolator.bco.radius", 2);

    AddChoice("interpolator.nn",     "Nearest Neighbor interpolation");
    SetParameterDescription("interpolator.nn","Nearest neighbor interpolation leads to poor image quality, but it is very fast.");

    AddChoice("interpolator.linear", "Linear interpolation");
    SetParameterDescription("interpolator.linear","Linear interpolation leads to average image quality but is quite fast");

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("inr", "QB_Toulouse_Ortho_PAN.tif");
    SetDocExampleParameterValue("inm", "QB_Toulouse_Ortho_XS.tif");
    SetDocExampleParameterValue("out", "SuperimposedXS_to_PAN.tif");
  }

  void DoUpdateParameters()
  {
    if (!HasUserValue("mode") &&
        GetParameterInt("mode") == Mode_Default &&
        HasValue("inr") &&
        HasValue("inm"))
      {
      FloatVectorImageType* refImage = GetParameterImage("inr");
      FloatVectorImageType* movingImage = GetParameterImage("inm");
      bool isRefPHR = false;
      bool isMovingPHR = false;

      otb::PleiadesImageMetadataInterface::Pointer phrIMI =
        otb::PleiadesImageMetadataInterface::New();
      phrIMI->SetMetaDataDictionary(refImage->GetMetaDataDictionary());
      isRefPHR = phrIMI->CanRead();

      phrIMI->SetMetaDataDictionary(movingImage->GetMetaDataDictionary());
      isMovingPHR = phrIMI->CanRead();

      if (isRefPHR && isMovingPHR)
        {
        ImageKeywordlist kwlPan;
        ImageKeywordlist kwlXS;

        itk::ExposeMetaData<ImageKeywordlist>(
          refImage->GetMetaDataDictionary(),
          MetaDataKey::OSSIMKeywordlistKey,
          kwlPan);

        itk::ExposeMetaData<ImageKeywordlist>(
          movingImage->GetMetaDataDictionary(),
          MetaDataKey::OSSIMKeywordlistKey,
          kwlXS);

        // Get geometric processing
        std::string panProcessing = kwlPan.GetMetadataByKey("support_data.processing_level");
        std::string xsProcessing = kwlXS.GetMetadataByKey("support_data.processing_level");

        if (panProcessing.compare("SENSOR") == 0 &&
            xsProcessing.compare("SENSOR") == 0)
          {
          SetParameterInt("mode",Mode_PHR);
          }
        }
      }
  }

  void DoExecute()
  {
    // Get the inputs
    FloatVectorImageType* refImage = GetParameterImage("inr");
    FloatVectorImageType* movingImage = GetParameterImage("inm");

    // Resample filter
    m_Resampler = ResamplerType::New();

    m_BasicResampler = BasicResamplerType::New();

    // Get Interpolator
    switch ( GetParameterInt("interpolator") )
      {
      case Interpolator_Linear:
      {
      LinInterpolatorType::Pointer interpolator = LinInterpolatorType::New();
      m_Resampler->SetInterpolator(interpolator);
      m_BasicResampler->SetInterpolator(interpolator);
      }
      break;
      case Interpolator_NNeighbor:
      {
      NNInterpolatorType::Pointer interpolator = NNInterpolatorType::New();
      m_Resampler->SetInterpolator(interpolator);
      m_BasicResampler->SetInterpolator(interpolator);
      }
      break;
      case Interpolator_BCO:
      {
      BCOInterpolatorType::Pointer interpolator = BCOInterpolatorType::New();
      interpolator->SetRadius(GetParameterInt("interpolator.bco.radius"));
      m_Resampler->SetInterpolator(interpolator);
      m_BasicResampler->SetInterpolator(interpolator);
      }
      break;
      }

    // Setup the DEM Handler
    otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");

    // Set up output image informations
    FloatVectorImageType::SpacingType spacing = refImage->GetSpacing();
    FloatVectorImageType::IndexType   start   = refImage->GetLargestPossibleRegion().GetIndex();
    FloatVectorImageType::SizeType    size    = refImage->GetLargestPossibleRegion().GetSize();
    FloatVectorImageType::PointType   origin  = refImage->GetOrigin();

    FloatVectorImageType::PixelType defaultValue;
    itk::NumericTraits<FloatVectorImageType::PixelType>::SetLength(defaultValue, movingImage->GetNumberOfComponentsPerPixel());

    switch ( GetParameterInt("mode") )
    {
    case Mode_Default:
      {
      if(IsParameterEnabled("lms"))
        {
        float defScalarSpacing = vcl_abs(GetParameterFloat("lms"));
        otbAppLogDEBUG("Generating coarse deformation field (spacing="<<defScalarSpacing<<")");
        FloatVectorImageType::SpacingType defSpacing;

        defSpacing[0] = defScalarSpacing;
        defSpacing[1] = defScalarSpacing;

        if (spacing[0]<0.0) defSpacing[0] *= -1.0;
        if (spacing[1]<0.0) defSpacing[1] *= -1.0;

        m_Resampler->SetDisplacementFieldSpacing(defSpacing);
        }

      // Setup transform through projRef and Keywordlist
      m_Resampler->SetInputKeywordList(movingImage->GetImageKeywordlist());
      m_Resampler->SetInputProjectionRef(movingImage->GetProjectionRef());

      m_Resampler->SetOutputKeywordList(refImage->GetImageKeywordlist());
      m_Resampler->SetOutputProjectionRef(refImage->GetProjectionRef());

      m_Resampler->SetInput(movingImage);

      m_Resampler->SetOutputOrigin(origin);
      m_Resampler->SetOutputSpacing(spacing);
      m_Resampler->SetOutputSize(size);
      m_Resampler->SetOutputStartIndex(start);

      m_Resampler->SetEdgePaddingValue(defaultValue);

      // Set the output image
      SetParameterOutputImage("out", m_Resampler->GetOutput());
      }
      break;
    case Mode_PHR:
      {
      otbAppLogINFO("Using the PHR mode");

      // Setup a simple affine transform using PHR support data
      ImageKeywordlist kwlPan;
      ImageKeywordlist kwlXS;

      itk::ExposeMetaData<ImageKeywordlist>(
        refImage->GetMetaDataDictionary(),
        MetaDataKey::OSSIMKeywordlistKey,
        kwlPan);

      itk::ExposeMetaData<ImageKeywordlist>(
        movingImage->GetMetaDataDictionary(),
        MetaDataKey::OSSIMKeywordlistKey,
        kwlXS);

      // Compute time delta
      std::string strStartTimePan = kwlPan.GetMetadataByKey("support_data.time_range_start");
      std::string strStartTimeXS = kwlXS.GetMetadataByKey("support_data.time_range_start");

      DateTimeAdapter::Pointer startTimePan = DateTimeAdapter::New();
      DateTimeAdapter::Pointer startTimeXS = DateTimeAdapter::New();

      startTimePan->SetFromIso8601(strStartTimePan);
      startTimeXS->SetFromIso8601(strStartTimeXS);

      double timeDelta = startTimeXS->GetDeltaInSeconds(startTimePan);

      // Retrieve line period in Pan
      std::string tmpStr = kwlPan.GetMetadataByKey("support_data.line_period");
      double linePeriodPan = atof(tmpStr.c_str());

      // Retrieve column start
      tmpStr = kwlPan.GetMetadataByKey("support_data.swath_first_col");
      int colStartPan = atoi(tmpStr.c_str());
      tmpStr = kwlXS.GetMetadataByKey("support_data.swath_first_col");
      int colStartXS = atoi(tmpStr.c_str());

      // Compute shift between MS and P (in Pan pixels)
      int lineShift_MS_P =int(vcl_floor((timeDelta/(linePeriodPan/1000))  + 0.5));
      int colShift_MS_P = colStartXS*4 - colStartPan - 4;

      // Apply the scaling
      TransformType::Pointer transform = TransformType::New();
      transform->Scale(4.0);

      // Resample filter assumes the origin is attached to the pixel center
      // in order to keep the top left corners unchanged, apply a 3/2 pixels
      // shift in each direction
      TransformType::OutputVectorType offset;
      offset[0] = 1.5 + static_cast<double>(colShift_MS_P);
      offset[1] = 1.5 + static_cast<double>(lineShift_MS_P);
      transform->Translate(offset);

      // Invert the transform as the resampler filter expect an output-to-input
      // transform (we have computed the input-to-output transform)
      TransformType::Pointer realTransform = TransformType::New();
      transform->GetInverse(realTransform);
      m_BasicResampler->SetTransform(realTransform);

      m_BasicResampler->SetInput(movingImage);

      m_BasicResampler->SetOutputOrigin(origin);
      m_BasicResampler->SetOutputSpacing(spacing);
      m_BasicResampler->SetOutputSize(size);
      m_BasicResampler->SetOutputStartIndex(start);

      m_BasicResampler->SetEdgePaddingValue(defaultValue);

      // Set the output image
      SetParameterOutputImage("out", m_BasicResampler->GetOutput());

      otbAppLogINFO("Line shift (in pix)  : "<< lineShift_MS_P);
      otbAppLogINFO("Col shift (in pix)   : "<< colShift_MS_P);
      }
      break;
    default:
      {
      otbAppLogWARNING("Unknown mode");
      }
      break;
    }

  }

  ResamplerType::Pointer           m_Resampler;

  BasicResamplerType::Pointer      m_BasicResampler;

};

} // end namespace Wrapper
} // end namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::Superimpose)

<|endoftext|>


<commit_before>

#include "json_wrapper.h"
#include <sstream>

using namespace std;

class TestClass : public json::CJSONValueObject<TestClass>  // inherit the JSON Object for file parsing.
{
    public:
        TestClass() : CJSONValueObject("TestClass", this), testInt(0), testString("") { }

        TestClass(int i, string s) : CJSONValueObject("TestClass", this), testInt(i), testString(s) {}

        TestClass( const TestClass& src) : CJSONValueObject("TestClass", this)
        {
            cout << "copy called"<< endl;
            CopyFrom(src);
            SetupJSONObject();
        }

        ~TestClass() { }//cout << "Destryoing TestClass object" << endl; Print(); }

        void SetupJSONObject()
        {
            //cout << "TestClass::SetupJSONObject"<<endl;
            AddIntegerValue("obj_test_int", &testInt);
            AddStringValue("obj_test_string", &testString);
        }

        void Print()
        {
            cout <<" int: " << testInt << endl;
            cout <<" string: " << testString << endl;

        }

        const int& getint() const { return testInt; }
        const string& getstring() const { return testString; }

        TestClass& CopyFrom(const TestClass& src)
        {
            testInt = src.getint();
            testString = src.getstring();
            return *this;
        }
        TestClass& operator=(const TestClass& src) { return CopyFrom(src); }
    private:
        int     testInt;
        string  testString;
};

class tabular : public json::CJSONValueObject<tabular>  // inherit the JSON Object for file parsing.
{
    public:
        tabular() : CJSONValueObject("indent", this)
        {
            length = 0;
            bUseSpace = false;

        }
        ~tabular()
        {
            for(size_t i = 0; i < vec.size(); i++)
            {
                if( vec[i] )
                    delete vec[i];
                vec[i] = NULL;
            }
            vec.clear();

//            for(size_t i = 0; i < vec2.size(); i++)
//                delete vec2[i];
//            vec2.clear();
        }

        void SetupJSONObject() // All the code you have to add to parse the file for this object!!!!
        {
            //cout << "tabular::SetupJSONObject"<<endl;
            this->AddIntegerValue("length", &length);
            this->AddBoolValue("use_space", &bUseSpace);

            //cout << "Checkpoint 1" << endl;
            // ok there are a few template parameters.
            AddNameValuePair<   std::vector<int*>,
                                json::CJSONValueArray<  int*,
                                                        json::CJSONValuePointer<    int,
                                                                                json::CJSONValueInt > > >("IntPointerArray", &vec);
        #ifdef c_plus_plus_11
            //cout << "Checkpoint 2" << endl;
            AddNameValuePair<   std::vector< std::shared_ptr<TestClass> >,
                                json::CJSONValueArray<  std::shared_ptr<TestClass>,
                                                        json::CJSONValueSmartPointer<   TestClass,
                                                                                std::shared_ptr,
                                                                                json::CJSONValueObject<TestClass> > > >("ObjectPointerArray", &vec2);

        #endif

        }

        void AllocateSomeMem()
        {
            char str[12] = "test_string";
            for ( size_t i = 0; i < 10; i++)
            {
                int* pInt = new int;
                *pInt = int(i);
                vec.push_back(pInt);
        #ifdef c_plus_plus_11
                std::shared_ptr<TestClass> pTest( new TestClass(i, string(&str[i])));
                vec2.push_back(pTest);
        #endif
            }
        }

        void Print()
        {
            fprintf(stdout, "length = %i, use_space = %s \n", length, (bUseSpace ? "true" : "false"));
        }
        void SetLength(size_t i ){length = int(i);}
    private:
        int                     length;
        bool                    bUseSpace;
        vector<int*>            vec;
    #ifdef c_plus_plus_11
        vector< std::shared_ptr<TestClass> >      vec2;
    #endif

};

class test : public json::CJSONValueObject<test>
{
    public:
        test(): CJSONValueObject("test", this) { cout << &testObjVec << endl;}
        test(string path) : CJSONValueObject("", this) // root object has no name. (see parser comment)
        {
            SetupJSONObject();
            LoadFromFile(path);
        }
        ~test() {
//            cout << "destroying test" << endl;
//            cout << "encoding:" << &encoding << endl;
//            cout << "plugins:" << &plugins << endl;
//            cout << "tabConfig:" << &tabConfig << endl;
//            cout << "testObjVec:" << &testObjVec << endl;
          }

    // Code to parse from file!!!
        void SetupJSONObject()
        {
            this->AddStringValue("encoding", &encoding);
            this->AddStringArrayValue("plug-ins", &plugins);
            tabConfig.SetupJSONObject();
            this->AddObjectValue("indent", &tabConfig);

            AddNameValuePair<   std::vector< TestClass >,
                                json::CJSONValueArray<  TestClass,
                                                        json::CJSONValueObject<TestClass> > > ("ObjectArray", &testObjVec);
        }

        bool LoadFromFile(const string& Path)
        {
            //cout << "test::LoadFromFile"<<endl;
            json::CJSONParser json;
            json.LoadFromFile(Path);    // opens the JSON file and loads the data into buffer.

            return json.ParseObject(this); // Parses all the data for this object.
        }
        bool DumpToFile(const string& Path)
        {
            json::CJSONParser json;
            return json.DumpObjectToFile(Path, this);
        }

    // End code to parse file.

        void Print()
        {
            printf("Encoding = %s \nplugins : \n", encoding.c_str());
            for(size_t i = 0; i < plugins.size(); i++)
            {
                printf("\t %s \n", plugins[i].c_str());
            }
            tabConfig.Print();
            cout << "printing " << &testObjVec << endl;
            for(size_t i = 0; i < testObjVec.size(); i++)
            {
                testObjVec[i].Print();
            }
            cout << "printing out " << &testObjVec << endl;
        }
        void AllocateSomeMem()
        {
            tabConfig.AllocateSomeMem();
            for(size_t i = 0; i < 2; i++)
            {
                stringstream ss;
                ss << i;
                string s;
                ss>>s;
                TestClass t(i, s);
                testObjVec.push_back(t);
            }
        }

        void SetTabSpace(size_t i)  { tabConfig.SetLength(i); }

    private:
        string              encoding;
        vector<string>      plugins;
        tabular             tabConfig;
        vector<TestClass>   testObjVec;

};

int main(int argc, const char * argv[])
{
    test newtest("test.json");
    newtest.AllocateSomeMem();
    newtest.Print();
    if(!newtest.DumpToFile("dump_smart_pointer.json"))
    {
        cout << "Error dumping the file." << endl;
    }

    test updatetest("update_test.json.sol");
    updatetest.SetTabSpace(10);
    updatetest.SaveToFile("update_test.json");

#ifdef c_plus_plus_11                       // c++11 specific testing
//    std::shared_ptr<int> pShared(new int);
//    std::unique_ptr<int> pUnique(new int);
//
//    json::CJSONValueSmartPointer<int, std::shared_ptr, json::CJSONValueInt> jsonShared("SharedPtr", &pShared);
//    json::CJSONValueSmartPointer<int, std::unique_ptr, json::CJSONValueInt> jsonUnique("UniquePtr", &pUnique);
//
//
//
//    tuple<int, int, double> t1(1, 2, 3.0);
//    tuple<json::CJSONValueInt, json::CJSONValueInt, json::CJSONValueDouble> t2( json::CJSONValueInt("Dummy", nullptr),
//                                                                                json::CJSONValueInt("Dummy", nullptr),
//                                                                                json::CJSONValueDouble("Dummy", nullptr));
//
//    json::CJSONValueTuple<      tuple<int, int, double>,    // Templates galore....
//                                json::CJSONValueInt, json::CJSONValueInt, json::CJSONValueDouble> mytuple("test", &t1);
//    json_t* pRet = NULL;
//    mytuple.Dump(pRet);
//    json_decref(pRet);
#endif // end c++11 specific testing

    test parseTest;
    parseTest.SetupJSONObject();
    parseTest.LoadFromFile("dump_smart_pointer.json");

    parseTest.Print();

    cout << "Exiting program" << endl;
    return 0;
}

<commit_msg>trivial changes<commit_after>

#include "json_wrapper.h"
#include <sstream>

using namespace std;

class TestClass : public json::CJSONValueObject<TestClass>  // inherit the JSON Object for file parsing.
{
    public:
        TestClass() : CJSONValueObject("TestClass", this), testInt(0), testString("") { }

        TestClass(int i, string s) : CJSONValueObject("TestClass", this), testInt(i), testString(s) {}

        TestClass( const TestClass& src) : CJSONValueObject("TestClass", this)
        {
            cout << "copy called"<< endl;
            CopyFrom(src);
            SetupJSONObject();
        }

        ~TestClass() { }//cout << "Destryoing TestClass object" << endl; Print(); }

        void SetupJSONObject()
        {
            //cout << "TestClass::SetupJSONObject"<<endl;
            AddIntegerValue("obj_test_int", &testInt);
            AddStringValue("obj_test_string", &testString);
        }

        void Print()
        {
            cout <<" int: " << testInt << endl;
            cout <<" string: " << testString << endl;

        }

        const int& getint() const { return testInt; }
        const string& getstring() const { return testString; }

        TestClass& CopyFrom(const TestClass& src)
        {
            testInt = src.getint();
            testString = src.getstring();
            return *this;
        }
        TestClass& operator=(const TestClass& src) { return CopyFrom(src); }
    private:
        int     testInt;
        string  testString;
};

class tabular : public json::CJSONValueObject<tabular>  // inherit the JSON Object for file parsing.
{
    public:
        tabular() : CJSONValueObject("indent", this)
        {
            length = 0;
            bUseSpace = false;

        }
        ~tabular()
        {
            for(size_t i = 0; i < vec.size(); i++)
            {
                if( vec[i] )
                    delete vec[i];
                vec[i] = NULL;
            }
            vec.clear();

//            for(size_t i = 0; i < vec2.size(); i++)
//                delete vec2[i];
//            vec2.clear();
        }

        void SetupJSONObject() // All the code you have to add to parse the file for this object!!!!
        {
            //cout << "tabular::SetupJSONObject"<<endl;
            this->AddIntegerValue("length", &length);
            this->AddBoolValue("use_space", &bUseSpace);

            //cout << "Checkpoint 1" << endl;
            // ok there are a few template parameters.
            AddNameValuePair<   std::vector<int*>,
                                json::CJSONValueArray<  int*,
                                                        json::CJSONValuePointer<    int,
                                                                                json::CJSONValueInt > > >("IntPointerArray", &vec);
        #ifdef c_plus_plus_11
            //cout << "Checkpoint 2" << endl;
            AddNameValuePair<   std::vector< std::shared_ptr<TestClass> >,
                                json::CJSONValueArray<  std::shared_ptr<TestClass>,
                                                        json::CJSONValueSmartPointer<   TestClass,
                                                                                std::shared_ptr,
                                                                                json::CJSONValueObject<TestClass> > > >("ObjectPointerArray", &vec2);

        #endif

        }

        void AllocateSomeMem()
        {
            char str[12] = "test_string";
            for ( size_t i = 0; i < 10; i++)
            {
                int* pInt = new int;
                *pInt = int(i);
                vec.push_back(pInt);
        #ifdef c_plus_plus_11
                std::shared_ptr<TestClass> pTest( new TestClass(i, string(&str[i])));
                vec2.push_back(pTest);
        #endif
            }
        }

        void Print()
        {
            fprintf(stdout, "length = %i, use_space = %s \n", length, (bUseSpace ? "true" : "false"));
        }
        void SetLength(size_t i ){length = int(i);}
    private:
        int                     length;
        bool                    bUseSpace;
        vector<int*>            vec;
    #ifdef c_plus_plus_11
        vector< std::shared_ptr<TestClass> >      vec2;
    #endif

};

class test : public json::CJSONValueObject<test>
{
    public:
        test(): CJSONValueObject("test", this) { cout << &testObjVec << endl;}
        test(string path) : CJSONValueObject("", this) // root object has no name. (see parser comment)
        {
            SetupJSONObject();
            LoadFromFile(path);
        }
        ~test() {
//            cout << "destroying test" << endl;
//            cout << "encoding:" << &encoding << endl;
//            cout << "plugins:" << &plugins << endl;
//            cout << "tabConfig:" << &tabConfig << endl;
//            cout << "testObjVec:" << &testObjVec << endl;
          }

    // Code to parse from file!!!
        void SetupJSONObject()
        {
            this->AddStringValue("encoding", &encoding);
            this->AddStringArrayValue("plug-ins", &plugins);
            tabConfig.SetupJSONObject();
            this->AddObjectValue("indent", &tabConfig);
            typedef json::CJSONValueArray<  TestClass, json::CJSONValueObject<TestClass> > testClassJsonArrayParser;
            AddNameValuePair< std::vector< TestClass >, testClassJsonArrayParser > ("ObjectArray", &testObjVec);
        }

        bool LoadFromFile(const string& Path)
        {
            //cout << "test::LoadFromFile"<<endl;
            json::CJSONParser json;
            json.LoadFromFile(Path);    // opens the JSON file and loads the data into buffer.

            return json.ParseObject(this); // Parses all the data for this object.
        }
        bool DumpToFile(const string& Path)
        {
            json::CJSONParser json;
            return json.DumpObjectToFile(Path, this);
        }

    // End code to parse file.

        void Print()
        {
            printf("Encoding = %s \nplugins : \n", encoding.c_str());
            for(size_t i = 0; i < plugins.size(); i++)
            {
                printf("\t %s \n", plugins[i].c_str());
            }
            tabConfig.Print();
            cout << "printing " << &testObjVec << endl;
            for(size_t i = 0; i < testObjVec.size(); i++)
            {
                testObjVec[i].Print();
            }
            cout << "printing out " << &testObjVec << endl;
        }
        void AllocateSomeMem()
        {
            tabConfig.AllocateSomeMem();
            for(size_t i = 0; i < 2; i++)
            {
                stringstream ss;
                ss << i;
                string s;
                ss>>s;
                TestClass t(i, s);
                testObjVec.push_back(t);
            }
        }

        void SetTabSpace(size_t i)  { tabConfig.SetLength(i); }

    private:
        string              encoding;
        vector<string>      plugins;
        tabular             tabConfig;
        vector<TestClass>   testObjVec;

};

int main(int argc, const char * argv[])
{
    test newtest("test.json");
    newtest.AllocateSomeMem();
    newtest.Print();
    if(!newtest.DumpToFile("dump_smart_pointer.json"))
    {
        cout << "Error dumping the file." << endl;
    }

    test updatetest("update_test.json.sol");
    updatetest.SetTabSpace(10);
    updatetest.SaveToFile("update_test.json");

#ifdef c_plus_plus_11                       // c++11 specific testing
//    std::shared_ptr<int> pShared(new int);
//    std::unique_ptr<int> pUnique(new int);
//
//    json::CJSONValueSmartPointer<int, std::shared_ptr, json::CJSONValueInt> jsonShared("SharedPtr", &pShared);
//    json::CJSONValueSmartPointer<int, std::unique_ptr, json::CJSONValueInt> jsonUnique("UniquePtr", &pUnique);
//
//
//
//    tuple<int, int, double> t1(1, 2, 3.0);
//    tuple<json::CJSONValueInt, json::CJSONValueInt, json::CJSONValueDouble> t2( json::CJSONValueInt("Dummy", nullptr),
//                                                                                json::CJSONValueInt("Dummy", nullptr),
//                                                                                json::CJSONValueDouble("Dummy", nullptr));
//
//    json::CJSONValueTuple<      tuple<int, int, double>,    // Templates galore....
//                                json::CJSONValueInt, json::CJSONValueInt, json::CJSONValueDouble> mytuple("test", &t1);
//    json_t* pRet = NULL;
//    mytuple.Dump(pRet);
//    json_decref(pRet);
#endif // end c++11 specific testing

    test parseTest;
    parseTest.SetupJSONObject();
    parseTest.LoadFromFile("dump_smart_pointer.json");

    parseTest.Print();

    cout << "Exiting program" << endl;
    return 0;
}

<|endoftext|>


<commit_before>// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/

#pragma once

#import "AKSoundpipeKernel.hpp"
#import "ParameterRamper.hpp"

#import <AudioKit/AudioKit-Swift.h>

extern "C" {
#include "soundpipe.h"
#include "md5.h"
#include "test.h"
}

class AKTesterDSPKernel : public AKDSPKernel, public AKBuffered {
public:
    // MARK: Member Functions

    AKTesterDSPKernel() {}

    void init(int channelCount, double sampleRate) override {
        AKDSPKernel::init(channelCount, sampleRate);

        sp_create(&sp);
        sp_srand(sp, 12345);
    }

    void setSamples(UInt32 numberOfSamples)  {
        totalSamples = numberOfSamples;
        sp_test_create(&sp_test, numberOfSamples);
    }

    NSString *getMD5() {
        md5 = [@"" cStringUsingEncoding:NSUTF8StringEncoding];
        sp_test_compare(sp_test, md5);
        return [NSString stringWithCString:sp_test->md5 encoding:NSUTF8StringEncoding];
    }
    int getSamples() {
        return samples;
    }

    void start() {
        started = true;
    }

    void stop() {
        started = false;
    }

    void destroy() {
        sp_test_destroy(&sp_test);
    }

    void reset() {
    }

    void setParameter(AUParameterAddress address, AUValue value) {
        switch (address) {
        }
    }

    AUValue getParameter(AUParameterAddress address) {
        switch (address) {
            default: return 0.0f;
        }
    }

    void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
        switch (address) {
        }
    }

    void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {
        // For each sample.

        for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {

            int frameOffset = int(frameIndex + bufferOffset);

            for (int channel = 0; channel < channels; ++channel) {
                float *in  = (float *)inBufferListPtr->mBuffers[channel].mData  + frameOffset;
                float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;
                if (started && samples < totalSamples) {
                    sp_test_add_sample(sp_test, (SPFLOAT)*in);
                    samples++;
                }
                // Suppress output
                *out = 0;
            }
        }
    }

    // MARK: Member Variables

private:

    sp_data *sp = nil;
    sp_test *sp_test = nil;
    UInt32 samples = 0;
    UInt32 totalSamples = 0;
    const char *md5;

public:
    bool started = true;
};

<commit_msg>Don't use interface header.<commit_after>// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/

#pragma once

#import "AKSoundpipeKernel.hpp"
#import "ParameterRamper.hpp"

extern "C" {
#include "soundpipe.h"
#include "md5.h"
#include "test.h"
}

class AKTesterDSPKernel : public AKDSPKernel, public AKBuffered {
public:
    // MARK: Member Functions

    AKTesterDSPKernel() {}

    void init(int channelCount, double sampleRate) override {
        AKDSPKernel::init(channelCount, sampleRate);

        sp_create(&sp);
        sp_srand(sp, 12345);
    }

    void setSamples(UInt32 numberOfSamples)  {
        totalSamples = numberOfSamples;
        sp_test_create(&sp_test, numberOfSamples);
    }

    NSString *getMD5() {
        md5 = [@"" cStringUsingEncoding:NSUTF8StringEncoding];
        sp_test_compare(sp_test, md5);
        return [NSString stringWithCString:sp_test->md5 encoding:NSUTF8StringEncoding];
    }
    int getSamples() {
        return samples;
    }

    void start() {
        started = true;
    }

    void stop() {
        started = false;
    }

    void destroy() {
        sp_test_destroy(&sp_test);
    }

    void reset() {
    }

    void setParameter(AUParameterAddress address, AUValue value) {
        switch (address) {
        }
    }

    AUValue getParameter(AUParameterAddress address) {
        switch (address) {
            default: return 0.0f;
        }
    }

    void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
        switch (address) {
        }
    }

    void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {
        // For each sample.

        for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {

            int frameOffset = int(frameIndex + bufferOffset);

            for (int channel = 0; channel < channels; ++channel) {
                float *in  = (float *)inBufferListPtr->mBuffers[channel].mData  + frameOffset;
                float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;
                if (started && samples < totalSamples) {
                    sp_test_add_sample(sp_test, (SPFLOAT)*in);
                    samples++;
                }
                // Suppress output
                *out = 0;
            }
        }
    }

    // MARK: Member Variables

private:

    sp_data *sp = nil;
    sp_test *sp_test = nil;
    UInt32 samples = 0;
    UInt32 totalSamples = 0;
    const char *md5;

public:
    bool started = true;
};

<|endoftext|>


<commit_before>/* Copyright © 2001-2019, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

This program 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 Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE equipment_test

#include <string>
#include <vector>
#include <map>

#include <boost/range/algorithm/sort.hpp>
#include <boost/test/unit_test.hpp>

#include "ed/build_helper.h"
#include "equipment/equipment_api.h"
#include "ptreferential/ptreferential.h"
#include "utils/logger.h"
#include "type/type.h"
#include "type/pt_data.h"
#include "tests/utils_test.h"

using namespace navitia;
using std::set;
using std::string;
using std::map;
using boost::posix_time::time_period;

struct logger_initialized {
    logger_initialized() { navitia::init_logger(); }
};
BOOST_GLOBAL_FIXTURE( logger_initialized );

namespace {

class Test_fixture {
public:
    ed::builder b;
    navitia::PbCreator pb_creator;
    const type::Data& data;

    Test_fixture(): b("20190101"), data(*b.data) {

        b.sa("sa1")("stop1", {{"CodeType1", {"code1", "code2"}}} );
        b.sa("sa2")("stop2", {{"CodeType3", {"code5"}}} );
        b.sa("sa3")("stop3", {{"CodeType1", {"code6"}}} );
        b.sa("sa4")("stop4", {});
        b.sa("sa5")("stop5", {{"CodeType3", {"code7"}}} );
        b.sa("sa6")("stop6", {{"CodeType1", {"code8"}}} );

        b.vj("A")("stop1", 8000,8050)("stop2", 8200,8250)("stop3", 9000,9050);
        b.vj("B")("stop4", 8000,8050)("stop5", 8200,8250)("stop6", 9000,9050);
        b.make();

        const ptime since = "20190101T000000"_dt;
        const ptime until = "21190101T000000"_dt;
        pb_creator.init(&data, since, time_period(since, until));
    }
};

BOOST_FIXTURE_TEST_CASE(test_stop_point_codes_creation, Test_fixture) {

    type::Indexes idx = ptref::make_query(nt::Type_e::StopPoint,
                        "(stop_point.has_code_type(CodeType1))",
                        data);

    set<string> stop_points_uris = get_uris<type::StopPoint>(idx, data);

    BOOST_CHECK_EQUAL(stop_points_uris.size(), 3);
    BOOST_CHECK_EQUAL_RANGE(stop_points_uris, (set<string>{"stop1", "stop3", "stop6"}));
}

BOOST_FIXTURE_TEST_CASE(test_stop_area_query, Test_fixture) {

    type::Indexes idx = ptref::make_query(nt::Type_e::StopArea,
                        "(stop_point.has_code_type(CodeType1))",
                        data);

    set<string> stop_area_uris = get_uris<type::StopArea>(idx, data);

    BOOST_CHECK_EQUAL(stop_area_uris.size(), 3);
    BOOST_CHECK_EQUAL_RANGE(stop_area_uris, (set<string>{"sa1", "sa3", "sa6"}));
}

BOOST_FIXTURE_TEST_CASE(test_stop_area_per_line_query, Test_fixture) {

    type::Indexes idx = ptref::make_query(nt::Type_e::StopArea,
                        "(line.uri=A and stop_point.has_code_type(CodeType1))",
                        data);

    set<string> stop_area_uris = get_uris<type::StopArea>(idx, data);

    BOOST_CHECK_EQUAL(stop_area_uris.size(), 2);
    BOOST_CHECK_EQUAL_RANGE(stop_area_uris, (set<string>{"sa1", "sa3"}));
}

BOOST_FIXTURE_TEST_CASE(equipment_report_get_lines, Test_fixture) {
    auto filter = "stop_point.has_code_type(CodeType1)";
    auto sa_per_line = equipment::get_stop_areas_per_line(data, filter);

    // Convert result from object pointers to uris
    map<string, set<string>> sa_per_line_uris;
    for(const auto & line : sa_per_line) {
        set<string> sa_uris;
        for(const auto & sa : line.second) { sa_uris.insert(sa->uri); }
        sa_per_line_uris[line.first->uri] = sa_uris;
    }

    map<string, set<string>> expected_uris {
        {"A", {"sa1", "sa3"}},
        {"B", {"sa6"}},
    };
    BOOST_CHECK_EQUAL_RANGE(sa_per_line_uris, expected_uris);
}

BOOST_FIXTURE_TEST_CASE(equipment_report_should_forbid_uris, Test_fixture) {
    auto filter = "stop_point.has_code_type(CodeType1)";
    auto sa_per_line = equipment::get_stop_areas_per_line(data, filter, {"A"});

    // Stop Areas "A" and "B" have cpde "CodeType1", but "A" has been forbidden,
    // Hense the fact that only "B" is returned
    BOOST_REQUIRE_EQUAL(sa_per_line.size(), 1);
    BOOST_REQUIRE_EQUAL(sa_per_line[0].first->uri, "B");
}

BOOST_FIXTURE_TEST_CASE(equipment_reports_test_api, Test_fixture) {
    const auto filter = "stop_point.has_code_type(CodeType1)";
    equipment::equipment_reports(pb_creator, filter, 10);

    BOOST_CHECK_EQUAL(pb_creator.equipment_reports_size(), 2);
    const auto resp = pb_creator.get_response();

    map<string, set<string>> sa_per_line_uris;
    for(const auto equip_rep : resp.equipment_reports()) {
        BOOST_REQUIRE(equip_rep.has_line());
        set<string> stop_area_uris;
        for(const auto sae : equip_rep.stop_area_equipments()){
            BOOST_REQUIRE(sae.has_stop_area());
            stop_area_uris.emplace(sae.stop_area().uri());
        }
        sa_per_line_uris[equip_rep.line().uri()] = stop_area_uris;
    }

     map<string, set<string>> expected_uris {
        {"A", {"sa1", "sa3"}},
        {"B", {"sa6"}},
    };
    BOOST_CHECK_EQUAL_RANGE(sa_per_line_uris, expected_uris);
}

BOOST_FIXTURE_TEST_CASE(equipment_reports_should_fail_on_bad_filter, Test_fixture) {
    const auto filter = "this filter is just nonsense";
    equipment::equipment_reports(pb_creator, filter, 10);

    BOOST_CHECK_NO_THROW();
    BOOST_CHECK(pb_creator.has_error());
}

BOOST_FIXTURE_TEST_CASE(equipment_reports_should_paginate_page_0, Test_fixture) {
    const auto filter = "stop_point.has_code_type(CodeType1)";
    // PAGE 0 - COUNT = 1
    equipment::equipment_reports(pb_creator, filter, 1, 0, 0);
    BOOST_REQUIRE_EQUAL(pb_creator.equipment_reports_size(), 1);
    auto line_A_uri = pb_creator.get_response().equipment_reports(0).line().uri();
    BOOST_CHECK_EQUAL(line_A_uri, "A");
}

BOOST_FIXTURE_TEST_CASE(equipment_reports_should_paginate_page_1, Test_fixture) {
    const auto filter = "stop_point.has_code_type(CodeType1)";
    // PAGE 1 - COUNT = 1
    equipment::equipment_reports(pb_creator, filter, 1, 0, 1);
    BOOST_REQUIRE_EQUAL(pb_creator.equipment_reports_size(), 1);
    auto line_A_uri = pb_creator.get_response().equipment_reports(0).line().uri();
    BOOST_CHECK_EQUAL(line_A_uri, "B");
}

} // namespace<commit_msg>add missing newline<commit_after>/* Copyright © 2001-2019, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

This program 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 Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE equipment_test

#include <string>
#include <vector>
#include <map>

#include <boost/range/algorithm/sort.hpp>
#include <boost/test/unit_test.hpp>

#include "ed/build_helper.h"
#include "equipment/equipment_api.h"
#include "ptreferential/ptreferential.h"
#include "utils/logger.h"
#include "type/type.h"
#include "type/pt_data.h"
#include "tests/utils_test.h"

using namespace navitia;
using std::set;
using std::string;
using std::map;
using boost::posix_time::time_period;

struct logger_initialized {
    logger_initialized() { navitia::init_logger(); }
};
BOOST_GLOBAL_FIXTURE( logger_initialized );

namespace {

class Test_fixture {
public:
    ed::builder b;
    navitia::PbCreator pb_creator;
    const type::Data& data;

    Test_fixture(): b("20190101"), data(*b.data) {

        b.sa("sa1")("stop1", {{"CodeType1", {"code1", "code2"}}} );
        b.sa("sa2")("stop2", {{"CodeType3", {"code5"}}} );
        b.sa("sa3")("stop3", {{"CodeType1", {"code6"}}} );
        b.sa("sa4")("stop4", {});
        b.sa("sa5")("stop5", {{"CodeType3", {"code7"}}} );
        b.sa("sa6")("stop6", {{"CodeType1", {"code8"}}} );

        b.vj("A")("stop1", 8000,8050)("stop2", 8200,8250)("stop3", 9000,9050);
        b.vj("B")("stop4", 8000,8050)("stop5", 8200,8250)("stop6", 9000,9050);
        b.make();

        const ptime since = "20190101T000000"_dt;
        const ptime until = "21190101T000000"_dt;
        pb_creator.init(&data, since, time_period(since, until));
    }
};

BOOST_FIXTURE_TEST_CASE(test_stop_point_codes_creation, Test_fixture) {

    type::Indexes idx = ptref::make_query(nt::Type_e::StopPoint,
                        "(stop_point.has_code_type(CodeType1))",
                        data);

    set<string> stop_points_uris = get_uris<type::StopPoint>(idx, data);

    BOOST_CHECK_EQUAL(stop_points_uris.size(), 3);
    BOOST_CHECK_EQUAL_RANGE(stop_points_uris, (set<string>{"stop1", "stop3", "stop6"}));
}

BOOST_FIXTURE_TEST_CASE(test_stop_area_query, Test_fixture) {

    type::Indexes idx = ptref::make_query(nt::Type_e::StopArea,
                        "(stop_point.has_code_type(CodeType1))",
                        data);

    set<string> stop_area_uris = get_uris<type::StopArea>(idx, data);

    BOOST_CHECK_EQUAL(stop_area_uris.size(), 3);
    BOOST_CHECK_EQUAL_RANGE(stop_area_uris, (set<string>{"sa1", "sa3", "sa6"}));
}

BOOST_FIXTURE_TEST_CASE(test_stop_area_per_line_query, Test_fixture) {

    type::Indexes idx = ptref::make_query(nt::Type_e::StopArea,
                        "(line.uri=A and stop_point.has_code_type(CodeType1))",
                        data);

    set<string> stop_area_uris = get_uris<type::StopArea>(idx, data);

    BOOST_CHECK_EQUAL(stop_area_uris.size(), 2);
    BOOST_CHECK_EQUAL_RANGE(stop_area_uris, (set<string>{"sa1", "sa3"}));
}

BOOST_FIXTURE_TEST_CASE(equipment_report_get_lines, Test_fixture) {
    auto filter = "stop_point.has_code_type(CodeType1)";
    auto sa_per_line = equipment::get_stop_areas_per_line(data, filter);

    // Convert result from object pointers to uris
    map<string, set<string>> sa_per_line_uris;
    for(const auto & line : sa_per_line) {
        set<string> sa_uris;
        for(const auto & sa : line.second) { sa_uris.insert(sa->uri); }
        sa_per_line_uris[line.first->uri] = sa_uris;
    }

    map<string, set<string>> expected_uris {
        {"A", {"sa1", "sa3"}},
        {"B", {"sa6"}},
    };
    BOOST_CHECK_EQUAL_RANGE(sa_per_line_uris, expected_uris);
}

BOOST_FIXTURE_TEST_CASE(equipment_report_should_forbid_uris, Test_fixture) {
    auto filter = "stop_point.has_code_type(CodeType1)";
    auto sa_per_line = equipment::get_stop_areas_per_line(data, filter, {"A"});

    // Stop Areas "A" and "B" have cpde "CodeType1", but "A" has been forbidden,
    // Hense the fact that only "B" is returned
    BOOST_REQUIRE_EQUAL(sa_per_line.size(), 1);
    BOOST_REQUIRE_EQUAL(sa_per_line[0].first->uri, "B");
}

BOOST_FIXTURE_TEST_CASE(equipment_reports_test_api, Test_fixture) {
    const auto filter = "stop_point.has_code_type(CodeType1)";
    equipment::equipment_reports(pb_creator, filter, 10);

    BOOST_CHECK_EQUAL(pb_creator.equipment_reports_size(), 2);
    const auto resp = pb_creator.get_response();

    map<string, set<string>> sa_per_line_uris;
    for(const auto equip_rep : resp.equipment_reports()) {
        BOOST_REQUIRE(equip_rep.has_line());
        set<string> stop_area_uris;
        for(const auto sae : equip_rep.stop_area_equipments()){
            BOOST_REQUIRE(sae.has_stop_area());
            stop_area_uris.emplace(sae.stop_area().uri());
        }
        sa_per_line_uris[equip_rep.line().uri()] = stop_area_uris;
    }

     map<string, set<string>> expected_uris {
        {"A", {"sa1", "sa3"}},
        {"B", {"sa6"}},
    };
    BOOST_CHECK_EQUAL_RANGE(sa_per_line_uris, expected_uris);
}

BOOST_FIXTURE_TEST_CASE(equipment_reports_should_fail_on_bad_filter, Test_fixture) {
    const auto filter = "this filter is just nonsense";
    equipment::equipment_reports(pb_creator, filter, 10);

    BOOST_CHECK_NO_THROW();
    BOOST_CHECK(pb_creator.has_error());
}

BOOST_FIXTURE_TEST_CASE(equipment_reports_should_paginate_page_0, Test_fixture) {
    const auto filter = "stop_point.has_code_type(CodeType1)";
    // PAGE 0 - COUNT = 1
    equipment::equipment_reports(pb_creator, filter, 1, 0, 0);
    BOOST_REQUIRE_EQUAL(pb_creator.equipment_reports_size(), 1);
    auto line_A_uri = pb_creator.get_response().equipment_reports(0).line().uri();
    BOOST_CHECK_EQUAL(line_A_uri, "A");
}

BOOST_FIXTURE_TEST_CASE(equipment_reports_should_paginate_page_1, Test_fixture) {
    const auto filter = "stop_point.has_code_type(CodeType1)";
    // PAGE 1 - COUNT = 1
    equipment::equipment_reports(pb_creator, filter, 1, 0, 1);
    BOOST_REQUIRE_EQUAL(pb_creator.equipment_reports_size(), 1);
    auto line_A_uri = pb_creator.get_response().equipment_reports(0).line().uri();
    BOOST_CHECK_EQUAL(line_A_uri, "B");
}

} // namespace
<|endoftext|>


<commit_before><commit_msg>remove unused variable<commit_after><|endoftext|>


<commit_before>/***********************************************************************
	filename: 	CEGUIDefaultResourceProvider.cpp
	created:	8/7/2004
	author:		James '_mental_' O'Sullivan

	purpose:	Implements the Resource Manager common functionality
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUIDefaultResourceProvider.h"
#include "CEGUIExceptions.h"

#include <fstream>

// Start of CEGUI namespace section
namespace CEGUI
{

    void DefaultResourceProvider::loadRawDataContainer(const String& filename, RawDataContainer& output, const String& resourceGroup)
    {
        if (filename.empty())
        {
            throw InvalidRequestException(
                "DefaultResourceProvider::load - Filename supplied for data loading must be valid");
        }

        String final_filename(getFinalFilename(filename, resourceGroup));

        std::ifstream dataFile(final_filename.c_str(), std::ios::binary|std::ios::ate);
        if( dataFile.fail())
        {
            throw InvalidRequestException(
                "DefaultResourceProvider::load - " + filename + " does not exist");
        }
        std::streampos size = dataFile.tellg();
        dataFile.seekg (0, std::ios::beg);

        unsigned char* buffer = new unsigned char [size];

        try {
            dataFile.read(reinterpret_cast<char*>(buffer), size);
        }
        catch(std::ifstream::failure e) {
            delete [] buffer;
            throw GenericException(
                "DefaultResourceProvider::loadRawDataContainer - Problem reading " + filename);
        }

        dataFile.close();

        output.setData(buffer);
        output.setSize(size);
    }

    void DefaultResourceProvider::unloadRawDataContainer(RawDataContainer& data)
    {
        uint8* ptr = data.getDataPtr();
        delete [] ptr;
        data.setData(0);
        data.setSize(0);
    }

    void DefaultResourceProvider::setResourceGroupDirectory(const String& resourceGroup, const String& directory)
    {
        d_resourceGroups[resourceGroup] = directory;
    }

    const String& DefaultResourceProvider::getResourceGroupDirectory(const String& resourceGroup)
    {
        return d_resourceGroups[resourceGroup];
    }

    void DefaultResourceProvider::clearResourceGroupDirectory(const String& resourceGroup)
    {
        ResourceGroupMap::iterator iter = d_resourceGroups.find(resourceGroup);

        if (iter != d_resourceGroups.end())
            d_resourceGroups.erase(iter);
    }

    String DefaultResourceProvider::getFinalFilename(const String& filename, const String& resourceGroup) const
    {
        String final_filename;

        // look up resource group directory
        ResourceGroupMap::const_iterator iter = d_resourceGroups.find(resourceGroup);

        // if there was an entry for this group, use it's directory as the
        // first part of the filename
        if (iter != d_resourceGroups.end())
            final_filename = (*iter).second;

        // append the filename part that we were passed
        final_filename += filename;

        // return result
        return final_filename;
    }

} // End of  CEGUI namespace section
<commit_msg>Bug fix: Global default resource group was not being used by DefaultResourceProvider.<commit_after>/***********************************************************************
	filename: 	CEGUIDefaultResourceProvider.cpp
	created:	8/7/2004
	author:		James '_mental_' O'Sullivan

	purpose:	Implements the Resource Manager common functionality
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUIDefaultResourceProvider.h"
#include "CEGUIExceptions.h"

#include <fstream>

// Start of CEGUI namespace section
namespace CEGUI
{

    void DefaultResourceProvider::loadRawDataContainer(const String& filename, RawDataContainer& output, const String& resourceGroup)
    {
        if (filename.empty())
        {
            throw InvalidRequestException(
                "DefaultResourceProvider::load - Filename supplied for data loading must be valid");
        }

        String final_filename(getFinalFilename(filename, resourceGroup));

        std::ifstream dataFile(final_filename.c_str(), std::ios::binary|std::ios::ate);
        if( dataFile.fail())
        {
            throw InvalidRequestException(
                "DefaultResourceProvider::load - " + filename + " does not exist");
        }
        std::streampos size = dataFile.tellg();
        dataFile.seekg (0, std::ios::beg);

        unsigned char* buffer = new unsigned char [size];

        try {
            dataFile.read(reinterpret_cast<char*>(buffer), size);
        }
        catch(std::ifstream::failure e) {
            delete [] buffer;
            throw GenericException(
                "DefaultResourceProvider::loadRawDataContainer - Problem reading " + filename);
        }

        dataFile.close();

        output.setData(buffer);
        output.setSize(size);
    }

    void DefaultResourceProvider::unloadRawDataContainer(RawDataContainer& data)
    {
        uint8* ptr = data.getDataPtr();
        delete [] ptr;
        data.setData(0);
        data.setSize(0);
    }

    void DefaultResourceProvider::setResourceGroupDirectory(const String& resourceGroup, const String& directory)
    {
        d_resourceGroups[resourceGroup] = directory;
    }

    const String& DefaultResourceProvider::getResourceGroupDirectory(const String& resourceGroup)
    {
        return d_resourceGroups[resourceGroup];
    }

    void DefaultResourceProvider::clearResourceGroupDirectory(const String& resourceGroup)
    {
        ResourceGroupMap::iterator iter = d_resourceGroups.find(resourceGroup);

        if (iter != d_resourceGroups.end())
            d_resourceGroups.erase(iter);
    }

    String DefaultResourceProvider::getFinalFilename(const String& filename, const String& resourceGroup) const
    {
        String final_filename;

        // look up resource group directory
        ResourceGroupMap::const_iterator iter =
            d_resourceGroups.find(resourceGroup.empty() ? d_defaultResourceGroup : resourceGroup);

        // if there was an entry for this group, use it's directory as the
        // first part of the filename
        if (iter != d_resourceGroups.end())
            final_filename = (*iter).second;

        // append the filename part that we were passed
        final_filename += filename;

        // return result
        return final_filename;
    }

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>#include <vtkConeSource.h>
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkOpenVRRenderWindow.h>
#include <vtkOpenVRRenderer.h>
#include <vtkOpenVRRenderWindowInteractor.h>
#include <vtkNamedColors.h>
#include <vtkProperty.h>
// Chethana B
// Organisation: Virtual Environments Lab, Chung-Ang Univeristy, Seoul.
int main(int, char *[])
{
  //Create a cone
  vtkSmartPointer<vtkConeSource> coneSource =    vtkSmartPointer<vtkConeSource>::New();
  coneSource->Update();

  //Create a mapper and actor
  vtkSmartPointer<vtkPolyDataMapper> mapper =    vtkSmartPointer<vtkPolyDataMapper>::New();
  mapper->SetInputConnection(coneSource->GetOutputPort());

  vtkSmartPointer<vtkActor> actor =    vtkSmartPointer<vtkActor>::New();
  actor->SetMapper(mapper);

  //Create a renderer, render window, and interactor
  vtkSmartPointer<vtkOpenVRRenderer> renderer =    vtkSmartPointer<vtkOpenVRRenderer>::New();
  vtkSmartPointer<vtkOpenVRRenderWindow> renderWindow =    vtkSmartPointer<vtkOpenVRRenderWindow>::New();
  renderWindow->AddRenderer(renderer);
  vtkSmartPointer<vtkOpenVRRenderWindowInteractor> renderWindowInteractor =    vtkSmartPointer<vtkOpenVRRenderWindowInteractor>::New();
  renderWindowInteractor->SetRenderWindow(renderWindow);

  //Add the actors to the scene
  renderer->AddActor(actor);
  renderer->SetBackground(.3, .6, .3); // Background color green

  //Render and interact
  renderWindow->Render();
  renderWindowInteractor->Start();

  return EXIT_SUCCESS;
}
<commit_msg>Updated OpenVRCone.cxx<commit_after>#include <vtkConeSource.h>
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkOpenVRRenderWindow.h>
#include <vtkOpenVRRenderer.h>
#include <vtkOpenVRRenderWindowInteractor.h>
#include <vtkNamedColors.h>
#include <vtkProperty.h>
// Chethana B
// Organisation: Virtual Environments Lab, Chung-Ang Univeristy, Seoul.
int main(int, char *[])
{
  //Create a cone
  vtkSmartPointer<vtkConeSource> coneSource = vtkSmartPointer<vtkConeSource>::New();
  coneSource->Update();

  //Create a mapper and actor
  vtkSmartPointer<vtkNamedColors> colors = vtkSmartPointer<vtkNamedColors>::New();
  vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  mapper->SetInputConnection(coneSource->GetOutputPort());

  vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
  actor->SetMapper(mapper);

  //Create a renderer, render window, and interactor
  vtkSmartPointer<vtkOpenVRRenderer> renderer = vtkSmartPointer<vtkOpenVRRenderer>::New();
  vtkSmartPointer<vtkOpenVRRenderWindow> renderWindow = vtkSmartPointer<vtkOpenVRRenderWindow>::New();
  renderWindow->AddRenderer(renderer);
  vtkSmartPointer<vtkOpenVRRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkOpenVRRenderWindowInteractor>::New();
  renderWindowInteractor->SetRenderWindow(renderWindow);

  //Add the actors to the scene
  renderer->AddActor(actor);
  renderer->SetBackground(colors->GetColor3d("ForestGreen").GetData());

  //Render and interact
  renderWindow->Render();
  renderWindowInteractor->Start();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "StageCanvas.h"
#include "StagePanel.h"

#include <easyejoy2d.h>

namespace tdtex
{

BEGIN_EVENT_TABLE(StageCanvas, d2d::OrthoCanvas)
	EVT_TIMER(TIMER_ID, StageCanvas::onTimer)
END_EVENT_TABLE()

StageCanvas::StageCanvas(StagePanel* panel)
	: d2d::OrthoCanvas(panel)
	, m_panel(panel)
	, m_timer(this, TIMER_ID)
{
	m_timer.Start(100);
}

void StageCanvas::initGL()
{
	d2d::OrthoCanvas::initGL();

	m_panel->Load();
}

void StageCanvas::onDraw()
{
	m_panel->Update();

  	m_panel->traverseSprites(d2d::DrawSpritesVisitor(), d2d::e_visible);
  	m_panel->traverseShapes(d2d::DrawShapesVisitor(), d2d::e_visible);

  	m_editPanel->drawEditTemp();

	d2d::ShaderMgr::Instance()->null();
 	m_panel->Draw();
 	DrawEJScreen();
}

void StageCanvas::onTimer(wxTimerEvent& event)
{
	Refresh();
}

void StageCanvas::DrawEJScreen() const
{
	float vb[16];

	vb[2] = 0, vb[3] = 0;
	vb[6] = 0, vb[7] = 1;
	vb[10] = 1, vb[11] = 1;
	vb[14] = 1, vb[15] = 0;

	int left = -40, right = 40;
	int down = -30, up = 30;

	vb[0] = left, vb[1] = down;
	vb[4] = left, vb[5] = up;
	vb[8] = right, vb[9] = up;
	vb[12] = right, vb[13] = down;

	GLuint tex = eejoy2d::EJScreen::Instance()->GetTexID();

	d2d::ShaderMgr* shader = d2d::ShaderMgr::Instance();

	shader->sprite();
	shader->Draw(vb, tex);
}

}<commit_msg>临时关掉EJScreen画到屏幕<commit_after>#include "StageCanvas.h"
#include "StagePanel.h"

#include <easyejoy2d.h>

namespace tdtex
{

BEGIN_EVENT_TABLE(StageCanvas, d2d::OrthoCanvas)
	EVT_TIMER(TIMER_ID, StageCanvas::onTimer)
END_EVENT_TABLE()

StageCanvas::StageCanvas(StagePanel* panel)
	: d2d::OrthoCanvas(panel)
	, m_panel(panel)
	, m_timer(this, TIMER_ID)
{
	m_timer.Start(100);
}

void StageCanvas::initGL()
{
	d2d::OrthoCanvas::initGL();

	m_panel->Load();
}

void StageCanvas::onDraw()
{
	m_panel->Update();

  	m_panel->traverseSprites(d2d::DrawSpritesVisitor(), d2d::e_visible);
  	m_panel->traverseShapes(d2d::DrawShapesVisitor(), d2d::e_visible);

  	m_editPanel->drawEditTemp();

 	d2d::ShaderMgr::Instance()->null();
  	m_panel->Draw();
//  	DrawEJScreen();
}

void StageCanvas::onTimer(wxTimerEvent& event)
{
	Refresh();
}

void StageCanvas::DrawEJScreen() const
{
	float vb[16];

	vb[2] = 0, vb[3] = 0;
	vb[6] = 0, vb[7] = 1;
	vb[10] = 1, vb[11] = 1;
	vb[14] = 1, vb[15] = 0;

 	int left = -200, right = 200;
 	int down = -150, up = 150;

	vb[0] = left, vb[1] = down;
	vb[4] = left, vb[5] = up;
	vb[8] = right, vb[9] = up;
	vb[12] = right, vb[13] = down;

	GLuint tex = eejoy2d::EJScreen::Instance()->GetTexID();

	d2d::ShaderMgr* shader = d2d::ShaderMgr::Instance();

	shader->sprite();
	shader->Draw(vb, tex);
}

}<|endoftext|>