<commit_before>#include "time.h"

#include <sstream>
#include <RegisterWindow.h>
#include <FL/fl_file_chooser.H>

RegisterWindow::RegisterWindow()
{
  m_FixedImageViewer = ImageViewerType::New() ;
  m_MovingImageViewer = ImageViewerType::New() ;
  m_RegisteredImageViewer = ImageViewerType::New() ;
  m_MixedChannelViewer = MixedChannelViewerType::New() ;

  m_FixedImageViewer->SetLabel( "Fixed Image" ) ;
  m_MovingImageViewer->SetLabel( "Moving Image" ) ;
  m_RegisteredImageViewer->SetLabel( "Registered Image" ) ;
  m_MixedChannelViewer->SetLabel( "Mixed Channel View" ) ;

  m_DebugViewer = ImageViewerType::New() ;
  m_DebugViewer->SetLabel( "Debug" ) ;

  m_ChannelSources[0] = fixed ;
  m_ChannelSources[1] = registered ;
  m_ChannelSources[2] = none ;

  m_FixedImageViewer->imageViewer->
    SetSelectionCallBack((void*) this,
                         RegisterWindow::SelectionCallBackWrapper) ;
  buStartRegistration->deactivate() ;
  buSaveRegisteredImage->deactivate() ;
  buShowDisplay->deactivate() ;
  lsDisplay->deactivate() ;
  menuFixedImageDisplay->deactivate() ;
  menuMovingImageDisplay->deactivate() ;
  menuRegisteredImageDisplay->deactivate() ;
  menuMixedChannel->deactivate() ;

  this->ShowStatus("Let's start by loading an image...");
}

RegisterWindow::~RegisterWindow()
{
}

void RegisterWindow::LoadMovingImage(void)
{
  const char * filename =
    fl_file_chooser("Moving Image filename","*.png","");
  if( !filename )
    {
      return;
    }

  m_MovingImageFileName = filename ;

  this->ShowStatus("Loading moving image file...");

  try
    {
      RegisterApplication::LoadMovingImage();
    }
  catch( ... )
    {
      this->ShowStatus("Problems reading file format");
      return;
    }

  if (m_FixedImage != 0 && m_MovingImage != 0)
    {
      buStartRegistration->activate() ;
    }

  lsDisplay->activate() ;
  buShowDisplay->activate() ;
  menuMovingImageDisplay->activate() ;

  this->ShowStatus("Moving Image Loaded");
}

void RegisterWindow::LoadFixedImage(void)
{
  const char * filename =
    fl_file_chooser("Fixed Image filename","*.png","");

  if( !filename )
    {
      return;
    }

  m_FixedImageFileName = filename ;

  this->ShowStatus("Loading fixed image file...");

  try
    {
      RegisterApplication::LoadFixedImage();
    }
  catch( ... )
    {
      this->ShowStatus("Problems reading file format");
      return;
    }

  m_TempBox.X1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[0] ;
  m_TempBox.Y1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[1] ;
  m_TempBox.X2 = m_TempBox.X1 +
    m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
  m_TempBox.Y2 = m_TempBox.Y1 +
    m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;

  outSelectedRegionBeginX->value(m_TempBox.X1) ;
  outSelectedRegionBeginY->value(m_TempBox.Y1) ;
  outSelectedRegionEndX->value(m_TempBox.X2) ;
  outSelectedRegionEndY->value(m_TempBox.Y2) ;

  m_FixedImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;

  lsDisplay->activate() ;
  buShowDisplay->activate() ;
  menuFixedImageDisplay->activate() ;
  if (m_FixedImage != 0 && m_MovingImage != 0)
    {
      buStartRegistration->activate() ;
    }

  this->ShowStatus("Fixed Image Loaded");
}

void RegisterWindow::Show()
{
  winMain->show() ;
}

void RegisterWindow::Hide()
{
  winMain->hide();
  m_FixedImageViewer->Hide();
  m_MovingImageViewer->Hide();
  m_RegisteredImageViewer->Hide();
  m_MixedChannelViewer->Hide() ;
}

void RegisterWindow::Quit(void)
{
  this->Hide() ;
}

void RegisterWindow::ShowStatus(const char * text)
{
  outStatus->value( text );
  Fl::check();
}

void RegisterWindow::ShowFixedImage(void)
{
  if( !m_FixedImageLoaded )
    {
      return;
    }

  m_FixedImageViewer->SetImage( m_FixedImage );
  m_FixedImageViewer->Show();
}

void RegisterWindow::ShowMovingImage(void)
{
  if( !m_MovingImageLoaded )
    {
      return;
    }

  m_MovingImageViewer->SetImage( m_MovingImage );
  m_MovingImageViewer->Show();

  if (m_FixedImage != 0)
    {
      m_TempBox.X1 = (int) outSelectedRegionBeginX->value() ;
      m_TempBox.Y1 = (int) outSelectedRegionBeginY->value() ;
      m_TempBox.X2 = (int) outSelectedRegionEndX->value() ;
      m_TempBox.Y2 = (int) outSelectedRegionEndY->value() ;
      m_MovingImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;
    }
}

void RegisterWindow::ShowRegisteredImage(void)
{
  if( !m_RegisteredImageAvailable )
    {
      return;
    }

  m_RegisteredImageViewer->SetImage( m_RegisteredImage );
  m_RegisteredImageViewer->Show();
}

void RegisterWindow::ShowMixedChannel(void)
{
  if( !m_RegisteredImageAvailable )
    {
      return;
    }
  int sizeX = m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
  int sizeY = m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;

  if (m_ChannelSources[0] == fixed)
    {
      m_MixedChannelViewer->SetRedChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[0] == registered)
    {
      m_MixedChannelViewer->SetRedChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(0, 0, sizeX, sizeY) ;
    }

  if (m_ChannelSources[1] == fixed)
    {
      m_MixedChannelViewer->SetGreenChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[1] == registered)
    {
      m_MixedChannelViewer->SetGreenChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(1, 0, sizeX, sizeY) ;
    }

  if (m_ChannelSources[2] == fixed)
    {
      m_MixedChannelViewer->SetBlueChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[2] == registered)
    {
      m_MixedChannelViewer->SetBlueChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(2, 0, sizeX, sizeY) ;
    }

  m_MixedChannelViewer->Show();
}

void RegisterWindow::Execute(void)
{
  clock_t time_begin ;
  clock_t time_end ;

  this->ShowStatus("Registering Moving Image against Fixed Image ...");
  grpControls->deactivate() ;
  this->UpdateParameters() ;

  time_begin = clock() ;
  RegisterApplication::Execute();
  time_end = clock() ;

  menuRegisteredImageDisplay->activate() ;
  menuMixedChannel->activate() ;
  buSaveRegisteredImage->activate() ;
  grpControls->activate() ;
  std::ostringstream message ;
  message
    << "Registration done in " <<
    double(time_end - time_begin) / CLOCKS_PER_SEC << "seconds."
    << std::endl ;
  message << "angle = "
    << m_Registrator->GetTransformParameters()[0] << ", x offset = "
    << m_Registrator->GetTransformParameters()[1] << ", y offset = "
    << m_Registrator->GetTransformParameters()[2] ;
  this->ShowStatus(message.str().c_str());

//    m_MovingImage->SetRequestedRegion(m_SelectedRegion) ;
//    m_DebugViewer->SetImage(m_MovingImage) ;
//    m_DebugViewer->Show() ;
//    m_MovingImage->SetRequestedRegionToLargestPossibleRegion() ;
}

void RegisterWindow::UpdateParameters(void)
{

  m_RegionBegin.resize(ImageDimension) ;
  m_RegionEnd.resize(ImageDimension) ;

  m_RegionBegin[0] = (int) outSelectedRegionBeginX->value() ;
  m_RegionBegin[1] = (int) outSelectedRegionBeginY->value() ;
  m_RegionEnd[0] = (int) outSelectedRegionEndX->value() ;
  m_RegionEnd[1] = (int) outSelectedRegionEndY->value() ;

  int i ;
  // crop images from original image using selected region
  for (i = 0 ; i < ImageDimension ; i++)
    {
      if (m_RegionEnd[i] > m_RegionBegin[i])
        {
          m_SelectedSize[i] = m_RegionEnd[i] - m_RegionBegin[i] ;
          m_SelectedIndex[i] = m_RegionBegin[i] ;
        }
      else
        {
          m_SelectedSize[i] = m_RegionBegin[i] - m_RegionEnd[i] ;
          m_SelectedIndex[i] = m_RegionEnd[i] ;
        }
    }

  m_SelectedRegion.SetIndex(m_SelectedIndex) ;
  m_SelectedRegion.SetSize(m_SelectedSize) ;

}

void RegisterWindow::ShowAdvancedOptionsWindow()
{
  winAdvancedOptions->show() ;
  inTranslationScale->value(m_TranslationScale) ;
  inRotationScale->value(m_RotationScale) ;
  inLearningRate->value(m_LearningRate) ;
  inNumberOfIterations->value(m_NumberOfIterations) ;

  if (m_ChannelSources[0] == fixed)
    {
      buRedFixedImage->setonly() ;
    }
  else if (m_ChannelSources[0] == registered)
    {
      buRedRegisteredImage->setonly() ;
    }
  else
    {
      buRedNone->setonly() ;
    }

  if (m_ChannelSources[1] == fixed)
    {
      buGreenFixedImage->setonly() ;
    }
  else if (m_ChannelSources[1] == registered)
    {
      buGreenRegisteredImage->setonly() ;
    }
  else
    {
      buGreenNone->setonly() ;
    }

  if (m_ChannelSources[2] == fixed)
    {
      buBlueFixedImage->setonly() ;
    }
  else if (m_ChannelSources[2] == registered)
    {
      buBlueRegisteredImage->setonly() ;
    }
  else
    {
      buBlueNone->setonly() ;
    }
}

void RegisterWindow::UpdateAdvancedOptions(void)
{
  m_TranslationScale = inTranslationScale->value() ;
  m_RotationScale = inRotationScale->value() ;
  m_LearningRate = inLearningRate->value() ;
  m_NumberOfIterations = (int) inNumberOfIterations->value() ;

  if (buRedFixedImage->value() == 1)
    {
      m_ChannelSources[0] = fixed ;
    }
  else if (buRedRegisteredImage->value() == 1)
    {
      m_ChannelSources[0] = registered ;
    }
  else
    {
      m_ChannelSources[0] = none ;
    }

  if (buGreenFixedImage->value() == 1)
    {
      m_ChannelSources[1] = fixed ;
    }
  else if (buGreenRegisteredImage->value() == 1)
    {
      m_ChannelSources[1] = registered ;
    }
  else
    {
      m_ChannelSources[1] = none ;
    }

  if (buBlueFixedImage->value() == 1)
    {
      m_ChannelSources[2] = fixed ;
    }
  else if (buBlueRegisteredImage->value() == 1)
    {
      m_ChannelSources[2] = registered ;
    }
  else
    {
      m_ChannelSources[2] = none ;
    }

  winAdvancedOptions->hide() ;
}

void RegisterWindow::CloseAdvancedOptionsWindow(void)
{
  winAdvancedOptions->hide() ;
}

void RegisterWindow::SaveRegisteredImage( void )
{

  const char * filename =
    fl_file_chooser("Registered Image filename","*.png","");

  if( !filename )
    {
      return;
    }

  this->ShowStatus("Saving registered image file...");

  try
    {
      RegisterApplication::SaveRegisteredImage( filename );
    }
  catch( ... )
    {
      this->ShowStatus("Problems saving file format");
      return;
    }

  this->ShowStatus("Registered Image Saved");
}

void RegisterWindow
::SelectionCallBackWrapper(void* ptrSelf,
                           fltk::Image2DViewerWindow::SelectionBoxType* box)
{
  RegisterWindow* self = (RegisterWindow*) ptrSelf ;
  self->UpdateSelectedRegion(box) ;
}

void RegisterWindow
::UpdateSelectedRegion(fltk::Image2DViewerWindow::SelectionBoxType* box)
{
  outSelectedRegionBeginX->value(box->X1) ;
  outSelectedRegionBeginY->value(box->Y1) ;
  outSelectedRegionEndX->value(box->X2) ;
  outSelectedRegionEndY->value(box->Y2) ;
  m_MovingImageViewer->imageViewer->SetSelectionBox(box) ;
}

<commit_msg>ENH: Default mask for filenames is now *.* since both PNG and MetaImages      can be loaded.<commit_after>#include "time.h"

#include <sstream>
#include <RegisterWindow.h>
#include <FL/fl_file_chooser.H>

RegisterWindow::RegisterWindow()
{
  m_FixedImageViewer = ImageViewerType::New() ;
  m_MovingImageViewer = ImageViewerType::New() ;
  m_RegisteredImageViewer = ImageViewerType::New() ;
  m_MixedChannelViewer = MixedChannelViewerType::New() ;

  m_FixedImageViewer->SetLabel( "Fixed Image" ) ;
  m_MovingImageViewer->SetLabel( "Moving Image" ) ;
  m_RegisteredImageViewer->SetLabel( "Registered Image" ) ;
  m_MixedChannelViewer->SetLabel( "Mixed Channel View" ) ;

  m_DebugViewer = ImageViewerType::New() ;
  m_DebugViewer->SetLabel( "Debug" ) ;

  m_ChannelSources[0] = fixed ;
  m_ChannelSources[1] = registered ;
  m_ChannelSources[2] = none ;

  m_FixedImageViewer->imageViewer->
    SetSelectionCallBack((void*) this,
                         RegisterWindow::SelectionCallBackWrapper) ;
  buStartRegistration->deactivate() ;
  buSaveRegisteredImage->deactivate() ;
  buShowDisplay->deactivate() ;
  lsDisplay->deactivate() ;
  menuFixedImageDisplay->deactivate() ;
  menuMovingImageDisplay->deactivate() ;
  menuRegisteredImageDisplay->deactivate() ;
  menuMixedChannel->deactivate() ;

  this->ShowStatus("Let's start by loading an image...");
}

RegisterWindow::~RegisterWindow()
{
}

void RegisterWindow::LoadMovingImage(void)
{
  const char * filename =
    fl_file_chooser("Moving Image filename","*.*","");
  if( !filename )
    {
      return;
    }

  m_MovingImageFileName = filename ;

  this->ShowStatus("Loading moving image file...");

  try
    {
      RegisterApplication::LoadMovingImage();
    }
  catch( ... )
    {
      this->ShowStatus("Problems reading file format");
      return;
    }

  if (m_FixedImage != 0 && m_MovingImage != 0)
    {
      buStartRegistration->activate() ;
    }

  lsDisplay->activate() ;
  buShowDisplay->activate() ;
  menuMovingImageDisplay->activate() ;

  this->ShowStatus("Moving Image Loaded");
}

void RegisterWindow::LoadFixedImage(void)
{
  const char * filename =
    fl_file_chooser("Fixed Image filename","*.*","");

  if( !filename )
    {
      return;
    }

  m_FixedImageFileName = filename ;

  this->ShowStatus("Loading fixed image file...");

  try
    {
      RegisterApplication::LoadFixedImage();
    }
  catch( ... )
    {
      this->ShowStatus("Problems reading file format");
      return;
    }

  m_TempBox.X1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[0] ;
  m_TempBox.Y1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[1] ;
  m_TempBox.X2 = m_TempBox.X1 +
    m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
  m_TempBox.Y2 = m_TempBox.Y1 +
    m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;

  outSelectedRegionBeginX->value(m_TempBox.X1) ;
  outSelectedRegionBeginY->value(m_TempBox.Y1) ;
  outSelectedRegionEndX->value(m_TempBox.X2) ;
  outSelectedRegionEndY->value(m_TempBox.Y2) ;

  m_FixedImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;

  lsDisplay->activate() ;
  buShowDisplay->activate() ;
  menuFixedImageDisplay->activate() ;
  if (m_FixedImage != 0 && m_MovingImage != 0)
    {
      buStartRegistration->activate() ;
    }

  this->ShowStatus("Fixed Image Loaded");
}

void RegisterWindow::Show()
{
  winMain->show() ;
}

void RegisterWindow::Hide()
{
  winMain->hide();
  m_FixedImageViewer->Hide();
  m_MovingImageViewer->Hide();
  m_RegisteredImageViewer->Hide();
  m_MixedChannelViewer->Hide() ;
}

void RegisterWindow::Quit(void)
{
  this->Hide() ;
}

void RegisterWindow::ShowStatus(const char * text)
{
  outStatus->value( text );
  Fl::check();
}

void RegisterWindow::ShowFixedImage(void)
{
  if( !m_FixedImageLoaded )
    {
      return;
    }

  m_FixedImageViewer->SetImage( m_FixedImage );
  m_FixedImageViewer->Show();
}

void RegisterWindow::ShowMovingImage(void)
{
  if( !m_MovingImageLoaded )
    {
      return;
    }

  m_MovingImageViewer->SetImage( m_MovingImage );
  m_MovingImageViewer->Show();

  if (m_FixedImage != 0)
    {
      m_TempBox.X1 = (int) outSelectedRegionBeginX->value() ;
      m_TempBox.Y1 = (int) outSelectedRegionBeginY->value() ;
      m_TempBox.X2 = (int) outSelectedRegionEndX->value() ;
      m_TempBox.Y2 = (int) outSelectedRegionEndY->value() ;
      m_MovingImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;
    }
}

void RegisterWindow::ShowRegisteredImage(void)
{
  if( !m_RegisteredImageAvailable )
    {
      return;
    }

  m_RegisteredImageViewer->SetImage( m_RegisteredImage );
  m_RegisteredImageViewer->Show();
}

void RegisterWindow::ShowMixedChannel(void)
{
  if( !m_RegisteredImageAvailable )
    {
      return;
    }
  int sizeX = m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
  int sizeY = m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;

  if (m_ChannelSources[0] == fixed)
    {
      m_MixedChannelViewer->SetRedChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[0] == registered)
    {
      m_MixedChannelViewer->SetRedChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(0, 0, sizeX, sizeY) ;
    }

  if (m_ChannelSources[1] == fixed)
    {
      m_MixedChannelViewer->SetGreenChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[1] == registered)
    {
      m_MixedChannelViewer->SetGreenChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(1, 0, sizeX, sizeY) ;
    }

  if (m_ChannelSources[2] == fixed)
    {
      m_MixedChannelViewer->SetBlueChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[2] == registered)
    {
      m_MixedChannelViewer->SetBlueChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(2, 0, sizeX, sizeY) ;
    }

  m_MixedChannelViewer->Show();
}

void RegisterWindow::Execute(void)
{
  clock_t time_begin ;
  clock_t time_end ;

  this->ShowStatus("Registering Moving Image against Fixed Image ...");
  grpControls->deactivate() ;
  this->UpdateParameters() ;

  time_begin = clock() ;
  RegisterApplication::Execute();
  time_end = clock() ;

  menuRegisteredImageDisplay->activate() ;
  menuMixedChannel->activate() ;
  buSaveRegisteredImage->activate() ;
  grpControls->activate() ;
  std::ostringstream message ;
  message
    << "Registration done in " <<
    double(time_end - time_begin) / CLOCKS_PER_SEC << "seconds."
    << std::endl ;
  message << "angle = "
    << m_Registrator->GetTransformParameters()[0] << ", x offset = "
    << m_Registrator->GetTransformParameters()[1] << ", y offset = "
    << m_Registrator->GetTransformParameters()[2] ;
  this->ShowStatus(message.str().c_str());

//    m_MovingImage->SetRequestedRegion(m_SelectedRegion) ;
//    m_DebugViewer->SetImage(m_MovingImage) ;
//    m_DebugViewer->Show() ;
//    m_MovingImage->SetRequestedRegionToLargestPossibleRegion() ;
}

void RegisterWindow::UpdateParameters(void)
{

  m_RegionBegin.resize(ImageDimension) ;
  m_RegionEnd.resize(ImageDimension) ;

  m_RegionBegin[0] = (int) outSelectedRegionBeginX->value() ;
  m_RegionBegin[1] = (int) outSelectedRegionBeginY->value() ;
  m_RegionEnd[0] = (int) outSelectedRegionEndX->value() ;
  m_RegionEnd[1] = (int) outSelectedRegionEndY->value() ;

  int i ;
  // crop images from original image using selected region
  for (i = 0 ; i < ImageDimension ; i++)
    {
      if (m_RegionEnd[i] > m_RegionBegin[i])
        {
          m_SelectedSize[i] = m_RegionEnd[i] - m_RegionBegin[i] ;
          m_SelectedIndex[i] = m_RegionBegin[i] ;
        }
      else
        {
          m_SelectedSize[i] = m_RegionBegin[i] - m_RegionEnd[i] ;
          m_SelectedIndex[i] = m_RegionEnd[i] ;
        }
    }

  m_SelectedRegion.SetIndex(m_SelectedIndex) ;
  m_SelectedRegion.SetSize(m_SelectedSize) ;

}

void RegisterWindow::ShowAdvancedOptionsWindow()
{
  winAdvancedOptions->show() ;
  inTranslationScale->value(m_TranslationScale) ;
  inRotationScale->value(m_RotationScale) ;
  inLearningRate->value(m_LearningRate) ;
  inNumberOfIterations->value(m_NumberOfIterations) ;

  if (m_ChannelSources[0] == fixed)
    {
      buRedFixedImage->setonly() ;
    }
  else if (m_ChannelSources[0] == registered)
    {
      buRedRegisteredImage->setonly() ;
    }
  else
    {
      buRedNone->setonly() ;
    }

  if (m_ChannelSources[1] == fixed)
    {
      buGreenFixedImage->setonly() ;
    }
  else if (m_ChannelSources[1] == registered)
    {
      buGreenRegisteredImage->setonly() ;
    }
  else
    {
      buGreenNone->setonly() ;
    }

  if (m_ChannelSources[2] == fixed)
    {
      buBlueFixedImage->setonly() ;
    }
  else if (m_ChannelSources[2] == registered)
    {
      buBlueRegisteredImage->setonly() ;
    }
  else
    {
      buBlueNone->setonly() ;
    }
}

void RegisterWindow::UpdateAdvancedOptions(void)
{
  m_TranslationScale = inTranslationScale->value() ;
  m_RotationScale = inRotationScale->value() ;
  m_LearningRate = inLearningRate->value() ;
  m_NumberOfIterations = (int) inNumberOfIterations->value() ;

  if (buRedFixedImage->value() == 1)
    {
      m_ChannelSources[0] = fixed ;
    }
  else if (buRedRegisteredImage->value() == 1)
    {
      m_ChannelSources[0] = registered ;
    }
  else
    {
      m_ChannelSources[0] = none ;
    }

  if (buGreenFixedImage->value() == 1)
    {
      m_ChannelSources[1] = fixed ;
    }
  else if (buGreenRegisteredImage->value() == 1)
    {
      m_ChannelSources[1] = registered ;
    }
  else
    {
      m_ChannelSources[1] = none ;
    }

  if (buBlueFixedImage->value() == 1)
    {
      m_ChannelSources[2] = fixed ;
    }
  else if (buBlueRegisteredImage->value() == 1)
    {
      m_ChannelSources[2] = registered ;
    }
  else
    {
      m_ChannelSources[2] = none ;
    }

  winAdvancedOptions->hide() ;
}

void RegisterWindow::CloseAdvancedOptionsWindow(void)
{
  winAdvancedOptions->hide() ;
}

void RegisterWindow::SaveRegisteredImage( void )
{

  const char * filename =
    fl_file_chooser("Registered Image filename","*.*","");

  if( !filename )
    {
      return;
    }

  this->ShowStatus("Saving registered image file...");

  try
    {
      RegisterApplication::SaveRegisteredImage( filename );
    }
  catch( ... )
    {
      this->ShowStatus("Problems saving file format");
      return;
    }

  this->ShowStatus("Registered Image Saved");
}

void RegisterWindow
::SelectionCallBackWrapper(void* ptrSelf,
                           fltk::Image2DViewerWindow::SelectionBoxType* box)
{
  RegisterWindow* self = (RegisterWindow*) ptrSelf ;
  self->UpdateSelectedRegion(box) ;
}

void RegisterWindow
::UpdateSelectedRegion(fltk::Image2DViewerWindow::SelectionBoxType* box)
{
  outSelectedRegionBeginX->value(box->X1) ;
  outSelectedRegionBeginY->value(box->Y1) ;
  outSelectedRegionEndX->value(box->X2) ;
  outSelectedRegionEndY->value(box->Y2) ;
  m_MovingImageViewer->imageViewer->SetSelectionBox(box) ;
}

<|endoftext|>


<commit_before>/**************************************************************************
 * The MIT License                                                        *
 * Copyright (c) 2013 Antony Arciuolo.                                    *
 * arciuolo@gmail.com                                                     *
 *                                                                        *
 * 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 OR COPYRIGHT HOLDERS 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 <oPlatform/oTest.h>
#include <oSurface/surface.h>
#include <oSurface/codec.h>

#include "../../test_services.h"

using namespace ouro::surface;

namespace ouro {
	namespace tests {

static void convert_and_test(test_services& services, const format& target_format, const char* filename_suffix, uint nth_test)
{
	path TestImagePath = "Test/Textures/lena_1.png";

	auto file = services.load_buffer(TestImagePath);
	auto source = decode(file, file.size());

	oTRACEA("Converting image to %s...", as_string(target_format));
	auto converted1 = source.convert(has_alpha(target_format) ? format::r8g8b8a8_unorm : format::r8g8b8x8_unorm);
	auto converted2 = converted1.convert(target_format);
	auto converted_encoded = encode(converted2, file_format::dds);

	// load the confirmed-good file and compare
	sstring fname;
	snprintf(fname, "GoldenImages/oSurface_bccodec%u.dds", nth_test);
	auto golden_file = services.load_buffer(fname);

	oCHECK(converted_encoded.size() == golden_file.size(), "size mismatch (%u != %u)", converted_encoded.size(), golden_file.size());
	oCHECK(!memcmp(converted_encoded, golden_file, golden_file.size()), "bytes mismatch");
}

void TESTsurface_bccodec(test_services& services)
{
	convert_and_test(services, format::bc1_unorm, "_BC1", 0);
	convert_and_test(services, format::bc3_unorm, "_BC3", 1);
	convert_and_test(services, format::bc7_unorm, "_BC7", 2);
	//convert_and_test(services, format::bc6h_uf16, "_BC6HU", 2);
}

	} // namespace tests
} // namespace ouro
<commit_msg>Add a save-to-desktop option in BC codec unit test<commit_after>/**************************************************************************
 * The MIT License                                                        *
 * Copyright (c) 2013 Antony Arciuolo.                                    *
 * arciuolo@gmail.com                                                     *
 *                                                                        *
 * 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 OR COPYRIGHT HOLDERS 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 <oPlatform/oTest.h>
#include <oSurface/surface.h>
#include <oSurface/codec.h>
#include <oCore/filesystem.h>

#include "../../test_services.h"

using namespace ouro::surface;

namespace ouro {
	namespace tests {

static void convert_and_test(test_services& services, const format& target_format, const char* filename_suffix, uint nth_test, bool save_to_desktop = false)
{
	path TestImagePath = "Test/Textures/lena_1.png";

	auto file = services.load_buffer(TestImagePath);
	auto source = decode(file, file.size());

	oTRACEA("Converting image to %s...", as_string(target_format));
	auto converted1 = source.convert(has_alpha(target_format) ? format::r8g8b8a8_unorm : format::r8g8b8x8_unorm);
	auto converted2 = converted1.convert(target_format);
	auto converted_encoded = encode(converted2, file_format::dds);

	if (save_to_desktop)
	{
		path filename = TestImagePath.filename();
		filename.insert_basename_suffix(filename_suffix);
		filename.replace_extension(".dds");
		filesystem::save(filesystem::desktop_path() / filename, converted_encoded, converted_encoded.size());
	}

	// load the confirmed-good file and compare
	sstring fname;
	snprintf(fname, "GoldenImages/oSurface_bccodec%u.dds", nth_test);
	auto golden_file = services.load_buffer(fname);

	oCHECK(converted_encoded.size() == golden_file.size(), "size mismatch (%u != %u)", converted_encoded.size(), golden_file.size());
	oCHECK(!memcmp(converted_encoded, golden_file, golden_file.size()), "bytes mismatch");
}

void TESTsurface_bccodec(test_services& services)
{
	convert_and_test(services, format::bc1_unorm, "_BC1", 0);
	convert_and_test(services, format::bc3_unorm, "_BC3", 1);
	convert_and_test(services, format::bc7_unorm, "_BC7", 2);
	//convert_and_test(services, format::bc6h_uf16, "_BC6HU", 2);
}

	} // namespace tests
} // namespace ouro
<|endoftext|>


<commit_before>
#include "cocoa/CCSet.h"
#include "basics/CAApplication.h"
#include "dispatcher/CAKeypadDispatcher.h"
#include "dispatcher/CATouch.h"
#include "dispatcher/CATouchDispatcher.h"
#include <android/log.h>
#include <jni.h>
#include "platform/android/CCEGLView.h"

using namespace CrossApp;

extern "C" {
    JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesBegin(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y)
    {
        CrossApp::CAEvent* theEvent = new CrossApp::CAEvent();
        theEvent->setEventType(CrossApp::EventType::androidEvent);
        intptr_t ids[5] = {0};      static_cast<intptr_t>(id);
        float x_s[5] = {0};         x_s[0] = x;
        float y_s[5] = {0};        y_s[0] = y;

        CAApplication::getApplication()->getOpenGLView()->handleTouchesBegin(1, ids, x_s, y_s, theEvent);
        theEvent->release();
    }

    JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesEnd(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y)
    {
        CrossApp::CAEvent* theEvent = new CrossApp::CAEvent();
        theEvent->setEventType(CrossApp::EventType::androidEvent);

        intptr_t ids[5] = {0};      ids[0] = static_cast<intptr_t>(id);
        float x_s[5] = {0};         x_s[0] = x;
        float y_s[5] = {0};        y_s[0] = y;

        CAApplication::getApplication()->getOpenGLView()->handleTouchesEnd(1, ids, x_s, y_s, theEvent);
        theEvent->release();
    }

    JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesMove(JNIEnv * env, jobject thiz, jintArray id_array, jfloatArray xs, jfloatArray ys) {
        int size = env->GetArrayLength(id_array);
        jint id[size];
        jfloat x[size];
        jfloat y[size];

        env->GetIntArrayRegion(id_array, 0, size, id);
        env->GetFloatArrayRegion(xs, 0, size, x);
        env->GetFloatArrayRegion(ys, 0, size, y);

        intptr_t ids[size];
        float x_s[size];
        float y_s[size];
        for (int i=0; i<size; i++)
        {
            ids[i] = static_cast<intptr_t>(id[i]);
            x_s[i] = x[i];
            y_s[i] = y[i];
        }

        CrossApp::CAEvent* theEvent = new CrossApp::CAEvent();
        theEvent->setEventType(CrossApp::EventType::androidEvent);
        CAApplication::getApplication()->getOpenGLView()->handleTouchesMove(size, ids, x_s, y_s, theEvent);
        theEvent->release();

    }

    JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesCancel(JNIEnv * env, jobject thiz, jintArray id_array, jfloatArray xs, jfloatArray ys) {
        int size = env->GetArrayLength(id_array);
        jint id[size];
        jfloat x[size];
        jfloat y[size];

        env->GetIntArrayRegion(id_array, 0, size, id);
        env->GetFloatArrayRegion(xs, 0, size, x);
        env->GetFloatArrayRegion(ys, 0, size, y);

        intptr_t ids[size];
        float x_s[size];
        float y_s[size];
        for (int i=0; i<size; i++)
        {
            ids[i] = static_cast<intptr_t>(id[i]);
            x_s[i] = x[i];
            y_s[i] = y[i];
        }

        CrossApp::CAEvent* theEvent = new CrossApp::CAEvent();
        theEvent->setEventType(CrossApp::EventType::androidEvent);
        CAApplication::getApplication()->getOpenGLView()->handleTouchesCancel(size, ids, x_s, y_s, theEvent);
        theEvent->release();

    }

    #define KEYCODE_BACK 0x04
    #define KEYCODE_MENU 0x52

    JNIEXPORT jboolean JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeKeyDown(JNIEnv * env, jobject thiz, jint keyCode) {
        CAApplication* application = CAApplication::getApplication();
        switch (keyCode) {
            case KEYCODE_BACK:
                if (application->getKeypadDispatcher()->dispatchKeypadMSG(CAKeypadDispatcher::KeypadMSGType::BackClicked))
                    return JNI_TRUE;
                break;
            case KEYCODE_MENU:
                if (application->getKeypadDispatcher()->dispatchKeypadMSG(CAKeypadDispatcher::KeypadMSGType::MenuClicked))
                    return JNI_TRUE;
                break;
            default:
                return JNI_FALSE;
        }
        return JNI_FALSE;
    }
}
<commit_msg>no message<commit_after>
#include "cocoa/CCSet.h"
#include "basics/CAApplication.h"
#include "dispatcher/CAKeypadDispatcher.h"
#include "dispatcher/CATouch.h"
#include "dispatcher/CATouchDispatcher.h"
#include <android/log.h>
#include <jni.h>
#include "platform/android/CCEGLView.h"

using namespace CrossApp;

extern "C" {
    JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesBegin(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y)
    {
        CrossApp::CAEvent* theEvent = new CrossApp::CAEvent();
        theEvent->setEventType(CrossApp::EventType::androidEvent);
        intptr_t ids[1] = {0};      static_cast<intptr_t>(id);
        float x_s[1] = {0};         x_s[0] = x;
        float y_s[1] = {0};        y_s[0] = y;

        CAApplication::getApplication()->getOpenGLView()->handleTouchesBegin(1, ids, x_s, y_s, theEvent);
        theEvent->release();
    }

    JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesEnd(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y)
    {
        CrossApp::CAEvent* theEvent = new CrossApp::CAEvent();
        theEvent->setEventType(CrossApp::EventType::androidEvent);

        intptr_t ids[1] = {0};      ids[0] = static_cast<intptr_t>(id);
        float x_s[1] = {0};         x_s[0] = x;
        float y_s[1] = {0};        y_s[0] = y;

        CAApplication::getApplication()->getOpenGLView()->handleTouchesEnd(1, ids, x_s, y_s, theEvent);
        theEvent->release();
    }

    JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesMove(JNIEnv * env, jobject thiz, jintArray id_array, jfloatArray xs, jfloatArray ys) {
        int size = env->GetArrayLength(id_array);
        jint id[size];
        jfloat x[size];
        jfloat y[size];

        env->GetIntArrayRegion(id_array, 0, size, id);
        env->GetFloatArrayRegion(xs, 0, size, x);
        env->GetFloatArrayRegion(ys, 0, size, y);

        intptr_t ids[size];
        float x_s[size];
        float y_s[size];
        for (int i=0; i<size; i++)
        {
            ids[i] = static_cast<intptr_t>(id[i]);
            x_s[i] = x[i];
            y_s[i] = y[i];
        }

        CrossApp::CAEvent* theEvent = new CrossApp::CAEvent();
        theEvent->setEventType(CrossApp::EventType::androidEvent);
        CAApplication::getApplication()->getOpenGLView()->handleTouchesMove(size, ids, x_s, y_s, theEvent);
        theEvent->release();

    }

    JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesCancel(JNIEnv * env, jobject thiz, jintArray id_array, jfloatArray xs, jfloatArray ys) {
        int size = env->GetArrayLength(id_array);
        jint id[size];
        jfloat x[size];
        jfloat y[size];

        env->GetIntArrayRegion(id_array, 0, size, id);
        env->GetFloatArrayRegion(xs, 0, size, x);
        env->GetFloatArrayRegion(ys, 0, size, y);

        intptr_t ids[size];
        float x_s[size];
        float y_s[size];
        for (int i=0; i<size; i++)
        {
            ids[i] = static_cast<intptr_t>(id[i]);
            x_s[i] = x[i];
            y_s[i] = y[i];
        }

        CrossApp::CAEvent* theEvent = new CrossApp::CAEvent();
        theEvent->setEventType(CrossApp::EventType::androidEvent);
        CAApplication::getApplication()->getOpenGLView()->handleTouchesCancel(size, ids, x_s, y_s, theEvent);
        theEvent->release();

    }

    #define KEYCODE_BACK 0x04
    #define KEYCODE_MENU 0x52

    JNIEXPORT jboolean JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeKeyDown(JNIEnv * env, jobject thiz, jint keyCode) {
        CAApplication* application = CAApplication::getApplication();
        switch (keyCode) {
            case KEYCODE_BACK:
                if (application->getKeypadDispatcher()->dispatchKeypadMSG(CAKeypadDispatcher::KeypadMSGType::BackClicked))
                    return JNI_TRUE;
                break;
            case KEYCODE_MENU:
                if (application->getKeypadDispatcher()->dispatchKeypadMSG(CAKeypadDispatcher::KeypadMSGType::MenuClicked))
                    return JNI_TRUE;
                break;
            default:
                return JNI_FALSE;
        }
        return JNI_FALSE;
    }
}
<|endoftext|>


<commit_before>#include "AnimationLoaderANM.h"
#include <Animation/AnimationClip.h>
#include <Resources/ResourceManager.h>
#include <IO/BinaryReader.h>
#include <acl/core/compressed_clip.h>

namespace Resources
{

const Core::CRTTI& CAnimationLoaderANM::GetResultType() const
{
	return DEM::Anim::CAnimationClip::RTTI;
}
//---------------------------------------------------------------------

PResourceObject CAnimationLoaderANM::CreateResource(CStrID UID)
{
	if (!pResMgr) return nullptr;

	const char* pOutSubId;
	IO::PStream Stream = pResMgr->CreateResourceStream(UID, pOutSubId);
	if (!Stream || !Stream->Open(IO::SAM_READ, IO::SAP_SEQUENTIAL)) return nullptr;

	IO::CBinaryReader Reader(*Stream);

	//U32 Magic;
	//if (!Reader.Read(Magic) || Magic != 'ANIM') return nullptr;

	U32 ClipDataSize;
	if (!Reader.Read(ClipDataSize) || !ClipDataSize) return nullptr;
	Stream->Seek(-sizeof(U32), IO::Seek_Current);

	void* pBuffer = n_malloc_aligned(ClipDataSize, alignof(acl::CompressedClip));

	if (!pBuffer || Stream->Read(pBuffer, ClipDataSize) != ClipDataSize)
	{
		SAFE_FREE_ALIGNED(pBuffer);
		return nullptr;
	}

	auto pClip = reinterpret_cast<acl::CompressedClip*>(pBuffer);
	if (!pClip->is_valid(true).empty())
	{
		SAFE_FREE_ALIGNED(pBuffer);
		return nullptr;
	}

	return n_new(DEM::Anim::CAnimationClip(pClip));
}
//---------------------------------------------------------------------

}
<commit_msg>Fixed animation clip reading<commit_after>#include "AnimationLoaderANM.h"
#include <Animation/AnimationClip.h>
#include <Resources/ResourceManager.h>
#include <IO/BinaryReader.h>
#include <acl/core/compressed_clip.h>

namespace Resources
{

const Core::CRTTI& CAnimationLoaderANM::GetResultType() const
{
	return DEM::Anim::CAnimationClip::RTTI;
}
//---------------------------------------------------------------------

PResourceObject CAnimationLoaderANM::CreateResource(CStrID UID)
{
	if (!pResMgr) return nullptr;

	const char* pOutSubId;
	IO::PStream Stream = pResMgr->CreateResourceStream(UID, pOutSubId);
	if (!Stream || !Stream->Open(IO::SAM_READ, IO::SAP_SEQUENTIAL)) return nullptr;

	IO::CBinaryReader Reader(*Stream);

	//U32 Magic;
	//if (!Reader.Read(Magic) || Magic != 'ANIM') return nullptr;

	U32 ClipDataSize;
	if (!Reader.Read(ClipDataSize) || !ClipDataSize) return nullptr;

	// Clip size is a part of clip data, so it must be read again as a part of the clip
	Stream->Seek(-4, IO::Seek_Current);

	void* pBuffer = n_malloc_aligned(ClipDataSize, alignof(acl::CompressedClip));

	if (!pBuffer || Stream->Read(pBuffer, ClipDataSize) != ClipDataSize)
	{
		SAFE_FREE_ALIGNED(pBuffer);
		return nullptr;
	}

	auto pClip = reinterpret_cast<acl::CompressedClip*>(pBuffer);
	if (!pClip->is_valid(true).empty())
	{
		SAFE_FREE_ALIGNED(pBuffer);
		return nullptr;
	}

	return n_new(DEM::Anim::CAnimationClip(pClip));
}
//---------------------------------------------------------------------

}
<|endoftext|>


<commit_before>//   Copyright 2016-2020 Jean-Francois Poilpret
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

/*
 * Check DS1307 I2C device (real-time clock) and display output to the UART console.
 * This program uses FastArduino DS1307 support API.
 *
 * Wiring:
 * NB: you should add pullup resistors (10K-22K typically) on both SDA and SCL lines.
 * WARNING: wiring is very sensitive for I2C connections! When using breadboard, ensure
 * wires connections are tight and stable.
 * - on ATmega328P based boards (including Arduino UNO):
 *   - A4 (PC4, SDA): connected to DS1307 SDA pin
 *   - A5 (PC5, SCL): connected to DS1307 SCL pin
 *   - direct USB access
 * - on Arduino LEONARDO:
 *   - D2 (PD1, SDA): connected to DS1307 SDA pin
 *   - D3 (PD0, SCL): connected to DS1307 SDA pin
 *   - direct USB access
 * - on Arduino MEGA:
 *   - D20 (PD1, SDA): connected to DS1307 SDA pin
 *   - D21 (PD0, SCL): connected to DS1307 SDA pin
 *   - direct USB access
 * - on ATtinyX4 based boards:
 *   - D6 (PA6, SDA): connected to DS1307 SDA pin
 *   - D4 (PA4, SCL): connected to DS1307 SDA pin
 *   - D8 (PB0, TX): connected to SerialUSB converter
 * - on ATtinyX5 based boards:
 *   - D0 (PB0, SDA): connected to DS1307 SDA pin
 *   - D2 (PB2, SCL): connected to DS1307 SDA pin
 *   - D3 (PB3, TX): connected to SerialUSB converter
 */

#include <fastarduino/time.h>
#include <fastarduino/new_i2c_handler.h>
#include <fastarduino/devices/new_ds1307.h>
#include <fastarduino/iomanip.h>
#include <fastarduino/new_i2c_debug.h>

#if defined(ARDUINO_UNO) || defined(ARDUINO_NANO) || defined(BREADBOARD_ATMEGA328P)
#define HARDWARE_UART 1
#include <fastarduino/uart.h>
static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
static constexpr uint8_t I2C_BUFFER_SIZE = 32;
static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE];
// Define vectors we need in the example
REGISTER_UATX_ISR(0)
#elif defined(ARDUINO_MEGA)
#define HARDWARE_UART 1
#include <fastarduino/uart.h>
static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
static constexpr uint8_t I2C_BUFFER_SIZE = 32;
static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE];
// Define vectors we need in the example
REGISTER_UATX_ISR(0)
#elif defined(ARDUINO_LEONARDO)
#define HARDWARE_UART 1
#include <fastarduino/uart.h>
static constexpr const board::USART UART = board::USART::USART1;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
static constexpr uint8_t I2C_BUFFER_SIZE = 32;
static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE];
// Define vectors we need in the example
REGISTER_UATX_ISR(1)
#elif defined(BREADBOARD_ATTINYX4)
#define HARDWARE_UART 0
#include <fastarduino/soft_uart.h>
static constexpr const board::DigitalPin TX = board::DigitalPin::D8_PB0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
#elif defined(BREADBOARD_ATTINYX5)
#define HARDWARE_UART 0
#include <fastarduino/soft_uart.h>
static constexpr const board::DigitalPin TX = board::DigitalPin::D3_PB3;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
#else
#error "Current target is not yet supported!"
#endif

// #define DEBUG_I2C

// UART buffer for traces
static char output_buffer[OUTPUT_BUFFER_SIZE];

using devices::rtc::DS1307;
using devices::rtc::WeekDay;
using devices::rtc::tm;
using devices::rtc::SquareWaveFrequency;
using namespace streams;

#if I2C_TRUE_ASYNC

#ifdef DEBUG_I2C
static constexpr const uint8_t DEBUG_SIZE = 32;
using DEBUGGER = i2c::debug::I2CAsyncDebugger<DEBUG_SIZE>;
using MANAGER = i2c::I2CManager<i2c::I2CMode::STANDARD, false, true, DEBUGGER&>;
#define TRACE() debugger.trace(out)
#else
using MANAGER = i2c::I2CManager<i2c::I2CMode::STANDARD, false, false>;
#define TRACE()
#endif
REGISTER_I2C_ISR(MANAGER)

#else

#define TRACE()
#ifdef DEBUG_I2C
using DEBUGGER = i2c::debug::I2CSyncDebugger;
using MANAGER = i2c::I2CManager<i2c::I2CMode::STANDARD, false, true, DEBUGGER&>;
#else
using MANAGER = i2c::I2CManager<i2c::I2CMode::STANDARD, false, false>;
#endif

#endif

void display_status(ostream& out, char index, uint8_t status)
{
	out << hex << F("status #") << index << ' ' << status << endl;
}

void display_ram(ostream& out, const uint8_t* data, uint8_t size)
{
	out << hex << F("RAM content\n");
	for (uint8_t i = 0; i < size; ++i)
	{
		if (!(i % 8)) out << endl;
		out << setw(2) << data[i] << ' ';
	}
	out << endl;
}

void display_time(ostream& out, const tm& time)
{
	out	<< dec << F("RTC: [")
		<< uint8_t(time.tm_wday) << ']'
		<< time.tm_mday << '.'
		<< time.tm_mon << '.'
		<< time.tm_year << ' '
		<< time.tm_hour << ':'
		<< time.tm_min << ':'
		<< time.tm_sec
		<< endl;
}

int main() __attribute__((OS_main));
int main()
{
	board::init();
	sei();
#if HARDWARE_UART
	serial::hard::UATX<UART> uart{output_buffer};
#else
	serial::soft::UATX<TX> uart{output_buffer};
#endif
	uart.begin(115200);
	ostream out = uart.out();
	out << F("Start") << endl;

	// Start TWI interface
	//====================
#if I2C_TRUE_ASYNC

#ifdef DEBUG_I2C
	DEBUGGER debugger;
	MANAGER manager{i2c_buffer, debugger, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS};
#else
	MANAGER manager{i2c_buffer, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS};
#endif

#else

#ifdef DEBUG_I2C
	DEBUGGER debugger{out};
	MANAGER manager{debugger, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS};
#else
	MANAGER manager{i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS};
#endif

#endif

	manager.begin();
	out << F("I2C interface started") << endl;
	display_status(out, '1', manager.status());
	time::delay_ms(1000);

	DS1307<MANAGER> rtc{manager};

	// read RAM content and print out
	uint8_t data[DS1307<MANAGER>::ram_size()];
	memset(data, 0, sizeof data);
	rtc.get_ram(0, data);
	display_status(out, '2', manager.status());
	display_ram(out, data, sizeof data);
	TRACE();

	tm time1;
	time1.tm_hour = 8;
	time1.tm_min = 45;
	time1.tm_sec = 30;
	time1.tm_wday = WeekDay::TUESDAY;
	time1.tm_mday = 13;
	time1.tm_mon = 6;
	time1.tm_year = 17;

	// Initialize clock date
	//=======================
	rtc.set_datetime(time1);
	display_status(out, '3', manager.status());
	TRACE();

	time::delay_ms(2000);

	// Read clock
	//============
	tm time2;
	rtc.get_datetime(time2);
	display_status(out, '4', manager.status());
	display_time(out, time2);
	TRACE();

	// Enable output clock
	//====================
	rtc.enable_output(SquareWaveFrequency::FREQ_1HZ);
	display_status(out, '5', manager.status());
	TRACE();

	// Provide 10 seconds delay to allow checking square wave output with an oscilloscope
	time::delay_ms(10000);

	rtc.disable_output(false);
	display_status(out, '6', manager.status());
	TRACE();

	// write RAM content
	for (uint8_t i = 0; i < sizeof(data); ++i)
		data[i] = i;
	rtc.set_ram(0, data);
	display_status(out, '7', manager.status());
	TRACE();

	// Stop TWI interface
	//===================
	manager.end();
	out << F("End") << endl;
}
<commit_msg>Refactor I2C debugging in RTC example.<commit_after>//   Copyright 2016-2020 Jean-Francois Poilpret
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

/*
 * Check DS1307 I2C device (real-time clock) and display output to the UART console.
 * This program uses FastArduino DS1307 support API.
 *
 * Wiring:
 * NB: you should add pullup resistors (10K-22K typically) on both SDA and SCL lines.
 * WARNING: wiring is very sensitive for I2C connections! When using breadboard, ensure
 * wires connections are tight and stable.
 * - on ATmega328P based boards (including Arduino UNO):
 *   - A4 (PC4, SDA): connected to DS1307 SDA pin
 *   - A5 (PC5, SCL): connected to DS1307 SCL pin
 *   - direct USB access
 * - on Arduino LEONARDO:
 *   - D2 (PD1, SDA): connected to DS1307 SDA pin
 *   - D3 (PD0, SCL): connected to DS1307 SDA pin
 *   - direct USB access
 * - on Arduino MEGA:
 *   - D20 (PD1, SDA): connected to DS1307 SDA pin
 *   - D21 (PD0, SCL): connected to DS1307 SDA pin
 *   - direct USB access
 * - on ATtinyX4 based boards:
 *   - D6 (PA6, SDA): connected to DS1307 SDA pin
 *   - D4 (PA4, SCL): connected to DS1307 SDA pin
 *   - D8 (PB0, TX): connected to SerialUSB converter
 * - on ATtinyX5 based boards:
 *   - D0 (PB0, SDA): connected to DS1307 SDA pin
 *   - D2 (PB2, SCL): connected to DS1307 SDA pin
 *   - D3 (PB3, TX): connected to SerialUSB converter
 */

#include <fastarduino/time.h>
#include <fastarduino/new_i2c_handler.h>
#include <fastarduino/devices/new_ds1307.h>
#include <fastarduino/iomanip.h>
#include <fastarduino/new_i2c_debug.h>

#if defined(ARDUINO_UNO) || defined(ARDUINO_NANO) || defined(BREADBOARD_ATMEGA328P)
#define HARDWARE_UART 1
#include <fastarduino/uart.h>
static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
static constexpr uint8_t I2C_BUFFER_SIZE = 32;
static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE];
// Define vectors we need in the example
REGISTER_UATX_ISR(0)
#elif defined(ARDUINO_MEGA)
#define HARDWARE_UART 1
#include <fastarduino/uart.h>
static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
static constexpr uint8_t I2C_BUFFER_SIZE = 32;
static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE];
// Define vectors we need in the example
REGISTER_UATX_ISR(0)
#elif defined(ARDUINO_LEONARDO)
#define HARDWARE_UART 1
#include <fastarduino/uart.h>
static constexpr const board::USART UART = board::USART::USART1;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
static constexpr uint8_t I2C_BUFFER_SIZE = 32;
static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE];
// Define vectors we need in the example
REGISTER_UATX_ISR(1)
#elif defined(BREADBOARD_ATTINYX4)
#define HARDWARE_UART 0
#include <fastarduino/soft_uart.h>
static constexpr const board::DigitalPin TX = board::DigitalPin::D8_PB0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
#elif defined(BREADBOARD_ATTINYX5)
#define HARDWARE_UART 0
#include <fastarduino/soft_uart.h>
static constexpr const board::DigitalPin TX = board::DigitalPin::D3_PB3;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
#else
#error "Current target is not yet supported!"
#endif

// #define DEBUG_I2C

// UART buffer for traces
static char output_buffer[OUTPUT_BUFFER_SIZE];

using devices::rtc::DS1307;
using devices::rtc::WeekDay;
using devices::rtc::tm;
using devices::rtc::SquareWaveFrequency;
using namespace streams;

#ifdef DEBUG_I2C
static constexpr const uint8_t DEBUG_SIZE = 32;
using DEBUGGER = i2c::debug::I2CAsyncDebugger<DEBUG_SIZE>;
using MANAGER = i2c::I2CManager<i2c::I2CMode::STANDARD, false, true, DEBUGGER&>;
#define TRACE(OUT) debugger.trace(OUT)
#else
using MANAGER = i2c::I2CManager<i2c::I2CMode::STANDARD, false, false>;
#define TRACE(OUT)
#endif

#if I2C_TRUE_ASYNC
REGISTER_I2C_ISR(MANAGER)
#endif

void display_status(ostream& out, char index, uint8_t status)
{
	out << hex << F("status #") << index << ' ' << status << endl;
}

void display_ram(ostream& out, const uint8_t* data, uint8_t size)
{
	out << hex << F("RAM content\n");
	for (uint8_t i = 0; i < size; ++i)
	{
		if (!(i % 8)) out << endl;
		out << setw(2) << data[i] << ' ';
	}
	out << endl;
}

void display_time(ostream& out, const tm& time)
{
	out	<< dec << F("RTC: [")
		<< uint8_t(time.tm_wday) << ']'
		<< time.tm_mday << '.'
		<< time.tm_mon << '.'
		<< time.tm_year << ' '
		<< time.tm_hour << ':'
		<< time.tm_min << ':'
		<< time.tm_sec
		<< endl;
}

int main() __attribute__((OS_main));
int main()
{
	board::init();
	sei();
#if HARDWARE_UART
	serial::hard::UATX<UART> uart{output_buffer};
#else
	serial::soft::UATX<TX> uart{output_buffer};
#endif
	uart.begin(115200);
	ostream out = uart.out();
	out << F("Start") << endl;

	// Start TWI interface
	//====================
#ifdef DEBUG_I2C
	DEBUGGER debugger;
#endif

#if I2C_TRUE_ASYNC
#ifdef DEBUG_I2C
	MANAGER manager{i2c_buffer, debugger, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS};
#else
	MANAGER manager{i2c_buffer, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS};
#endif
#else
#ifdef DEBUG_I2C
	MANAGER manager{debugger, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS};
#else
	MANAGER manager{i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS};
#endif
#endif

	manager.begin();
	out << F("I2C interface started") << endl;
	display_status(out, '1', manager.status());
	time::delay_ms(1000);

	DS1307<MANAGER> rtc{manager};

	// read RAM content and print out
	uint8_t data[DS1307<MANAGER>::ram_size()];
	memset(data, 0, sizeof data);
	rtc.get_ram(0, data);
	display_status(out, '2', manager.status());
	display_ram(out, data, sizeof data);
	TRACE(out);

	tm time1;
	time1.tm_hour = 8;
	time1.tm_min = 45;
	time1.tm_sec = 30;
	time1.tm_wday = WeekDay::TUESDAY;
	time1.tm_mday = 13;
	time1.tm_mon = 6;
	time1.tm_year = 17;

	// Initialize clock date
	//=======================
	rtc.set_datetime(time1);
	display_status(out, '3', manager.status());
	TRACE(out);

	time::delay_ms(2000);

	// Read clock
	//============
	tm time2;
	rtc.get_datetime(time2);
	display_status(out, '4', manager.status());
	display_time(out, time2);
	TRACE(out);

	// Enable output clock
	//====================
	rtc.enable_output(SquareWaveFrequency::FREQ_1HZ);
	display_status(out, '5', manager.status());
	TRACE(out);

	// Provide 10 seconds delay to allow checking square wave output with an oscilloscope
	time::delay_ms(10000);

	rtc.disable_output(false);
	display_status(out, '6', manager.status());
	TRACE(out);

	// write RAM content
	for (uint8_t i = 0; i < sizeof(data); ++i)
		data[i] = i;
	rtc.set_ram(0, data);
	display_status(out, '7', manager.status());
	TRACE(out);

	// Stop TWI interface
	//===================
	manager.end();
	out << F("End") << endl;
}
<|endoftext|>


<commit_before>//
// $Id$
//
// This source file is a part of the Berlin Project.
// Copyright (C) 1998 Graydon Hoare <graydon@pobox.com>
// http://www.berlin-consortium.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public License
// as published by the Free Software Foundation; either version 2 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
// General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//

// this file is a bunch of little utilities for helping with name service, which
// is so baroque and ugly it mucks up readability if you include code
// inplace to handle it.

#include <Warsaw/config.hh>
#include <Berlin/NameUtil.hh>
#include <Berlin/Debug.hh>

static CosNaming::NamingContext_var rootContext;
static omni_mutex rootContext_mutex;

// this verifies that we have a root context reference. there's really
// no point in trying to catch these. If you have no name service,
// you're sunk.
static void getRootContext(CORBA::ORB_ptr orb) {
  try{

    if (CORBA::is_nil(rootContext)) {
      debug::log("Looking up Root Nameservice", debug::name);
      CORBA::Object_var initServ = orb->resolve_initial_references("NameService");
      rootContext = CosNaming::NamingContext::_narrow(initServ);

      if (CORBA::is_nil(rootContext)) {
	debug::log("Root name context is nil!", debug::name);
	throw CORBA::ORB::InvalidName();
      }
    }
  }  catch(CosNaming::NamingContext::NotFound& ex) {
    debug::log("Root Name Context not found.", debug::name);
    throw ex;
  } catch (CORBA::COMM_FAILURE& ex) {
    debug::log("had a COMM_FAILURE during root name service lookup", debug::name);
    throw ex;
  } catch (...) {
    debug::log("unknown exception during root name service lookup", debug::name);
    throw CosNaming::NamingContext::NotFound();
  }
}

const CosNaming::Name charPtrToName(char *ch) {
  CosNaming::Name objectName;
  objectName.length(1);
  objectName[0].id   = (const char*) ch;
  objectName[0].kind = (const char*) "Object";
  return objectName;
}

void bindObjectToName(CORBA::ORB_ptr orb, CORBA::Object_ptr obj, char *ch) {
  rootContext_mutex.lock();
  getRootContext(orb);
  CosNaming::Name ourName = charPtrToName(ch);
  rootContext->rebind(ourName, obj);
  rootContext_mutex.unlock();
}

CORBA::Object_ptr lookup(CORBA::ORB_ptr orb, char *ch)
  throw (lookupFailureException) {

  CORBA::Object_var tmpobj;

  rootContext_mutex.lock();
  getRootContext(orb);
  rootContext_mutex.unlock();

  CosNaming::Name ourName = charPtrToName(ch);

  try {
    tmpobj = rootContext->resolve(ourName);
  }
  catch (CORBA::COMM_FAILURE& ex) {
    debug::log("unable to contact name service for factory lookup", debug::name);
    throw lookupFailureException();
  }
  catch (...) {
    debug::log("Caught a system exception while using the naming service.", debug::name);
    throw lookupFailureException();
  }
  return CORBA::Object::_duplicate(tmpobj);
}

<commit_msg>minor nameservice changes - don't throw when in try{} block<commit_after>//
// $Id$
//
// This source file is a part of the Berlin Project.
// Copyright (C) 1998 Graydon Hoare <graydon@pobox.com>
// http://www.berlin-consortium.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public License
// as published by the Free Software Foundation; either version 2 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
// General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//

// this file is a bunch of little utilities for helping with name service, which
// is so baroque and ugly it mucks up readability if you include code
// inplace to handle it.

#include <Warsaw/config.hh>
#include <Berlin/NameUtil.hh>
#include <Berlin/Debug.hh>

static CosNaming::NamingContext_var rootContext;
static omni_mutex rootContext_mutex;

// this verifies that we have a root context reference. there's really
// no point in trying to catch these. If you have no name service,
// you're sunk.
static void getRootContext(CORBA::ORB_ptr orb) {
  try {
    if (CORBA::is_nil(rootContext)) {
      debug::log("Looking up Root Nameservice", debug::name);
      CORBA::Object_var initServ;
      initServ = orb->resolve_initial_references("NameService");
      rootContext = CosNaming::NamingContext::_narrow(initServ);
    }
  } catch(CORBA::ORB::InvalidName& ex) {
    debug::log("Service required is invalid [does not exist].", debug::name);
    throw ex;
  } catch(CosNaming::NamingContext::NotFound& ex) {
    debug::log("Root Name Context not found.", debug::name);
    throw ex;
  } catch (CORBA::COMM_FAILURE& ex) {
    debug::log("had a COMM_FAILURE during root name service lookup", debug::name);
    throw ex;
  } catch (...) {
    debug::log("unknown exception during root name service lookup", debug::name);
    throw CosNaming::NamingContext::NotFound();
  }

  // can't throw an exception if you are in a try {} block :)
  if (CORBA::is_nil(rootContext)) {
    debug::log("Root name context is nil!", debug::name);
    throw CORBA::ORB::InvalidName();
  }
}

const CosNaming::Name charPtrToName(char *ch) {
  CosNaming::Name objectName;
  objectName.length(1);
  objectName[0].id   = (const char*) ch;
  objectName[0].kind = (const char*) "Object";
  return objectName;
}

void bindObjectToName(CORBA::ORB_ptr orb, CORBA::Object_ptr obj, char *ch) {
  rootContext_mutex.lock();
  getRootContext(orb);
  CosNaming::Name ourName = charPtrToName(ch);
  rootContext->rebind(ourName, obj);
  rootContext_mutex.unlock();
}

CORBA::Object_ptr lookup(CORBA::ORB_ptr orb, char *ch)
  throw (lookupFailureException) {

  CORBA::Object_var tmpobj;

  rootContext_mutex.lock();
  getRootContext(orb);
  rootContext_mutex.unlock();

  CosNaming::Name ourName = charPtrToName(ch);

  try {
    tmpobj = rootContext->resolve(ourName);
  }
  catch (CORBA::COMM_FAILURE& ex) {
    debug::log("unable to contact name service for factory lookup", debug::name);
    throw lookupFailureException();
  }
  catch (...) {
    debug::log("Caught a system exception while using the naming service.", debug::name);
    throw lookupFailureException();
  }
  return CORBA::Object::_duplicate(tmpobj);
}

<|endoftext|>


<commit_before>#include <jni.h>
#include <sstream>
#include <string>
#include <stdio.h>

#include <android/log.h>

#include "utils.cpp"
#include "amanda.cpp"

extern "C" {

// Process a frame
JNIEXPORT jboolean JNICALL
Java_com_example_tristan_appattempt_LearnActivity_processFrame(JNIEnv *env, jobject instance,
																	jlong iAddr1, jlong iAddr2, jchar c) {

	// Prepare source and destination image pointers
	Mat *src = (Mat *) iAddr1;
	Mat *dst = (Mat *) iAddr2;
	flip(*src, *src, 1);
	//__android_log_print(ANDROID_LOG_ERROR, "MyLogs", "GlobalN address: %p", &globalN);

	//cropImage(*src, *dst);

	return checkIfCorrect(*src, c);
}

// Assigns values to configuration globals
JNIEXPORT void JNICALL
Java_com_example_tristan_appattempt_LearnActivity_initGlobals(JNIEnv *env, jobject instance,
																   jstring externalStoragePath) {

	sign_cascade_folder = jstring2string(env, externalStoragePath) + "/signcoach/data/";
	__android_log_print(ANDROID_LOG_ERROR, "initGlobals", "sign_cascade_folder: %s", sign_cascade_folder.c_str());

	FILE* file = fopen("/sdcard/textTest.txt","w+");
	if (file == NULL) {
		__android_log_print(ANDROID_LOG_ERROR, "initGlobals", "Error fopen: %d (%s)", errno, strerror(errno));
	} else {
		__android_log_print(ANDROID_LOG_ERROR, "initGlobals", "File open!");
	}
	fputs("hello, world\n", file);
	fclose(file);
}

}<commit_msg>fixed jni problems after root change<commit_after>#include <jni.h>
#include <sstream>
#include <string>
#include <stdio.h>

#include <android/log.h>

#include "utils.cpp"
#include "amanda.cpp"

extern "C" {

// Process a frame
JNIEXPORT jboolean JNICALL
Java_com_danycabrera_signcoach_LearnActivity_processFrame(JNIEnv *env, jobject instance,
																	jlong iAddr1, jlong iAddr2, jchar c) {

	// Prepare source and destination image pointers
	Mat *src = (Mat *) iAddr1;
	Mat *dst = (Mat *) iAddr2;
	flip(*src, *src, 1);
	//__android_log_print(ANDROID_LOG_ERROR, "MyLogs", "GlobalN address: %p", &globalN);

	//cropImage(*src, *dst);

	return checkIfCorrect(*src, c);
}

// Assigns values to configuration globals
JNIEXPORT void JNICALL
Java_com_danycabrera_signcoach_MainActivity_initGlobals(JNIEnv *env, jobject instance,
																   jstring externalStoragePath) {

	sign_cascade_folder = jstring2string(env, externalStoragePath) + "/signcoach/data/";
	__android_log_print(ANDROID_LOG_ERROR, "initGlobals", "sign_cascade_folder: %s", sign_cascade_folder.c_str());

	FILE* file = fopen("/sdcard/textTest.txt","w+");
	if (file == NULL) {
		__android_log_print(ANDROID_LOG_ERROR, "initGlobals", "Error fopen: %d (%s)", errno, strerror(errno));
	} else {
		__android_log_print(ANDROID_LOG_ERROR, "initGlobals", "File open!");
	}
	fputs("hello, world\n", file);
	fclose(file);
}

}<|endoftext|>


<commit_before>#include "glwidget.h"

#include <QTimer>

#include "emitter.h"
#include "dummyrenderer.h"

GLWidget::GLWidget(QWidget *parent) :
  QGLWidget(parent),
  _timer(NULL),
  _elapsedTimer(NULL),
  _lastFrameTime(0),
  _emitter(NULL) {
}

GLWidget::~GLWidget() {
  if(_timer) delete _timer;
  if(_elapsedTimer) delete _elapsedTimer;
  if(_emitter) delete _emitter;
}

QSize GLWidget::minimumSizeHint() const {
  return QSize(80, 60);
}

QSize GLWidget::sizeHint() const {
  return QSize(800, 600);
}

void GLWidget::animate() {
  int current = _elapsedTimer->elapsed();
  int elapsed = (float)(current - _lastFrameTime);
  _lastFrameTime = current;

  _emitter->update(elapsed);

  updateGL();
}

void GLWidget::initializeGL() {
  glClearColor(.0, .0, .0, 1.0);
  glShadeModel(GL_FLAT);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);

  // Create the elapsed timer
  _elapsedTimer = new QElapsedTimer();
  _elapsedTimer->start();

  // Fire the animation timer
  if(_timer != NULL) delete _timer;
  _timer = new QTimer(this);
  connect(_timer, SIGNAL(timeout()), this, SLOT(animate()));
  _timer->start(0);

  //@TODO: do time management in a better way

  _emitter = new Emitter(Vector4D(), Vector4D(1, 1, 1, 1), 100);
  _emitter->renderer(new DummyRenderer());
}

void GLWidget::paintGL() {
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  _emitter->draw();
}

void GLWidget::resizeGL(int w, int h) {
  glViewport(0, 0, (GLuint) w, (GLuint) h);
}
<commit_msg>Fixed DummyRenderer reference<commit_after>#include "glwidget.h"

#include <QTimer>

#include "emitter.h"
#include "renderers/dummyrenderer.h"

GLWidget::GLWidget(QWidget *parent) :
  QGLWidget(parent),
  _timer(NULL),
  _elapsedTimer(NULL),
  _lastFrameTime(0),
  _emitter(NULL) {
}

GLWidget::~GLWidget() {
  if(_timer) delete _timer;
  if(_elapsedTimer) delete _elapsedTimer;
  if(_emitter) delete _emitter;
}

QSize GLWidget::minimumSizeHint() const {
  return QSize(80, 60);
}

QSize GLWidget::sizeHint() const {
  return QSize(800, 600);
}

void GLWidget::animate() {
  int current = _elapsedTimer->elapsed();
  int elapsed = (float)(current - _lastFrameTime);
  _lastFrameTime = current;

  _emitter->update(elapsed);

  updateGL();
}

void GLWidget::initializeGL() {
  glClearColor(.0, .0, .0, 1.0);
  glShadeModel(GL_FLAT);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);

  // Create the elapsed timer
  _elapsedTimer = new QElapsedTimer();
  _elapsedTimer->start();

  // Fire the animation timer
  if(_timer != NULL) delete _timer;
  _timer = new QTimer(this);
  connect(_timer, SIGNAL(timeout()), this, SLOT(animate()));
  _timer->start(0);

  //@TODO: do time management in a better way

  _emitter = new Emitter(Vector4D(), Vector4D(1, 1, 1, 1), 100);
  _emitter->renderer(new DummyRenderer());
}

void GLWidget::paintGL() {
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  _emitter->draw();
}

void GLWidget::resizeGL(int w, int h) {
  glViewport(0, 0, (GLuint) w, (GLuint) h);
}
<|endoftext|>


<commit_before>/**************************************************************************
 *
 * Copyright 2011 Jose Fonseca
 * All Rights Reserved.
 *
 * 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 OR COPYRIGHT HOLDERS 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 "glimports.hpp"
#include "glws.hpp"

namespace glws {

class XlibVisual : public Visual
{
public:
    XVisualInfo *visinfo;

    XlibVisual(XVisualInfo *vi) :
        visinfo(vi)
    {}

    ~XlibVisual() {
        XFree(visinfo);
    }
};

class XlibDrawable : public Drawable
{
public:
    Display *display;
    Window window;

    XlibDrawable(const Visual *vis, Display *dpy, Window win) :
        Drawable(vis),
        display(dpy),
        window(win)
    {}

    ~XlibDrawable() {
        XDestroyWindow(display, window);
    }

    void
    resize(unsigned w, unsigned h) {
        Drawable::resize(w, h);
        XResizeWindow(display, window, w, h);
    }

    void swapBuffers(void) {
        glXSwapBuffers(display, window);
    }
};

class XlibContext : public Context
{
public:
    Display *display;
    GLXContext context;

    XlibContext(const Visual *vis, Display *dpy, GLXContext ctx) :
        Context(vis),
        display(dpy),
        context(ctx)
    {}

    ~XlibContext() {
        glXDestroyContext(display, context);
    }
};

class XlibWindowSystem : public WindowSystem
{
private:
    Display *display;
    int screen;

public:
    XlibWindowSystem() {
        display = XOpenDisplay(NULL);
        screen = DefaultScreen(display);
    }

    ~XlibWindowSystem() {
        XCloseDisplay(display);
    }

    Visual *
    createVisual(bool doubleBuffer) {
        int single_attribs[] = {
            GLX_RGBA,
            GLX_RED_SIZE, 1,
            GLX_GREEN_SIZE, 1,
            GLX_BLUE_SIZE, 1,
            GLX_DEPTH_SIZE, 1,
            None
        };

        int double_attribs[] = {
            GLX_RGBA,
            GLX_RED_SIZE, 1,
            GLX_GREEN_SIZE, 1,
            GLX_BLUE_SIZE, 1,
            GLX_DOUBLEBUFFER,
            GLX_DEPTH_SIZE, 1,
            None
        };

        XVisualInfo *visinfo;

        visinfo = glXChooseVisual(display, screen, doubleBuffer ? double_attribs : single_attribs);

        return new XlibVisual(visinfo);
    }

    Drawable *
    createDrawable(const Visual *visual)
    {
        XVisualInfo *visinfo = dynamic_cast<const XlibVisual *>(visual)->visinfo;

        Window root = RootWindow(display, screen);

        /* window attributes */
        XSetWindowAttributes attr;
        attr.background_pixel = 0;
        attr.border_pixel = 0;
        attr.colormap = XCreateColormap(display, root, visinfo->visual, AllocNone);
        attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;

        unsigned long mask;
        mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

        int x = 0, y = 0, width = 256, height = 256;

        Window window = XCreateWindow(
            display, root,
            x, y, width, height,
            0,
            visinfo->depth,
            InputOutput,
            visinfo->visual,
            mask,
            &attr);

        XSizeHints sizehints;
        sizehints.x = x;
        sizehints.y = y;
        sizehints.width  = width;
        sizehints.height = height;
        sizehints.flags = USSize | USPosition;
        XSetNormalHints(display, window, &sizehints);

        const char *name = "glretrace";
        XSetStandardProperties(
            display, window, name, name,
            None, (char **)NULL, 0, &sizehints);

        XMapWindow(display, window);

        return new XlibDrawable(visual, display, window);
    }

    Context *
    createContext(const Visual *visual)
    {
        XVisualInfo *visinfo = dynamic_cast<const XlibVisual *>(visual)->visinfo;
        GLXContext context = glXCreateContext(display, visinfo, NULL, True);
        return new XlibContext(visual, display, context);
    }

    bool
    makeCurrent(Drawable *drawable, Context *context)
    {
        Window win = drawable ? dynamic_cast<XlibDrawable *>(drawable)->window : NULL;
        GLXContext ctx = context ? dynamic_cast<XlibContext *>(context)->context : NULL;

        return glXMakeCurrent(display, win, ctx);
    }

    bool
    processEvents(void) {
        while (XPending(display) > 0) {
            XEvent event;
            XNextEvent(display, &event);
            // TODO
        }
        return true;
    }
};

WindowSystem *createNativeWindowSystem(void) {
    return new XlibWindowSystem();
}

} /* namespace glretrace */
<commit_msg>Minor cleanup.<commit_after>/**************************************************************************
 *
 * Copyright 2011 Jose Fonseca
 * All Rights Reserved.
 *
 * 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 OR COPYRIGHT HOLDERS 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 "glimports.hpp"
#include "glws.hpp"

namespace glws {

class GlxVisual : public Visual
{
public:
    XVisualInfo *visinfo;

    GlxVisual(XVisualInfo *vi) :
        visinfo(vi)
    {}

    ~GlxVisual() {
        XFree(visinfo);
    }
};

class GlxDrawable : public Drawable
{
public:
    Display *display;
    Window window;

    GlxDrawable(const Visual *vis, Display *dpy, Window win) :
        Drawable(vis),
        display(dpy),
        window(win)
    {}

    ~GlxDrawable() {
        XDestroyWindow(display, window);
    }

    void
    resize(unsigned w, unsigned h) {
        Drawable::resize(w, h);
        XResizeWindow(display, window, w, h);
    }

    void swapBuffers(void) {
        glXSwapBuffers(display, window);
    }
};

class GlxContext : public Context
{
public:
    Display *display;
    GLXContext context;

    GlxContext(const Visual *vis, Display *dpy, GLXContext ctx) :
        Context(vis),
        display(dpy),
        context(ctx)
    {}

    ~GlxContext() {
        glXDestroyContext(display, context);
    }
};

class GlxWindowSystem : public WindowSystem
{
private:
    Display *display;
    int screen;

public:
    GlxWindowSystem() {
        display = XOpenDisplay(NULL);
        screen = DefaultScreen(display);
    }

    ~GlxWindowSystem() {
        XCloseDisplay(display);
    }

    Visual *
    createVisual(bool doubleBuffer) {
        int single_attribs[] = {
            GLX_RGBA,
            GLX_RED_SIZE, 1,
            GLX_GREEN_SIZE, 1,
            GLX_BLUE_SIZE, 1,
            GLX_DEPTH_SIZE, 1,
            None
        };

        int double_attribs[] = {
            GLX_RGBA,
            GLX_RED_SIZE, 1,
            GLX_GREEN_SIZE, 1,
            GLX_BLUE_SIZE, 1,
            GLX_DOUBLEBUFFER,
            GLX_DEPTH_SIZE, 1,
            None
        };

        XVisualInfo *visinfo;

        visinfo = glXChooseVisual(display, screen, doubleBuffer ? double_attribs : single_attribs);

        return new GlxVisual(visinfo);
    }

    Drawable *
    createDrawable(const Visual *visual)
    {
        XVisualInfo *visinfo = dynamic_cast<const GlxVisual *>(visual)->visinfo;

        Window root = RootWindow(display, screen);

        /* window attributes */
        XSetWindowAttributes attr;
        attr.background_pixel = 0;
        attr.border_pixel = 0;
        attr.colormap = XCreateColormap(display, root, visinfo->visual, AllocNone);
        attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;

        unsigned long mask;
        mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

        int x = 0, y = 0, width = 256, height = 256;

        Window window = XCreateWindow(
            display, root,
            x, y, width, height,
            0,
            visinfo->depth,
            InputOutput,
            visinfo->visual,
            mask,
            &attr);

        XSizeHints sizehints;
        sizehints.x = x;
        sizehints.y = y;
        sizehints.width  = width;
        sizehints.height = height;
        sizehints.flags = USSize | USPosition;
        XSetNormalHints(display, window, &sizehints);

        const char *name = "glretrace";
        XSetStandardProperties(
            display, window, name, name,
            None, (char **)NULL, 0, &sizehints);

        XMapWindow(display, window);

        return new GlxDrawable(visual, display, window);
    }

    Context *
    createContext(const Visual *visual)
    {
        XVisualInfo *visinfo = dynamic_cast<const GlxVisual *>(visual)->visinfo;
        GLXContext context = glXCreateContext(display, visinfo, NULL, True);
        return new GlxContext(visual, display, context);
    }

    bool
    makeCurrent(Drawable *drawable, Context *context)
    {
        if (!drawable || !context) {
            return glXMakeCurrent(display, NULL, NULL);
        } else {
            GlxDrawable *glxDrawable = dynamic_cast<GlxDrawable *>(drawable);
            GlxContext *glxContext = dynamic_cast<GlxContext *>(context);

            return glXMakeCurrent(display, glxDrawable->window, glxContext->context);
        }
    }

    bool
    processEvents(void) {
        while (XPending(display) > 0) {
            XEvent event;
            XNextEvent(display, &event);
            // TODO
        }
        return true;
    }
};

WindowSystem *createNativeWindowSystem(void) {
    return new GlxWindowSystem();
}

} /* namespace glretrace */
<|endoftext|>


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <boost/exception/to_string.hpp>

#include "Examples/ExampleStapling/StapleElement.h"
#include "Examples/ExampleStapling/StaplerBehavior.h"
#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Graphics/SceneryRepresentation.h"
#include "SurgSim/Input/InputComponent.h"
#include "SurgSim/Physics/Constraint.h"
#include "SurgSim/Physics/ConstraintComponent.h"
#include "SurgSim/Physics/Localization.h"
#include "SurgSim/Physics/RigidCollisionRepresentation.h"
#include "SurgSim/Physics/RigidRepresentationBilateral3D.h"

using SurgSim::Physics::ConstraintImplementation;
using SurgSim::Physics::RigidRepresentationBilateral3D;
using SurgSim::Physics::Localization;

StaplerBehavior::StaplerBehavior(const std::string& name):
	SurgSim::Framework::Behavior(name),
	m_numElements(0),
	m_buttonPreviouslyPressed(false)
{
}

void StaplerBehavior::setInputComponent(std::shared_ptr<SurgSim::Input::InputComponent> inputComponent)
{
	m_from = inputComponent;
}

void StaplerBehavior::setCollisionRepresentation(
	 std::shared_ptr<SurgSim::Collision::Representation> staplerRepresentation)
{
	m_collisionRepresentation = staplerRepresentation;
}

static std::shared_ptr<SurgSim::Collision::Representation> findMostCollidedRepresentation(
	const std::shared_ptr<SurgSim::Collision::Representation>& object)
{
	typedef std::unordered_map<std::shared_ptr<SurgSim::Collision::Representation>,
							   std::list<std::shared_ptr<SurgSim::Collision::Contact>>> MapType;

	MapType collisionsMap = object->getCollisions();

	if (collisionsMap.empty())
	{
		return nullptr;
	}

	auto result = std::max_element(collisionsMap.begin(),
								   collisionsMap.end(),
								   [](const MapType::value_type& lhs, const MapType::value_type& rhs)
								   { return lhs.second.size() < rhs.second.size(); });

	return (*result).first;
}

static std::shared_ptr<SurgSim::Collision::Contact> findDeepestContact(
	const std::shared_ptr<SurgSim::Collision::Representation>& object,
	const std::shared_ptr<SurgSim::Collision::Representation>& intersectingObject)
{
	const std::list<std::shared_ptr<SurgSim::Collision::Contact>>& contacts
		= object->getCollisions().at(intersectingObject);

	if (contacts.empty())
	{
		return nullptr;
	}

	auto result = std::max_element(contacts.begin(),
								   contacts.end(),
								   [](const std::shared_ptr<SurgSim::Collision::Contact>& lhs,
									  const std::shared_ptr<SurgSim::Collision::Contact>& rhs)
								   { return lhs->depth < rhs->depth; });

	return *result;
}

void StaplerBehavior::update(double dt)
{
	SurgSim::DataStructures::DataGroup dataGroup;
	m_from->getData(&dataGroup);

	// Check if the stapler is being pressed.
	bool button1 = false;
	dataGroup.booleans().get("button1", &button1);

	bool processButtonPush = button1 && m_buttonPreviouslyPressed;
	m_buttonPreviouslyPressed = button1;

	if (!processButtonPush)
	{
		return;
	}

	// Create the staple (not added to the scene right now).
	std::string stapleName = "stapleId_" + boost::to_string(m_numElements++);
	auto staple = std::make_shared<StapleElement>(stapleName);
	staple->setPose(m_collisionRepresentation->getPose());

	std::vector<std::shared_ptr<SurgSim::Collision::Representation>> virtualStaples;
	virtualStaples.push_back(m_collisionRepresentation);

	int toothId = 0;
	auto virtualStaple = virtualStaples.begin();
	bool stapleElementCreated = false;
	for (; virtualStaple != virtualStaples.end(); ++virtualStaple)
	{
		// The virtual staple could be in contact with any number of objects in the scene.
		// Find the object it has most collision pairs with.
		std::shared_ptr<SurgSim::Collision::Representation> mostCollidedObject
			= findMostCollidedRepresentation(*virtualStaple);

		if (mostCollidedObject == nullptr)
		{
			continue;
		}

		// Iterate through the list of collision pairs to find a point of constraint with the deepest contact.
		std::shared_ptr<SurgSim::Collision::Contact> chosenContact
			= findDeepestContact(*virtualStaple, mostCollidedObject);

		if (chosenContact == nullptr)
		{
			continue;
		}

		// Create the staple with no collision representation.
		if (!stapleElementCreated)
		{
			staple->setHasCollisionRepresentation(false);
			getScene()->addSceneElement(staple);
			stapleElementCreated = true;
		}

		// Get the physics representation of the mostCollidedObject.
		// Done by dynamic type casting.
		std::shared_ptr<SurgSim::Physics::RigidCollisionRepresentation> rigidCollisionRepresentation =
			std::dynamic_pointer_cast<SurgSim::Physics::RigidCollisionRepresentation>(mostCollidedObject);

		if (rigidCollisionRepresentation == nullptr)
		{
			continue;
		}

		std::shared_ptr<SurgSim::Physics::RigidRepresentationBase> physicsRepresentation =
			rigidCollisionRepresentation->getRigidRepresentation();

		if (physicsRepresentation == nullptr)
		{
			continue;
		}

		// Create a bilateral constraint between the physicsRepresentation and staple.
		// First find the points where the constraint is going to be applied.
		std::shared_ptr<Localization> stapleLocalization;
		std::shared_ptr<Localization> otherLocalization;

		stapleLocalization =
			staple->getPhysicsRepresentation()->createLocalization(chosenContact->penetrationPoints.first);
		stapleLocalization->setRepresentation(staple->getPhysicsRepresentation());

		otherLocalization = physicsRepresentation->createLocalization(chosenContact->penetrationPoints.second);
		otherLocalization->setRepresentation(physicsRepresentation);

		// Create the Constraint.
		std::shared_ptr<SurgSim::Physics::Constraint> constraint =
			std::make_shared<SurgSim::Physics::Constraint>(
				std::make_shared<SurgSim::Physics::ConstraintData>(),
				std::make_shared<RigidRepresentationBilateral3D>(),
				stapleLocalization,
				std::make_shared<RigidRepresentationBilateral3D>(),
				otherLocalization);

		std::shared_ptr<SurgSim::Physics::ConstraintComponent> constraintComponent =
			std::make_shared<SurgSim::Physics::ConstraintComponent>(
				stapleName + "_bilateral_constraint_" + boost::to_string(toothId++));

		constraintComponent->setConstraint(constraint);
		staple->addComponent(constraintComponent);
	}

	if (!stapleElementCreated)
	{
		// Create the staple element.
		getScene()->addSceneElement(staple);
	}
}

int StaplerBehavior::getTargetManagerType() const
{
	return SurgSim::Framework::MANAGER_TYPE_INPUT;
}

bool StaplerBehavior::doInitialize()
{
	SURGSIM_ASSERT(m_from) << "StaplerBehavior: no InputComponent held.";
	return true;
}

bool StaplerBehavior::doWakeUp()
{
	return true;
}
<commit_msg>Staple example, fix minor issue with adding staple<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <boost/exception/to_string.hpp>

#include "Examples/ExampleStapling/StapleElement.h"
#include "Examples/ExampleStapling/StaplerBehavior.h"
#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Graphics/SceneryRepresentation.h"
#include "SurgSim/Input/InputComponent.h"
#include "SurgSim/Physics/Constraint.h"
#include "SurgSim/Physics/ConstraintComponent.h"
#include "SurgSim/Physics/Localization.h"
#include "SurgSim/Physics/RigidCollisionRepresentation.h"
#include "SurgSim/Physics/RigidRepresentationBilateral3D.h"

using SurgSim::Physics::ConstraintImplementation;
using SurgSim::Physics::RigidRepresentationBilateral3D;
using SurgSim::Physics::Localization;

StaplerBehavior::StaplerBehavior(const std::string& name):
	SurgSim::Framework::Behavior(name),
	m_numElements(0),
	m_buttonPreviouslyPressed(false)
{
}

void StaplerBehavior::setInputComponent(std::shared_ptr<SurgSim::Input::InputComponent> inputComponent)
{
	m_from = inputComponent;
}

void StaplerBehavior::setCollisionRepresentation(
	 std::shared_ptr<SurgSim::Collision::Representation> staplerRepresentation)
{
	m_collisionRepresentation = staplerRepresentation;
}

static std::shared_ptr<SurgSim::Collision::Representation> findMostCollidedRepresentation(
	const std::shared_ptr<SurgSim::Collision::Representation>& object)
{
	typedef std::unordered_map<std::shared_ptr<SurgSim::Collision::Representation>,
							   std::list<std::shared_ptr<SurgSim::Collision::Contact>>> MapType;

	MapType collisionsMap = object->getCollisions();

	if (collisionsMap.empty())
	{
		return nullptr;
	}

	auto result = std::max_element(collisionsMap.begin(),
								   collisionsMap.end(),
								   [](const MapType::value_type& lhs, const MapType::value_type& rhs)
								   { return lhs.second.size() < rhs.second.size(); });

	return (*result).first;
}

static std::shared_ptr<SurgSim::Collision::Contact> findDeepestContact(
	const std::shared_ptr<SurgSim::Collision::Representation>& object,
	const std::shared_ptr<SurgSim::Collision::Representation>& intersectingObject)
{
	const std::list<std::shared_ptr<SurgSim::Collision::Contact>>& contacts
		= object->getCollisions().at(intersectingObject);

	if (contacts.empty())
	{
		return nullptr;
	}

	auto result = std::max_element(contacts.begin(),
								   contacts.end(),
								   [](const std::shared_ptr<SurgSim::Collision::Contact>& lhs,
									  const std::shared_ptr<SurgSim::Collision::Contact>& rhs)
								   { return lhs->depth < rhs->depth; });

	return *result;
}

void StaplerBehavior::update(double dt)
{
	SurgSim::DataStructures::DataGroup dataGroup;
	m_from->getData(&dataGroup);

	// Check if the stapler is being pressed.
	bool button1 = false;
	dataGroup.booleans().get("button1", &button1);

	bool processButtonPush = button1 && m_buttonPreviouslyPressed;
	m_buttonPreviouslyPressed = button1;

	if (!processButtonPush)
	{
		return;
	}

	// Create the staple (not added to the scene right now).
	std::string stapleName = "stapleId_" + boost::to_string(m_numElements++);
	auto staple = std::make_shared<StapleElement>(stapleName);
	staple->setPose(m_collisionRepresentation->getPose());

	std::vector<std::shared_ptr<SurgSim::Collision::Representation>> virtualStaples;
	virtualStaples.push_back(m_collisionRepresentation);

	int toothId = 0;
	auto virtualStaple = virtualStaples.begin();
	bool stapleElementCreated = false;
	for (; virtualStaple != virtualStaples.end(); ++virtualStaple)
	{
		// The virtual staple could be in contact with any number of objects in the scene.
		// Find the object it has most collision pairs with.
		std::shared_ptr<SurgSim::Collision::Representation> mostCollidedObject
			= findMostCollidedRepresentation(*virtualStaple);

		if (mostCollidedObject == nullptr)
		{
			continue;
		}

		// Iterate through the list of collision pairs to find a point of constraint with the deepest contact.
		std::shared_ptr<SurgSim::Collision::Contact> chosenContact
			= findDeepestContact(*virtualStaple, mostCollidedObject);

		if (chosenContact == nullptr)
		{
			continue;
		}

		// Get the physics representation of the mostCollidedObject.
		// Done by dynamic type casting.
		std::shared_ptr<SurgSim::Physics::RigidCollisionRepresentation> rigidCollisionRepresentation =
			std::dynamic_pointer_cast<SurgSim::Physics::RigidCollisionRepresentation>(mostCollidedObject);

		if (rigidCollisionRepresentation == nullptr)
		{
			continue;
		}

		std::shared_ptr<SurgSim::Physics::RigidRepresentationBase> physicsRepresentation =
			rigidCollisionRepresentation->getRigidRepresentation();

		if (physicsRepresentation == nullptr)
		{
			continue;
		}

		// Create the staple with no collision representation.
		if (!stapleElementCreated)
		{
			staple->setHasCollisionRepresentation(false);
			getScene()->addSceneElement(staple);
			stapleElementCreated = true;
		}

		// Create a bilateral constraint between the physicsRepresentation and staple.
		// First find the points where the constraint is going to be applied.
		std::shared_ptr<Localization> stapleLocalization;
		std::shared_ptr<Localization> otherLocalization;

		stapleLocalization =
			staple->getPhysicsRepresentation()->createLocalization(chosenContact->penetrationPoints.first);
		stapleLocalization->setRepresentation(staple->getPhysicsRepresentation());

		otherLocalization = physicsRepresentation->createLocalization(chosenContact->penetrationPoints.second);
		otherLocalization->setRepresentation(physicsRepresentation);

		// Create the Constraint.
		std::shared_ptr<SurgSim::Physics::Constraint> constraint =
			std::make_shared<SurgSim::Physics::Constraint>(
				std::make_shared<SurgSim::Physics::ConstraintData>(),
				std::make_shared<RigidRepresentationBilateral3D>(),
				stapleLocalization,
				std::make_shared<RigidRepresentationBilateral3D>(),
				otherLocalization);

		std::shared_ptr<SurgSim::Physics::ConstraintComponent> constraintComponent =
			std::make_shared<SurgSim::Physics::ConstraintComponent>(
				stapleName + "_bilateral_constraint_" + boost::to_string(toothId++));

		constraintComponent->setConstraint(constraint);
		staple->addComponent(constraintComponent);
	}

	if (!stapleElementCreated)
	{
		// Create the staple element.
		getScene()->addSceneElement(staple);
	}
}

int StaplerBehavior::getTargetManagerType() const
{
	return SurgSim::Framework::MANAGER_TYPE_INPUT;
}

bool StaplerBehavior::doInitialize()
{
	SURGSIM_ASSERT(m_from) << "StaplerBehavior: no InputComponent held.";
	return true;
}

bool StaplerBehavior::doWakeUp()
{
	return true;
}
<|endoftext|>