<commit_before>/*=========================================================================
*
*  Copyright Insight Software Consortium
*
*  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.txt
*
*  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 "sitkProcessObject.h"
#include "sitkCommand.h"

#include "itkProcessObject.h"
#include "itkCommand.h"
#include "itkImageToImageFilter.h"

#include <iostream>
#include <algorithm>

#include "nsstd/functional.h"

namespace itk {
namespace simple {

namespace
{
static bool GlobalDefaultDebug = false;

static itk::AnyEvent eventAnyEvent;
static itk::AbortEvent eventAbortEvent;
static itk::DeleteEvent eventDeleteEvent;
static itk::EndEvent eventEndEvent;
static itk::IterationEvent eventIterationEvent;
static itk::ProgressEvent eventProgressEvent;
static itk::StartEvent eventStartEvent;
static itk::UserEvent eventUserEvent;
static itk::MultiResolutionIterationEvent eventMultiResolutionIterationEvent;

// Local class to adapt a sitk::Command to ITK's command.
// It utilizes a raw pointer, and relies on the sitk
// ProcessObject<->Command reference to automatically remove it.
class SimpleAdaptorCommand
  : public itk::Command
{
public:

  typedef SimpleAdaptorCommand Self;
  typedef SmartPointer< Self > Pointer;

  itkNewMacro(Self);

  itkTypeMacro(SimpleAdaptorCommand, Command);

  void SetSimpleCommand( itk::simple::Command *cmd )
    {
      m_That=cmd;
    }

  /**  Invoke the member function. */
  virtual void Execute(Object *, const EventObject & ) SITK_OVERRIDE
  {
    if (m_That)
      {
      m_That->Execute();
      }
  }

  /**  Invoke the member function with a const object */
  virtual void Execute(const Object *, const EventObject & ) SITK_OVERRIDE
  {
    if ( m_That )
      {
      m_That->Execute();
      }
  }

protected:
  itk::simple::Command *                    m_That;
  SimpleAdaptorCommand():m_That(0) {}
  virtual ~SimpleAdaptorCommand() {}

private:
  SimpleAdaptorCommand(const Self &); //purposely not implemented
  void operator=(const Self &);        //purposely not implemented
};

} // end anonymous namespace

//----------------------------------------------------------------------------

//
// Default constructor that initializes parameters
//
ProcessObject::ProcessObject ()
  : m_Debug(ProcessObject::GetGlobalDefaultDebug()),
    m_NumberOfThreads(ProcessObject::GetGlobalDefaultNumberOfThreads()),
    m_ActiveProcess(SITK_NULLPTR),
    m_ProgressMeasurement(0.0)
{
}

//
// Destructor
//
ProcessObject::~ProcessObject ()
{
  // ensure to remove reference between sitk commands and process object
  Self::RemoveAllCommands();
}

std::string ProcessObject::ToString() const
{
  std::ostringstream out;

  out << "  Debug: ";
  this->ToStringHelper(out, this->m_Debug) << std::endl;

  out << "  NumberOfThreads: ";
  this->ToStringHelper(out, this->m_NumberOfThreads) << std::endl;

  out << "  Commands:" << (m_Commands.empty()?" (none)":"") << std::endl;
  for( std::list<EventCommand>::const_iterator i = m_Commands.begin();
       i != m_Commands.end();
       ++i)
    {
    assert( i->m_Command );
    out << "    Event: " << i->m_Event << " Command: " << i->m_Command->GetName() << std::endl;
    }

  out << "  ProgressMeasurement: ";
  this->ToStringHelper(out, this->m_ProgressMeasurement) << std::endl;

  out << "  ActiveProcess:" << (this->m_ActiveProcess?"":" (none)") <<std::endl;
  if( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->Print(out, itk::Indent(4));
    }

  return out.str();
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const signed char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const unsigned char &v)
{
  os << int(v);
  return os;
}

void ProcessObject::DebugOn()
{
  this->m_Debug = true;
}

void ProcessObject::DebugOff()
{
  this->m_Debug = false;
}

bool ProcessObject::GetDebug() const
{
  return this->m_Debug;
}

void ProcessObject::SetDebug(bool debugFlag)
{
  this->m_Debug = debugFlag;
}

void ProcessObject::GlobalDefaultDebugOn()
{
  GlobalDefaultDebug = true;
}

void ProcessObject::GlobalDefaultDebugOff()

{
  GlobalDefaultDebug = false;
}

bool ProcessObject::GetGlobalDefaultDebug()
{
  return GlobalDefaultDebug;
}

void ProcessObject::SetGlobalDefaultDebug(bool debugFlag)
{
  GlobalDefaultDebug = debugFlag;
}

void ProcessObject::GlobalWarningDisplayOn()
{
  itk::Object::GlobalWarningDisplayOn();
}

void ProcessObject::GlobalWarningDisplayOff()
{
  itk::Object::GlobalWarningDisplayOff();
}

bool ProcessObject::GetGlobalWarningDisplay()
{
  return itk::Object::GetGlobalWarningDisplay();
}

void ProcessObject::SetGlobalWarningDisplay(bool flag)
{
  itk::Object::SetGlobalWarningDisplay(flag);
}

double ProcessObject::GetGlobalDefaultCoordinateTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultCoordinateTolerance();
}

void ProcessObject::SetGlobalDefaultCoordinateTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultCoordinateTolerance(tolerance);
}

double ProcessObject::GetGlobalDefaultDirectionTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultDirectionTolerance();
}

void ProcessObject::SetGlobalDefaultDirectionTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultDirectionTolerance(tolerance);
}

void ProcessObject::SetGlobalDefaultNumberOfThreads(unsigned int n)
{
  itk::ProcessObject::MultiThreaderType::SetGlobalDefaultNumberOfThreads(n);
}

unsigned int ProcessObject::GetGlobalDefaultNumberOfThreads()
{
  return itk::ProcessObject::MultiThreaderType::GetGlobalDefaultNumberOfThreads();
}

void ProcessObject::SetNumberOfThreads(unsigned int n)
{
  m_NumberOfThreads = n;
}

unsigned int ProcessObject::GetNumberOfThreads() const
{
  return m_NumberOfThreads;
}

int ProcessObject::AddCommand(EventEnum event, Command &cmd)
{
  // add to our list of event, command pairs
  m_Commands.push_back(EventCommand(event,&cmd));

  // register ourselves with the command
  cmd.AddProcessObject(this);

  if (this->m_ActiveProcess)
    {
    this->AddObserverToActiveProcessObject( m_Commands.back() );
    }
  else
    {
    m_Commands.back().m_ITKTag = std::numeric_limits<unsigned long>::max();
    }

  return 0;
}

void ProcessObject::RemoveAllCommands()
{
  // set's the m_Commands to an empty list via a swap
  std::list<EventCommand> oldCommands;
  swap(oldCommands, m_Commands);

  // remove commands from active process object
  std::list<EventCommand>::iterator i = oldCommands.begin();
  while( i != oldCommands.end() && this->m_ActiveProcess )
    {
    this->RemoveObserverFromActiveProcessObject(*i);
    ++i;
    }

  // we must only call RemoveProcessObject once for each command
  // so make a unique list of the Commands.
  oldCommands.sort();
  oldCommands.unique();
  i = oldCommands.begin();
  while( i != oldCommands.end() )
    {
    // note: this may call onCommandDelete, but we have already copied
    // this->m_Command will be empty
    i++->m_Command->RemoveProcessObject(this);
    }
}

bool ProcessObject::HasCommand( EventEnum event ) const
{
  std::list<EventCommand>::const_iterator i = m_Commands.begin();
  while( i != m_Commands.end() )
    {
    if (i->m_Event == event)
      {
      return true;
      }
    ++i;
    }
  return false;
}

float ProcessObject::GetProgress( ) const
{
  if ( this->m_ActiveProcess )
    {
    return this->m_ActiveProcess->GetProgress();
    }
  return m_ProgressMeasurement;
}

void ProcessObject::Abort()
{
  if ( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->AbortGenerateDataOn();
    }
}

void ProcessObject::PreUpdate(itk::ProcessObject *p)
{
  assert(p);

  // propagate number of threads
  p->SetNumberOfThreads(this->GetNumberOfThreads());

  try
    {
    this->m_ActiveProcess = p;

    // add command on active process deletion
    itk::SimpleMemberCommand<Self>::Pointer onDelete = itk::SimpleMemberCommand<Self>::New();
    onDelete->SetCallbackFunction(this, &Self::OnActiveProcessDelete);
    p->AddObserver(itk::DeleteEvent(), onDelete);

    // register commands
    for (std::list<EventCommand>::iterator i = m_Commands.begin();
         i != m_Commands.end();
         ++i)
      {
      this->AddObserverToActiveProcessObject(*i);
      }

    }
  catch (...)
    {
    this->m_ActiveProcess = SITK_NULLPTR;
    throw;
    }

  sitkDebugMacro( "Executing ITK filter:\n" << *p );

}

unsigned long ProcessObject::AddITKObserver( const itk::EventObject &e,
                                             itk::Command *c)
{
  assert(this->m_ActiveProcess);
  return this->m_ActiveProcess->AddObserver(e,c);
}

void ProcessObject::RemoveITKObserver( EventCommand &e )
{
  assert(this->m_ActiveProcess);
  this->m_ActiveProcess->RemoveObserver(e.m_ITKTag);
}

const itk::EventObject &ProcessObject::GetITKEventObject(EventEnum e)
{
  switch (e)
    {
    case sitkAnyEvent:
      return eventAnyEvent;
    case sitkAbortEvent:
      return eventAbortEvent;
    case sitkDeleteEvent:
      return eventDeleteEvent;
    case sitkEndEvent:
      return eventEndEvent;
    case sitkIterationEvent:
      return eventIterationEvent;
    case sitkProgressEvent:
      return eventProgressEvent;
    case sitkStartEvent:
      return eventStartEvent;
    case sitkUserEvent:
      return eventUserEvent;
    case sitkMultiResolutionIterationEvent:
      return eventMultiResolutionIterationEvent;
    default:
      sitkExceptionMacro("LogicError: Unexpected event case!");
    }
}

itk::ProcessObject *ProcessObject::GetActiveProcess( )
{
  if (this->m_ActiveProcess)
    {
    return this->m_ActiveProcess;
    }
  sitkExceptionMacro("No active process for \"" << this->GetName() << "\"!");
}

void ProcessObject::OnActiveProcessDelete( )
{
  if (this->m_ActiveProcess)
    {
    this->m_ProgressMeasurement = this->m_ActiveProcess->GetProgress();
    }
  else
    {
    this->m_ProgressMeasurement = 0.0f;
    }

  // clear registered command IDs
  for (std::list<EventCommand>::iterator i = m_Commands.begin();
         i != m_Commands.end();
         ++i)
      {
      i->m_ITKTag = std::numeric_limits<unsigned long>::max();
      }

  this->m_ActiveProcess = SITK_NULLPTR;
}

void ProcessObject::onCommandDelete(const itk::simple::Command *cmd) SITK_NOEXCEPT
{
  // remove command from m_Command book keeping list, and remove it
  // from the  ITK ProcessObject
  std::list<EventCommand>::iterator i =  this->m_Commands.begin();
  while ( i !=  this->m_Commands.end() )
    {
    if ( cmd == i->m_Command )
      {
      if ( this->m_ActiveProcess )
        {
        this->RemoveObserverFromActiveProcessObject( *i );
        }
      this->m_Commands.erase(i++);
      }
    else
      {
      ++i;
      }

    }
}

unsigned long ProcessObject::AddObserverToActiveProcessObject( EventCommand &eventCommand )
{
  assert( this->m_ActiveProcess );

  if (eventCommand.m_ITKTag != std::numeric_limits<unsigned long>::max())
    {
    sitkExceptionMacro("Commands already registered to another process object!");
    }

  const itk::EventObject &itkEvent = GetITKEventObject(eventCommand.m_Event);

  // adapt sitk command to itk command
  SimpleAdaptorCommand::Pointer itkCommand = SimpleAdaptorCommand::New();
  itkCommand->SetSimpleCommand(eventCommand.m_Command);
  itkCommand->SetObjectName(eventCommand.m_Command->GetName()+" "+itkEvent.GetEventName());

  return eventCommand.m_ITKTag = this->AddITKObserver( itkEvent, itkCommand );
}

void ProcessObject::RemoveObserverFromActiveProcessObject( EventCommand &e )
 {
   assert( this->m_ActiveProcess );

   if (e.m_ITKTag != std::numeric_limits<unsigned long>::max() )
     {
     this->RemoveITKObserver(e);
     e.m_ITKTag = std::numeric_limits<unsigned long>::max();
     }

 }

} // end namespace simple
} // end namespace itk
<commit_msg>Use TextOutput for OutputWindow<commit_after>/*=========================================================================
*
*  Copyright Insight Software Consortium
*
*  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.txt
*
*  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 "sitkProcessObject.h"
#include "sitkCommand.h"

#include "itkProcessObject.h"
#include "itkCommand.h"
#include "itkImageToImageFilter.h"
#include "itkTextOutput.h"

#include <iostream>
#include <algorithm>

#include "nsstd/functional.h"

namespace itk {
namespace simple {

namespace
{
static bool GlobalDefaultDebug = false;

static itk::AnyEvent eventAnyEvent;
static itk::AbortEvent eventAbortEvent;
static itk::DeleteEvent eventDeleteEvent;
static itk::EndEvent eventEndEvent;
static itk::IterationEvent eventIterationEvent;
static itk::ProgressEvent eventProgressEvent;
static itk::StartEvent eventStartEvent;
static itk::UserEvent eventUserEvent;
static itk::MultiResolutionIterationEvent eventMultiResolutionIterationEvent;

// Local class to adapt a sitk::Command to ITK's command.
// It utilizes a raw pointer, and relies on the sitk
// ProcessObject<->Command reference to automatically remove it.
class SimpleAdaptorCommand
  : public itk::Command
{
public:

  typedef SimpleAdaptorCommand Self;
  typedef SmartPointer< Self > Pointer;

  itkNewMacro(Self);

  itkTypeMacro(SimpleAdaptorCommand, Command);

  void SetSimpleCommand( itk::simple::Command *cmd )
    {
      m_That=cmd;
    }

  /**  Invoke the member function. */
  virtual void Execute(Object *, const EventObject & ) SITK_OVERRIDE
  {
    if (m_That)
      {
      m_That->Execute();
      }
  }

  /**  Invoke the member function with a const object */
  virtual void Execute(const Object *, const EventObject & ) SITK_OVERRIDE
  {
    if ( m_That )
      {
      m_That->Execute();
      }
  }

protected:
  itk::simple::Command *                    m_That;
  SimpleAdaptorCommand():m_That(0) {}
  virtual ~SimpleAdaptorCommand() {}

private:
  SimpleAdaptorCommand(const Self &); //purposely not implemented
  void operator=(const Self &);        //purposely not implemented
};

} // end anonymous namespace

//----------------------------------------------------------------------------

//
// Default constructor that initializes parameters
//
ProcessObject::ProcessObject ()
  : m_Debug(ProcessObject::GetGlobalDefaultDebug()),
    m_NumberOfThreads(ProcessObject::GetGlobalDefaultNumberOfThreads()),
    m_ActiveProcess(SITK_NULLPTR),
    m_ProgressMeasurement(0.0)
{
  static bool firstTime=true;
  if (firstTime)
    {
    if (itk::OutputWindow::GetInstance()->GetObjectName() == "Win32OutputWindow")
      {
      itk::OutputWindow::SetInstance( itk::TextOutput::New() );
      }
    firstTime = false;
    }
}

//
// Destructor
//
ProcessObject::~ProcessObject ()
{
  // ensure to remove reference between sitk commands and process object
  Self::RemoveAllCommands();
}

std::string ProcessObject::ToString() const
{
  std::ostringstream out;

  out << "  Debug: ";
  this->ToStringHelper(out, this->m_Debug) << std::endl;

  out << "  NumberOfThreads: ";
  this->ToStringHelper(out, this->m_NumberOfThreads) << std::endl;

  out << "  Commands:" << (m_Commands.empty()?" (none)":"") << std::endl;
  for( std::list<EventCommand>::const_iterator i = m_Commands.begin();
       i != m_Commands.end();
       ++i)
    {
    assert( i->m_Command );
    out << "    Event: " << i->m_Event << " Command: " << i->m_Command->GetName() << std::endl;
    }

  out << "  ProgressMeasurement: ";
  this->ToStringHelper(out, this->m_ProgressMeasurement) << std::endl;

  out << "  ActiveProcess:" << (this->m_ActiveProcess?"":" (none)") <<std::endl;
  if( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->Print(out, itk::Indent(4));
    }

  return out.str();
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const signed char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const unsigned char &v)
{
  os << int(v);
  return os;
}

void ProcessObject::DebugOn()
{
  this->m_Debug = true;
}

void ProcessObject::DebugOff()
{
  this->m_Debug = false;
}

bool ProcessObject::GetDebug() const
{
  return this->m_Debug;
}

void ProcessObject::SetDebug(bool debugFlag)
{
  this->m_Debug = debugFlag;
}

void ProcessObject::GlobalDefaultDebugOn()
{
  GlobalDefaultDebug = true;
}

void ProcessObject::GlobalDefaultDebugOff()

{
  GlobalDefaultDebug = false;
}

bool ProcessObject::GetGlobalDefaultDebug()
{
  return GlobalDefaultDebug;
}

void ProcessObject::SetGlobalDefaultDebug(bool debugFlag)
{
  GlobalDefaultDebug = debugFlag;
}

void ProcessObject::GlobalWarningDisplayOn()
{
  itk::Object::GlobalWarningDisplayOn();
}

void ProcessObject::GlobalWarningDisplayOff()
{
  itk::Object::GlobalWarningDisplayOff();
}

bool ProcessObject::GetGlobalWarningDisplay()
{
  return itk::Object::GetGlobalWarningDisplay();
}

void ProcessObject::SetGlobalWarningDisplay(bool flag)
{
  itk::Object::SetGlobalWarningDisplay(flag);
}

double ProcessObject::GetGlobalDefaultCoordinateTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultCoordinateTolerance();
}

void ProcessObject::SetGlobalDefaultCoordinateTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultCoordinateTolerance(tolerance);
}

double ProcessObject::GetGlobalDefaultDirectionTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultDirectionTolerance();
}

void ProcessObject::SetGlobalDefaultDirectionTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultDirectionTolerance(tolerance);
}

void ProcessObject::SetGlobalDefaultNumberOfThreads(unsigned int n)
{
  itk::ProcessObject::MultiThreaderType::SetGlobalDefaultNumberOfThreads(n);
}

unsigned int ProcessObject::GetGlobalDefaultNumberOfThreads()
{
  return itk::ProcessObject::MultiThreaderType::GetGlobalDefaultNumberOfThreads();
}

void ProcessObject::SetNumberOfThreads(unsigned int n)
{
  m_NumberOfThreads = n;
}

unsigned int ProcessObject::GetNumberOfThreads() const
{
  return m_NumberOfThreads;
}

int ProcessObject::AddCommand(EventEnum event, Command &cmd)
{
  // add to our list of event, command pairs
  m_Commands.push_back(EventCommand(event,&cmd));

  // register ourselves with the command
  cmd.AddProcessObject(this);

  if (this->m_ActiveProcess)
    {
    this->AddObserverToActiveProcessObject( m_Commands.back() );
    }
  else
    {
    m_Commands.back().m_ITKTag = std::numeric_limits<unsigned long>::max();
    }

  return 0;
}

void ProcessObject::RemoveAllCommands()
{
  // set's the m_Commands to an empty list via a swap
  std::list<EventCommand> oldCommands;
  swap(oldCommands, m_Commands);

  // remove commands from active process object
  std::list<EventCommand>::iterator i = oldCommands.begin();
  while( i != oldCommands.end() && this->m_ActiveProcess )
    {
    this->RemoveObserverFromActiveProcessObject(*i);
    ++i;
    }

  // we must only call RemoveProcessObject once for each command
  // so make a unique list of the Commands.
  oldCommands.sort();
  oldCommands.unique();
  i = oldCommands.begin();
  while( i != oldCommands.end() )
    {
    // note: this may call onCommandDelete, but we have already copied
    // this->m_Command will be empty
    i++->m_Command->RemoveProcessObject(this);
    }
}

bool ProcessObject::HasCommand( EventEnum event ) const
{
  std::list<EventCommand>::const_iterator i = m_Commands.begin();
  while( i != m_Commands.end() )
    {
    if (i->m_Event == event)
      {
      return true;
      }
    ++i;
    }
  return false;
}

float ProcessObject::GetProgress( ) const
{
  if ( this->m_ActiveProcess )
    {
    return this->m_ActiveProcess->GetProgress();
    }
  return m_ProgressMeasurement;
}

void ProcessObject::Abort()
{
  if ( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->AbortGenerateDataOn();
    }
}

void ProcessObject::PreUpdate(itk::ProcessObject *p)
{
  assert(p);

  // propagate number of threads
  p->SetNumberOfThreads(this->GetNumberOfThreads());

  try
    {
    this->m_ActiveProcess = p;

    // add command on active process deletion
    itk::SimpleMemberCommand<Self>::Pointer onDelete = itk::SimpleMemberCommand<Self>::New();
    onDelete->SetCallbackFunction(this, &Self::OnActiveProcessDelete);
    p->AddObserver(itk::DeleteEvent(), onDelete);

    // register commands
    for (std::list<EventCommand>::iterator i = m_Commands.begin();
         i != m_Commands.end();
         ++i)
      {
      this->AddObserverToActiveProcessObject(*i);
      }

    }
  catch (...)
    {
    this->m_ActiveProcess = SITK_NULLPTR;
    throw;
    }

  sitkDebugMacro( "Executing ITK filter:\n" << *p );

}

unsigned long ProcessObject::AddITKObserver( const itk::EventObject &e,
                                             itk::Command *c)
{
  assert(this->m_ActiveProcess);
  return this->m_ActiveProcess->AddObserver(e,c);
}

void ProcessObject::RemoveITKObserver( EventCommand &e )
{
  assert(this->m_ActiveProcess);
  this->m_ActiveProcess->RemoveObserver(e.m_ITKTag);
}

const itk::EventObject &ProcessObject::GetITKEventObject(EventEnum e)
{
  switch (e)
    {
    case sitkAnyEvent:
      return eventAnyEvent;
    case sitkAbortEvent:
      return eventAbortEvent;
    case sitkDeleteEvent:
      return eventDeleteEvent;
    case sitkEndEvent:
      return eventEndEvent;
    case sitkIterationEvent:
      return eventIterationEvent;
    case sitkProgressEvent:
      return eventProgressEvent;
    case sitkStartEvent:
      return eventStartEvent;
    case sitkUserEvent:
      return eventUserEvent;
    case sitkMultiResolutionIterationEvent:
      return eventMultiResolutionIterationEvent;
    default:
      sitkExceptionMacro("LogicError: Unexpected event case!");
    }
}

itk::ProcessObject *ProcessObject::GetActiveProcess( )
{
  if (this->m_ActiveProcess)
    {
    return this->m_ActiveProcess;
    }
  sitkExceptionMacro("No active process for \"" << this->GetName() << "\"!");
}

void ProcessObject::OnActiveProcessDelete( )
{
  if (this->m_ActiveProcess)
    {
    this->m_ProgressMeasurement = this->m_ActiveProcess->GetProgress();
    }
  else
    {
    this->m_ProgressMeasurement = 0.0f;
    }

  // clear registered command IDs
  for (std::list<EventCommand>::iterator i = m_Commands.begin();
         i != m_Commands.end();
         ++i)
      {
      i->m_ITKTag = std::numeric_limits<unsigned long>::max();
      }

  this->m_ActiveProcess = SITK_NULLPTR;
}

void ProcessObject::onCommandDelete(const itk::simple::Command *cmd) SITK_NOEXCEPT
{
  // remove command from m_Command book keeping list, and remove it
  // from the  ITK ProcessObject
  std::list<EventCommand>::iterator i =  this->m_Commands.begin();
  while ( i !=  this->m_Commands.end() )
    {
    if ( cmd == i->m_Command )
      {
      if ( this->m_ActiveProcess )
        {
        this->RemoveObserverFromActiveProcessObject( *i );
        }
      this->m_Commands.erase(i++);
      }
    else
      {
      ++i;
      }

    }
}

unsigned long ProcessObject::AddObserverToActiveProcessObject( EventCommand &eventCommand )
{
  assert( this->m_ActiveProcess );

  if (eventCommand.m_ITKTag != std::numeric_limits<unsigned long>::max())
    {
    sitkExceptionMacro("Commands already registered to another process object!");
    }

  const itk::EventObject &itkEvent = GetITKEventObject(eventCommand.m_Event);

  // adapt sitk command to itk command
  SimpleAdaptorCommand::Pointer itkCommand = SimpleAdaptorCommand::New();
  itkCommand->SetSimpleCommand(eventCommand.m_Command);
  itkCommand->SetObjectName(eventCommand.m_Command->GetName()+" "+itkEvent.GetEventName());

  return eventCommand.m_ITKTag = this->AddITKObserver( itkEvent, itkCommand );
}

void ProcessObject::RemoveObserverFromActiveProcessObject( EventCommand &e )
 {
   assert( this->m_ActiveProcess );

   if (e.m_ITKTag != std::numeric_limits<unsigned long>::max() )
     {
     this->RemoveITKObserver(e);
     e.m_ITKTag = std::numeric_limits<unsigned long>::max();
     }

 }

} // end namespace simple
} // end namespace itk
<|endoftext|>


<commit_before>/*=========================================================================
*
*  Copyright NumFOCUS
*
*  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.txt
*
*  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 "sitkProcessObject.h"
#include "sitkCommand.h"

#include "itkProcessObject.h"
#include "itkCommand.h"
#include "sitkFunctionCommand.h"
#include "itkImageToImageFilter.h"
#include "itkTextOutput.h"

#include <iostream>
#include <algorithm>
#include <cstring>
#include <functional>

namespace itk {
namespace simple {

namespace
{
static bool GlobalDefaultDebug = false;

static itk::AnyEvent eventAnyEvent;
static itk::AbortEvent eventAbortEvent;
static itk::DeleteEvent eventDeleteEvent;
static itk::EndEvent eventEndEvent;
static itk::IterationEvent eventIterationEvent;
static itk::ProgressEvent eventProgressEvent;
static itk::StartEvent eventStartEvent;
static itk::UserEvent eventUserEvent;
static itk::MultiResolutionIterationEvent eventMultiResolutionIterationEvent;

// Local class to adapt a sitk::Command to ITK's command.
// It utilizes a raw pointer, and relies on the sitk
// ProcessObject<->Command reference to automatically remove it.
class SimpleAdaptorCommand
  : public itk::Command
{
public:

  using Self = SimpleAdaptorCommand;
  using Pointer = SmartPointer< Self >;

  itkNewMacro(Self);

  itkTypeMacro(SimpleAdaptorCommand, Command);

  void SetSimpleCommand( itk::simple::Command *cmd )
    {
      m_That=cmd;
    }

  /**  Invoke the member function. */
  void Execute(Object *, const EventObject & ) override
  {
    if (m_That)
      {
      m_That->Execute();
      }
  }

  /**  Invoke the member function with a const object */
  void Execute(const Object *, const EventObject & ) override
  {
    if ( m_That )
      {
      m_That->Execute();
      }
  }

  SimpleAdaptorCommand(const Self &) = delete;
  void operator=(const Self &) = delete;

protected:
  itk::simple::Command *                    m_That{nullptr};
  SimpleAdaptorCommand() = default;
  ~SimpleAdaptorCommand() override = default;
};

} // end anonymous namespace

//----------------------------------------------------------------------------

//
// Default constructor that initializes parameters
//
ProcessObject::ProcessObject ()
  : m_Debug(ProcessObject::GetGlobalDefaultDebug()),
    m_NumberOfThreads(itk::MultiThreaderBase::GetGlobalDefaultNumberOfThreads()),
    m_NumberOfWorkUnits(0),
    m_ActiveProcess(nullptr),
    m_ProgressMeasurement(0.0)
{
  static bool firstTime=true;
  if (firstTime)
    {
    if (!strcmp(itk::OutputWindow::GetInstance()->GetNameOfClass(), "Win32OutputWindow"))
      {
      itk::OutputWindow::SetInstance( itk::TextOutput::New() );
      }
    firstTime = false;
    }
}

//
// Destructor
//
ProcessObject::~ProcessObject ()
{
  // ensure to remove reference between sitk commands and process object
  Self::RemoveAllCommands();
}

std::string ProcessObject::ToString() const
{
  std::ostringstream out;

  out << "  Debug: ";
  this->ToStringHelper(out, this->m_Debug) << std::endl;

  out << "  NumberOfThreads: ";
  this->ToStringHelper(out, this->m_NumberOfThreads) << std::endl;

  out << "  NumberOfWorkUnits: ";
  this->ToStringHelper(out, this->m_NumberOfWorkUnits) << std::endl;

  out << "  Commands:" << (m_Commands.empty()?" (none)":"") << std::endl;
  for( const auto &eventCommand : m_Commands)
    {
    assert( eventCommand.m_Command );
    out << "    Event: " << eventCommand.m_Event << " Command: " << eventCommand.m_Command->GetName() << std::endl;
    }

  out << "  ProgressMeasurement: ";
  this->ToStringHelper(out, this->m_ProgressMeasurement) << std::endl;

  out << "  ActiveProcess:" << (this->m_ActiveProcess?"":" (none)") <<std::endl;
  if( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->Print(out, itk::Indent(4));
    }

  return out.str();
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const signed char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const unsigned char &v)
{
  os << int(v);
  return os;
}

void ProcessObject::DebugOn()
{
  this->m_Debug = true;
}

void ProcessObject::DebugOff()
{
  this->m_Debug = false;
}

bool ProcessObject::GetDebug() const
{
  return this->m_Debug;
}

void ProcessObject::SetDebug(bool debugFlag)
{
  this->m_Debug = debugFlag;
}

void ProcessObject::GlobalDefaultDebugOn()
{
  GlobalDefaultDebug = true;
}

void ProcessObject::GlobalDefaultDebugOff()

{
  GlobalDefaultDebug = false;
}

bool ProcessObject::GetGlobalDefaultDebug()
{
  return GlobalDefaultDebug;
}

void ProcessObject::SetGlobalDefaultDebug(bool debugFlag)
{
  GlobalDefaultDebug = debugFlag;
}

void ProcessObject::GlobalWarningDisplayOn()
{
  itk::Object::GlobalWarningDisplayOn();
}

void ProcessObject::GlobalWarningDisplayOff()
{
  itk::Object::GlobalWarningDisplayOff();
}

bool ProcessObject::GetGlobalWarningDisplay()
{
  return itk::Object::GetGlobalWarningDisplay();
}

void ProcessObject::SetGlobalWarningDisplay(bool flag)
{
  itk::Object::SetGlobalWarningDisplay(flag);
}

double ProcessObject::GetGlobalDefaultCoordinateTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultCoordinateTolerance();
}

void ProcessObject::SetGlobalDefaultCoordinateTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultCoordinateTolerance(tolerance);
}

double ProcessObject::GetGlobalDefaultDirectionTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultDirectionTolerance();
}

void ProcessObject::SetGlobalDefaultDirectionTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultDirectionTolerance(tolerance);
}

void ProcessObject::SetGlobalDefaultNumberOfThreads(unsigned int n)
{
  itk::MultiThreaderBase::SetGlobalDefaultNumberOfThreads(n);
}

unsigned int ProcessObject::GetGlobalDefaultNumberOfThreads()
{
  return itk::MultiThreaderBase::GetGlobalDefaultNumberOfThreads();
}

bool ProcessObject::SetGlobalDefaultThreader(const std::string &threader)
{
  auto threaderEnum = itk::MultiThreaderBase::ThreaderTypeFromString(threader);
  if (threaderEnum == itk::MultiThreaderBase::ThreaderEnum::Unknown
#if !defined(ITK_USE_TBB)
      || threaderEnum == itk::MultiThreaderBase::ThreaderEnum::Unknown
#endif
    )
    {
    return false;
    }
  itk::MultiThreaderBase::SetGlobalDefaultThreader(threaderEnum);
  return true;
}

std::string ProcessObject::GetGlobalDefaultThreader()
{
  auto threaderEnum =  itk::MultiThreaderBase::GetGlobalDefaultThreader();
  return itk::MultiThreaderBase::ThreaderTypeToString(threaderEnum);
}

void ProcessObject::SetNumberOfThreads(unsigned int n)
{
  m_NumberOfThreads = n;
}

unsigned int ProcessObject::GetNumberOfThreads() const
{
  return m_NumberOfThreads;
}

void ProcessObject::SetNumberOfWorkUnits(unsigned int n)
{
  m_NumberOfWorkUnits = n;
}

unsigned int ProcessObject::GetNumberOfWorkUnits() const
{
  return m_NumberOfWorkUnits;
}

int ProcessObject::AddCommand(EventEnum event, Command &cmd)
{
  // add to our list of event, command pairs
  m_Commands.emplace_back(event,&cmd);

  // register ourselves with the command
  cmd.AddProcessObject(this);

  if (this->m_ActiveProcess)
    {
    this->AddObserverToActiveProcessObject( m_Commands.back() );
    }
  else
    {
    m_Commands.back().m_ITKTag = std::numeric_limits<unsigned long>::max();
    }

  return 0;
}

int ProcessObject::AddCommand(itk::simple::EventEnum event, const std::function<void()> &func)
{
  std::unique_ptr<FunctionCommand> cmd(new FunctionCommand());
  cmd->SetCallbackFunction(func);

  int id = this->AddCommand(event, *cmd.get());
  cmd->GetOwnedByObjects();
  cmd.release();
  return id;
}

void ProcessObject::RemoveAllCommands()
{
  // set's the m_Commands to an empty list via a swap
  std::list<EventCommand> oldCommands;
  swap(oldCommands, m_Commands);

  // remove commands from active process object
  std::list<EventCommand>::iterator i = oldCommands.begin();
  while( i != oldCommands.end() && this->m_ActiveProcess )
    {
    this->RemoveObserverFromActiveProcessObject(*i);
    ++i;
    }

  // we must only call RemoveProcessObject once for each command
  // so make a unique list of the Commands.
  oldCommands.sort();
  oldCommands.unique();
  i = oldCommands.begin();
  while( i != oldCommands.end() )
    {
    // note: this may call onCommandDelete, but we have already copied
    // this->m_Command will be empty
    i++->m_Command->RemoveProcessObject(this);
    }
}

bool ProcessObject::HasCommand( EventEnum event ) const
{
  for ( const auto& eventCommand: m_Commands)
    {
    if (eventCommand.m_Event == event)
      {
      return true;
      }
    }
  return false;
}

float ProcessObject::GetProgress( ) const
{
  if ( this->m_ActiveProcess )
    {
    return this->m_ActiveProcess->GetProgress();
    }
  return m_ProgressMeasurement;
}

void ProcessObject::Abort()
{
  if ( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->AbortGenerateDataOn();
    }
}

void ProcessObject::PreUpdate(itk::ProcessObject *p)
{
  assert(p);

  // propagate number of threads
  if ( this->GetNumberOfWorkUnits() != 0 )
    {
    p->SetNumberOfWorkUnits(this->GetNumberOfWorkUnits());
    }

  p->GetMultiThreader()->SetMaximumNumberOfThreads(this->GetNumberOfThreads());

  try
    {
    this->m_ActiveProcess = p;

    // add command on active process deletion
    p->AddObserver(eventDeleteEvent, [this](const itk::EventObject &) {this->OnActiveProcessDelete();});

    // register commands
    for (auto &eventCommand: m_Commands )
      {
      this->AddObserverToActiveProcessObject(eventCommand);
      }

    }
  catch (...)
    {
    this->m_ActiveProcess = nullptr;
    throw;
    }

  sitkDebugMacro( "Executing ITK filter:\n" << *p );

}

unsigned long ProcessObject::AddITKObserver( const itk::EventObject &e,
                                             itk::Command *c)
{
  assert(this->m_ActiveProcess);
  return this->m_ActiveProcess->AddObserver(e,c);
}

void ProcessObject::RemoveITKObserver( EventCommand &e )
{
  assert(this->m_ActiveProcess);
  this->m_ActiveProcess->RemoveObserver(e.m_ITKTag);
}

const itk::EventObject &ProcessObject::GetITKEventObject(EventEnum e)
{
  switch (e)
    {
    case sitkAnyEvent:
      return eventAnyEvent;
    case sitkAbortEvent:
      return eventAbortEvent;
    case sitkDeleteEvent:
      return eventDeleteEvent;
    case sitkEndEvent:
      return eventEndEvent;
    case sitkIterationEvent:
      return eventIterationEvent;
    case sitkProgressEvent:
      return eventProgressEvent;
    case sitkStartEvent:
      return eventStartEvent;
    case sitkUserEvent:
      return eventUserEvent;
    case sitkMultiResolutionIterationEvent:
      return eventMultiResolutionIterationEvent;
    default:
      sitkExceptionMacro("LogicError: Unexpected event case!");
    }
}

itk::ProcessObject *ProcessObject::GetActiveProcess( )
{
  if (this->m_ActiveProcess)
    {
    return this->m_ActiveProcess;
    }
  sitkExceptionMacro("No active process for \"" << this->GetName() << "\"!");
}

void ProcessObject::OnActiveProcessDelete( )
{
  if (this->m_ActiveProcess)
    {
    this->m_ProgressMeasurement = this->m_ActiveProcess->GetProgress();
    }
  else
    {
    this->m_ProgressMeasurement = 0.0f;
    }

  // clear registered command IDs
  for (std::list<EventCommand>::iterator i = m_Commands.begin();
         i != m_Commands.end();
         ++i)
      {
      i->m_ITKTag = std::numeric_limits<unsigned long>::max();
      }

  this->m_ActiveProcess = nullptr;
}

void ProcessObject::onCommandDelete(const itk::simple::Command *cmd) noexcept
{
  // remove command from m_Command book keeping list, and remove it
  // from the  ITK ProcessObject
  std::list<EventCommand>::iterator i =  this->m_Commands.begin();
  while ( i !=  this->m_Commands.end() )
    {
    if ( cmd == i->m_Command )
      {
      if ( this->m_ActiveProcess )
        {
        this->RemoveObserverFromActiveProcessObject( *i );
        }
      this->m_Commands.erase(i++);
      }
    else
      {
      ++i;
      }

    }
}

unsigned long ProcessObject::AddObserverToActiveProcessObject( EventCommand &eventCommand )
{
  assert( this->m_ActiveProcess );

  if (eventCommand.m_ITKTag != std::numeric_limits<unsigned long>::max())
    {
    sitkExceptionMacro("Commands already registered to another process object!");
    }

  const itk::EventObject &itkEvent = GetITKEventObject(eventCommand.m_Event);

  // adapt sitk command to itk command
  SimpleAdaptorCommand::Pointer itkCommand = SimpleAdaptorCommand::New();
  itkCommand->SetSimpleCommand(eventCommand.m_Command);
  itkCommand->SetObjectName(eventCommand.m_Command->GetName()+" "+itkEvent.GetEventName());

  return eventCommand.m_ITKTag = this->AddITKObserver( itkEvent, itkCommand );
}

void ProcessObject::RemoveObserverFromActiveProcessObject( EventCommand &e )
 {
   assert( this->m_ActiveProcess );

   if (e.m_ITKTag != std::numeric_limits<unsigned long>::max() )
     {
     this->RemoveITKObserver(e);
     e.m_ITKTag = std::numeric_limits<unsigned long>::max();
     }

 }

} // end namespace simple
} // end namespace itk
<commit_msg>Correct setting of command ownership<commit_after>/*=========================================================================
*
*  Copyright NumFOCUS
*
*  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.txt
*
*  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 "sitkProcessObject.h"
#include "sitkCommand.h"

#include "itkProcessObject.h"
#include "itkCommand.h"
#include "sitkFunctionCommand.h"
#include "itkImageToImageFilter.h"
#include "itkTextOutput.h"

#include <iostream>
#include <algorithm>
#include <cstring>
#include <functional>

namespace itk {
namespace simple {

namespace
{
static bool GlobalDefaultDebug = false;

static itk::AnyEvent eventAnyEvent;
static itk::AbortEvent eventAbortEvent;
static itk::DeleteEvent eventDeleteEvent;
static itk::EndEvent eventEndEvent;
static itk::IterationEvent eventIterationEvent;
static itk::ProgressEvent eventProgressEvent;
static itk::StartEvent eventStartEvent;
static itk::UserEvent eventUserEvent;
static itk::MultiResolutionIterationEvent eventMultiResolutionIterationEvent;

// Local class to adapt a sitk::Command to ITK's command.
// It utilizes a raw pointer, and relies on the sitk
// ProcessObject<->Command reference to automatically remove it.
class SimpleAdaptorCommand
  : public itk::Command
{
public:

  using Self = SimpleAdaptorCommand;
  using Pointer = SmartPointer< Self >;

  itkNewMacro(Self);

  itkTypeMacro(SimpleAdaptorCommand, Command);

  void SetSimpleCommand( itk::simple::Command *cmd )
    {
      m_That=cmd;
    }

  /**  Invoke the member function. */
  void Execute(Object *, const EventObject & ) override
  {
    if (m_That)
      {
      m_That->Execute();
      }
  }

  /**  Invoke the member function with a const object */
  void Execute(const Object *, const EventObject & ) override
  {
    if ( m_That )
      {
      m_That->Execute();
      }
  }

  SimpleAdaptorCommand(const Self &) = delete;
  void operator=(const Self &) = delete;

protected:
  itk::simple::Command *                    m_That{nullptr};
  SimpleAdaptorCommand() = default;
  ~SimpleAdaptorCommand() override = default;
};

} // end anonymous namespace

//----------------------------------------------------------------------------

//
// Default constructor that initializes parameters
//
ProcessObject::ProcessObject ()
  : m_Debug(ProcessObject::GetGlobalDefaultDebug()),
    m_NumberOfThreads(itk::MultiThreaderBase::GetGlobalDefaultNumberOfThreads()),
    m_NumberOfWorkUnits(0),
    m_ActiveProcess(nullptr),
    m_ProgressMeasurement(0.0)
{
  static bool firstTime=true;
  if (firstTime)
    {
    if (!strcmp(itk::OutputWindow::GetInstance()->GetNameOfClass(), "Win32OutputWindow"))
      {
      itk::OutputWindow::SetInstance( itk::TextOutput::New() );
      }
    firstTime = false;
    }
}

//
// Destructor
//
ProcessObject::~ProcessObject ()
{
  // ensure to remove reference between sitk commands and process object
  Self::RemoveAllCommands();
}

std::string ProcessObject::ToString() const
{
  std::ostringstream out;

  out << "  Debug: ";
  this->ToStringHelper(out, this->m_Debug) << std::endl;

  out << "  NumberOfThreads: ";
  this->ToStringHelper(out, this->m_NumberOfThreads) << std::endl;

  out << "  NumberOfWorkUnits: ";
  this->ToStringHelper(out, this->m_NumberOfWorkUnits) << std::endl;

  out << "  Commands:" << (m_Commands.empty()?" (none)":"") << std::endl;
  for( const auto &eventCommand : m_Commands)
    {
    assert( eventCommand.m_Command );
    out << "    Event: " << eventCommand.m_Event << " Command: " << eventCommand.m_Command->GetName() << std::endl;
    }

  out << "  ProgressMeasurement: ";
  this->ToStringHelper(out, this->m_ProgressMeasurement) << std::endl;

  out << "  ActiveProcess:" << (this->m_ActiveProcess?"":" (none)") <<std::endl;
  if( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->Print(out, itk::Indent(4));
    }

  return out.str();
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const signed char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const unsigned char &v)
{
  os << int(v);
  return os;
}

void ProcessObject::DebugOn()
{
  this->m_Debug = true;
}

void ProcessObject::DebugOff()
{
  this->m_Debug = false;
}

bool ProcessObject::GetDebug() const
{
  return this->m_Debug;
}

void ProcessObject::SetDebug(bool debugFlag)
{
  this->m_Debug = debugFlag;
}

void ProcessObject::GlobalDefaultDebugOn()
{
  GlobalDefaultDebug = true;
}

void ProcessObject::GlobalDefaultDebugOff()

{
  GlobalDefaultDebug = false;
}

bool ProcessObject::GetGlobalDefaultDebug()
{
  return GlobalDefaultDebug;
}

void ProcessObject::SetGlobalDefaultDebug(bool debugFlag)
{
  GlobalDefaultDebug = debugFlag;
}

void ProcessObject::GlobalWarningDisplayOn()
{
  itk::Object::GlobalWarningDisplayOn();
}

void ProcessObject::GlobalWarningDisplayOff()
{
  itk::Object::GlobalWarningDisplayOff();
}

bool ProcessObject::GetGlobalWarningDisplay()
{
  return itk::Object::GetGlobalWarningDisplay();
}

void ProcessObject::SetGlobalWarningDisplay(bool flag)
{
  itk::Object::SetGlobalWarningDisplay(flag);
}

double ProcessObject::GetGlobalDefaultCoordinateTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultCoordinateTolerance();
}

void ProcessObject::SetGlobalDefaultCoordinateTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultCoordinateTolerance(tolerance);
}

double ProcessObject::GetGlobalDefaultDirectionTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultDirectionTolerance();
}

void ProcessObject::SetGlobalDefaultDirectionTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultDirectionTolerance(tolerance);
}

void ProcessObject::SetGlobalDefaultNumberOfThreads(unsigned int n)
{
  itk::MultiThreaderBase::SetGlobalDefaultNumberOfThreads(n);
}

unsigned int ProcessObject::GetGlobalDefaultNumberOfThreads()
{
  return itk::MultiThreaderBase::GetGlobalDefaultNumberOfThreads();
}

bool ProcessObject::SetGlobalDefaultThreader(const std::string &threader)
{
  auto threaderEnum = itk::MultiThreaderBase::ThreaderTypeFromString(threader);
  if (threaderEnum == itk::MultiThreaderBase::ThreaderEnum::Unknown
#if !defined(ITK_USE_TBB)
      || threaderEnum == itk::MultiThreaderBase::ThreaderEnum::Unknown
#endif
    )
    {
    return false;
    }
  itk::MultiThreaderBase::SetGlobalDefaultThreader(threaderEnum);
  return true;
}

std::string ProcessObject::GetGlobalDefaultThreader()
{
  auto threaderEnum =  itk::MultiThreaderBase::GetGlobalDefaultThreader();
  return itk::MultiThreaderBase::ThreaderTypeToString(threaderEnum);
}

void ProcessObject::SetNumberOfThreads(unsigned int n)
{
  m_NumberOfThreads = n;
}

unsigned int ProcessObject::GetNumberOfThreads() const
{
  return m_NumberOfThreads;
}

void ProcessObject::SetNumberOfWorkUnits(unsigned int n)
{
  m_NumberOfWorkUnits = n;
}

unsigned int ProcessObject::GetNumberOfWorkUnits() const
{
  return m_NumberOfWorkUnits;
}

int ProcessObject::AddCommand(EventEnum event, Command &cmd)
{
  // add to our list of event, command pairs
  m_Commands.emplace_back(event,&cmd);

  // register ourselves with the command
  cmd.AddProcessObject(this);

  if (this->m_ActiveProcess)
    {
    this->AddObserverToActiveProcessObject( m_Commands.back() );
    }
  else
    {
    m_Commands.back().m_ITKTag = std::numeric_limits<unsigned long>::max();
    }

  return 0;
}

int ProcessObject::AddCommand(itk::simple::EventEnum event, const std::function<void()> &func)
{
  std::unique_ptr<FunctionCommand> cmd(new FunctionCommand());
  cmd->SetCallbackFunction(func);

  int id = this->AddCommand(event, *cmd.get());
  cmd->OwnedByObjectsOn();
  cmd.release();
  return id;
}

void ProcessObject::RemoveAllCommands()
{
  // set's the m_Commands to an empty list via a swap
  std::list<EventCommand> oldCommands;
  swap(oldCommands, m_Commands);

  // remove commands from active process object
  std::list<EventCommand>::iterator i = oldCommands.begin();
  while( i != oldCommands.end() && this->m_ActiveProcess )
    {
    this->RemoveObserverFromActiveProcessObject(*i);
    ++i;
    }

  // we must only call RemoveProcessObject once for each command
  // so make a unique list of the Commands.
  oldCommands.sort();
  oldCommands.unique();
  i = oldCommands.begin();
  while( i != oldCommands.end() )
    {
    // note: this may call onCommandDelete, but we have already copied
    // this->m_Command will be empty
    i++->m_Command->RemoveProcessObject(this);
    }
}

bool ProcessObject::HasCommand( EventEnum event ) const
{
  for ( const auto& eventCommand: m_Commands)
    {
    if (eventCommand.m_Event == event)
      {
      return true;
      }
    }
  return false;
}

float ProcessObject::GetProgress( ) const
{
  if ( this->m_ActiveProcess )
    {
    return this->m_ActiveProcess->GetProgress();
    }
  return m_ProgressMeasurement;
}

void ProcessObject::Abort()
{
  if ( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->AbortGenerateDataOn();
    }
}

void ProcessObject::PreUpdate(itk::ProcessObject *p)
{
  assert(p);

  // propagate number of threads
  if ( this->GetNumberOfWorkUnits() != 0 )
    {
    p->SetNumberOfWorkUnits(this->GetNumberOfWorkUnits());
    }

  p->GetMultiThreader()->SetMaximumNumberOfThreads(this->GetNumberOfThreads());

  try
    {
    this->m_ActiveProcess = p;

    // add command on active process deletion
    p->AddObserver(eventDeleteEvent, [this](const itk::EventObject &) {this->OnActiveProcessDelete();});

    // register commands
    for (auto &eventCommand: m_Commands )
      {
      this->AddObserverToActiveProcessObject(eventCommand);
      }

    }
  catch (...)
    {
    this->m_ActiveProcess = nullptr;
    throw;
    }

  sitkDebugMacro( "Executing ITK filter:\n" << *p );

}

unsigned long ProcessObject::AddITKObserver( const itk::EventObject &e,
                                             itk::Command *c)
{
  assert(this->m_ActiveProcess);
  return this->m_ActiveProcess->AddObserver(e,c);
}

void ProcessObject::RemoveITKObserver( EventCommand &e )
{
  assert(this->m_ActiveProcess);
  this->m_ActiveProcess->RemoveObserver(e.m_ITKTag);
}

const itk::EventObject &ProcessObject::GetITKEventObject(EventEnum e)
{
  switch (e)
    {
    case sitkAnyEvent:
      return eventAnyEvent;
    case sitkAbortEvent:
      return eventAbortEvent;
    case sitkDeleteEvent:
      return eventDeleteEvent;
    case sitkEndEvent:
      return eventEndEvent;
    case sitkIterationEvent:
      return eventIterationEvent;
    case sitkProgressEvent:
      return eventProgressEvent;
    case sitkStartEvent:
      return eventStartEvent;
    case sitkUserEvent:
      return eventUserEvent;
    case sitkMultiResolutionIterationEvent:
      return eventMultiResolutionIterationEvent;
    default:
      sitkExceptionMacro("LogicError: Unexpected event case!");
    }
}

itk::ProcessObject *ProcessObject::GetActiveProcess( )
{
  if (this->m_ActiveProcess)
    {
    return this->m_ActiveProcess;
    }
  sitkExceptionMacro("No active process for \"" << this->GetName() << "\"!");
}

void ProcessObject::OnActiveProcessDelete( )
{
  if (this->m_ActiveProcess)
    {
    this->m_ProgressMeasurement = this->m_ActiveProcess->GetProgress();
    }
  else
    {
    this->m_ProgressMeasurement = 0.0f;
    }

  // clear registered command IDs
  for (std::list<EventCommand>::iterator i = m_Commands.begin();
         i != m_Commands.end();
         ++i)
      {
      i->m_ITKTag = std::numeric_limits<unsigned long>::max();
      }

  this->m_ActiveProcess = nullptr;
}

void ProcessObject::onCommandDelete(const itk::simple::Command *cmd) noexcept
{
  // remove command from m_Command book keeping list, and remove it
  // from the  ITK ProcessObject
  std::list<EventCommand>::iterator i =  this->m_Commands.begin();
  while ( i !=  this->m_Commands.end() )
    {
    if ( cmd == i->m_Command )
      {
      if ( this->m_ActiveProcess )
        {
        this->RemoveObserverFromActiveProcessObject( *i );
        }
      this->m_Commands.erase(i++);
      }
    else
      {
      ++i;
      }

    }
}

unsigned long ProcessObject::AddObserverToActiveProcessObject( EventCommand &eventCommand )
{
  assert( this->m_ActiveProcess );

  if (eventCommand.m_ITKTag != std::numeric_limits<unsigned long>::max())
    {
    sitkExceptionMacro("Commands already registered to another process object!");
    }

  const itk::EventObject &itkEvent = GetITKEventObject(eventCommand.m_Event);

  // adapt sitk command to itk command
  SimpleAdaptorCommand::Pointer itkCommand = SimpleAdaptorCommand::New();
  itkCommand->SetSimpleCommand(eventCommand.m_Command);
  itkCommand->SetObjectName(eventCommand.m_Command->GetName()+" "+itkEvent.GetEventName());

  return eventCommand.m_ITKTag = this->AddITKObserver( itkEvent, itkCommand );
}

void ProcessObject::RemoveObserverFromActiveProcessObject( EventCommand &e )
 {
   assert( this->m_ActiveProcess );

   if (e.m_ITKTag != std::numeric_limits<unsigned long>::max() )
     {
     this->RemoveITKObserver(e);
     e.m_ITKTag = std::numeric_limits<unsigned long>::max();
     }

 }

} // end namespace simple
} // end namespace itk
<|endoftext|>


<commit_before>// $Id$
//
//  Copyright (C) 2003-2006 Rational Discovery LLC
//
//   @@ All Rights Reserved  @@
//

#include "RDDepictor.h"
#include <RDGeneral/types.h>
#include <GraphMol/ROMol.h>
#include <GraphMol/Conformer.h>
#include <math.h>
#include <GraphMol/MolOps.h>
#include <GraphMol/Rings.h>
#include <Geometry/point.h>
#include <Geometry/Transform2D.h>
#include "EmbeddedFrag.h"
#include "DepictUtils.h"
#include <iostream>
#include <boost/dynamic_bitset.hpp>
#include <algorithm>

namespace RDDepict {
  namespace DepictorLocal {
    // arings: indices of atoms in rings
    void embedFusedSystems(const RDKit::ROMol &mol,
                           const RDKit::VECT_INT_VECT &arings,
                           std::list<EmbeddedFrag> &efrags) {
      RDKit::INT_INT_VECT_MAP neighMap;
      RingUtils::makeRingNeighborMap(arings, neighMap);

      RDKit::INT_VECT fused;
      int cnrs = arings.size();
      boost::dynamic_bitset<> fusDone(cnrs);
      int curr = 0;

      while (curr < cnrs) {
        // embed all ring and fused ring systems
        fused.resize(0);
        RingUtils::pickFusedRings(curr, neighMap, fused, fusDone);
        RDKit::VECT_INT_VECT frings;
        frings.reserve(fused.size());
        for (RDKit::INT_VECT_CI rid = fused.begin();
             rid != fused.end(); ++rid) {
          frings.push_back(arings[*rid]);
        }
        EmbeddedFrag efrag(&mol, frings);
        efrag.setupNewNeighs();
        efrags.push_back(efrag);
        int rix;
        for (rix = 0; rix < cnrs; ++rix) {
          if (!fusDone[rix]) {
            curr = rix;
            break;
          }
        }
        if (rix == cnrs) {
          break;
        }
      }

    }

    void embedCisTransSystems(const RDKit::ROMol &mol,
                              std::list<EmbeddedFrag> &efrags) {
      for (RDKit::ROMol::ConstBondIterator cbi = mol.beginBonds();
           cbi != mol.endBonds(); ++cbi) {
        // check if this bond is in a cis/trans double bond
        // and it is not a ring bond
        if (((*cbi)->getBondType() == RDKit::Bond::DOUBLE) // this is a double bond
            && ((*cbi)->getStereo() > RDKit::Bond::STEREOANY) // and has stereo chemistry specified
            && (!(*cbi)->getOwningMol().getRingInfo()->numBondRings((*cbi)->getIdx())) ){ // not in a ring
          EmbeddedFrag efrag(*cbi);
          efrag.setupNewNeighs();
          efrags.push_back(efrag);
        }
      }
    }

    RDKit::INT_LIST getNonEmbeddedAtoms(const RDKit::ROMol &mol,
                                        const std::list<EmbeddedFrag> &efrags) {
      RDKit::INT_LIST res;
      boost::dynamic_bitset<> done(mol.getNumAtoms());
      for (std::list<EmbeddedFrag>::const_iterator efri = efrags.begin();
           efri != efrags.end(); efri++) {
        const INT_EATOM_MAP &oatoms = efri->GetEmbeddedAtoms();
        for (INT_EATOM_MAP_CI ori = oatoms.begin(); ori != oatoms.end(); ori++) {
          done[ori->first]=1;
        }
      }
      for (RDKit::ROMol::ConstAtomIterator ai = mol.beginAtoms();
           ai != mol.endAtoms(); ai++) {
        int aid = (*ai)->getIdx();
        if (!done[aid]){
          res.push_back(aid);
        }
      }
      return res;
    }

    // find the largest fragments that is not done yet (
    //  i.e. merged with the master fragments)
    // if do not find anything we return efrags.end()
    std::list<EmbeddedFrag>::iterator
    _findLargestFrag(std::list<EmbeddedFrag> &efrags) {
      std::list<EmbeddedFrag>::iterator mfri;
      int msiz = 0;
      for (std::list<EmbeddedFrag>::iterator efri = efrags.begin();
           efri != efrags.end(); efri++) {
        if ((!efri->isDone()) && (efri->Size() > msiz) ) {
          msiz = efri->Size();
          mfri = efri;
        }
      }
      if (msiz == 0) {
        mfri = efrags.end();
      }
      return mfri;
    }

    void _shiftCoords(std::list<EmbeddedFrag> &efrags) {
      // shift the coordinates if there are multiple fragments
      // so that the fargments do not overlap each other

      for(std::list<EmbeddedFrag>::iterator efi=efrags.begin();
          efi!=efrags.end();efi++){
        efi->computeBox();
      }
      std::list<EmbeddedFrag>::iterator eri = efrags.begin();
      double xmax = eri->getBoxPx();
      double xmin = eri->getBoxNx();
      double ymax = eri->getBoxPy();
      double ymin = eri->getBoxNy();

      ++eri;
      while (eri != efrags.end()) {
        bool xshift = true;
        if (xmax+xmin > ymax+ymin) {
          xshift = false;
        }
        double xn = eri->getBoxNx();
        double xp = eri->getBoxPx();
        double yn = eri->getBoxNy();
        double yp = eri->getBoxPy();
        RDGeom::Point2D shift(0.0,0.0);
        if (xshift) {
          shift.x = xmax + xn + 1.0;
          shift.y = 0.0;
          xmax += xp + xn + 1.0;
        } else {
          shift.x = 0.0;
          shift.y = ymax + yn + 1.0;
          ymax += yp + yn + 1.0;
        }
        eri->Translate(shift);

        ++eri;
      }
    }
  }

  void computeInitialCoords(RDKit::ROMol &mol,
                            const RDGeom::INT_POINT2D_MAP *coordMap,
                            std::list<EmbeddedFrag> &efrags) {

    // so that cis/trans bonds will be marked
    RDKit::MolOps::assignBondStereoCodes(mol, false);

    efrags.clear();
    RDKit::VECT_INT_VECT arings;

    // first find all the rings
    int nrings = RDKit::MolOps::symmetrizeSSSR(mol, arings);

    // user specfied coordinates exist
    bool preSpec = false;
    // first embed any atoms for which the coordinates have been specified.
    if ((coordMap) && (coordMap->size() > 0) ) {
      EmbeddedFrag efrag(&mol, *coordMap);
      // add this to the list of embedded fragments
      efrags.push_back(efrag);
      preSpec = true;
    }

    if (arings.size() > 0) {
      // first deal with the fused rings
      DepictorLocal::embedFusedSystems(mol, arings, efrags);
    }
    // deal with any cis/trans systems
    DepictorLocal::embedCisTransSystems(mol, efrags);

    // now get the atoms that are not yet embedded in either a cis/trans system
    // or a ring system (or simply the first atom)
    RDKit::INT_LIST nratms = DepictorLocal::getNonEmbeddedAtoms(mol, efrags);

    std::list<EmbeddedFrag>::iterator mri;
    if (preSpec) {
      // if the user specified coordinates on some of the atoms use that as
      // as the starting fragment and it should be at the beginning of the vector
      mri = efrags.begin();
    } else {
      // otherwise - find the largest fragment that was embedded
      mri = DepictorLocal::_findLargestFrag(efrags);
    }

    while ((mri != efrags.end()) || (nratms.size() > 0)) {
      if (mri == efrags.end()) {
        // we are out of embedded fragments, if there are any
        // non embedded atoms use them to start a fragment
	int mrank, rank;
	mrank = static_cast<int>(RDKit::MAX_INT);
	RDKit::INT_LIST_I nri, mnri;
	for (nri = nratms.begin(); nri != nratms.end(); nri++) {
          int aid = (*nri);
          const RDKit::Atom *at=mol.getAtomWithIdx(*nri);
          if(at->hasProp("_CIPRank")){
            at->getProp("_CIPRank", rank);
          } else {
            rank = 2*mol.getNumAtoms()+(*nri);
          }
	  if (rank < mrank) {
	    mrank = rank;
	    mnri = nri;
	  }
	}
        EmbeddedFrag efrag((*mnri), &mol);
        nratms.erase(mnri);
        efrags.push_back(efrag);
        mri = efrags.end();
        mri--;
      }
      mri->markDone();
      mri->expandEfrag(nratms, efrags);
      mri = DepictorLocal::_findLargestFrag(efrags);
    }
    // at this point any remaining efrags should belong individual fragments in the molecule

  }

  unsigned int copyCoordinate(RDKit::ROMol &mol, std::list<EmbeddedFrag> &efrags, bool clearConfs) {
    // create a conformation to store the coordinates and add it to the molecule
    RDKit::Conformer *conf = new RDKit::Conformer(mol.getNumAtoms());

    std::list<EmbeddedFrag>::iterator eri;
    for (eri = efrags.begin(); eri != efrags.end(); eri++) {
      const INT_EATOM_MAP &eatoms = eri->GetEmbeddedAtoms();
      INT_EATOM_MAP_CI eai;
      for (eai = eatoms.begin(); eai != eatoms.end(); eai++) {
        int aid = eai->first;
        RDGeom::Point2D cr = eai->second.loc;
        RDGeom::Point3D fcr(cr.x, cr.y, 0.0);
        conf->setAtomPos(aid, fcr);
      }
    }
    unsigned int confId = 0;
    if (clearConfs) {
      // clear all the conformation on the molecules and assign conf ID 0 to this
      // conformation
      mol.clearConformers();
      conf->setId(confId);
      // conf ID has already been set in this case to 0 - not other
      // confs on the molecule at this point
      mol.addConformer(conf);
    } else {
      // let add conf assign a conformation ID for the conformation
      confId = mol.addConformer(conf, true);
    }
    return confId;
  }
  //
  //
  // 50,000 foot algorithm:
  //   1) Find rings
  //   2) Find fused systems
  //   3) embed largest fused system
  //   4) foreeach unfinished atom:
  //      1) find neighbors
  //      2) if neighbor is non-ring atom, embed it; otherwise merge the
  //         ring system
  //      3) add all atoms just merged/embedded to unfinished atom list
  //
  //
  unsigned int compute2DCoords(RDKit::ROMol &mol,
                               const RDGeom::INT_POINT2D_MAP *coordMap,
                               bool canonOrient, bool clearConfs,
                               unsigned int nFlipsPerSample, unsigned int nSamples,
                               int sampleSeed, bool permuteDeg4Nodes) {

    // storage for pieces of a molecule/s that are embedded in 2D
    std::list<EmbeddedFrag> efrags;
    computeInitialCoords(mol, coordMap, efrags);

    // perform random sampling here to improve the density
    std::list<EmbeddedFrag>::iterator eri;
    for (eri = efrags.begin(); eri != efrags.end(); eri++) {
      // either sample the 2D space by randomly flipping rotatable bonds
      // in the structure or flip onyl bonds along the shortest path between
      // colliding atoms - don't do both
      if ((nSamples > 0) && (nFlipsPerSample > 0)) {
        eri->randomSampleFlipsAndPermutations(nFlipsPerSample, nSamples, sampleSeed,
                                              0, 0.0, permuteDeg4Nodes);
      } else
        eri->removeCollisionsBondFlip();
    }
    for (eri = efrags.begin(); eri != efrags.end(); eri++) {
      // if there are any remaining collisions
      eri->removeCollisionsOpenAngles();
      eri->removeCollisionsShortenBonds();
    }
    if (!coordMap) {
      if (canonOrient || efrags.size() >= 2) {
      // if we do not have any prespecified coordinates - canonicalize the
      // oreintation of the fragment so that the longest axes fall along the x-axis etc.
        for (eri = efrags.begin(); eri != efrags.end(); eri++) {
          eri->canonicalizeOrientation();
        }
      }
    }
    DepictorLocal::_shiftCoords(efrags);
    // create a confomation on the moelcule and copy the coodinates
    unsigned int cid = copyCoordinate(mol, efrags, clearConfs);
    return cid;
  }

  //! \brief Compute the 2D coordinates such the interatom distances mimic those in ditance matrix
  /*!
    This function generates 2D coordinates such that the inter atom distance mimic those specified via
    dmat. This is done by randomly sampling(flipping) the rotatable bonds in the molecule and evaluating
    a cost function which contains two components. The first component is the sum of inverse of the squared
    inter-atom distances, this helps in spreading the atoms far from each other. The second component is
    the sum of squares of the difference in distance between those in dmat and the generated structure.
    The user can adjust the relative importance of the two components via a adjustable paramter (see below)

    ARGUMENTS:
    \param mol - molecule involved in the frgament
    \param dmat - the distance matrix we want to mimic, this is symmteric N by N matrix when N is the number
                  of atoms in mol. All ngative entries in dmat are ignored.
    \param canonOrient - canonicalze the orientation after the 2D embedding is done
    \param clearConfs - clear any previously existing conformations on mol before adding a conformation
    \param weightDistMat - A value between 0.0 and 1.0, this determines the importance of mimicing the
                           the inter atoms distances in dmat. (1.0 - weightDistMat) is the weight associated
                           to spreading out the structure (density) in the cost function
    \param nFlipsPerSample - the number of rotatable bonds that are flips at random for each sample
    \param nSample - the number of samples
    \param sampleSeed - seed for the random sampling process
  */
  unsigned int compute2DCoordsMimicDistMat(RDKit::ROMol &mol, const DOUBLE_SMART_PTR *dmat,
                                           bool canonOrient, bool clearConfs, double weightDistMat,
                                           unsigned int nFlipsPerSample, unsigned int nSamples,
                                           int sampleSeed, bool permuteDeg4Nodes){
    // storage for pieces of a molecule/s that are embedded in 2D
    std::list<EmbeddedFrag> efrags;
    computeInitialCoords(mol, 0, efrags);

    // now perform random flips of rotatable bonds so taht we can sample the space
    // and try to mimic the distances in dmat
    std::list<EmbeddedFrag>::iterator eri;
    for (eri = efrags.begin(); eri != efrags.end(); eri++) {
      eri->randomSampleFlipsAndPermutations(nFlipsPerSample, nSamples, sampleSeed, dmat,
                                            weightDistMat, permuteDeg4Nodes);
    }
    if (canonOrient || efrags.size() >= 2) {
      // if we do not have any prespecified coordinates - canonicalize the
      // oreintation of the fragment so that the longest axes fall along the x-axis etc.
      for (eri = efrags.begin(); eri != efrags.end(); eri++) {
        eri->canonicalizeOrientation();
      }
    }

    DepictorLocal::_shiftCoords(efrags);
    // create a confomation on the moelcule and copy the coodinates
    unsigned int cid = copyCoordinate(mol, efrags, clearConfs);
    return cid;
  }

}

<commit_msg>be more systematic about ranking atoms<commit_after>// $Id$
//
//  Copyright (C) 2003-2006 Rational Discovery LLC
//
//   @@ All Rights Reserved  @@
//

#include "RDDepictor.h"
#include <RDGeneral/types.h>
#include <GraphMol/ROMol.h>
#include <GraphMol/Conformer.h>
#include <math.h>
#include <GraphMol/MolOps.h>
#include <GraphMol/Rings.h>
#include <Geometry/point.h>
#include <Geometry/Transform2D.h>
#include "EmbeddedFrag.h"
#include "DepictUtils.h"
#include <iostream>
#include <boost/dynamic_bitset.hpp>
#include <algorithm>

namespace RDDepict {
  namespace DepictorLocal {
    // arings: indices of atoms in rings
    void embedFusedSystems(const RDKit::ROMol &mol,
                           const RDKit::VECT_INT_VECT &arings,
                           std::list<EmbeddedFrag> &efrags) {
      RDKit::INT_INT_VECT_MAP neighMap;
      RingUtils::makeRingNeighborMap(arings, neighMap);

      RDKit::INT_VECT fused;
      int cnrs = arings.size();
      boost::dynamic_bitset<> fusDone(cnrs);
      int curr = 0;

      while (curr < cnrs) {
        // embed all ring and fused ring systems
        fused.resize(0);
        RingUtils::pickFusedRings(curr, neighMap, fused, fusDone);
        RDKit::VECT_INT_VECT frings;
        frings.reserve(fused.size());
        for (RDKit::INT_VECT_CI rid = fused.begin();
             rid != fused.end(); ++rid) {
          frings.push_back(arings[*rid]);
        }
        EmbeddedFrag efrag(&mol, frings);
        efrag.setupNewNeighs();
        efrags.push_back(efrag);
        int rix;
        for (rix = 0; rix < cnrs; ++rix) {
          if (!fusDone[rix]) {
            curr = rix;
            break;
          }
        }
        if (rix == cnrs) {
          break;
        }
      }

    }

    void embedCisTransSystems(const RDKit::ROMol &mol,
                              std::list<EmbeddedFrag> &efrags) {
      for (RDKit::ROMol::ConstBondIterator cbi = mol.beginBonds();
           cbi != mol.endBonds(); ++cbi) {
        // check if this bond is in a cis/trans double bond
        // and it is not a ring bond
        if (((*cbi)->getBondType() == RDKit::Bond::DOUBLE) // this is a double bond
            && ((*cbi)->getStereo() > RDKit::Bond::STEREOANY) // and has stereo chemistry specified
            && (!(*cbi)->getOwningMol().getRingInfo()->numBondRings((*cbi)->getIdx())) ){ // not in a ring
          EmbeddedFrag efrag(*cbi);
          efrag.setupNewNeighs();
          efrags.push_back(efrag);
        }
      }
    }

    RDKit::INT_LIST getNonEmbeddedAtoms(const RDKit::ROMol &mol,
                                        const std::list<EmbeddedFrag> &efrags) {
      RDKit::INT_LIST res;
      boost::dynamic_bitset<> done(mol.getNumAtoms());
      for (std::list<EmbeddedFrag>::const_iterator efri = efrags.begin();
           efri != efrags.end(); efri++) {
        const INT_EATOM_MAP &oatoms = efri->GetEmbeddedAtoms();
        for (INT_EATOM_MAP_CI ori = oatoms.begin(); ori != oatoms.end(); ori++) {
          done[ori->first]=1;
        }
      }
      for (RDKit::ROMol::ConstAtomIterator ai = mol.beginAtoms();
           ai != mol.endAtoms(); ai++) {
        int aid = (*ai)->getIdx();
        if (!done[aid]){
          res.push_back(aid);
        }
      }
      return res;
    }

    // find the largest fragments that is not done yet (
    //  i.e. merged with the master fragments)
    // if do not find anything we return efrags.end()
    std::list<EmbeddedFrag>::iterator
    _findLargestFrag(std::list<EmbeddedFrag> &efrags) {
      std::list<EmbeddedFrag>::iterator mfri;
      int msiz = 0;
      for (std::list<EmbeddedFrag>::iterator efri = efrags.begin();
           efri != efrags.end(); efri++) {
        if ((!efri->isDone()) && (efri->Size() > msiz) ) {
          msiz = efri->Size();
          mfri = efri;
        }
      }
      if (msiz == 0) {
        mfri = efrags.end();
      }
      return mfri;
    }

    void _shiftCoords(std::list<EmbeddedFrag> &efrags) {
      // shift the coordinates if there are multiple fragments
      // so that the fargments do not overlap each other

      for(std::list<EmbeddedFrag>::iterator efi=efrags.begin();
          efi!=efrags.end();efi++){
        efi->computeBox();
      }
      std::list<EmbeddedFrag>::iterator eri = efrags.begin();
      double xmax = eri->getBoxPx();
      double xmin = eri->getBoxNx();
      double ymax = eri->getBoxPy();
      double ymin = eri->getBoxNy();

      ++eri;
      while (eri != efrags.end()) {
        bool xshift = true;
        if (xmax+xmin > ymax+ymin) {
          xshift = false;
        }
        double xn = eri->getBoxNx();
        double xp = eri->getBoxPx();
        double yn = eri->getBoxNy();
        double yp = eri->getBoxPy();
        RDGeom::Point2D shift(0.0,0.0);
        if (xshift) {
          shift.x = xmax + xn + 1.0;
          shift.y = 0.0;
          xmax += xp + xn + 1.0;
        } else {
          shift.x = 0.0;
          shift.y = ymax + yn + 1.0;
          ymax += yp + yn + 1.0;
        }
        eri->Translate(shift);

        ++eri;
      }
    }
  }

  void computeInitialCoords(RDKit::ROMol &mol,
                            const RDGeom::INT_POINT2D_MAP *coordMap,
                            std::list<EmbeddedFrag> &efrags) {

    // so that cis/trans bonds will be marked
    RDKit::MolOps::assignBondStereoCodes(mol, false);

    efrags.clear();
    RDKit::VECT_INT_VECT arings;

    // first find all the rings
    int nrings = RDKit::MolOps::symmetrizeSSSR(mol, arings);

    // user specfied coordinates exist
    bool preSpec = false;
    // first embed any atoms for which the coordinates have been specified.
    if ((coordMap) && (coordMap->size() > 0) ) {
      EmbeddedFrag efrag(&mol, *coordMap);
      // add this to the list of embedded fragments
      efrags.push_back(efrag);
      preSpec = true;
    }

    if (arings.size() > 0) {
      // first deal with the fused rings
      DepictorLocal::embedFusedSystems(mol, arings, efrags);
    }
    // deal with any cis/trans systems
    DepictorLocal::embedCisTransSystems(mol, efrags);

    // now get the atoms that are not yet embedded in either a cis/trans system
    // or a ring system (or simply the first atom)
    RDKit::INT_LIST nratms = DepictorLocal::getNonEmbeddedAtoms(mol, efrags);

    std::list<EmbeddedFrag>::iterator mri;
    if (preSpec) {
      // if the user specified coordinates on some of the atoms use that as
      // as the starting fragment and it should be at the beginning of the vector
      mri = efrags.begin();
    } else {
      // otherwise - find the largest fragment that was embedded
      mri = DepictorLocal::_findLargestFrag(efrags);
    }

    while ((mri != efrags.end()) || (nratms.size() > 0)) {
      if (mri == efrags.end()) {
        // we are out of embedded fragments, if there are any
        // non embedded atoms use them to start a fragment
	int mrank, rank;
	mrank = static_cast<int>(RDKit::MAX_INT);
	RDKit::INT_LIST_I nri, mnri;
	for (nri = nratms.begin(); nri != nratms.end(); nri++) {
          int aid = (*nri);
          const RDKit::Atom *at=mol.getAtomWithIdx(*nri);
          if(at->hasProp("_CIPRank")){
            at->getProp("_CIPRank", rank);
          } else {
	    // if the thing has no CIP rank, just set it high:
            rank = 2*mol.getNumAtoms();
          }
	  rank *= 1000;
	  // use the atom index as well so that we at least
	  // get reproduceable depictions in cases where things
	  // have identical ranks.
	  rank += *nri;
	  if (rank < mrank) {
	    mrank = rank;
	    mnri = nri;
	  }
	}
        EmbeddedFrag efrag((*mnri), &mol);
        nratms.erase(mnri);
        efrags.push_back(efrag);
        mri = efrags.end();
        mri--;
      }
      mri->markDone();
      mri->expandEfrag(nratms, efrags);
      mri = DepictorLocal::_findLargestFrag(efrags);
    }
    // at this point any remaining efrags should belong individual fragments in the molecule

  }

  unsigned int copyCoordinate(RDKit::ROMol &mol, std::list<EmbeddedFrag> &efrags, bool clearConfs) {
    // create a conformation to store the coordinates and add it to the molecule
    RDKit::Conformer *conf = new RDKit::Conformer(mol.getNumAtoms());

    std::list<EmbeddedFrag>::iterator eri;
    for (eri = efrags.begin(); eri != efrags.end(); eri++) {
      const INT_EATOM_MAP &eatoms = eri->GetEmbeddedAtoms();
      INT_EATOM_MAP_CI eai;
      for (eai = eatoms.begin(); eai != eatoms.end(); eai++) {
        int aid = eai->first;
        RDGeom::Point2D cr = eai->second.loc;
        RDGeom::Point3D fcr(cr.x, cr.y, 0.0);
        conf->setAtomPos(aid, fcr);
      }
    }
    unsigned int confId = 0;
    if (clearConfs) {
      // clear all the conformation on the molecules and assign conf ID 0 to this
      // conformation
      mol.clearConformers();
      conf->setId(confId);
      // conf ID has already been set in this case to 0 - not other
      // confs on the molecule at this point
      mol.addConformer(conf);
    } else {
      // let add conf assign a conformation ID for the conformation
      confId = mol.addConformer(conf, true);
    }
    return confId;
  }
  //
  //
  // 50,000 foot algorithm:
  //   1) Find rings
  //   2) Find fused systems
  //   3) embed largest fused system
  //   4) foreach unfinished atom:
  //      1) find neighbors
  //      2) if neighbor is non-ring atom, embed it; otherwise merge the
  //         ring system
  //      3) add all atoms just merged/embedded to unfinished atom list
  //
  //
  unsigned int compute2DCoords(RDKit::ROMol &mol,
                               const RDGeom::INT_POINT2D_MAP *coordMap,
                               bool canonOrient, bool clearConfs,
                               unsigned int nFlipsPerSample,
			       unsigned int nSamples,
                               int sampleSeed, bool permuteDeg4Nodes) {

    // storage for pieces of a molecule/s that are embedded in 2D
    std::list<EmbeddedFrag> efrags;
    computeInitialCoords(mol, coordMap, efrags);

    // perform random sampling here to improve the density
    std::list<EmbeddedFrag>::iterator eri;
    for (eri = efrags.begin(); eri != efrags.end(); eri++) {
      // either sample the 2D space by randomly flipping rotatable
      // bonds in the structure or flip onyl bonds along the shortest
      // path between colliding atoms - don't do both
      if ((nSamples > 0) && (nFlipsPerSample > 0)) {
        eri->randomSampleFlipsAndPermutations(nFlipsPerSample, nSamples,
					      sampleSeed, 0, 0.0,
					      permuteDeg4Nodes);
      } else {
        eri->removeCollisionsBondFlip();
      }
    }
    for (eri = efrags.begin(); eri != efrags.end(); eri++) {
      // if there are any remaining collisions
      eri->removeCollisionsOpenAngles();
      eri->removeCollisionsShortenBonds();
    }
    if (!coordMap) {
      if (canonOrient || efrags.size() >= 2) {
      // if we do not have any prespecified coordinates - canonicalize
      // the orientation of the fragment so that the longest axes fall
      // along the x-axis etc.
        for (eri = efrags.begin(); eri != efrags.end(); eri++) {
          eri->canonicalizeOrientation();
        }
      }
    }
    DepictorLocal::_shiftCoords(efrags);
    // create a confomation on the moelcule and copy the coodinates
    unsigned int cid = copyCoordinate(mol, efrags, clearConfs);
    return cid;
  }

  //! \brief Compute the 2D coordinates such the interatom distances
  //!        mimic those in a distance matrix
  /*!
    This function generates 2D coordinates such that the inter atom
    distance mimic those specified via dmat. This is done by randomly
    sampling(flipping) the rotatable bonds in the molecule and
    evaluating a cost function which contains two components. The
    first component is the sum of inverse of the squared inter-atom
    distances, this helps in spreading the atoms far from each
    other. The second component is the sum of squares of the
    difference in distance between those in dmat and the generated
    structure.  The user can adjust the relative importance of the two
    components via a adjustable paramter (see below)

    ARGUMENTS:
    \param mol - molecule involved in the frgament

    \param dmat - the distance matrix we want to mimic, this is
                  symmteric N by N matrix when N is the number of
                  atoms in mol. All ngative entries in dmat are
                  ignored.

    \param canonOrient - canonicalze the orientation after the 2D
                         embedding is done

    \param clearConfs - clear any previously existing conformations on
                        mol before adding a conformation

    \param weightDistMat - A value between 0.0 and 1.0, this
                           determines the importance of mimicing the
                           the inter atoms distances in dmat. (1.0 -
                           weightDistMat) is the weight associated to
                           spreading out the structure (density) in
                           the cost function

    \param nFlipsPerSample - the number of rotatable bonds that are
                             randomly flipped for each sample

    \param nSample - the number of samples

    \param sampleSeed - seed for the random sampling process
  */
  unsigned int compute2DCoordsMimicDistMat(RDKit::ROMol &mol,
					   const DOUBLE_SMART_PTR *dmat,
                                           bool canonOrient,
					   bool clearConfs, double weightDistMat,
                                           unsigned int nFlipsPerSample,
					   unsigned int nSamples,
                                           int sampleSeed,
					   bool permuteDeg4Nodes){
    // storage for pieces of a molecule/s that are embedded in 2D
    std::list<EmbeddedFrag> efrags;
    computeInitialCoords(mol, 0, efrags);

    // now perform random flips of rotatable bonds so taht we can sample the space
    // and try to mimic the distances in dmat
    std::list<EmbeddedFrag>::iterator eri;
    for (eri = efrags.begin(); eri != efrags.end(); eri++) {
      eri->randomSampleFlipsAndPermutations(nFlipsPerSample, nSamples, sampleSeed, dmat,
                                            weightDistMat, permuteDeg4Nodes);
    }
    if (canonOrient || efrags.size() >= 2) {
      // if we do not have any prespecified coordinates - canonicalize the
      // oreintation of the fragment so that the longest axes fall along the x-axis etc.
      for (eri = efrags.begin(); eri != efrags.end(); eri++) {
        eri->canonicalizeOrientation();
      }
    }

    DepictorLocal::_shiftCoords(efrags);
    // create a confomation on the moelcule and copy the coodinates
    unsigned int cid = copyCoordinate(mol, efrags, clearConfs);
    return cid;
  }

}

<|endoftext|>


<commit_before>/*
 * TinyJS
 *
 * A single-file Javascript-alike engine
 *
 * - Useful language functions
 *
 * Authored By Gordon Williams <gw@pur3.co.uk>
 *
 * Copyright (C) 2009 Pur3 Ltd
 *
 * 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 "ascript_pch.hpp"
#include "TinyJS_Functions.h"
#include "scriptMain.h"
#include "mvmFunctions.h"
#include "jsArray.h"
#include "asString.h"

#include <math.h>
#include <cstdlib>
#include <sstream>

using namespace std;
// ----------------------------------------------- Actual Functions

ASValue scMathRand(ExecutionContext* ec)
{
    return jsDouble(double(rand()) / RAND_MAX);
}

ASValue scMathRandInt(ExecutionContext* ec)
{
    const int min = ec->getParam(0).toInt32();
    const int max = ec->getParam(1).toInt32();
    const int val = min + (int) (rand() % (1 + max - min));
    return jsInt(val);
}

ASValue scCharToInt(ExecutionContext* ec)
{
    string str = ec->getParam(0).toString(ec);
    int val = 0;
    if (str.length() > 0)
        val = (int) str.c_str()[0];
    return jsInt(val);
}

ASValue scIntegerParseInt(ExecutionContext* ec)
{
    //TODO: Make it more standard compliant (octal support, return NaN if fails...)
    //We can reuse the code which parses numeric constants.
    string str = ec->getParam(0).toString(ec);
    int val = strtol(str.c_str(), 0, 0);
    return jsInt(val);
}

ASValue scIntegerValueOf(ExecutionContext* ec)
{
    string str = ec->getParam(0).toString(ec);

    int val = 0;
    if (str.length() == 1)
        val = str[0];
    return jsInt(val);
}

ASValue scJSONStringify(ExecutionContext* ec)
{
    std::string result;
    result = ec->getParam(0).getJSON(0);
    return jsString(result);
}

ASValue scEval(ExecutionContext* ec)
{
    std::string str = ec->getParam(0).toString(ec);

    return evaluate (str.c_str(), createDefaultGlobals());
}

void registerDefaultClasses(Ref<JSObject> scope)
{
    scope->writeField("Object", JSObject::DefaultClass->value(), true);
    scope->writeField("String", JSString::StringClass->value(), true);
    //scope->writeField("Array", JSArray::ArrayClass, true);
}

// ----------------------------------------------- Register Functions
/**
 * Register default functions into the given scope.
 * @param scope
 */
void registerFunctions(Ref<JSObject> scope)
{
    registerDefaultClasses(scope);

    addNative("function eval(jsCode)", scEval, scope); // execute the given string (an expression) and return the result

    addNative("function Math.rand()", scMathRand, scope);
    addNative("function Math.randInt(min, max)", scMathRandInt, scope);
    addNative("function charToInt(ch)", scCharToInt, scope); //  convert a character to an int - get its value

    addNative("function parseInt(str)", scIntegerParseInt, scope); // string to int
    addNative("function Integer.valueOf(str)", scIntegerValueOf, scope); // value of a single character
    addNative("function JSON.stringify(obj, replacer)", scJSONStringify, scope); // convert to JSON. replacer is ignored at the moment
    //TODO: Add JSON.parse()
}

<commit_msg>BUGFIX: Array class was not registered.<commit_after>/*
 * TinyJS
 *
 * A single-file Javascript-alike engine
 *
 * - Useful language functions
 *
 * Authored By Gordon Williams <gw@pur3.co.uk>
 *
 * Copyright (C) 2009 Pur3 Ltd
 *
 * 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 "ascript_pch.hpp"
#include "TinyJS_Functions.h"
#include "scriptMain.h"
#include "mvmFunctions.h"
#include "jsArray.h"
#include "asString.h"

#include <math.h>
#include <cstdlib>
#include <sstream>

using namespace std;
// ----------------------------------------------- Actual Functions

ASValue scMathRand(ExecutionContext* ec)
{
    return jsDouble(double(rand()) / RAND_MAX);
}

ASValue scMathRandInt(ExecutionContext* ec)
{
    const int min = ec->getParam(0).toInt32();
    const int max = ec->getParam(1).toInt32();
    const int val = min + (int) (rand() % (1 + max - min));
    return jsInt(val);
}

ASValue scCharToInt(ExecutionContext* ec)
{
    string str = ec->getParam(0).toString(ec);
    int val = 0;
    if (str.length() > 0)
        val = (int) str.c_str()[0];
    return jsInt(val);
}

ASValue scIntegerParseInt(ExecutionContext* ec)
{
    //TODO: Make it more standard compliant (octal support, return NaN if fails...)
    //We can reuse the code which parses numeric constants.
    string str = ec->getParam(0).toString(ec);
    int val = strtol(str.c_str(), 0, 0);
    return jsInt(val);
}

ASValue scIntegerValueOf(ExecutionContext* ec)
{
    string str = ec->getParam(0).toString(ec);

    int val = 0;
    if (str.length() == 1)
        val = str[0];
    return jsInt(val);
}

ASValue scJSONStringify(ExecutionContext* ec)
{
    std::string result;
    result = ec->getParam(0).getJSON(0);
    return jsString(result);
}

ASValue scEval(ExecutionContext* ec)
{
    std::string str = ec->getParam(0).toString(ec);

    return evaluate (str.c_str(), createDefaultGlobals());
}

void registerDefaultClasses(Ref<JSObject> scope)
{
    scope->writeField("Object", JSObject::DefaultClass->value(), true);
    scope->writeField("String", JSString::StringClass->value(), true);
    scope->writeField("Array", JSArray::ArrayClass->value(), true);
}

// ----------------------------------------------- Register Functions
/**
 * Register default functions into the given scope.
 * @param scope
 */
void registerFunctions(Ref<JSObject> scope)
{
    registerDefaultClasses(scope);

    addNative("function eval(jsCode)", scEval, scope); // execute the given string (an expression) and return the result

    addNative("function Math.rand()", scMathRand, scope);
    addNative("function Math.randInt(min, max)", scMathRandInt, scope);
    addNative("function charToInt(ch)", scCharToInt, scope); //  convert a character to an int - get its value

    addNative("function parseInt(str)", scIntegerParseInt, scope); // string to int
    addNative("function Integer.valueOf(str)", scIntegerValueOf, scope); // value of a single character
    addNative("function JSON.stringify(obj, replacer)", scJSONStringify, scope); // convert to JSON. replacer is ignored at the moment
    //TODO: Add JSON.parse()
}

<|endoftext|>


<commit_before>#include "VBackdrop.h"
#include <cmath>

void VBackdrop::updateTransform()
{
	if (sprite.getPosition() != Position)
		sprite.setPosition(Position);
	if (sprite.getRotation() != Angle)
		sprite.setRotation(Angle);
	if (sprite.getScale() != Scale)
		sprite.setScale(Scale);
	if (sprite.getColor() != Tint)
		sprite.setColor(Tint);
}

void VBackdrop::updateFrame()
{
	if (sprite.getColor() != Tint)
		sprite.setColor(Tint);
}

VSprite* VBackdrop::LoadGraphic(sf::String filename, bool animated, int width, int height, int offsetX, int offsetY, int texWidth, int texHeight)
{
	VSUPERCLASS::LoadGraphic(filename);
	texture.setRepeated(true);
	Size.x = 0;
	Size.y = 0;
	return this;
}

VSprite* VBackdrop::LoadGraphicFromTexture(sf::Texture texture, bool animated, int width, int height, int offsetX, int offsetY, int texWidth, int texHeight)
{
	VSUPERCLASS::LoadGraphicFromTexture(texture);
	texture.setRepeated(true);
	Size.x = 0;
	Size.y = 0;
	return this;
}

void VBackdrop::Draw(sf::RenderTarget& RenderTarget)
{
	VObject::Draw(RenderTarget);

	//Todo: Move this transform code to VObject, along with the line to restore the original transform.
	sf::View renderTargetView = RenderTarget.getView();
	sf::View scrollView = RenderTarget.getDefaultView();

	sf::Vector2f scroll = (renderTargetView.getCenter() - scrollView.getCenter());
	if (!CameraScroll)
		scroll = Scroll;

	scroll.x *= ScrollFactor.x;
	scroll.y *= ScrollFactor.y;

	sf::Vector2f texSize = sf::Vector2f(texture.getSize());

	if (RepeatX)
	{
		texSize.x = renderTargetView.getSize().x;
		texSize.x /= Scale.x;
	}

	if (RepeatY)
	{
		texSize.y = renderTargetView.getSize().y;
		texSize.y /= Scale.y;
	}

	sf::IntRect Rect;
	Rect.left = static_cast<int>((scroll.x * (RepeatX ? 1 : 0)) - (texSize.x / 2.0f));
	Rect.top = static_cast<int>((scroll.y * (RepeatY ? 1 : 0)) - (texSize.y / 2.0f));
	Rect.width = static_cast<int>(texSize.x);
	Rect.height = static_cast<int>(texSize.y);

	if (!CameraScroll)
	{
		Rect.left += texSize.x / 2.0f;
		Rect.top += texSize.y / 2.0f;
	}

	sprite.setTextureRect(Rect);

	sf::Vector2f oldPosition = sprite.getPosition();
	sf::Vector2f newPosition = oldPosition + (scrollView.getSize() / 2.0f - renderTargetView.getSize() / 2.0f);
	newPosition.x -= RepeatX ? 0 : scroll.x;
	newPosition.y -= RepeatY ? 0 : scroll.y;
	sprite.setPosition(newPosition);

	scroll = renderTargetView.getCenter() - scrollView.getCenter();
	scroll.x *= RepeatX ? 0 : ScrollFactor.x;
	scroll.y *= RepeatY ? 0 : ScrollFactor.y;

	float rotate = renderTargetView.getRotation() - scrollView.getRotation();
	rotate *= RotateFactor;

	float zoom = renderTargetView.getSize().x / scrollView.getSize().x;
	zoom--;
	zoom *= ZoomFactor;
	zoom++;

	scrollView.move(scroll);
	scrollView.rotate(rotate);
	scrollView.zoom(zoom);
	scrollView.setViewport(renderTargetView.getViewport());

	sf::FloatRect renderBox = sprite.getGlobalBounds();
	float maxSize = fmaxf(scrollView.getSize().x, scrollView.getSize().y);
	sf::FloatRect scrollBox = sf::FloatRect(scrollView.getCenter() - sf::Vector2f(maxSize, maxSize) / 2.0f, sf::Vector2f(maxSize, maxSize));

	if (renderBox.left < scrollBox.left + scrollBox.width &&
		renderBox.left + renderBox.width > scrollBox.left &&
		renderBox.top <	 scrollBox.top + scrollBox.height &&
		renderBox.top + renderBox.height > scrollBox.top)
	{
		RenderTarget.setView(scrollView);
		RenderTarget.draw(sprite, RenderState);
		RenderTarget.setView(renderTargetView);
	}

	sprite.setPosition(oldPosition);
}
<commit_msg>Casting<commit_after>#include "VBackdrop.h"
#include <cmath>

void VBackdrop::updateTransform()
{
	if (sprite.getPosition() != Position)
		sprite.setPosition(Position);
	if (sprite.getRotation() != Angle)
		sprite.setRotation(Angle);
	if (sprite.getScale() != Scale)
		sprite.setScale(Scale);
	if (sprite.getColor() != Tint)
		sprite.setColor(Tint);
}

void VBackdrop::updateFrame()
{
	if (sprite.getColor() != Tint)
		sprite.setColor(Tint);
}

VSprite* VBackdrop::LoadGraphic(sf::String filename, bool animated, int width, int height, int offsetX, int offsetY, int texWidth, int texHeight)
{
	VSUPERCLASS::LoadGraphic(filename);
	texture.setRepeated(true);
	Size.x = 0;
	Size.y = 0;
	return this;
}

VSprite* VBackdrop::LoadGraphicFromTexture(sf::Texture texture, bool animated, int width, int height, int offsetX, int offsetY, int texWidth, int texHeight)
{
	VSUPERCLASS::LoadGraphicFromTexture(texture);
	texture.setRepeated(true);
	Size.x = 0;
	Size.y = 0;
	return this;
}

void VBackdrop::Draw(sf::RenderTarget& RenderTarget)
{
	VObject::Draw(RenderTarget);

	//Todo: Move this transform code to VObject, along with the line to restore the original transform.
	sf::View renderTargetView = RenderTarget.getView();
	sf::View scrollView = RenderTarget.getDefaultView();

	sf::Vector2f scroll = (renderTargetView.getCenter() - scrollView.getCenter());
	if (!CameraScroll)
		scroll = Scroll;

	scroll.x *= ScrollFactor.x;
	scroll.y *= ScrollFactor.y;

	sf::Vector2f texSize = sf::Vector2f(texture.getSize());

	if (RepeatX)
	{
		texSize.x = renderTargetView.getSize().x;
		texSize.x /= Scale.x;
	}

	if (RepeatY)
	{
		texSize.y = renderTargetView.getSize().y;
		texSize.y /= Scale.y;
	}

	sf::IntRect Rect;
	Rect.left = static_cast<int>((scroll.x * (RepeatX ? 1 : 0)) - (texSize.x / 2.0f));
	Rect.top = static_cast<int>((scroll.y * (RepeatY ? 1 : 0)) - (texSize.y / 2.0f));
	Rect.width = static_cast<int>(texSize.x);
	Rect.height = static_cast<int>(texSize.y);

	if (!CameraScroll)
	{
		Rect.left += static_cast<int>(texSize.x / 2.0f);
		Rect.top += static_cast<int>(texSize.y / 2.0f);
	}

	sprite.setTextureRect(Rect);

	sf::Vector2f oldPosition = sprite.getPosition();
	sf::Vector2f newPosition = oldPosition + (scrollView.getSize() / 2.0f - renderTargetView.getSize() / 2.0f);
	newPosition.x -= RepeatX ? 0 : scroll.x;
	newPosition.y -= RepeatY ? 0 : scroll.y;
	sprite.setPosition(newPosition);

	scroll = renderTargetView.getCenter() - scrollView.getCenter();
	scroll.x *= RepeatX ? 0 : ScrollFactor.x;
	scroll.y *= RepeatY ? 0 : ScrollFactor.y;

	float rotate = renderTargetView.getRotation() - scrollView.getRotation();
	rotate *= RotateFactor;

	float zoom = renderTargetView.getSize().x / scrollView.getSize().x;
	zoom--;
	zoom *= ZoomFactor;
	zoom++;

	scrollView.move(scroll);
	scrollView.rotate(rotate);
	scrollView.zoom(zoom);
	scrollView.setViewport(renderTargetView.getViewport());

	sf::FloatRect renderBox = sprite.getGlobalBounds();
	float maxSize = fmaxf(scrollView.getSize().x, scrollView.getSize().y);
	sf::FloatRect scrollBox = sf::FloatRect(scrollView.getCenter() - sf::Vector2f(maxSize, maxSize) / 2.0f, sf::Vector2f(maxSize, maxSize));

	if (renderBox.left < scrollBox.left + scrollBox.width &&
		renderBox.left + renderBox.width > scrollBox.left &&
		renderBox.top <	 scrollBox.top + scrollBox.height &&
		renderBox.top + renderBox.height > scrollBox.top)
	{
		RenderTarget.setView(scrollView);
		RenderTarget.draw(sprite, RenderState);
		RenderTarget.setView(renderTargetView);
	}

	sprite.setPosition(oldPosition);
}
<|endoftext|>