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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

=========================================================================*/

#include "mitkPointSet.h"
#include "mitkOperation.h"
#include "mitkOperationActor.h"
#include "mitkPointOperation.h"
#include "mitkInteractionConst.h"
#include "mitkXMLWriter.h"
#include "mitkXMLReader.h"
#include "mitkPointSetWriter.h"
#include "mitkPointSetReader.h"
#include "mitkRenderingManager.h"

#include <itkSmartPointerForwardReference.txx>

mitk::PointSet::PointSet()
{
  m_Initialized = false;
  m_PointSetSeries.resize( 1 );

  m_PointSetSeries[0] = DataType::New();
  PointDataContainer::Pointer pointData = PointDataContainer::New();
  m_PointSetSeries[0]->SetPointData( pointData );
  m_CalculateBoundingBox = false;

  Superclass::InitializeTimeSlicedGeometry(1);
}

mitk::PointSet::~PointSet()
{
}

bool mitk::PointSet::IsEmpty(int t) const
{
  return IsInitialized() && (GetSize(t) <= 0);
}

void mitk::PointSet::Resize( unsigned int timeSteps )
{
  // Check if the vector is long enough to contain the new element
  // at the given position. If not, expand it with sufficient pre-initialized
  // elements.
  //
  // NOTE: This method will never REDUCE the vector size; it should only
  // be used to make sure that the vector has enough elements to include the
  // specified time step.

  unsigned int oldSize = m_PointSetSeries.size();

  if ( timeSteps > oldSize )
  {
    Superclass::Resize( timeSteps );

    m_PointSetSeries.resize( timeSteps );
    for ( unsigned int i = oldSize; i < timeSteps; ++i )
    {
      m_PointSetSeries[i] = DataType::New();
      PointDataContainer::Pointer pointData = PointDataContainer::New();
      m_PointSetSeries[i]->SetPointData( pointData );
    }

    //if the size changes, then compute the boundingbox
    m_CalculateBoundingBox = true;
  }

  if ( timeSteps != oldSize )
  {
    this->InvokeEvent( PointSetTimeStepsChangeEvent() );
  }
}

unsigned int mitk::PointSet::GetPointSetSeriesSize() const
{
  return m_PointSetSeries.size();
}

int mitk::PointSet::GetSize( int t ) const
{
  if ( t < (int)m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t]->GetNumberOfPoints();
  }
  else
  {
    return 0;
  }
}

mitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet( int t ) const
{
  if ( t < (int)m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t];
  }
  else
  {
    return NULL;
  }
}

int mitk::PointSet::SearchPoint( Point3D point, float distance, int t  )
{
  if ( t >= (int)m_PointSetSeries.size() )
  {
    return -1;
  }

  // Out is the point which is checked to be the searched point
  PointType out;
  out.Fill( 0 );
  PointType indexPoint;

  this->GetGeometry( t )->WorldToIndex(point, indexPoint);

  // Searching the first point in the Set, that is +- distance far away fro
  // the given point
  unsigned int i;
  PointsContainer::Iterator it, end;
  end = m_PointSetSeries[t]->GetPoints()->End();
  int bestIndex = -1;
  distance = distance * distance;

  // To correct errors from converting index to world and world to index
  if (distance == 0.0)
  {
    distance = 0.000001;
  }

  ScalarType bestDist = distance;
  ScalarType dist, tmp;

  for ( it = m_PointSetSeries[t]->GetPoints()->Begin(), i = 0;
        it != end;
        ++it, ++i )
  {
    bool ok = m_PointSetSeries[t]->GetPoints()
      ->GetElementIfIndexExists( it->Index(), &out );

    if ( !ok )
    {
      return -1;
    }
    else if ( indexPoint == out ) //if totaly equal
    {
      return it->Index();
    }

    //distance calculation
    tmp = out[0] - indexPoint[0]; dist  = tmp * tmp;
    tmp = out[1] - indexPoint[1]; dist += tmp * tmp;
    tmp = out[2] - indexPoint[2]; dist += tmp * tmp;

    if ( dist < bestDist )
    {
      bestIndex = it->Index();
      bestDist  = dist;
    }
  }
  return bestIndex;
}

mitk::PointSet::PointType
mitk::PointSet::GetPoint( int position, int t ) const
{
  PointType out;
  out.Fill(0);

  if ( (unsigned int) t >= m_PointSetSeries.size() )
  {
    return out;
  }

  if ( m_PointSetSeries[t]->GetPoints()->IndexExists(position) )
  {
    m_PointSetSeries[t]->GetPoint( position, &out );

    this->GetGeometry(t)->IndexToWorld( out, out );

    return out;
  }
  else
  {
    return out;
  }
}

bool
mitk::PointSet
::GetPointIfExists( PointIdentifier id, PointType* point, int t )
{
  if ( (unsigned int) t >= m_PointSetSeries.size() )
  {
    return false;
  }

  if ( m_PointSetSeries[t]->GetPoints()->GetElementIfIndexExists(id, point) )
  {
    this->GetGeometry( t )->IndexToWorld( *point, *point );
    return true;
  }
  else
  {
    return false;
  }
}

void mitk::PointSet::SetPoint( PointIdentifier id, PointType point, int t )
{
  // Adapt the size of the data vector if necessary
  this->Resize( t+1 );

  mitk::Point3D indexPoint;
  this->GetGeometry( t )->WorldToIndex( point, indexPoint );
  m_PointSetSeries[t]->SetPoint( id, indexPoint );

  //boundingbox has to be computed anyway
  m_CalculateBoundingBox = true;
  this->Modified();
}

void mitk::PointSet::InsertPoint( PointIdentifier id, PointType point, int t )
{
  if ( (unsigned int) t < m_PointSetSeries.size() )
  {
    mitk::Point3D indexPoint;
    this->GetGeometry( t )->WorldToIndex( point, indexPoint );
    m_PointSetSeries[t]->GetPoints()->InsertElement( id, indexPoint );

    //boundingbox has to be computed anyway
    m_CalculateBoundingBox = true;
  }
}

bool mitk::PointSet::IndexExists( int position, int t )
{
  if ( (unsigned int) t < m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t]->GetPoints()->IndexExists( position );
  }
  else
  {
    return false;
  }
}

bool mitk::PointSet::GetSelectInfo( int position, int t )
{
  if ( this->IndexExists( position, t ) )
  {
    PointDataType pointData = { 0, false, PTUNDEFINED };
    m_PointSetSeries[t]->GetPointData( position, &pointData );
    return pointData.selected;
  }
  else
  {
    return false;
  }
}

const int mitk::PointSet::GetNumberOfSelected( int t )
{
  if ( (unsigned int) t >= m_PointSetSeries.size() )
  {
    return 0;
  }

  int numberOfSelected = 0;
  PointDataIterator it;
  for ( it = m_PointSetSeries[t]->GetPointData()->Begin();
        it != m_PointSetSeries[t]->GetPointData()->End();
        it++ )
  {
    if (it->Value().selected == true)
    {
      ++numberOfSelected;
    }
  }

  return numberOfSelected;
}

int mitk::PointSet::SearchSelectedPoint( int t )
{
  if ( (unsigned int) t >= m_PointSetSeries.size() )
  {
    return -1;
  }

  PointDataIterator it;
  for ( it = m_PointSetSeries[t]->GetPointData()->Begin();
        it != m_PointSetSeries[t]->GetPointData()->End();
        it++ )
  {
    if ( it->Value().selected == true )
    {
      return it->Index();
    }
  }
  return -1;
}

void mitk::PointSet::ExecuteOperation( Operation* operation )
{
  int timeStep = -1;

  mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

  if ( pointOp )
  {
    timeStep = this->GetTimeSlicedGeometry()
      ->MSToTimeStep( pointOp->GetTimeInMS() );
  }

  if ( timeStep < 0 )
  {
    std::cerr << "Time step (" << timeStep << ") outside of PointSet time bounds" << std::endl;
    return;
  }

  switch (operation->GetOperationType())
  {
  case OpNOTHING:
    break;

  case OpINSERT://inserts the point at the given position and selects it.
    {
      int position = pointOp->GetIndex();

      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      //transfer from world to index coordinates
      mitk::Geometry3D* geometry = this->GetGeometry( timeStep );
      if (geometry == NULL)
      {
        std::cout<<"mitkPointSet.cpp::L362: GetGeometry returned NULL!\n";
        return;
      }
      geometry->WorldToIndex(pt, pt);

      m_PointSetSeries[timeStep]->GetPoints()->InsertElement(position, pt);

      PointDataType pointData =
      {
        pointOp->GetIndex(),
        pointOp->GetSelected(),
        pointOp->GetPointType()
      };

      m_PointSetSeries[timeStep]->GetPointData()
        ->InsertElement(position, pointData);

      this->Modified();

      //boundingbox has to be computed
      m_CalculateBoundingBox = true;

      this->InvokeEvent( PointSetAddEvent() );
      this->OnPointSetChange();
    }
    break;

  case OpMOVE://moves the point given by index
    {
      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      //transfer from world to index coordinates
      this->GetGeometry( timeStep )->WorldToIndex(pt, pt);

      m_PointSetSeries[timeStep]->SetPoint(pointOp->GetIndex(), pt);

      this->OnPointSetChange();

      this->Modified();

      //boundingbox has to be computed anyway
      m_CalculateBoundingBox = true;

      this->InvokeEvent( PointSetMoveEvent() );
    }
    break;

  case OpREMOVE://removes the point at given by position
    {
      m_PointSetSeries[timeStep]->GetPoints()
        ->DeleteIndex((unsigned)pointOp->GetIndex());
      m_PointSetSeries[timeStep]->GetPointData()
        ->DeleteIndex((unsigned)pointOp->GetIndex());

      this->OnPointSetChange();

      this->Modified();
      //boundingbox has to be computed anyway
      m_CalculateBoundingBox = true;

      this->InvokeEvent( PointSetRemoveEvent() );
    }
    break;

  case OpSELECTPOINT://select the given point
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = true;
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  case OpDESELECTPOINT://unselect the given point
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = false;
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  case OpSETPOINTTYPE:
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.pointSpec = pointOp->GetPointType();
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  default:
    itkWarningMacro("mitkPointSet could not understrand the operation. Please check!");
    break;
  }

  //to tell the mappers, that the data is modifierd and has to be updated
  //only call modified if anything is done, so call in cases
  //this->Modified();

  mitk::OperationEndEvent endevent(operation);
  ((const itk::Object*)this)->InvokeEvent(endevent);

  //*todo has to be done here, cause of update-pipeline not working yet
  // As discussed lately, don't mess with the rendering from inside data structures
  //mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}

void mitk::PointSet::UpdateOutputInformation()
{
  if ( this->GetSource( ) )
  {
      this->GetSource( )->UpdateOutputInformation( );
  }

  //
  // first make sure, that the associated time sliced geometry has
  // the same number of geometry 3d's as PointSets are present
  //
  mitk::TimeSlicedGeometry* timeGeometry = GetTimeSlicedGeometry();
  if ( timeGeometry->GetTimeSteps() != m_PointSetSeries.size() )
  {
    itkExceptionMacro(<<"timeGeometry->GetTimeSteps() != m_PointSetSeries.size() -- use Initialize(timeSteps) with correct number of timeSteps!");
  }

  //
  // Iterate over the PointSets and update the Geometry
  // information of each of the items.
  //
  if (m_CalculateBoundingBox)
  {
    for ( unsigned int i = 0 ; i < m_PointSetSeries.size() ; ++i )
    {
      const DataType::BoundingBoxType *bb = m_PointSetSeries[i]->GetBoundingBox();
      BoundingBox::BoundsArrayType itkBounds = bb->GetBounds();
      this->GetGeometry(i)->SetBounds(itkBounds);
    }
    m_CalculateBoundingBox = false;
  }
  this->GetTimeSlicedGeometry()->UpdateInformation();
}

void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion()
{
}

bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}

bool mitk::PointSet::VerifyRequestedRegion()
{
    return true;
}

void mitk::PointSet::SetRequestedRegion( itk::DataObject * )
{
}

bool mitk::PointSet::WriteXMLData( XMLWriter& xmlWriter )
{
  BaseData::WriteXMLData( xmlWriter );
  std::string fileName = xmlWriter.GetRelativePath();
  if(!xmlWriter.IsFileExtension(".mps", fileName))
    fileName += ".mps";

  if(xmlWriter.SaveSourceFiles()){
    PointSetWriter::Pointer writer = PointSetWriter::New();
    fileName = xmlWriter.GetAbsolutePath();
    if(!xmlWriter.IsFileExtension(".mps", fileName))
      fileName += ".mps";
    writer->SetFileName( fileName.c_str() );
    writer->SetInput( this );
    writer->Update();
  }
  xmlWriter.WriteProperty( XMLReader::FILENAME, fileName.c_str() );
  return true;
}

bool mitk::PointSet::ReadXMLData( XMLReader& xmlReader )
{
  BaseData::ReadXMLData( xmlReader );

  std::string fileName;
  xmlReader.GetAttribute( XMLReader::FILENAME, fileName );

  if ( fileName.empty() )
    return false;

  PointSetReader::Pointer reader = PointSetReader::New();
  reader->SetFileName( fileName.c_str() );
  reader->Update();
  mitk::PointSet::Pointer psp =
    dynamic_cast<mitk::PointSet*>( reader->GetOutput() );
  if (psp.IsNotNull())
  {
    m_PointSetSeries[0] = psp->GetPointSet();
  }

  if ( m_PointSetSeries[0].IsNull() )
  {
    return false;
  }

  return true;
}
<commit_msg>BUG: Issue PointSetTimeStepsChangeEvent() in ::Resize() only when the PointSet has more time steps than before (bug #956)<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

=========================================================================*/

#include "mitkPointSet.h"
#include "mitkOperation.h"
#include "mitkOperationActor.h"
#include "mitkPointOperation.h"
#include "mitkInteractionConst.h"
#include "mitkXMLWriter.h"
#include "mitkXMLReader.h"
#include "mitkPointSetWriter.h"
#include "mitkPointSetReader.h"
#include "mitkRenderingManager.h"

#include <itkSmartPointerForwardReference.txx>

mitk::PointSet::PointSet()
{
  m_Initialized = false;
  m_PointSetSeries.resize( 1 );

  m_PointSetSeries[0] = DataType::New();
  PointDataContainer::Pointer pointData = PointDataContainer::New();
  m_PointSetSeries[0]->SetPointData( pointData );
  m_CalculateBoundingBox = false;

  Superclass::InitializeTimeSlicedGeometry(1);
}

mitk::PointSet::~PointSet()
{
}

bool mitk::PointSet::IsEmpty(int t) const
{
  return IsInitialized() && (GetSize(t) <= 0);
}

void mitk::PointSet::Resize( unsigned int timeSteps )
{
  // Check if the vector is long enough to contain the new element
  // at the given position. If not, expand it with sufficient pre-initialized
  // elements.
  //
  // NOTE: This method will never REDUCE the vector size; it should only
  // be used to make sure that the vector has enough elements to include the
  // specified time step.

  unsigned int oldSize = m_PointSetSeries.size();

  if ( timeSteps > oldSize )
  {
    Superclass::Resize( timeSteps );

    m_PointSetSeries.resize( timeSteps );
    for ( unsigned int i = oldSize; i < timeSteps; ++i )
    {
      m_PointSetSeries[i] = DataType::New();
      PointDataContainer::Pointer pointData = PointDataContainer::New();
      m_PointSetSeries[i]->SetPointData( pointData );
    }

    //if the size changes, then compute the boundingbox
    m_CalculateBoundingBox = true;

    this->InvokeEvent( PointSetTimeStepsChangeEvent() );
  }
}

unsigned int mitk::PointSet::GetPointSetSeriesSize() const
{
  return m_PointSetSeries.size();
}

int mitk::PointSet::GetSize( int t ) const
{
  if ( t < (int)m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t]->GetNumberOfPoints();
  }
  else
  {
    return 0;
  }
}

mitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet( int t ) const
{
  if ( t < (int)m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t];
  }
  else
  {
    return NULL;
  }
}

int mitk::PointSet::SearchPoint( Point3D point, float distance, int t  )
{
  if ( t >= (int)m_PointSetSeries.size() )
  {
    return -1;
  }

  // Out is the point which is checked to be the searched point
  PointType out;
  out.Fill( 0 );
  PointType indexPoint;

  this->GetGeometry( t )->WorldToIndex(point, indexPoint);

  // Searching the first point in the Set, that is +- distance far away fro
  // the given point
  unsigned int i;
  PointsContainer::Iterator it, end;
  end = m_PointSetSeries[t]->GetPoints()->End();
  int bestIndex = -1;
  distance = distance * distance;

  // To correct errors from converting index to world and world to index
  if (distance == 0.0)
  {
    distance = 0.000001;
  }

  ScalarType bestDist = distance;
  ScalarType dist, tmp;

  for ( it = m_PointSetSeries[t]->GetPoints()->Begin(), i = 0;
        it != end;
        ++it, ++i )
  {
    bool ok = m_PointSetSeries[t]->GetPoints()
      ->GetElementIfIndexExists( it->Index(), &out );

    if ( !ok )
    {
      return -1;
    }
    else if ( indexPoint == out ) //if totaly equal
    {
      return it->Index();
    }

    //distance calculation
    tmp = out[0] - indexPoint[0]; dist  = tmp * tmp;
    tmp = out[1] - indexPoint[1]; dist += tmp * tmp;
    tmp = out[2] - indexPoint[2]; dist += tmp * tmp;

    if ( dist < bestDist )
    {
      bestIndex = it->Index();
      bestDist  = dist;
    }
  }
  return bestIndex;
}

mitk::PointSet::PointType
mitk::PointSet::GetPoint( int position, int t ) const
{
  PointType out;
  out.Fill(0);

  if ( (unsigned int) t >= m_PointSetSeries.size() )
  {
    return out;
  }

  if ( m_PointSetSeries[t]->GetPoints()->IndexExists(position) )
  {
    m_PointSetSeries[t]->GetPoint( position, &out );

    this->GetGeometry(t)->IndexToWorld( out, out );

    return out;
  }
  else
  {
    return out;
  }
}

bool
mitk::PointSet
::GetPointIfExists( PointIdentifier id, PointType* point, int t )
{
  if ( (unsigned int) t >= m_PointSetSeries.size() )
  {
    return false;
  }

  if ( m_PointSetSeries[t]->GetPoints()->GetElementIfIndexExists(id, point) )
  {
    this->GetGeometry( t )->IndexToWorld( *point, *point );
    return true;
  }
  else
  {
    return false;
  }
}

void mitk::PointSet::SetPoint( PointIdentifier id, PointType point, int t )
{
  // Adapt the size of the data vector if necessary
  this->Resize( t+1 );

  mitk::Point3D indexPoint;
  this->GetGeometry( t )->WorldToIndex( point, indexPoint );
  m_PointSetSeries[t]->SetPoint( id, indexPoint );

  //boundingbox has to be computed anyway
  m_CalculateBoundingBox = true;
  this->Modified();
}

void mitk::PointSet::InsertPoint( PointIdentifier id, PointType point, int t )
{
  if ( (unsigned int) t < m_PointSetSeries.size() )
  {
    mitk::Point3D indexPoint;
    this->GetGeometry( t )->WorldToIndex( point, indexPoint );
    m_PointSetSeries[t]->GetPoints()->InsertElement( id, indexPoint );

    //boundingbox has to be computed anyway
    m_CalculateBoundingBox = true;
  }
}

bool mitk::PointSet::IndexExists( int position, int t )
{
  if ( (unsigned int) t < m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t]->GetPoints()->IndexExists( position );
  }
  else
  {
    return false;
  }
}

bool mitk::PointSet::GetSelectInfo( int position, int t )
{
  if ( this->IndexExists( position, t ) )
  {
    PointDataType pointData = { 0, false, PTUNDEFINED };
    m_PointSetSeries[t]->GetPointData( position, &pointData );
    return pointData.selected;
  }
  else
  {
    return false;
  }
}

const int mitk::PointSet::GetNumberOfSelected( int t )
{
  if ( (unsigned int) t >= m_PointSetSeries.size() )
  {
    return 0;
  }

  int numberOfSelected = 0;
  PointDataIterator it;
  for ( it = m_PointSetSeries[t]->GetPointData()->Begin();
        it != m_PointSetSeries[t]->GetPointData()->End();
        it++ )
  {
    if (it->Value().selected == true)
    {
      ++numberOfSelected;
    }
  }

  return numberOfSelected;
}

int mitk::PointSet::SearchSelectedPoint( int t )
{
  if ( (unsigned int) t >= m_PointSetSeries.size() )
  {
    return -1;
  }

  PointDataIterator it;
  for ( it = m_PointSetSeries[t]->GetPointData()->Begin();
        it != m_PointSetSeries[t]->GetPointData()->End();
        it++ )
  {
    if ( it->Value().selected == true )
    {
      return it->Index();
    }
  }
  return -1;
}

void mitk::PointSet::ExecuteOperation( Operation* operation )
{
  int timeStep = -1;

  mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

  if ( pointOp )
  {
    timeStep = this->GetTimeSlicedGeometry()
      ->MSToTimeStep( pointOp->GetTimeInMS() );
  }

  if ( timeStep < 0 )
  {
    std::cerr << "Time step (" << timeStep << ") outside of PointSet time bounds" << std::endl;
    return;
  }

  switch (operation->GetOperationType())
  {
  case OpNOTHING:
    break;

  case OpINSERT://inserts the point at the given position and selects it.
    {
      int position = pointOp->GetIndex();

      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      //transfer from world to index coordinates
      mitk::Geometry3D* geometry = this->GetGeometry( timeStep );
      if (geometry == NULL)
      {
        std::cout<<"mitkPointSet.cpp::L362: GetGeometry returned NULL!\n";
        return;
      }
      geometry->WorldToIndex(pt, pt);

      m_PointSetSeries[timeStep]->GetPoints()->InsertElement(position, pt);

      PointDataType pointData =
      {
        pointOp->GetIndex(),
        pointOp->GetSelected(),
        pointOp->GetPointType()
      };

      m_PointSetSeries[timeStep]->GetPointData()
        ->InsertElement(position, pointData);

      this->Modified();

      //boundingbox has to be computed
      m_CalculateBoundingBox = true;

      this->InvokeEvent( PointSetAddEvent() );
      this->OnPointSetChange();
    }
    break;

  case OpMOVE://moves the point given by index
    {
      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      //transfer from world to index coordinates
      this->GetGeometry( timeStep )->WorldToIndex(pt, pt);

      m_PointSetSeries[timeStep]->SetPoint(pointOp->GetIndex(), pt);

      this->OnPointSetChange();

      this->Modified();

      //boundingbox has to be computed anyway
      m_CalculateBoundingBox = true;

      this->InvokeEvent( PointSetMoveEvent() );
    }
    break;

  case OpREMOVE://removes the point at given by position
    {
      m_PointSetSeries[timeStep]->GetPoints()
        ->DeleteIndex((unsigned)pointOp->GetIndex());
      m_PointSetSeries[timeStep]->GetPointData()
        ->DeleteIndex((unsigned)pointOp->GetIndex());

      this->OnPointSetChange();

      this->Modified();
      //boundingbox has to be computed anyway
      m_CalculateBoundingBox = true;

      this->InvokeEvent( PointSetRemoveEvent() );
    }
    break;

  case OpSELECTPOINT://select the given point
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = true;
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  case OpDESELECTPOINT://unselect the given point
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = false;
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  case OpSETPOINTTYPE:
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.pointSpec = pointOp->GetPointType();
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  default:
    itkWarningMacro("mitkPointSet could not understrand the operation. Please check!");
    break;
  }

  //to tell the mappers, that the data is modifierd and has to be updated
  //only call modified if anything is done, so call in cases
  //this->Modified();

  mitk::OperationEndEvent endevent(operation);
  ((const itk::Object*)this)->InvokeEvent(endevent);

  //*todo has to be done here, cause of update-pipeline not working yet
  // As discussed lately, don't mess with the rendering from inside data structures
  //mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}

void mitk::PointSet::UpdateOutputInformation()
{
  if ( this->GetSource( ) )
  {
      this->GetSource( )->UpdateOutputInformation( );
  }

  //
  // first make sure, that the associated time sliced geometry has
  // the same number of geometry 3d's as PointSets are present
  //
  mitk::TimeSlicedGeometry* timeGeometry = GetTimeSlicedGeometry();
  if ( timeGeometry->GetTimeSteps() != m_PointSetSeries.size() )
  {
    itkExceptionMacro(<<"timeGeometry->GetTimeSteps() != m_PointSetSeries.size() -- use Initialize(timeSteps) with correct number of timeSteps!");
  }

  //
  // Iterate over the PointSets and update the Geometry
  // information of each of the items.
  //
  if (m_CalculateBoundingBox)
  {
    for ( unsigned int i = 0 ; i < m_PointSetSeries.size() ; ++i )
    {
      const DataType::BoundingBoxType *bb = m_PointSetSeries[i]->GetBoundingBox();
      BoundingBox::BoundsArrayType itkBounds = bb->GetBounds();
      this->GetGeometry(i)->SetBounds(itkBounds);
    }
    m_CalculateBoundingBox = false;
  }
  this->GetTimeSlicedGeometry()->UpdateInformation();
}

void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion()
{
}

bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}

bool mitk::PointSet::VerifyRequestedRegion()
{
    return true;
}

void mitk::PointSet::SetRequestedRegion( itk::DataObject * )
{
}

bool mitk::PointSet::WriteXMLData( XMLWriter& xmlWriter )
{
  BaseData::WriteXMLData( xmlWriter );
  std::string fileName = xmlWriter.GetRelativePath();
  if(!xmlWriter.IsFileExtension(".mps", fileName))
    fileName += ".mps";

  if(xmlWriter.SaveSourceFiles()){
    PointSetWriter::Pointer writer = PointSetWriter::New();
    fileName = xmlWriter.GetAbsolutePath();
    if(!xmlWriter.IsFileExtension(".mps", fileName))
      fileName += ".mps";
    writer->SetFileName( fileName.c_str() );
    writer->SetInput( this );
    writer->Update();
  }
  xmlWriter.WriteProperty( XMLReader::FILENAME, fileName.c_str() );
  return true;
}

bool mitk::PointSet::ReadXMLData( XMLReader& xmlReader )
{
  BaseData::ReadXMLData( xmlReader );

  std::string fileName;
  xmlReader.GetAttribute( XMLReader::FILENAME, fileName );

  if ( fileName.empty() )
    return false;

  PointSetReader::Pointer reader = PointSetReader::New();
  reader->SetFileName( fileName.c_str() );
  reader->Update();
  mitk::PointSet::Pointer psp =
    dynamic_cast<mitk::PointSet*>( reader->GetOutput() );
  if (psp.IsNotNull())
  {
    m_PointSetSeries[0] = psp->GetPointSet();
  }

  if ( m_PointSetSeries[0].IsNull() )
  {
    return false;
  }

  return true;
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <functional>
#include <string>
#include <tuple>
#include <vector>

#include <Common.hpp>
#include <Engine.hpp>

namespace K3
{
  using namespace std;

  template<typename T>
  string toString(const T& not_string)
  {
    ostringstream strm;
    strm << not_string;
    return strm.str();
  }

  template<>
  string toString(const Address& not_string);

  template<typename T>
  T fromString(string str)
  {
    istringstream strm(str);
    T not_string;
    strm >> not_string;
    return not_string;
  }

  string generateCollectionFilename(Engine * engine);
  string openCollectionFile(Engine * engine, const Identifier& name, IOMode mode);
  Identifier openCollectionFile(Engine * engine, const Identifier& name, IOMode mode);
  Identifier emptyFile(Engine * engine);

  template<typename AccumT>
  AccumT foldOpenFile(Engine * engine, std::function<AccumT(AccumT, Value)> accumulation, AccumT initial_accumulator, const Identifier& file_id)
  {
    while (engine->hasRead(file_id))
    {
      shared_ptr<Value> cur_val = engine->doReadExternal(file_id);
      if (cur_val)
        initial_accumulator = accumulation(initial_accumulator, *cur_val);
      else
        return initial_accumulator;
    }
    return initial_accumulator;
  }

  template<typename AccumT>
  AccumT foldFile(Engine * engine, std::function<AccumT(AccumT, Value)> accumulation, AccumT initial_accumulator, const Identifier& file_id)
  {
    openCollectionFile(engine, file_id, IOMode::Read);
    AccumT result = foldOpenFile<AccumT>(engine, accumulation, initial_accumulator, file_id);
    engine->close(file_id);
    return result;
  }

  string copyFile(Engine * engine, const string& old_id);

  template<typename Iterator>
  Identifier initialFile(Engine* engine, Iterator start, Iterator finish)
  {
    Identifier new_id = generateCollectionFilename(engine);
    openCollectionFile(engine, new_id, IOMode::Write);
    for (Iterator iter = start; iter != finish; ++iter )
    {
        engine->doWriteExternal(new_id, *iter);
    }
    engine->close(new_id);
    return new_id;
  }

  shared_ptr<Value> peekFile(Engine * engine, const Identifier& file_id);

  Identifier mapFile(Engine * engine, std::function<Value(Value)> function, const Identifier& file_ds);
  void mapFile_(Engine * engine, std::function<void(Value)> function, const Identifier& file_id);

  Identifier filterFile(Engine * engine, std::function<bool(Value)> predicate, const Identifier& old_id);

  Identifier insertFile(Engine * engine, const Identifier& old_id, const Value& v);

  Identifier deleteFile(Engine * engine, const Identifier& old_id, const Value& v);

  Identifier updateFile(Engine * engine, const Value& old_val, const Value& new_val, const Identifier& file_id);

  Identifier combineFile(Engine * engine, const Identifier& self, const Identifier& values);

  tuple<Identifier, Identifier> splitFile(Engine * engine, const Identifier& file_id);

  typedef Value E;

  class FileDS
  {
    protected:
      Engine * engine;
      Identifier file_id;

      public:
      FileDS(Engine * eng)
          : engine(eng), file_id(generateCollectionFilename(eng))
      {
        emptyFile(eng);
      }

      template<typename Iterator>
      FileDS(Engine * eng, Iterator start, Iterator finish)
          : engine(eng), file_id(initialFile(eng, start, finish))
      { }

      FileDS(const FileDS& other)
          : engine(other.engine), file_id(copyFile(other.engine, other.file_id))
      { }

    private:
      FileDS(Engine * eng, Identifier f)
          : engine(eng), file_id(f)
      { }

    public:
      shared_ptr<E> peek() const
      {
        return peekFile(engine, file_id);
      }

      void insert_basic(const E& v)
      {
        file_id = insertFile(engine, file_id, v);
      }
      void delete_first(const E& v)
      {
        file_id = deleteFile(engine, file_id, v);
      }
      void update_first(const E& v, const E& v2)
      {
        file_id = updateFile(engine, v, v2, file_id);
      }

      template<typename Z>
      Z fold(std::function<Z(Z, E)> accum, Z initial_accumulator)
      {
        return foldFile<Z>(engine, accum, initial_accumulator, file_id);
      }

      //template<typename T>
      typedef Value T;
      FileDS map(std::function<T(E)> func)
      {
        return FileDS(engine,
                mapFile(engine, func, file_id)
                );
      }

      void iterate(std::function<void(E)> func)
      {
        mapFile_(engine, func, file_id);
      }

      FileDS filter(std::function<bool(E)> predicate)
      {
        return FileDS(engine,
                filterFile(engine, predicate, file_id)
                );
      }

      tuple< FileDS, FileDS > split()
      {
        tuple<Identifier, Identifier> halves = splitFile(engine, file_id);
        return make_tuple(
                FileDS(engine, get<0>(halves)),
                FileDS(engine, get<1>(halves))
                );
      }
      FileDS combine(FileDS other)
      {
        return FileDS(engine,
                combineFile(engine, file_id, other.file_id)
                );
      }
  };
};<commit_msg>FileDS constructor uses the name of the new file<commit_after>#include <algorithm>
#include <functional>
#include <string>
#include <tuple>
#include <vector>

#include <Common.hpp>
#include <Engine.hpp>

namespace K3
{
  using namespace std;

  template<typename T>
  string toString(const T& not_string)
  {
    ostringstream strm;
    strm << not_string;
    return strm.str();
  }

  template<>
  string toString(const Address& not_string);

  template<typename T>
  T fromString(string str)
  {
    istringstream strm(str);
    T not_string;
    strm >> not_string;
    return not_string;
  }

  string generateCollectionFilename(Engine * engine);
  string openCollectionFile(Engine * engine, const Identifier& name, IOMode mode);
  Identifier openCollectionFile(Engine * engine, const Identifier& name, IOMode mode);
  Identifier emptyFile(Engine * engine);

  template<typename AccumT>
  AccumT foldOpenFile(Engine * engine, std::function<AccumT(AccumT, Value)> accumulation, AccumT initial_accumulator, const Identifier& file_id)
  {
    while (engine->hasRead(file_id))
    {
      shared_ptr<Value> cur_val = engine->doReadExternal(file_id);
      if (cur_val)
        initial_accumulator = accumulation(initial_accumulator, *cur_val);
      else
        return initial_accumulator;
    }
    return initial_accumulator;
  }

  template<typename AccumT>
  AccumT foldFile(Engine * engine, std::function<AccumT(AccumT, Value)> accumulation, AccumT initial_accumulator, const Identifier& file_id)
  {
    openCollectionFile(engine, file_id, IOMode::Read);
    AccumT result = foldOpenFile<AccumT>(engine, accumulation, initial_accumulator, file_id);
    engine->close(file_id);
    return result;
  }

  string copyFile(Engine * engine, const string& old_id);

  template<typename Iterator>
  Identifier initialFile(Engine* engine, Iterator start, Iterator finish)
  {
    Identifier new_id = generateCollectionFilename(engine);
    openCollectionFile(engine, new_id, IOMode::Write);
    for (Iterator iter = start; iter != finish; ++iter )
    {
        engine->doWriteExternal(new_id, *iter);
    }
    engine->close(new_id);
    return new_id;
  }

  shared_ptr<Value> peekFile(Engine * engine, const Identifier& file_id);

  Identifier mapFile(Engine * engine, std::function<Value(Value)> function, const Identifier& file_ds);
  void mapFile_(Engine * engine, std::function<void(Value)> function, const Identifier& file_id);

  Identifier filterFile(Engine * engine, std::function<bool(Value)> predicate, const Identifier& old_id);

  Identifier insertFile(Engine * engine, const Identifier& old_id, const Value& v);

  Identifier deleteFile(Engine * engine, const Identifier& old_id, const Value& v);

  Identifier updateFile(Engine * engine, const Value& old_val, const Value& new_val, const Identifier& file_id);

  Identifier combineFile(Engine * engine, const Identifier& self, const Identifier& values);

  tuple<Identifier, Identifier> splitFile(Engine * engine, const Identifier& file_id);

  typedef Value E;

  class FileDS
  {
    protected:
      Engine * engine;
      Identifier file_id;

      public:
      FileDS(Engine * eng)
          : engine(eng), file_id(emptyFile(eng))
      { }

      template<typename Iterator>
      FileDS(Engine * eng, Iterator start, Iterator finish)
          : engine(eng), file_id(initialFile(eng, start, finish))
      { }

      FileDS(const FileDS& other)
          : engine(other.engine), file_id(copyFile(other.engine, other.file_id))
      { }

    private:
      FileDS(Engine * eng, Identifier f)
          : engine(eng), file_id(f)
      { }

    public:
      shared_ptr<E> peek() const
      {
        return peekFile(engine, file_id);
      }

      void insert_basic(const E& v)
      {
        file_id = insertFile(engine, file_id, v);
      }
      void delete_first(const E& v)
      {
        file_id = deleteFile(engine, file_id, v);
      }
      void update_first(const E& v, const E& v2)
      {
        file_id = updateFile(engine, v, v2, file_id);
      }

      template<typename Z>
      Z fold(std::function<Z(Z, E)> accum, Z initial_accumulator)
      {
        return foldFile<Z>(engine, accum, initial_accumulator, file_id);
      }

      //template<typename T>
      typedef Value T;
      FileDS map(std::function<T(E)> func)
      {
        return FileDS(engine,
                mapFile(engine, func, file_id)
                );
      }

      void iterate(std::function<void(E)> func)
      {
        mapFile_(engine, func, file_id);
      }

      FileDS filter(std::function<bool(E)> predicate)
      {
        return FileDS(engine,
                filterFile(engine, predicate, file_id)
                );
      }

      tuple< FileDS, FileDS > split()
      {
        tuple<Identifier, Identifier> halves = splitFile(engine, file_id);
        return make_tuple(
                FileDS(engine, get<0>(halves)),
                FileDS(engine, get<1>(halves))
                );
      }
      FileDS combine(FileDS other)
      {
        return FileDS(engine,
                combineFile(engine, file_id, other.file_id)
                );
      }
  };
};
<|endoftext|>


<commit_before>#include <bits/stdc++.h>
using namespace std;
struct node{
    int value;
    node* next;
};
void solve(int level)
{
    node* pascal=new node[level+1];
//    memset(pascal, 0, sizeof(pascal));
    printf("1\n1 1\n");
    node* inib=new node;
    node* terminate=new node;
    inib->value=1;
    inib->next=terminate;
//    cout<<pascal<<" "<<pascal->next<<"\n";
    (pascal+1)->next=inib;
//    cout<<"p\n";
    (pascal+1)->value=1;
    if(level==1)
        return;
    for(int x=2; x<=level; x++)
    {
//        cout<<x<<"x\n";
        (pascal+x)->value=1;
        node* visit=&pascal[x-1];
        node* construct=&pascal[x];
        printf("%d ", construct->value);
        while(visit->next!=terminate)
        {
            node* temp=new node;
            temp->value=visit->value+visit->next->value;
//            cout<<temp->value<<"t ";
            construct->next=temp;
            visit=visit->next;
            construct=construct->next;
            printf("%d ", construct->value);
        }
        construct->next=inib;
        printf("%d\n", inib->value);
    }
}
int main()
{
    int level;
    scanf("%d", &level);
    solve(level);
    return 0;
}
<commit_msg>Add existing file<commit_after>#include <bits/stdc++.h>
using namespace std;
struct node{
    int value;
    node* next;
};
void solve(int level)
{
    node* pascal=new node[level+1];//levels of the triangle
//    memset(pascal, 0, sizeof(pascal));
    printf("1\n1 1\n");
    node* inib=new node;
    node* terminate=new node;//the back end for all linked list
    inib->value=1;
    inib->next=terminate;
//    cout<<pascal<<" "<<pascal->next<<"\n";
    (pascal+1)->next=inib;
//    cout<<"p\n";
    (pascal+1)->value=1;
    if(level==1)
        return;
    for(int x=2; x<=level; x++)
    {
//        cout<<x<<"x\n";
        (pascal+x)->value=1;//the first number of every level is 1
        node* visit=&pascal[x-1];//the pointer that visits the previous level
        node* construct=&pascal[x];
        printf("%d ", construct->value);
        while(visit->next!=terminate)//Reference to line 13
        {//construction process
            node* temp=new node;
            temp->value=visit->value+visit->next->value;
//            cout<<temp->value<<"t ";
            construct->next=temp;
            visit=visit->next;
            construct=construct->next;
            printf("%d ", construct->value);
        }
        construct->next=inib;
        printf("%d\n", inib->value);
    }
}
int main()
{
    int level;
    scanf("%d", &level);
    solve(level);
    return 0;
}
<|endoftext|>


<commit_before>#include <cstdio>

#include <pqxx/pqxx> /* libpqxx is used to instantiate C++ client */

int main(int argc, char **argv) {

  try {
    pqxx::connection C(
        "host=127.0.0.1 port=5431 user=postgres sslmode=disable"
    );
    printf("Connected to %s\n", C.dbname());
    pqxx::work txn1(C);

    txn1.exec("DROP TABLE IF EXISTS employee;");
    txn1.exec("CREATE TABLE employee(id INT, name VARCHAR(100));");
    txn1.commit();

    pqxx::work txn2(C);
    txn2.exec("INSERT INTO employee VALUES (1, 'a');");
    txn2.exec("INSERT INTO employee VALUES (2, 'b');");
    txn2.exec("INSERT INTO employee VALUES (3, 'c');");

    pqxx::result R = txn2.exec("SELECT name FROM employee where id=1;");
    txn2.commit();

    printf("txn2 result set size = %lu\n", R.size());

  } catch (const std::exception &e) {
    printf("Exception occurred: %s\n", e.what());
    exit(-1);
  }

  return 0;
}
<commit_msg>refactor code<commit_after>#include <cstdio>
#include <cassert>

#include <pqxx/pqxx> /* libpqxx is used to instantiate C++ client */

void Populate(pqxx::work &txn_handle, const size_t table_size) {
  for (size_t i = 0; i < table_size; ++i) {
    txn_handle.exec("INSERT INTO employee VALUES (" + std::to_string(i) + ", 'a');");
  }
}

void Select(pqxx::work &txn_handle, const size_t num_tuple) {
  for (size_t i = 0; i < num_tuple; ++i) {
    pqxx::result R = txn_handle.exec("SELECT name FROM employee WHERE id=" + std::to_string(i) + ";");
    printf("txn result set size = %lu\n", R.size());
  }
}

int main(int argc, char **argv) {

  if (argc != 2 && argc != 3) {
    printf("please input arguments\n");
    return -1;
  }

  try {
    pqxx::connection C(
      "host=172.19.146.5 port=5432 user=postgres sslmode=disable"
    );
    printf("Connected to %s\n", C.dbname());

    if (std::string(argv[1]) == "populate") {

      size_t table_size = 100;

      if (argc != 2) {
        assert(argc == 3);
        table_size = atoi(argv[2]);
      }

      printf("populate table!\n");
      pqxx::work txn(C);
      txn.exec("DROP TABLE IF EXISTS employee;");
      txn.exec("CREATE TABLE employee(id INT, name VARCHAR(100));");
      Populate(txn, table_size);
      txn.commit();

    } else if (std::string(argv[1]) == "select") {

      size_t num_tuple = 1;

      if (argc != 2) {
        assert(argc == 3);
        num_tuple = atoi(argv[2]);
      }

      printf("select from table!\n");
      pqxx::work txn(C);
      Select(txn, num_tuple);
      txn.commit();
    } else {
      printf("please input correct arguments \n");
      return -1;
    }

  } catch (const std::exception &e) {
    printf("Exception occurred: %s\n", e.what());
    exit(-1);
  }

  return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include <assert.h>

#ifndef _MANAGED
#include "glog/logging.h"
#endif
#include "quantities/elementary_functions.hpp"

namespace principia {
namespace geometry {

namespace {
__declspec(noreturn) void noreturn() {}
}  // namespace

// We want zero initialisation here, so the default constructor won't do.
template<typename Scalar>
inline R3Element<Scalar>::R3Element() : x(), y(), z() {}

template<typename Scalar>
inline R3Element<Scalar>::R3Element(Scalar const& x,
                                    Scalar const& y,
                                    Scalar const& z) : x(x), y(y), z(z) {}

template<typename Scalar>
inline Scalar& R3Element<Scalar>::operator[](int const index) {
  switch (index) {
    case 0:
      return x;
    case 1:
      return y;
    case 2:
      return z;
    default:
      LOG(FATAL) << "Index = " << index;
      noreturn();
  }
}

template<typename Scalar>
inline Scalar const& R3Element<Scalar>::operator[](int const index) const {
  switch (index) {
    case 0:
      return x;
    case 1:
      return y;
    case 2:
      return z;
    default:
#ifndef _MANAGED
      LOG(FATAL) << "Index = " << index;
#endif
      noreturn();
  }
}

template<typename Scalar>
inline R3Element<Scalar>& R3Element<Scalar>::operator+=(
    R3Element<Scalar> const& right){
  return *this = *this + right;
}

template<typename Scalar>
inline R3Element<Scalar>& R3Element<Scalar>::operator-=(
    R3Element<Scalar> const& right) {
  return *this = *this - right;
}

template<typename Scalar>
inline R3Element<Scalar>& R3Element<Scalar>::operator*=(double const right) {
  return *this = *this * right;
}

template<typename Scalar>
inline R3Element<Scalar>& R3Element<Scalar>::operator/=(double const right) {
  return *this = *this / right;
}

template<typename Scalar>
inline Scalar R3Element<Scalar>::Norm() const {
  return quantities::Sqrt(Dot(*this, *this));
}

template<typename Scalar>
inline R3Element<Scalar> operator+(R3Element<Scalar> const& right) {
  return R3Element<Scalar>(+right.x, +right.y, +right.z);
}

template<typename Scalar>
inline R3Element<Scalar> operator-(R3Element<Scalar> const& right) {
  return R3Element<Scalar>(-right.x, -right.y, -right.z);
}

template<typename Scalar>
inline R3Element<Scalar> operator+(
    R3Element<Scalar> const& left,
    R3Element<Scalar> const& right) {
  return R3Element<Scalar>(left.x + right.x,
                           left.y + right.y,
                           left.z + right.z);
}

template<typename Scalar>
inline R3Element<Scalar> operator-(
    R3Element<Scalar> const& left,
    R3Element<Scalar> const& right) {
  return R3Element<Scalar>(left.x - right.x,
                           left.y - right.y,
                           left.z - right.z);
}

template<typename Scalar>
inline R3Element<Scalar> operator*(double const left,
                                   R3Element<Scalar> const& right) {
  return R3Element<Scalar>(left * right.x,
                           left * right.y,
                           left * right.z);
}

template<typename Scalar>
inline R3Element<Scalar> operator*(R3Element<Scalar> const& left,
                                   double const right) {
  return R3Element<Scalar>(left.x * right,
                           left.y * right,
                           left.z * right);
}

template<typename Scalar>
inline R3Element<Scalar> operator/(R3Element<Scalar> const& left,
                                   double const right) {
  return R3Element<Scalar>(left.x / right,
                           left.y / right,
                           left.z / right);
}

template<typename LDimension, typename RScalar>
inline R3Element<quantities::Product<quantities::Quantity<LDimension>, RScalar>>
operator*(quantities::Quantity<LDimension> const& left,
          R3Element<RScalar> const& right) {
  return R3Element<quantities::Product<quantities::Quantity<LDimension>,
                                       RScalar>>(
      left * right.x,
      left * right.y,
      left * right.z);
}

template<typename LScalar, typename RDimension>
inline R3Element<quantities::Product<LScalar, quantities::Quantity<RDimension>>>
operator*(R3Element<LScalar> const& left,
          quantities::Quantity<RDimension> const& right) {
  return R3Element<quantities::Product<LScalar,
                                       quantities::Quantity<RDimension>>>(
      left.x * right,
      left.y * right,
      left.z * right);
}

template<typename LScalar, typename RDimension>
inline R3Element<quantities::Quotient<LScalar,
                                      quantities::Quantity<RDimension>>>
operator/(R3Element<LScalar> const& left,
          quantities::Quantity<RDimension> const& right) {
  return R3Element<quantities::Quotient<LScalar,
                                        quantities::Quantity<RDimension>>>(
      left.x / right,
      left.y / right,
      left.z / right);
}

template<typename Scalar>
bool operator==(R3Element<Scalar> const& left,
                R3Element<Scalar> const& right) {
  return left.x == right.x && left.y == right.y && left.z == right.z;
}

template<typename Scalar>
bool operator!=(R3Element<Scalar> const& left,
                R3Element<Scalar> const& right) {
  return left.x != right.x || left.y != right.y || left.z != right.z;
}

template<typename Scalar>
std::ostream& operator<<(std::ostream& out,
                         R3Element<Scalar> const& r3_element) {
  out << "{" << r3_element.x << ", "
             << r3_element.y << ", "
             << r3_element.z << "}";
  return out;
}

template<typename LScalar, typename RScalar>
inline R3Element<quantities::Product<LScalar, RScalar>> Cross(
    R3Element<LScalar> const& left,
    R3Element<RScalar> const& right) {
  return R3Element<quantities::Product<LScalar, RScalar>>(
      left.y * right.z - left.z * right.y,
      left.z * right.x - left.x * right.z,
      left.x * right.y - left.y * right.x);
}

template<typename LScalar, typename RScalar>
inline quantities::Product<LScalar, RScalar> Dot(
    R3Element<LScalar> const& left,
    R3Element<RScalar> const& right) {
  return left.x * right.x + left.y * right.y + left.z * right.z;
}

}  // namespace geometry
}  // namespace principia
<commit_msg>Fix lint.<commit_after>#pragma once

#include <assert.h>

#ifndef _MANAGED
#include "glog/logging.h"
#endif
#include "quantities/elementary_functions.hpp"

namespace principia {
namespace geometry {

namespace {
__declspec(noreturn) void noreturn() {}
}  // namespace

// We want zero initialisation here, so the default constructor won't do.
template<typename Scalar>
inline R3Element<Scalar>::R3Element() : x(), y(), z() {}

template<typename Scalar>
inline R3Element<Scalar>::R3Element(Scalar const& x,
                                    Scalar const& y,
                                    Scalar const& z) : x(x), y(y), z(z) {}

template<typename Scalar>
inline Scalar& R3Element<Scalar>::operator[](int const index) {
  switch (index) {
    case 0:
      return x;
    case 1:
      return y;
    case 2:
      return z;
    default:
      LOG(FATAL) << "Index = " << index;
      noreturn();
  }
}

template<typename Scalar>
inline Scalar const& R3Element<Scalar>::operator[](int const index) const {
  switch (index) {
    case 0:
      return x;
    case 1:
      return y;
    case 2:
      return z;
    default:
#ifndef _MANAGED
      LOG(FATAL) << "Index = " << index;
#endif
      noreturn();
  }
}

template<typename Scalar>
inline R3Element<Scalar>& R3Element<Scalar>::operator+=(
    R3Element<Scalar> const& right) {
  return *this = *this + right;
}

template<typename Scalar>
inline R3Element<Scalar>& R3Element<Scalar>::operator-=(
    R3Element<Scalar> const& right) {
  return *this = *this - right;
}

template<typename Scalar>
inline R3Element<Scalar>& R3Element<Scalar>::operator*=(double const right) {
  return *this = *this * right;
}

template<typename Scalar>
inline R3Element<Scalar>& R3Element<Scalar>::operator/=(double const right) {
  return *this = *this / right;
}

template<typename Scalar>
inline Scalar R3Element<Scalar>::Norm() const {
  return quantities::Sqrt(Dot(*this, *this));
}

template<typename Scalar>
inline R3Element<Scalar> operator+(R3Element<Scalar> const& right) {
  return R3Element<Scalar>(+right.x, +right.y, +right.z);
}

template<typename Scalar>
inline R3Element<Scalar> operator-(R3Element<Scalar> const& right) {
  return R3Element<Scalar>(-right.x, -right.y, -right.z);
}

template<typename Scalar>
inline R3Element<Scalar> operator+(
    R3Element<Scalar> const& left,
    R3Element<Scalar> const& right) {
  return R3Element<Scalar>(left.x + right.x,
                           left.y + right.y,
                           left.z + right.z);
}

template<typename Scalar>
inline R3Element<Scalar> operator-(
    R3Element<Scalar> const& left,
    R3Element<Scalar> const& right) {
  return R3Element<Scalar>(left.x - right.x,
                           left.y - right.y,
                           left.z - right.z);
}

template<typename Scalar>
inline R3Element<Scalar> operator*(double const left,
                                   R3Element<Scalar> const& right) {
  return R3Element<Scalar>(left * right.x,
                           left * right.y,
                           left * right.z);
}

template<typename Scalar>
inline R3Element<Scalar> operator*(R3Element<Scalar> const& left,
                                   double const right) {
  return R3Element<Scalar>(left.x * right,
                           left.y * right,
                           left.z * right);
}

template<typename Scalar>
inline R3Element<Scalar> operator/(R3Element<Scalar> const& left,
                                   double const right) {
  return R3Element<Scalar>(left.x / right,
                           left.y / right,
                           left.z / right);
}

template<typename LDimension, typename RScalar>
inline R3Element<quantities::Product<quantities::Quantity<LDimension>, RScalar>>
operator*(quantities::Quantity<LDimension> const& left,
          R3Element<RScalar> const& right) {
  return R3Element<quantities::Product<quantities::Quantity<LDimension>,
                                       RScalar>>(
      left * right.x,
      left * right.y,
      left * right.z);
}

template<typename LScalar, typename RDimension>
inline R3Element<quantities::Product<LScalar, quantities::Quantity<RDimension>>>
operator*(R3Element<LScalar> const& left,
          quantities::Quantity<RDimension> const& right) {
  return R3Element<quantities::Product<LScalar,
                                       quantities::Quantity<RDimension>>>(
      left.x * right,
      left.y * right,
      left.z * right);
}

template<typename LScalar, typename RDimension>
inline R3Element<quantities::Quotient<LScalar,
                                      quantities::Quantity<RDimension>>>
operator/(R3Element<LScalar> const& left,
          quantities::Quantity<RDimension> const& right) {
  return R3Element<quantities::Quotient<LScalar,
                                        quantities::Quantity<RDimension>>>(
      left.x / right,
      left.y / right,
      left.z / right);
}

template<typename Scalar>
bool operator==(R3Element<Scalar> const& left,
                R3Element<Scalar> const& right) {
  return left.x == right.x && left.y == right.y && left.z == right.z;
}

template<typename Scalar>
bool operator!=(R3Element<Scalar> const& left,
                R3Element<Scalar> const& right) {
  return left.x != right.x || left.y != right.y || left.z != right.z;
}

template<typename Scalar>
std::ostream& operator<<(std::ostream& out,
                         R3Element<Scalar> const& r3_element) {
  out << "{" << r3_element.x << ", "
             << r3_element.y << ", "
             << r3_element.z << "}";
  return out;
}

template<typename LScalar, typename RScalar>
inline R3Element<quantities::Product<LScalar, RScalar>> Cross(
    R3Element<LScalar> const& left,
    R3Element<RScalar> const& right) {
  return R3Element<quantities::Product<LScalar, RScalar>>(
      left.y * right.z - left.z * right.y,
      left.z * right.x - left.x * right.z,
      left.x * right.y - left.y * right.x);
}

template<typename LScalar, typename RScalar>
inline quantities::Product<LScalar, RScalar> Dot(
    R3Element<LScalar> const& left,
    R3Element<RScalar> const& right) {
  return left.x * right.x + left.y * right.y + left.z * right.z;
}

}  // namespace geometry
}  // namespace principia
<|endoftext|>


<commit_before>#include "clssnapshot.h"
#include <QPainter>
#include <QHBoxLayout>

clsSnapshot::clsSnapshot(quint16 universe, CID cid, QString name, QWidget *parent) : QWidget(parent),
    m_universe(universe),
    m_priority(DEFAULT_SACN_PRIORITY),
    m_cid(cid),
    m_sbUniverse(new QSpinBox(this)),
    m_sbPriority(new QSpinBox(this)),
    m_btnPlayback(new QToolButton(this)),
    m_lblStatus(new QLabel(this)),
    m_controlWidget(new QWidget(this)),
    m_sender(Q_NULLPTR),
    m_listener(Q_NULLPTR),
    m_camera(new QSound(":/sound/camera.wav", this)),
    m_backgroundMatches(false)
{
    m_sbUniverse->setMinimum(MIN_SACN_UNIVERSE);
    m_sbUniverse->setMaximum(MAX_SACN_UNIVERSE);
    m_sbUniverse->setValue(m_universe);
    connect(m_sbUniverse, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, [this](int value) { setUniverse(value); } );

    m_sbPriority->setMinimum(MIN_SACN_PRIORITY);
    m_sbPriority->setMaximum(MAX_SACN_PRIORITY);
    m_sbPriority->setValue(m_priority);
    connect(m_sbPriority, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, [this](int value) { setPriority(value); } );

    connect(m_btnPlayback, SIGNAL(clicked(bool)), this, SLOT(btnEnableClicked(bool)));
    updateIcons();

    m_sender = sACNManager::getInstance()->getSender(m_universe, m_cid);
    m_sender->setName(name);
    connect(m_sender.data(), &sACNSentUniverse::sendingTimeout, [this]() { emit senderTimedOut();} );
    setUniverse(m_universe);

    m_btnPlayback->setAutoRaise(true);
    m_controlWidget->setAutoFillBackground(true);
    QHBoxLayout *layout = new QHBoxLayout(m_controlWidget);
    layout->setMargin(0);
    layout->setContentsMargins(0,0,0,0);
    layout->addStretch();
    layout->addWidget(m_btnPlayback);
    layout->addWidget(m_lblStatus);
    layout->addStretch();
}

clsSnapshot::~clsSnapshot() {
}

void clsSnapshot::setUniverse(quint16 universe) {
    Q_ASSERT(universe >= MIN_SACN_UNIVERSE);
    Q_ASSERT(universe <= MAX_SACN_UNIVERSE);

    m_universe = universe;

    m_sbUniverse->setValue(m_universe);

    if (m_listener)
        m_listener->deleteLater();
    m_listener = sACNManager::getInstance()->getListener(m_universe);
    connect(m_listener.data(), SIGNAL(levelsChanged()), this, SLOT(levelsChanged()));
    connect(m_listener.data(), SIGNAL(sourceFound()), this, SLOT(levelsChanged()));
    connect(m_listener.data(), SIGNAL(sourceLost()), this, SLOT(levelsChanged()));
    connect(m_listener.data(), SIGNAL(sourceResumed()), this, SLOT(levelsChanged()));

    m_sender->setUniverse(m_universe);
}

void clsSnapshot::setPriority(quint8 priority) {
    Q_ASSERT(priority >= MIN_SACN_PRIORITY);
    Q_ASSERT(priority <= MAX_SACN_PRIORITY);

    m_priority = priority;

    m_sbPriority->setValue(m_priority);

    m_sender->setPerSourcePriority(m_priority);
}

void clsSnapshot::updateIcons() {
    if (!hasData())
        m_btnPlayback->setIcon(icons[ICON_SNAPSHOT]);
    else if (m_sender->isSending())
    {
        m_btnPlayback->setIcon(icons[ICON_PAUSE]);
    }
    else
        m_btnPlayback->setIcon(icons[ICON_PLAY]);

    if(!hasData())
    {
        m_lblStatus->setPixmap(statusIcons[STATUSICON_NONE]);
        m_lblStatus->setToolTip(statusIconTooltips[STATUSICON_NONE]);
    }
    else if(!m_sender->isSending())
    {
        m_lblStatus->setPixmap(statusIcons[STATUSICON_NONE]);
        m_lblStatus->setToolTip(statusIconTooltips[STATUSICON_NONE]);
    }
    else if(m_backgroundMatches)
    {
        m_lblStatus->setPixmap(statusIcons[STATUSICON_MATCHING]);
        m_lblStatus->setToolTip(statusIconTooltips[STATUSICON_MATCHING]);
    }
    else
    {
        m_lblStatus->setPixmap(statusIcons[STATUSICON_NOTMATCHING]);
        m_lblStatus->setToolTip(statusIconTooltips[STATUSICON_NOTMATCHING]);
    }

    // Enabled status
    m_sbUniverse->setEnabled(!isPlaying());
    m_sbPriority->setEnabled(!isPlaying());
}

void clsSnapshot::takeSnapshot() {
    m_levelData.clear();

    // Copy current merged universe
    for(int addr=0; addr<MAX_DMX_ADDRESS; addr++)
    {
        if (m_listener->mergedLevels().at(addr).level == -1)
            m_levelData.append(static_cast<char>(0));
        else
            m_levelData.append(m_listener->mergedLevels().at(addr).level);
    }

    updateIcons();

    emit snapshotTaken();
}

void clsSnapshot::playSnapshot() {
    if (!hasData())
    {
        updateIcons();
        return;
    }

    m_sender->startSending();
    m_sender->setLevel(reinterpret_cast<const quint8*>(m_levelData.constData()), std::min(m_levelData.count(), MAX_DMX_ADDRESS));
    updateIcons();
    emit senderStarted();
}

void clsSnapshot::stopSnapshot() {
    if (!hasData())
    {
        updateIcons();
        return;
    }

    m_sender->stopSending();
    updateIcons();
    emit senderStopped();
}

void clsSnapshot::btnEnableClicked(bool value) {
    Q_UNUSED(value);
    if (!hasData())
    {
        m_camera->play();
        takeSnapshot();
        return;
    } else if (isPlaying())
        stopSnapshot();
    else
        playSnapshot();
}

void clsSnapshot::levelsChanged()
{
    QByteArray background;

    int addr = 0;
    for (auto merged: m_listener->mergedLevels())
    {
        int level = 0;
        if ((merged.winningSource) && (merged.winningSource->src_cid == m_sender->cid()))
        {
            // I'm winning....
            if (merged.otherSources.isEmpty())
            {
                //...and the only source
                level = merged.level;
            } else {
                // ...find highest background priority
                int priority = 0;
                for (auto source: merged.otherSources)
                {
                    if (source->doing_per_channel)
                    {
                        if (source->priority_array[addr] > priority)
                        {
                            priority = source->priority;
                            level = source->level_array[addr];
                        }
                    } else {
                        if (source->priority > priority)
                        {
                            priority = source->priority;
                            level = source->level_array[addr];
                        }
                    }
                }
            }
        }
        else
        {
            // I'm not winning...
            level = merged.level;
        }

        background.append(level);

        if (addr < MAX_DMX_ADDRESS)
            addr++;
    }

    if ((background == m_levelData) != m_backgroundMatches)
    {
        m_backgroundMatches = (background == m_levelData);

        if (background == m_levelData)
            emit snapshotMatches();
        else
            emit snapshotDiffers();
    }

    updateIcons();
}

<commit_msg>Potential fix for #197<commit_after>#include "clssnapshot.h"
#include <QPainter>
#include <QHBoxLayout>

clsSnapshot::clsSnapshot(quint16 universe, CID cid, QString name, QWidget *parent) : QWidget(parent),
    m_universe(universe),
    m_priority(DEFAULT_SACN_PRIORITY),
    m_cid(cid),
    m_sbUniverse(new QSpinBox(this)),
    m_sbPriority(new QSpinBox(this)),
    m_btnPlayback(new QToolButton(this)),
    m_lblStatus(new QLabel(this)),
    m_controlWidget(new QWidget(this)),
    m_sender(Q_NULLPTR),
    m_listener(Q_NULLPTR),
    m_camera(new QSound(":/sound/camera.wav", this)),
    m_backgroundMatches(false)
{
    m_sbUniverse->setMinimum(MIN_SACN_UNIVERSE);
    m_sbUniverse->setMaximum(MAX_SACN_UNIVERSE);
    m_sbUniverse->setValue(m_universe);
    connect(m_sbUniverse, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, [this](int value) { setUniverse(value); } );

    m_sbPriority->setMinimum(MIN_SACN_PRIORITY);
    m_sbPriority->setMaximum(MAX_SACN_PRIORITY);
    m_sbPriority->setValue(m_priority);
    connect(m_sbPriority, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, [this](int value) { setPriority(value); } );

    connect(m_btnPlayback, SIGNAL(clicked(bool)), this, SLOT(btnEnableClicked(bool)));
    updateIcons();

    m_sender = sACNManager::getInstance()->getSender(m_universe, m_cid);
    m_sender->setName(name);
    connect(m_sender.data(), &sACNSentUniverse::sendingTimeout, [this]() { emit senderTimedOut();} );
    setUniverse(m_universe);

    m_btnPlayback->setAutoRaise(true);
    m_controlWidget->setAutoFillBackground(true);
    QHBoxLayout *layout = new QHBoxLayout(m_controlWidget);
    layout->setMargin(0);
    layout->setContentsMargins(0,0,0,0);
    layout->addStretch();
    layout->addWidget(m_btnPlayback);
    layout->addWidget(m_lblStatus);
    layout->addStretch();
}

clsSnapshot::~clsSnapshot() {
}

void clsSnapshot::setUniverse(quint16 universe) {
    Q_ASSERT(universe >= MIN_SACN_UNIVERSE);
    Q_ASSERT(universe <= MAX_SACN_UNIVERSE);

    m_universe = universe;

    m_sbUniverse->setValue(m_universe);

    // Bug #197
    //if (m_listener)
    //    m_listener->deleteLater();
    m_listener = sACNManager::getInstance()->getListener(m_universe);
    connect(m_listener.data(), SIGNAL(levelsChanged()), this, SLOT(levelsChanged()));
    connect(m_listener.data(), SIGNAL(sourceFound(sACNSource *source)), this, SLOT(levelsChanged()));
    connect(m_listener.data(), SIGNAL(sourceLost(sACNSource *source)), this, SLOT(levelsChanged()));
    connect(m_listener.data(), SIGNAL(sourceResumed(sACNSource *source)), this, SLOT(levelsChanged()));

    m_sender->setUniverse(m_universe);
}

void clsSnapshot::setPriority(quint8 priority) {
    Q_ASSERT(priority >= MIN_SACN_PRIORITY);
    Q_ASSERT(priority <= MAX_SACN_PRIORITY);

    m_priority = priority;

    m_sbPriority->setValue(m_priority);

    m_sender->setPerSourcePriority(m_priority);
}

void clsSnapshot::updateIcons() {
    if (!hasData())
        m_btnPlayback->setIcon(icons[ICON_SNAPSHOT]);
    else if (m_sender->isSending())
    {
        m_btnPlayback->setIcon(icons[ICON_PAUSE]);
    }
    else
        m_btnPlayback->setIcon(icons[ICON_PLAY]);

    if(!hasData())
    {
        m_lblStatus->setPixmap(statusIcons[STATUSICON_NONE]);
        m_lblStatus->setToolTip(statusIconTooltips[STATUSICON_NONE]);
    }
    else if(!m_sender->isSending())
    {
        m_lblStatus->setPixmap(statusIcons[STATUSICON_NONE]);
        m_lblStatus->setToolTip(statusIconTooltips[STATUSICON_NONE]);
    }
    else if(m_backgroundMatches)
    {
        m_lblStatus->setPixmap(statusIcons[STATUSICON_MATCHING]);
        m_lblStatus->setToolTip(statusIconTooltips[STATUSICON_MATCHING]);
    }
    else
    {
        m_lblStatus->setPixmap(statusIcons[STATUSICON_NOTMATCHING]);
        m_lblStatus->setToolTip(statusIconTooltips[STATUSICON_NOTMATCHING]);
    }

    // Enabled status
    m_sbUniverse->setEnabled(!isPlaying());
    m_sbPriority->setEnabled(!isPlaying());
}

void clsSnapshot::takeSnapshot() {
    m_levelData.clear();

    // Copy current merged universe
    for(int addr=0; addr<MAX_DMX_ADDRESS; addr++)
    {
        if (m_listener->mergedLevels().at(addr).level == -1)
            m_levelData.append(static_cast<char>(0));
        else
            m_levelData.append(m_listener->mergedLevels().at(addr).level);
    }

    updateIcons();

    emit snapshotTaken();
}

void clsSnapshot::playSnapshot() {
    if (!hasData())
    {
        updateIcons();
        return;
    }

    m_sender->startSending();
    m_sender->setLevel(reinterpret_cast<const quint8*>(m_levelData.constData()), std::min(m_levelData.count(), MAX_DMX_ADDRESS));
    updateIcons();
    emit senderStarted();
}

void clsSnapshot::stopSnapshot() {
    if (!hasData())
    {
        updateIcons();
        return;
    }

    m_sender->stopSending();
    updateIcons();
    emit senderStopped();
}

void clsSnapshot::btnEnableClicked(bool value) {
    Q_UNUSED(value);
    if (!hasData())
    {
        m_camera->play();
        takeSnapshot();
        return;
    } else if (isPlaying())
        stopSnapshot();
    else
        playSnapshot();
}

void clsSnapshot::levelsChanged()
{
    QByteArray background;

    int addr = 0;
    for (auto merged: m_listener->mergedLevels())
    {
        int level = 0;
        if ((merged.winningSource) && (merged.winningSource->src_cid == m_sender->cid()))
        {
            // I'm winning....
            if (merged.otherSources.isEmpty())
            {
                //...and the only source
                level = merged.level;
            } else {
                // ...find highest background priority
                int priority = 0;
                for (auto source: merged.otherSources)
                {
                    if (source->doing_per_channel)
                    {
                        if (source->priority_array[addr] > priority)
                        {
                            priority = source->priority;
                            level = source->level_array[addr];
                        }
                    } else {
                        if (source->priority > priority)
                        {
                            priority = source->priority;
                            level = source->level_array[addr];
                        }
                    }
                }
            }
        }
        else
        {
            // I'm not winning...
            level = merged.level;
        }

        background.append(level);

        if (addr < MAX_DMX_ADDRESS)
            addr++;
    }

    if ((background == m_levelData) != m_backgroundMatches)
    {
        m_backgroundMatches = (background == m_levelData);

        if (background == m_levelData)
            emit snapshotMatches();
        else
            emit snapshotDiffers();
    }

    updateIcons();
}

<|endoftext|>


<commit_before>#include <Bull/Render/Context/Context.hpp>
#include <Bull/Render/Context/GlContext.hpp>

namespace Bull
{
    unsigned int ContextResource::s_instanceCount = 0;

    void ContextResource::ensureContext()
    {
        prv::GlContext::ensureContext();
    }

    ContextResource::ContextResource()
    {
        s_instanceCount += 1;

        if(s_instanceCount == 1)
        {
            prv::GlContext::globalInit();
        }
    }

    ContextResource::~ContextResource() = default;
}
<commit_msg>[Render/ContextResource] Fix missing count down of ContextResource destruction<commit_after>#include <Bull/Render/Context/Context.hpp>
#include <Bull/Render/Context/GlContext.hpp>

namespace Bull
{
    unsigned int ContextResource::s_instanceCount = 0;

    void ContextResource::ensureContext()
    {
        prv::GlContext::ensureContext();
    }

    ContextResource::ContextResource()
    {
        s_instanceCount += 1;

        if(s_instanceCount == 1)
        {
            prv::GlContext::globalInit();
        }
    }

    ContextResource::~ContextResource()
    {
        s_instanceCount -= 1;
    }
}
<|endoftext|>


<commit_before>//
// CMatrixBlock/instance_method_assign.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_ASSIGN_HPP
#define EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_ASSIGN_HPP

namespace EigenJS {

EIGENJS_INSTANCE_METHOD(CMatrixBlock, assign,
{
  NanScope();

  if (args.Length() == 1) {
    CMatrixBlock* obj =
        node::ObjectWrap::Unwrap<CMatrixBlock>( args.This() );
    typename CMatrixBlock::value_type& value = **obj;

    if (CMatrix::is_cmatrix(args[0])) {
      const CMatrix* const& rhs_obj =
        node::ObjectWrap::Unwrap<CMatrix>(args[0]->ToObject());
      const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_cmatrix;

      NanReturnValue(args.This());
    } else if (CVector::is_cvector(args[0])) {
      const CVector* const& rhs_obj =
        node::ObjectWrap::Unwrap<CVector>(args[0]->ToObject());
      const typename CVector::value_type& rhs_cvector = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_cvector;

      NanReturnValue(args.This());
    } else if (CRowVector::is_rowvector(args[0])) {
      const CRowVector* const& rhs_obj =
        node::ObjectWrap::Unwrap<CRowVector>(args[0]->ToObject());
      const typename CRowVector::value_type& rhs_crowvector = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_crowvector;

      NanReturnValue(args.This());
    } else if (Matrix::is_matrix(args[0])) {
      const Matrix* const& rhs_obj =
        node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
      const typename Matrix::value_type& rhs_matrix = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_matrix.template cast<typename Complex::value_type>();

      NanReturnValue(args.This());
    } else if (Vector::is_vector(args[0])) {
      const Vector* const& rhs_obj =
        node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());
      const typename Vector::value_type& rhs_vector = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_vector.template cast<typename Complex::value_type>();

      NanReturnValue(args.This());
    } else if (RowVector::is_rowvector(args[0])) {
      const RowVector* const& rhs_obj =
        node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());
      const typename RowVector::value_type& rhs_rowvector = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_rowvector.template cast<typename Complex::value_type>();

      NanReturnValue(args.This());
    }
  }

  EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
  NanReturnUndefined();
})

}  // namespace EigenJS

#endif  // EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_ASSIGN_HPP
<commit_msg>src: fixed a mistake<commit_after>//
// CMatrixBlock/instance_method_assign.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_ASSIGN_HPP
#define EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_ASSIGN_HPP

namespace EigenJS {

EIGENJS_INSTANCE_METHOD(CMatrixBlock, assign,
{
  NanScope();

  if (args.Length() == 1) {
    CMatrixBlock* obj =
        node::ObjectWrap::Unwrap<CMatrixBlock>( args.This() );
    typename CMatrixBlock::value_type& value = **obj;

    if (CMatrix::is_cmatrix(args[0])) {
      const CMatrix* const& rhs_obj =
        node::ObjectWrap::Unwrap<CMatrix>(args[0]->ToObject());
      const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_cmatrix;

      NanReturnValue(args.This());
    } else if (CVector::is_cvector(args[0])) {
      const CVector* const& rhs_obj =
        node::ObjectWrap::Unwrap<CVector>(args[0]->ToObject());
      const typename CVector::value_type& rhs_cvector = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_cvector;

      NanReturnValue(args.This());
    } else if (CRowVector::is_crowvector(args[0])) {
      const CRowVector* const& rhs_obj =
        node::ObjectWrap::Unwrap<CRowVector>(args[0]->ToObject());
      const typename CRowVector::value_type& rhs_crowvector = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_crowvector;

      NanReturnValue(args.This());
    } else if (Matrix::is_matrix(args[0])) {
      const Matrix* const& rhs_obj =
        node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
      const typename Matrix::value_type& rhs_matrix = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_matrix.template cast<typename Complex::value_type>();

      NanReturnValue(args.This());
    } else if (Vector::is_vector(args[0])) {
      const Vector* const& rhs_obj =
        node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());
      const typename Vector::value_type& rhs_vector = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_vector.template cast<typename Complex::value_type>();

      NanReturnValue(args.This());
    } else if (RowVector::is_rowvector(args[0])) {
      const RowVector* const& rhs_obj =
        node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());
      const typename RowVector::value_type& rhs_rowvector = **rhs_obj;

      if (T::is_nonconformate_arguments(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value = rhs_rowvector.template cast<typename Complex::value_type>();

      NanReturnValue(args.This());
    }
  }

  EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
  NanReturnUndefined();
})

}  // namespace EigenJS

#endif  // EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_ASSIGN_HPP
<|endoftext|>


<commit_before>#ifndef ___INANITY_GRAPHICS_OPENGL_HPP___
#define ___INANITY_GRAPHICS_OPENGL_HPP___

#include "../Object.hpp"

#define GLEW_STATIC
#define GLEW_NO_GLU

#if defined(___INANITY_PLATFORM_WINDOWS)

#include "../deps/glew/include/GL/glew.h"
#include "../platform/windows.hpp"
#include "../deps/glew/include/GL/wglew.h"

#elif defined(___INANITY_PLATFORM_LINUX) || defined(___INANITY_PLATFORM_FREEBSD)

#include "../deps/glew/include/GL/glew.h"
#include <GL/gl.h>

#elif defined(___INANITY_PLATFORM_MACOS)

#include "../deps/glew/include/GL/glew.h"
#include </System/Library/Frameworks/OpenGL.framework/Headers/gl.h>

#elif defined(___INANITY_PLATFORM_EMSCRIPTEN)

#include <GL/glew.h>
#include <GL/gl.h>

// hacks for missing parts of Emscripten's GLEW
extern "C"
{
	void glBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
	void glVertexAttribIFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
	void glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);
	void glVertexAttribBinding(GLuint attribindex, GLuint bindingindex);
	void glVertexBindingDivisor(GLuint bindingindex, GLuint divisor);
	void glTexStorage1D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
	void glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
	void glTexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
};

#else

#error Unknown platform

#endif

#endif
<commit_msg>avoid warnings when defining GLEW macros<commit_after>#ifndef ___INANITY_GRAPHICS_OPENGL_HPP___
#define ___INANITY_GRAPHICS_OPENGL_HPP___

#include "../Object.hpp"

#if !defined(GLEW_STATIC)
#define GLEW_STATIC
#endif
#if !defined(GLEW_NO_GLU)
#define GLEW_NO_GLU
#endif

#if defined(___INANITY_PLATFORM_WINDOWS)

#include "../deps/glew/include/GL/glew.h"
#include "../platform/windows.hpp"
#include "../deps/glew/include/GL/wglew.h"

#elif defined(___INANITY_PLATFORM_LINUX) || defined(___INANITY_PLATFORM_FREEBSD)

#include "../deps/glew/include/GL/glew.h"
#include <GL/gl.h>

#elif defined(___INANITY_PLATFORM_MACOS)

#include "../deps/glew/include/GL/glew.h"
#include </System/Library/Frameworks/OpenGL.framework/Headers/gl.h>

#elif defined(___INANITY_PLATFORM_EMSCRIPTEN)

#include <GL/glew.h>
#include <GL/gl.h>

// hacks for missing parts of Emscripten's GLEW
extern "C"
{
	void glBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
	void glVertexAttribIFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
	void glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);
	void glVertexAttribBinding(GLuint attribindex, GLuint bindingindex);
	void glVertexBindingDivisor(GLuint bindingindex, GLuint divisor);
	void glTexStorage1D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
	void glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
	void glTexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
};

#else

#error Unknown platform

#endif

#endif
<|endoftext|>


<commit_before>// Kosaraju - SCC O(V+E)
vi adj[N], adjt[N];
int ord[N], ordn, scc[N], sccn, vis[N];

void dfs(int u) {
  vis[u] = 1;
  for (int v : adj[u]) if (!vis[v]) dfs(v);
  ord[ordn++] = u;
}

void dfst(int u) {
  vis[u] = 0;
  for (int v : adjt[u]) if (vis[v]) dfst(v);
  scc[u] = sccn;
}

// in main
sccn = ordn = 1;
for (int i = 1; i <= n; ++i) if (!vis[i]) dfs(i);
for (int i = n; i > 0; --i) if (vis[ord[i]]) dfst(ord[i]), sccn++;
<commit_msg>Update kosaraju.cpp<commit_after>// Kosaraju - SCC O(V+E)

vi adj[N], adjt[N];
int n, ordn, cnt, vis[N], ord[N], cmp[N];

void dfs(int x) {
  vis[x] = 1;
  for (auto v : adj[x]) if (!vis[v]) dfs(v);
  ord[ordn++] = x;
}

void dfst(int x) {
  cmp[x] = cnt, vis[x] = 0;
  for (auto v : adjt[u]) if (vis[v]) dfst(v);
}

// in main
for (int i = 1; i <= n; ++i) if (!vis[i]) dfs(i);
for (int i = ordn-1; i >= 0; --i) if (vis[ord[i]]) cnt++, dfst(ord[i]);
<|endoftext|>