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

  Program:   Visualization Toolkit
  Module:    vtkImageToStructuredPoints.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkImageToStructuredPoints.h"

//----------------------------------------------------------------------------
vtkImageToStructuredPoints::vtkImageToStructuredPoints()
{
  this->Input = NULL;
  this->WholeImage = 1;
  this->InputMemoryLimit = 50000000;  // A very big image indeed.
  this->SetSplitOrder(VTK_IMAGE_TIME_AXIS, VTK_IMAGE_Z_AXIS,
		      VTK_IMAGE_Y_AXIS, VTK_IMAGE_X_AXIS);
}

//----------------------------------------------------------------------------
vtkImageToStructuredPoints::~vtkImageToStructuredPoints()
{
}

//----------------------------------------------------------------------------
void vtkImageToStructuredPoints::Update()
{
  int execute;

  // make sure input is available
  if ( !this->Input )
    {
    vtkErrorMacro(<< "No input...can't execute!");
    return;
    }

  execute = this->Input->GetPipelineMTime() > this->ExecuteTime
    || this->GetMTime() > this->ExecuteTime
    || this->Region.GetMTime() > this->ExecuteTime;

  if (execute)
    {
    vtkDebugMacro(<< "Update: Condition satisfied, executeTime = "
                  << this->ExecuteTime
                  << ", modifiedTime = " << this->GetMTime()
                  << ", input MTime = " << this->Input->GetPipelineMTime()
                  << ", released = " << this->Output->GetDataReleased());

    if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
    this->Output->Initialize(); //clear output
    this->Execute();
    this->ExecuteTime.Modified();
    this->SetDataReleased(0);
    if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
    }
}

void vtkImageToStructuredPoints::Execute()
{
  vtkImageRegion *region = new vtkImageRegion;
  int regionBounds[8];
  int *dataBounds;
  int *bounds, dim[3];
  float aspectRatio[3] = {1.0, 1.0, 1.0};
  float origin[3];
  vtkStructuredPoints *output = this->GetOutput();

  // error checking
  if ( this->Input == NULL )
    {
    vtkErrorMacro(<<"Execute:Please specify an input!");
    return;
    }

  // Set the coordinate system of the region
  region->SetAxes(this->Region.GetAxes());

  // Fill in image information.
  this->Input->UpdateImageInformation(region);

  // Determine the bounds of the region we are converting
  if (this->WholeImage)
    {
    region->GetImageBounds3d(regionBounds);
    }
  else
    {
    this->Region.GetBounds3d(regionBounds);
    }
  regionBounds[6] = regionBounds[7] = this->Region.GetDefaultCoordinate3();
  region->SetBounds4d(regionBounds);

  // Update the data for the region.
  if ( region->GetVolume() < this->InputMemoryLimit)
    {
    this->Input->UpdateRegion(region);
    }
  if ( ! region->IsAllocated())
    {
    // We need to stream
    region->SetDataType(this->Input->GetDataType());
    region->Allocate();
    if ( ! region->IsAllocated())
      {
      vtkErrorMacro(<< "Execute: Could not allocate region.");
      return;
      }
    if ( ! this->SplitExecute(region))
      {
      vtkErrorMacro(<< "Execute: Streaming Failed.");
      return;
      }
    }

  // If data is not the same size as the region, we need to reformat.
  // Assume that relativeCoordinates == absoluteCoordinates.
  dataBounds = region->GetData()->GetBounds();
  if (dataBounds[0] != regionBounds[0] || dataBounds[1] != regionBounds[1] ||
      dataBounds[2] != regionBounds[2] || dataBounds[3] != regionBounds[3] ||
      dataBounds[4] != regionBounds[4] || dataBounds[5] != regionBounds[5] ||
      dataBounds[6] != regionBounds[6] || dataBounds[7] != regionBounds[7])
    {
    vtkImageRegion *temp = region;
    region = new vtkImageRegion;
    region->SetBounds4d(regionBounds);
    region->CopyRegionData(temp);
    temp->Delete();
    }

  // setup the structured points with the scalars
  bounds = region->GetBounds3d();
  region->GetAspectRatio3d(aspectRatio);
  origin[0] = (float)(bounds[0]);
  origin[1] = (float)(bounds[2]);
  origin[2] = (float)(bounds[4]);
  dim[0] = bounds[1] - bounds[0] + 1;
  dim[1] = bounds[3] - bounds[2] + 1;
  dim[2] = bounds[5] - bounds[4] + 1;
  output->SetDimensions(dim);
  output->SetAspectRatio(aspectRatio);
  output->SetOrigin(origin);
  output->GetPointData()->SetScalars(region->GetData()->GetScalars());

  // delete the temporary structures
  region->Delete();
}

//----------------------------------------------------------------------------
// Description:
// This function is for streaming.  It divides a region into two pieces,
// An executes each one.  The spliting logic is hardwired.  First
// the TIME axis is split then ZYX and COMPONENT axes are split.
int vtkImageToStructuredPoints::SplitExecute(vtkImageRegion *outRegion)
{
  int saveBounds[VTK_IMAGE_BOUNDS_DIMENSIONS];
  int splitBounds[VTK_IMAGE_BOUNDS_DIMENSIONS];
  int splitAxisIdx = 0;
  int splitAxis;
  int *splitAxes;
  int min, max;
  vtkImageRegion *inRegion;

  // Save the  region state to restore later
  outRegion->GetBounds(saveBounds);

  // Split output into two pieces and update separately.
  inRegion = new vtkImageRegion;
  splitAxes = this->SplitOrder.GetAxes();
  vtkDebugMacro ("Split order is: " << splitAxes[0] << ", "
				    << splitAxes[1] << ", "
				    << splitAxes[2] << ", "
				    << splitAxes[3]);
  outRegion->GetBounds(splitBounds);
  vtkDebugMacro (<<"Initial split region bounds are: " <<
         splitBounds[0] << ", " <<
         splitBounds[1] << ", " <<
         splitBounds[2] << ", " <<
         splitBounds[3] << ", " <<
         splitBounds[4] << ", " <<
         splitBounds[5] << ", " <<
         splitBounds[6] << ", " <<
         splitBounds[7]);

  while (splitBounds[splitAxes[splitAxisIdx] * 2] == splitBounds[splitAxes[splitAxisIdx] * 2 + 1])
    {
    ++splitAxisIdx;
    if (splitAxes[splitAxisIdx] >= VTK_IMAGE_DIMENSIONS)
      {
      vtkErrorMacro(<< "SplitExecute: Cannot split one pixel.");
      return 0;
      }
    }
  splitAxis = splitAxes[splitAxisIdx];
  min = splitBounds[splitAxis * 2];
  max = splitBounds[splitAxis * 2 + 1];
  // lower part
  splitBounds[splitAxis * 2 + 1] = (min + max) / 2;
  inRegion->SetBounds(splitBounds);
  outRegion->SetBounds(splitBounds);
  if ( inRegion->GetVolume() < this->InputMemoryLimit)
    {
    vtkDebugMacro (<<"Updating Split Region: bounds are: " <<
         splitBounds[0] << ", " <<
         splitBounds[1] << ", " <<
         splitBounds[2] << ", " <<
         splitBounds[3] << ", " <<
         splitBounds[4] << ", " <<
         splitBounds[5]);
    this->Input->UpdateRegion(inRegion);
    }
  if (inRegion->IsAllocated())
    {
    outRegion->CopyRegionData(inRegion);
    inRegion->ReleaseData();
    }
  else
    {
    if ( ! this->SplitExecute(outRegion))
      {
      vtkErrorMacro(<< "SplitExecute: Split failed.");
      return 0;
      }
    }
  // upper part
  splitBounds[splitAxis * 2] = splitBounds[splitAxis * 2 + 1] + 1;
  splitBounds[splitAxis * 2 + 1] = max;
  inRegion->SetBounds(splitBounds);
  outRegion->SetBounds(splitBounds);
  if ( inRegion->GetVolume() < this->InputMemoryLimit)
    {
    vtkDebugMacro (<<"Updating Split Region: bounds are: " <<
         splitBounds[0] << ", " <<
         splitBounds[1] << ", " <<
         splitBounds[2] << ", " <<
         splitBounds[3] << ", " <<
         splitBounds[4] << ", " <<
         splitBounds[5]);
    this->Input->UpdateRegion(inRegion);
    }
  if (inRegion->IsAllocated())
    {
    outRegion->CopyRegionData(inRegion);
    inRegion->ReleaseData();
    }
  else
    {
    if ( ! this->SplitExecute(outRegion))
      {
      vtkErrorMacro(<< "SplitExecute: Split failed.");
      return 0;
      }
    }

  // Clean up
  inRegion->Delete();
  outRegion->SetBounds(saveBounds);
}

<commit_msg>Fixed small bug.  LARGE BUG STILL REMAINS. It assumes that coordinate system is ABSOLUTE!!!<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImageToStructuredPoints.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkImageToStructuredPoints.h"

//----------------------------------------------------------------------------
vtkImageToStructuredPoints::vtkImageToStructuredPoints()
{
  this->Input = NULL;
  this->WholeImage = 1;
  this->InputMemoryLimit = 50000000;  // A very big image indeed.
  this->SetSplitOrder(VTK_IMAGE_TIME_AXIS, VTK_IMAGE_Z_AXIS,
		      VTK_IMAGE_Y_AXIS, VTK_IMAGE_X_AXIS);
}

//----------------------------------------------------------------------------
vtkImageToStructuredPoints::~vtkImageToStructuredPoints()
{
}

//----------------------------------------------------------------------------
void vtkImageToStructuredPoints::Update()
{
  int execute;

  // make sure input is available
  if ( !this->Input )
    {
    vtkErrorMacro(<< "No input...can't execute!");
    return;
    }

  execute = this->Input->GetPipelineMTime() > this->ExecuteTime
    || this->GetMTime() > this->ExecuteTime
    || this->Region.GetMTime() > this->ExecuteTime;

  if (execute)
    {
    vtkDebugMacro(<< "Update: Condition satisfied, executeTime = "
                  << this->ExecuteTime
                  << ", modifiedTime = " << this->GetMTime()
                  << ", input MTime = " << this->Input->GetPipelineMTime()
                  << ", released = " << this->Output->GetDataReleased());

    if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
    this->Output->Initialize(); //clear output
    this->Execute();
    this->ExecuteTime.Modified();
    this->SetDataReleased(0);
    if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
    }
}

void vtkImageToStructuredPoints::Execute()
{
  vtkImageRegion *region = new vtkImageRegion;
  int regionBounds[8];
  int *dataBounds;
  int *bounds, dim[3];
  float aspectRatio[3] = {1.0, 1.0, 1.0};
  float origin[3];
  vtkStructuredPoints *output = this->GetOutput();

  // error checking
  if ( this->Input == NULL )
    {
    vtkErrorMacro(<<"Execute:Please specify an input!");
    return;
    }

  // Set the coordinate system of the region
  region->SetAxes(this->Region.GetAxes());

  // Fill in image information.
  this->Input->UpdateImageInformation(region);

  // Determine the bounds of the region we are converting
  if (this->WholeImage)
    {
    region->GetImageBounds3d(regionBounds);
    }
  else
    {
    this->Region.GetBounds3d(regionBounds);
    }
  regionBounds[6] = regionBounds[7] = this->Region.GetDefaultCoordinate3();
  region->SetBounds4d(regionBounds);

  // Update the data for the region.
  if ( region->GetVolume() < this->InputMemoryLimit)
    {
    this->Input->UpdateRegion(region);
    }
  if ( ! region->IsAllocated())
    {
    // We need to stream
    region->SetDataType(this->Input->GetDataType());
    region->Allocate();
    if ( ! region->IsAllocated())
      {
      vtkErrorMacro(<< "Execute: Could not allocate region.");
      return;
      }
    if ( ! this->SplitExecute(region))
      {
      vtkErrorMacro(<< "Execute: Streaming Failed.");
      return;
      }
    }

  // If data is not the same size as the region, we need to reformat.
  // Assume that relativeCoordinates == absoluteCoordinates.
  dataBounds = region->GetData()->GetBounds();
  if (dataBounds[0] != regionBounds[0] || dataBounds[1] != regionBounds[1] ||
      dataBounds[2] != regionBounds[2] || dataBounds[3] != regionBounds[3] ||
      dataBounds[4] != regionBounds[4] || dataBounds[5] != regionBounds[5] ||
      dataBounds[6] != regionBounds[6] || dataBounds[7] != regionBounds[7])
    {
    vtkImageRegion *temp = region;
    region = new vtkImageRegion;
    region->SetBounds4d(regionBounds);
    region->CopyRegionData(temp);
    temp->Delete();
    }

  // setup the structured points with the scalars
  bounds = region->GetBounds3d();
  region->GetAspectRatio3d(aspectRatio);
  origin[0] = (float)(bounds[0]) * aspectRatio[0];
  origin[1] = (float)(bounds[2]) * aspectRatio[1];
  origin[2] = (float)(bounds[4]) * aspectRatio[2];
  dim[0] = bounds[1] - bounds[0] + 1;
  dim[1] = bounds[3] - bounds[2] + 1;
  dim[2] = bounds[5] - bounds[4] + 1;
  output->SetDimensions(dim);
  output->SetAspectRatio(aspectRatio);
  output->SetOrigin(origin);
  output->GetPointData()->SetScalars(region->GetData()->GetScalars());

  // delete the temporary structures
  region->Delete();
}

//----------------------------------------------------------------------------
// Description:
// This function is for streaming.  It divides a region into two pieces,
// An executes each one.  The spliting logic is hardwired.  First
// the TIME axis is split then ZYX and COMPONENT axes are split.
int vtkImageToStructuredPoints::SplitExecute(vtkImageRegion *outRegion)
{
  int saveBounds[VTK_IMAGE_BOUNDS_DIMENSIONS];
  int splitBounds[VTK_IMAGE_BOUNDS_DIMENSIONS];
  int splitAxisIdx = 0;
  int splitAxis;
  int *splitAxes;
  int min, max;
  vtkImageRegion *inRegion;

  // Save the  region state to restore later
  outRegion->GetBounds(saveBounds);

  // Split output into two pieces and update separately.
  inRegion = new vtkImageRegion;
  splitAxes = this->SplitOrder.GetAxes();
  vtkDebugMacro ("Split order is: " << splitAxes[0] << ", "
				    << splitAxes[1] << ", "
				    << splitAxes[2] << ", "
				    << splitAxes[3]);
  outRegion->GetBounds(splitBounds);
  vtkDebugMacro (<<"Initial split region bounds are: " <<
         splitBounds[0] << ", " <<
         splitBounds[1] << ", " <<
         splitBounds[2] << ", " <<
         splitBounds[3] << ", " <<
         splitBounds[4] << ", " <<
         splitBounds[5] << ", " <<
         splitBounds[6] << ", " <<
         splitBounds[7]);

  splitAxis = splitAxes[splitAxisIdx];
  while (splitBounds[splitAxis * 2] == splitBounds[splitAxis * 2 + 1])
    {
    ++splitAxisIdx;
    if (splitAxisIdx >= VTK_IMAGE_DIMENSIONS)
      {
      vtkErrorMacro(<< "SplitExecute: Cannot split one pixel.");
      return 0;
      }
    splitAxis = splitAxes[splitAxisIdx];
    }
  min = splitBounds[splitAxis * 2];
  max = splitBounds[splitAxis * 2 + 1];
  // lower part
  splitBounds[splitAxis * 2 + 1] = (min + max) / 2;
  inRegion->SetBounds(splitBounds);
  outRegion->SetBounds(splitBounds);
  if ( inRegion->GetVolume() < this->InputMemoryLimit)
    {
    vtkDebugMacro (<<"Updating Split Region: bounds are: " <<
         splitBounds[0] << ", " <<
         splitBounds[1] << ", " <<
         splitBounds[2] << ", " <<
         splitBounds[3] << ", " <<
         splitBounds[4] << ", " <<
         splitBounds[5]);
    this->Input->UpdateRegion(inRegion);
    }
  if (inRegion->IsAllocated())
    {
    outRegion->CopyRegionData(inRegion);
    inRegion->ReleaseData();
    }
  else
    {
    if ( ! this->SplitExecute(outRegion))
      {
      vtkErrorMacro(<< "SplitExecute: Split failed.");
      return 0;
      }
    }
  // upper part
  splitBounds[splitAxis * 2] = splitBounds[splitAxis * 2 + 1] + 1;
  splitBounds[splitAxis * 2 + 1] = max;
  inRegion->SetBounds(splitBounds);
  outRegion->SetBounds(splitBounds);
  if ( inRegion->GetVolume() < this->InputMemoryLimit)
    {
    vtkDebugMacro (<<"Updating Split Region: bounds are: " <<
         splitBounds[0] << ", " <<
         splitBounds[1] << ", " <<
         splitBounds[2] << ", " <<
         splitBounds[3] << ", " <<
         splitBounds[4] << ", " <<
         splitBounds[5]);
    this->Input->UpdateRegion(inRegion);
    }
  if (inRegion->IsAllocated())
    {
    outRegion->CopyRegionData(inRegion);
    inRegion->ReleaseData();
    }
  else
    {
    if ( ! this->SplitExecute(outRegion))
      {
      vtkErrorMacro(<< "SplitExecute: Split failed.");
      return 0;
      }
    }

  // Clean up
  inRegion->Delete();
  outRegion->SetBounds(saveBounds);
}

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkProgrammableGlyphFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkProgrammableGlyphFilter.h"
#include "vtkTransform.h"
#include "vtkVectors.h"
#include "vtkNormals.h"
#include "vtkMath.h"

// Construct object with scaling on, scaling mode is by scalar value,
// scale factor = 1.0, the range is (0,1), orient geometry is on, and
// orientation is by vector. Clamping and indexing are turned off. No
// initial sources are defined.
vtkProgrammableGlyphFilter::vtkProgrammableGlyphFilter()
{
  this->Source = NULL;

  this->GlyphMethod = NULL;
  this->GlyphMethodArgDelete = NULL;
  this->GlyphMethodArg = NULL;

  this->Point[0] = this->Point[1] = this->Point[2] = 0.0;
  this->PointId = -1;
  this->PointData = NULL;

  this->ColorMode = VTK_COLOR_BY_INPUT;
}

vtkProgrammableGlyphFilter::~vtkProgrammableGlyphFilter()
{
  if ((this->GlyphMethodArg)&&(this->GlyphMethodArgDelete))
    {
    (*this->GlyphMethodArgDelete)(this->GlyphMethodArg);
    }

  this->SetSource(NULL);
}

void vtkProgrammableGlyphFilter::Execute()
{
  vtkDataSet *input = this->GetInput();
  vtkPointData *inputPD = input->GetPointData();
  vtkCellData *inputCD = input->GetCellData();
  vtkPolyData *output = this->GetOutput();
  vtkPointData *outputPD = output->GetPointData();
  vtkCellData *outputCD = output->GetCellData();
  vtkPoints *newPts, *sourcePts;
  vtkScalars *ptScalars=NULL, *cellScalars=NULL;
  vtkScalars *inPtScalars, *inCellScalars;
  int numPts = input->GetNumberOfPoints();
  vtkPointData *sourcePD;
  vtkCellData *sourceCD;
  int numSourcePts, numSourceCells, ptOffset=0, scalarOffset;
  int cellId, ptId, id, i, idx, npts;
  vtkIdList *pts=vtkIdList::New();
  vtkIdList *cellPts;
  pts->Allocate(VTK_CELL_SIZE);
  vtkCell *cell;

  // Initialize
  vtkDebugMacro(<<"Generating programmable glyphs!");

  if ( numPts < 1 )
    {
    vtkErrorMacro(<<"No input points to glyph");
    }

  sourcePD = this->Source->GetPointData();
  sourceCD = this->Source->GetCellData();
  numSourcePts = this->Source->GetNumberOfPoints();
  numSourceCells = this->Source->GetNumberOfCells();

  outputPD->CopyScalarsOff(); //'cause we control the coloring process
  outputCD->CopyScalarsOff();

  output->Allocate(numSourceCells*numPts,numSourceCells*numPts);
  outputPD->CopyAllocate(sourcePD, numSourcePts*numPts, numSourcePts*numPts);
  outputCD->CopyAllocate(sourceCD, numSourceCells*numPts, numSourceCells*numPts);
  newPts = vtkPoints::New();
  newPts->Allocate(numSourcePts*numPts);

  // figure out how to color the data and setup
  if ( this->ColorMode == VTK_COLOR_BY_INPUT )
    {
    if ( (inPtScalars = inputPD->GetScalars()) )
      {
      ptScalars = vtkScalars::New();
      ptScalars->Allocate(numSourcePts*numPts);
      }
    if ( (inCellScalars = inputCD->GetScalars()) )
      {
      cellScalars = vtkScalars::New();
      cellScalars->Allocate(numSourcePts*numPts);
      }
    }
  else // VTK_COLOR_BY_SOURCE
    {
    if ( (inPtScalars = sourcePD->GetScalars()) )
      {
      ptScalars = vtkScalars::New();
      ptScalars->Allocate(numSourcePts*numPts);
      }
    if ( (inCellScalars = sourceCD->GetScalars()) )
      {
      cellScalars = vtkScalars::New();
      cellScalars->Allocate(numSourcePts*numPts);
      }
    }

  // Loop over all points, invoking glyph method and Update(), then append output
  // of source to output of this filter.
  //
  this->Updating = 1; // to prevent infinite recursion
  this->PointData = input->GetPointData();
  for (this->PointId=0; this->PointId < numPts; this->PointId++)
    {
    if ( ! (this->PointId % 10000) )
      {
      this->UpdateProgress ((float)this->PointId/numPts);
      if (this->GetAbortExecute()) break;
      }

    input->GetPoint(this->PointId, this->Point);

    if ( this->GlyphMethod )
      {
      (*this->GlyphMethod)(this->GlyphMethodArg);
      }

    if ( this->Source )
      {
      this->Source->Update();

      sourcePts = this->Source->GetPoints();
      numSourcePts = this->Source->GetNumberOfPoints();
      numSourceCells = this->Source->GetNumberOfCells();
      sourcePD = this->Source->GetPointData();
      sourceCD = this->Source->GetCellData();

      // Copy all data from source to output.
      for (ptId=0; ptId < numSourcePts; ptId++)
        {
        id = newPts->InsertNextPoint(sourcePts->GetPoint(ptId));
        outputPD->CopyData(sourcePD, ptId, id);
        }

      for (cellId=0; cellId < numSourceCells; cellId++)
        {
        cell = this->Source->GetCell(cellId);
        cellPts = cell->GetPointIds();
        npts = cellPts->GetNumberOfIds();
        for (pts->Reset(), i=0; i < npts; i++)
          {
          pts->InsertId(i,cellPts->GetId(i) + ptOffset);
          }
        id = output->InsertNextCell(cell->GetCellType(),pts);
        outputCD->CopyData(sourceCD, cellId, id);
        }

      // If we're coloring the output with scalars, do that now
      if ( ptScalars )
        {
        for (ptId=0; ptId < numSourcePts; ptId++)
          {
          idx = (this->ColorMode == VTK_COLOR_BY_INPUT ? this->PointId : ptId);
          ptScalars->InsertNextScalar(inPtScalars->GetScalar(idx));
          }
        }
      else if ( cellScalars )
        {
        for (cellId=0; cellId < numSourceCells; cellId++)
          {
          idx = (this->ColorMode == VTK_COLOR_BY_INPUT ? this->PointId : cellId);
          cellScalars->InsertNextScalar(inCellScalars->GetScalar(idx));
          }
        }

      ptOffset += numSourcePts;

      }//if a source is available
    } //for all input points

  this->Updating = 0;

  pts->Delete();

  output->SetPoints(newPts);
  newPts->Delete();

  if ( ptScalars )
    {
    outputPD->SetScalars(ptScalars);
    ptScalars->Delete();
    }

  if ( cellScalars )
    {
    outputCD->SetScalars(cellScalars);
    cellScalars->Delete();
    }

  output->Squeeze();
}

// Override update method because execution can branch two ways (via Input
// and Source).
void vtkProgrammableGlyphFilter::Update()
{
  // make sure input is available
  if ( this->Input == NULL || this->Source == NULL )
    {
    vtkErrorMacro(<< "No input or source...can't execute!");
    return;
    }

  // prevent chasing our tail
  if (this->Updating) return;

  this->Updating = 1;
  this->Input->Update();
  if ( this->Source ) this->Source->Update();
  this->Updating = 0;

  if (this->Input->GetMTime() > this->ExecuteTime ||
  (this->Source && this->Source->GetMTime() > this->ExecuteTime) ||
  this->GetMTime() > this->ExecuteTime )
    {
    if ( this->Input->GetDataReleased() ) this->Input->ForceUpdate();
    if ( this->Source && this->Source->GetDataReleased() )
      this->Source->ForceUpdate();

    if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
    this->Output->Initialize(); //clear output
    // reset AbortExecute flag and Progress
    this->AbortExecute = 0;
    this->Progress = 0.0;
    this->Execute();
    this->ExecuteTime.Modified();
    if ( !this->AbortExecute ) this->UpdateProgress(1.0);
    this->SetDataReleased(0);
    if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
    }

  if ( this->Input->ShouldIReleaseData() ) this->Input->ReleaseData();
  if ( this->Source && this->Source->ShouldIReleaseData() )
    this->Source->ReleaseData();
}

// Specify function to be called before object executes.
void vtkProgrammableGlyphFilter::SetGlyphMethod(void (*f)(void *), void *arg)
{
  if ( f != this->GlyphMethod || arg != this->GlyphMethodArg )
    {
    // delete the current arg if there is one and a delete meth
    if ((this->GlyphMethodArg)&&(this->GlyphMethodArgDelete))
      {
      (*this->GlyphMethodArgDelete)(this->GlyphMethodArg);
      }
    this->GlyphMethod = f;
    this->GlyphMethodArg = arg;
    this->Modified();
    }
}

// Set the arg delete method. This is used to free user memory.
void vtkProgrammableGlyphFilter::SetGlyphMethodArgDelete(void (*f)(void *))
{
  if ( f != this->GlyphMethodArgDelete)
    {
    this->GlyphMethodArgDelete = f;
    this->Modified();
    }
}

// Description:
// Return the method of coloring as a descriptive character string.
inline char *vtkProgrammableGlyphFilter::GetColorModeAsString(void)
{
  if ( this->ColorMode == VTK_COLOR_BY_INPUT )
    {
    return "ColorByInput";
    }
  else
    {
    return "ColorBySource";
    }
}

void vtkProgrammableGlyphFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkDataSetToPolyDataFilter::PrintSelf(os,indent);

  os << indent << "Source: " << (void *)this->Source << "\n";

  os << indent << "Color Mode: " << this->GetColorModeAsString() << endl;

  if ( this->GlyphMethod )
    {
    os << indent << "Glyph Method defined\n";
    }
  else
    {
    os << indent << "No Glyph Method\n";
    }

}
<commit_msg>ERR: removed inline from GetColorModeAsString. Non portable for Sun /opt/../CC and HP compilers.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkProgrammableGlyphFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkProgrammableGlyphFilter.h"
#include "vtkTransform.h"
#include "vtkVectors.h"
#include "vtkNormals.h"
#include "vtkMath.h"

// Construct object with scaling on, scaling mode is by scalar value,
// scale factor = 1.0, the range is (0,1), orient geometry is on, and
// orientation is by vector. Clamping and indexing are turned off. No
// initial sources are defined.
vtkProgrammableGlyphFilter::vtkProgrammableGlyphFilter()
{
  this->Source = NULL;

  this->GlyphMethod = NULL;
  this->GlyphMethodArgDelete = NULL;
  this->GlyphMethodArg = NULL;

  this->Point[0] = this->Point[1] = this->Point[2] = 0.0;
  this->PointId = -1;
  this->PointData = NULL;

  this->ColorMode = VTK_COLOR_BY_INPUT;
}

vtkProgrammableGlyphFilter::~vtkProgrammableGlyphFilter()
{
  if ((this->GlyphMethodArg)&&(this->GlyphMethodArgDelete))
    {
    (*this->GlyphMethodArgDelete)(this->GlyphMethodArg);
    }

  this->SetSource(NULL);
}

void vtkProgrammableGlyphFilter::Execute()
{
  vtkDataSet *input = this->GetInput();
  vtkPointData *inputPD = input->GetPointData();
  vtkCellData *inputCD = input->GetCellData();
  vtkPolyData *output = this->GetOutput();
  vtkPointData *outputPD = output->GetPointData();
  vtkCellData *outputCD = output->GetCellData();
  vtkPoints *newPts, *sourcePts;
  vtkScalars *ptScalars=NULL, *cellScalars=NULL;
  vtkScalars *inPtScalars, *inCellScalars;
  int numPts = input->GetNumberOfPoints();
  vtkPointData *sourcePD;
  vtkCellData *sourceCD;
  int numSourcePts, numSourceCells, ptOffset=0, scalarOffset;
  int cellId, ptId, id, i, idx, npts;
  vtkIdList *pts=vtkIdList::New();
  vtkIdList *cellPts;
  pts->Allocate(VTK_CELL_SIZE);
  vtkCell *cell;

  // Initialize
  vtkDebugMacro(<<"Generating programmable glyphs!");

  if ( numPts < 1 )
    {
    vtkErrorMacro(<<"No input points to glyph");
    }

  sourcePD = this->Source->GetPointData();
  sourceCD = this->Source->GetCellData();
  numSourcePts = this->Source->GetNumberOfPoints();
  numSourceCells = this->Source->GetNumberOfCells();

  outputPD->CopyScalarsOff(); //'cause we control the coloring process
  outputCD->CopyScalarsOff();

  output->Allocate(numSourceCells*numPts,numSourceCells*numPts);
  outputPD->CopyAllocate(sourcePD, numSourcePts*numPts, numSourcePts*numPts);
  outputCD->CopyAllocate(sourceCD, numSourceCells*numPts, numSourceCells*numPts);
  newPts = vtkPoints::New();
  newPts->Allocate(numSourcePts*numPts);

  // figure out how to color the data and setup
  if ( this->ColorMode == VTK_COLOR_BY_INPUT )
    {
    if ( (inPtScalars = inputPD->GetScalars()) )
      {
      ptScalars = vtkScalars::New();
      ptScalars->Allocate(numSourcePts*numPts);
      }
    if ( (inCellScalars = inputCD->GetScalars()) )
      {
      cellScalars = vtkScalars::New();
      cellScalars->Allocate(numSourcePts*numPts);
      }
    }
  else // VTK_COLOR_BY_SOURCE
    {
    if ( (inPtScalars = sourcePD->GetScalars()) )
      {
      ptScalars = vtkScalars::New();
      ptScalars->Allocate(numSourcePts*numPts);
      }
    if ( (inCellScalars = sourceCD->GetScalars()) )
      {
      cellScalars = vtkScalars::New();
      cellScalars->Allocate(numSourcePts*numPts);
      }
    }

  // Loop over all points, invoking glyph method and Update(), then append output
  // of source to output of this filter.
  //
  this->Updating = 1; // to prevent infinite recursion
  this->PointData = input->GetPointData();
  for (this->PointId=0; this->PointId < numPts; this->PointId++)
    {
    if ( ! (this->PointId % 10000) )
      {
      this->UpdateProgress ((float)this->PointId/numPts);
      if (this->GetAbortExecute()) break;
      }

    input->GetPoint(this->PointId, this->Point);

    if ( this->GlyphMethod )
      {
      (*this->GlyphMethod)(this->GlyphMethodArg);
      }

    if ( this->Source )
      {
      this->Source->Update();

      sourcePts = this->Source->GetPoints();
      numSourcePts = this->Source->GetNumberOfPoints();
      numSourceCells = this->Source->GetNumberOfCells();
      sourcePD = this->Source->GetPointData();
      sourceCD = this->Source->GetCellData();

      // Copy all data from source to output.
      for (ptId=0; ptId < numSourcePts; ptId++)
        {
        id = newPts->InsertNextPoint(sourcePts->GetPoint(ptId));
        outputPD->CopyData(sourcePD, ptId, id);
        }

      for (cellId=0; cellId < numSourceCells; cellId++)
        {
        cell = this->Source->GetCell(cellId);
        cellPts = cell->GetPointIds();
        npts = cellPts->GetNumberOfIds();
        for (pts->Reset(), i=0; i < npts; i++)
          {
          pts->InsertId(i,cellPts->GetId(i) + ptOffset);
          }
        id = output->InsertNextCell(cell->GetCellType(),pts);
        outputCD->CopyData(sourceCD, cellId, id);
        }

      // If we're coloring the output with scalars, do that now
      if ( ptScalars )
        {
        for (ptId=0; ptId < numSourcePts; ptId++)
          {
          idx = (this->ColorMode == VTK_COLOR_BY_INPUT ? this->PointId : ptId);
          ptScalars->InsertNextScalar(inPtScalars->GetScalar(idx));
          }
        }
      else if ( cellScalars )
        {
        for (cellId=0; cellId < numSourceCells; cellId++)
          {
          idx = (this->ColorMode == VTK_COLOR_BY_INPUT ? this->PointId : cellId);
          cellScalars->InsertNextScalar(inCellScalars->GetScalar(idx));
          }
        }

      ptOffset += numSourcePts;

      }//if a source is available
    } //for all input points

  this->Updating = 0;

  pts->Delete();

  output->SetPoints(newPts);
  newPts->Delete();

  if ( ptScalars )
    {
    outputPD->SetScalars(ptScalars);
    ptScalars->Delete();
    }

  if ( cellScalars )
    {
    outputCD->SetScalars(cellScalars);
    cellScalars->Delete();
    }

  output->Squeeze();
}

// Override update method because execution can branch two ways (via Input
// and Source).
void vtkProgrammableGlyphFilter::Update()
{
  // make sure input is available
  if ( this->Input == NULL || this->Source == NULL )
    {
    vtkErrorMacro(<< "No input or source...can't execute!");
    return;
    }

  // prevent chasing our tail
  if (this->Updating) return;

  this->Updating = 1;
  this->Input->Update();
  if ( this->Source ) this->Source->Update();
  this->Updating = 0;

  if (this->Input->GetMTime() > this->ExecuteTime ||
  (this->Source && this->Source->GetMTime() > this->ExecuteTime) ||
  this->GetMTime() > this->ExecuteTime )
    {
    if ( this->Input->GetDataReleased() ) this->Input->ForceUpdate();
    if ( this->Source && this->Source->GetDataReleased() )
      this->Source->ForceUpdate();

    if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
    this->Output->Initialize(); //clear output
    // reset AbortExecute flag and Progress
    this->AbortExecute = 0;
    this->Progress = 0.0;
    this->Execute();
    this->ExecuteTime.Modified();
    if ( !this->AbortExecute ) this->UpdateProgress(1.0);
    this->SetDataReleased(0);
    if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
    }

  if ( this->Input->ShouldIReleaseData() ) this->Input->ReleaseData();
  if ( this->Source && this->Source->ShouldIReleaseData() )
    this->Source->ReleaseData();
}

// Specify function to be called before object executes.
void vtkProgrammableGlyphFilter::SetGlyphMethod(void (*f)(void *), void *arg)
{
  if ( f != this->GlyphMethod || arg != this->GlyphMethodArg )
    {
    // delete the current arg if there is one and a delete meth
    if ((this->GlyphMethodArg)&&(this->GlyphMethodArgDelete))
      {
      (*this->GlyphMethodArgDelete)(this->GlyphMethodArg);
      }
    this->GlyphMethod = f;
    this->GlyphMethodArg = arg;
    this->Modified();
    }
}

// Set the arg delete method. This is used to free user memory.
void vtkProgrammableGlyphFilter::SetGlyphMethodArgDelete(void (*f)(void *))
{
  if ( f != this->GlyphMethodArgDelete)
    {
    this->GlyphMethodArgDelete = f;
    this->Modified();
    }
}

// Description:
// Return the method of coloring as a descriptive character string.
char *vtkProgrammableGlyphFilter::GetColorModeAsString(void)
{
  if ( this->ColorMode == VTK_COLOR_BY_INPUT )
    {
    return "ColorByInput";
    }
  else
    {
    return "ColorBySource";
    }
}

void vtkProgrammableGlyphFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkDataSetToPolyDataFilter::PrintSelf(os,indent);

  os << indent << "Source: " << (void *)this->Source << "\n";

  os << indent << "Color Mode: " << this->GetColorModeAsString() << endl;

  if ( this->GlyphMethod )
    {
    os << indent << "Glyph Method defined\n";
    }
  else
    {
    os << indent << "No Glyph Method\n";
    }

}
<|endoftext|>


<commit_before>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2017-2019 Baldur Karlsson
 *
 * 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.
 ******************************************************************************/

#define CATCH_CONFIG_RUNNER
#define CATCH_CONFIG_NOSTDOUT
#include "catch.hpp"
#include "api/replay/renderdoc_replay.h"
#include "serialise/serialiser.h"
#include "strings/string_utils.h"

// since we force use of ToStr for everything and don't allow using catch's stringstream (so that
// enums get forwarded to ToStr) we need to implement ToStr for one of Catch's structs.
template <>
std::string DoStringise(const Catch::SourceLineInfo &el)
{
  return StringFormat::Fmt("%s:%zu", el.file, el.line);
}

struct AppVeyorListener : Catch::TestEventListenerBase
{
  using TestEventListenerBase::TestEventListenerBase;    // inherit constructor

  std::string errorList;
  double durationInSeconds = 0.0;

  struct TestCase
  {
    double durationInSeconds;
    bool passed;
    std::string errorList;
    std::string name;
    std::string filename;

    std::string MakeJSON();
  };

  std::vector<TestCase> m_testcases;

  virtual bool assertionEnded(Catch::AssertionStats const &assertionStats) override
  {
    Catch::TestEventListenerBase::assertionEnded(assertionStats);

    using namespace Catch;

    if(!assertionStats.assertionResult.isOk())
    {
      std::ostringstream msg;
      msg << "-------------------------------------------------------------------------------\n";
      for(size_t i = 0; i < m_sectionStack.size(); i++)
      {
        if(i > 0)
          msg << "  > ";
        msg << m_sectionStack[i].name;
        msg << "\n";
      }
      msg << "-------------------------------------------------------------------------------\n";
      msg << assertionStats.assertionResult.getSourceInfo() << ": ";

      switch(assertionStats.assertionResult.getResultType())
      {
        case ResultWas::ExpressionFailed: msg << "Failed"; break;
        case ResultWas::ThrewException: msg << "Threw exception"; break;
        case ResultWas::FatalErrorCondition: msg << "Fatal error'd"; break;
        case ResultWas::DidntThrowException: msg << "Didn't throw expected exception"; break;
        case ResultWas::ExplicitFailure: msg << "Explicitly failed"; break;

        case ResultWas::Ok:
        case ResultWas::Info:
        case ResultWas::Warning:
        case ResultWas::Unknown:
        case ResultWas::FailureBit:
        case ResultWas::Exception: break;
      }

      if(assertionStats.infoMessages.size() >= 1)
        msg << " with message(s):";
      for(auto it = assertionStats.infoMessages.begin(); it != assertionStats.infoMessages.end(); ++it)
        msg << "\n" << it->message;

      if(assertionStats.assertionResult.hasExpression())
      {
        msg << "\n  " << assertionStats.assertionResult.getExpressionInMacro()
            << "\nwith expansion:\n  " << assertionStats.assertionResult.getExpandedExpression()
            << "\n";
      }

      errorList += msg.str();
    }

    return true;
  }

  virtual void sectionEnded(Catch::SectionStats const &sectionStats) override
  {
    durationInSeconds += sectionStats.durationInSeconds;

    Catch::TestEventListenerBase::sectionEnded(sectionStats);
  }

  virtual void testCaseEnded(Catch::TestCaseStats const &testCaseStats) override
  {
    m_testcases.push_back({
        durationInSeconds, testCaseStats.totals.assertions.allOk(), errorList,
        testCaseStats.testInfo.name, testCaseStats.testInfo.lineInfo.file,
    });

    errorList.clear();
    durationInSeconds = 0.0;

    Catch::TestEventListenerBase::testCaseEnded(testCaseStats);
  }

  // we dump all the test data at the end, because appveyor can't be trusted to get it right
  // incrementally. This means if the program crashes mid-run we don't get partial test output, but
  // it should at least by identified as an issue.
  virtual void testRunEnded(Catch::TestRunStats const &testRunStats) override
  {
    const char *url = Process::GetEnvVariable("APPVEYOR_API_URL");

    if(url)
    {
      if(strncmp(url, "http://", 7))
        return;

      url += 7;

      const char *sep = strchr(url, ':');

      if(!sep)
        return;

      std::string hostname = std::string(url, sep);

      url = sep + 1;

      uint16_t port = 0;
      while(*url >= '0' && *url <= '9')
      {
        port *= 10;
        port += int((*url) - '0');
        url++;
      }

      Network::Socket *sock = Network::CreateClientSocket(hostname.c_str(), port, 10);

      if(sock)
      {
        std::string json;

        json += "[\n";
        for(size_t i = 0; i < m_testcases.size(); i++)
        {
          json += m_testcases[i].MakeJSON();

          if(i + 1 < m_testcases.size())
            json += ",";

          json += "\n";
        }
        json += "]";

        std::string http;
        http += StringFormat::Fmt("POST /api/tests/batch HTTP/1.1\r\n");
        http += StringFormat::Fmt("Host: %s\r\n", hostname.c_str());
        http += "Connection: close\r\n";
        http += "Content-Type: application/json\r\n";
        http += StringFormat::Fmt("Content-Length: %zu\r\n", json.size());
        http += "User-Agent: Catch.hpp appveyor updater\r\n";
        http += "\r\n";
        http += json;

        sock->SendDataBlocking(http.c_str(), (uint32_t)http.size());
      }

      SAFE_DELETE(sock);
    }
  }
};

static std::string escape(const std::string &input)
{
  std::string ret = input;
  size_t i = ret.find_first_of("\"\n\\", 0);
  while(i != std::string::npos)
  {
    if(ret[i] == '"')
      ret.replace(i, 1, "\\\"");
    else if(ret[i] == '\\')
      ret.replace(i, 1, "\\\\");
    else if(ret[i] == '\n')
      ret.replace(i, 1, "\\n");

    i = ret.find_first_of("\"\n\\", i + 2);
  }

  return ret;
}

std::string AppVeyorListener::TestCase::MakeJSON()
{
  std::string json;

  return StringFormat::Fmt(
      R"({
    "testName": "%s",
    "testFramework": "Catch.hpp",
    "fileName": "%s",
    "outcome": "%s",
    "durationMilliseconds": "%d",
    "ErrorMessage": "%s",
    "ErrorStackTrace": "",
    "StdOut": "",
    "StdErr": ""
})",
      escape(name).c_str(), escape(filename).c_str(), passed ? "Passed" : "Failed",
      (int)RDCMAX(durationInSeconds * 1000.0, 0.0), escape(trim(errorList)).c_str());
}

CATCH_REGISTER_LISTENER(AppVeyorListener)

class LogOutputter : public std::stringbuf
{
public:
  LogOutputter() {}
  virtual int sync() override
  {
    std::string msg = this->str();
    OSUtility::WriteOutput(OSUtility::Output_DebugMon, msg.c_str());
    OSUtility::WriteOutput(OSUtility::Output_StdOut, msg.c_str());
    this->str("");
    return 0;
  }

  // force a sync on every output
  virtual std::streamsize xsputn(const char *s, std::streamsize n) override
  {
    std::streamsize ret = std::stringbuf::xsputn(s, n);
    sync();
    return ret;
  }
};

std::ostream *catch_stream = NULL;

namespace Catch
{
std::ostream &cout()
{
  return *catch_stream;
}
std::ostream &cerr()
{
  return *catch_stream;
}
std::ostream &clog()
{
  return *catch_stream;
}
}

extern "C" RENDERDOC_API int RENDERDOC_CC RENDERDOC_RunUnitTests(const rdcstr &command,
                                                                 const rdcarray<rdcstr> &args)
{
  LogOutputter logbuf;
  std::ostream logstream(&logbuf);
  catch_stream = &logstream;

  Catch::Session session;

  session.configData().name = "RenderDoc";
  session.configData().shouldDebugBreak = OSUtility::DebuggerPresent();

  const char **argv = new const char *[args.size() + 1];
  argv[0] = command.c_str();
  for(size_t i = 0; i < args.size(); i++)
    argv[i + 1] = args[i].c_str();

  int ret = session.applyCommandLine(args.count() + 1, argv);

  delete[] argv;

  // command line error
  if(ret != 0)
    return ret;

  int numFailed = session.run();

  // Note that on unices only the lower 8 bits are usually used, clamping
  // the return value to 255 prevents false negative when some multiple
  // of 256 tests has failed
  return (numFailed < 0xff ? numFailed : 0xff);
}<commit_msg>Don't compile Catch2 into release builds<commit_after>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2017-2019 Baldur Karlsson
 *
 * 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 "common/globalconfig.h"

#if ENABLED(ENABLE_UNIT_TESTS)

#define CATCH_CONFIG_RUNNER
#define CATCH_CONFIG_NOSTDOUT
#include "serialise/serialiser.h"
#include "strings/string_utils.h"
#include "catch.hpp"

// since we force use of ToStr for everything and don't allow using catch's stringstream (so that
// enums get forwarded to ToStr) we need to implement ToStr for one of Catch's structs.
template <>
std::string DoStringise(const Catch::SourceLineInfo &el)
{
  return StringFormat::Fmt("%s:%zu", el.file, el.line);
}

struct AppVeyorListener : Catch::TestEventListenerBase
{
  using TestEventListenerBase::TestEventListenerBase;    // inherit constructor

  std::string errorList;
  double durationInSeconds = 0.0;

  struct TestCase
  {
    double durationInSeconds;
    bool passed;
    std::string errorList;
    std::string name;
    std::string filename;

    std::string MakeJSON();
  };

  std::vector<TestCase> m_testcases;

  virtual bool assertionEnded(Catch::AssertionStats const &assertionStats) override
  {
    Catch::TestEventListenerBase::assertionEnded(assertionStats);

    using namespace Catch;

    if(!assertionStats.assertionResult.isOk())
    {
      std::ostringstream msg;
      msg << "-------------------------------------------------------------------------------\n";
      for(size_t i = 0; i < m_sectionStack.size(); i++)
      {
        if(i > 0)
          msg << "  > ";
        msg << m_sectionStack[i].name;
        msg << "\n";
      }
      msg << "-------------------------------------------------------------------------------\n";
      msg << assertionStats.assertionResult.getSourceInfo() << ": ";

      switch(assertionStats.assertionResult.getResultType())
      {
        case ResultWas::ExpressionFailed: msg << "Failed"; break;
        case ResultWas::ThrewException: msg << "Threw exception"; break;
        case ResultWas::FatalErrorCondition: msg << "Fatal error'd"; break;
        case ResultWas::DidntThrowException: msg << "Didn't throw expected exception"; break;
        case ResultWas::ExplicitFailure: msg << "Explicitly failed"; break;

        case ResultWas::Ok:
        case ResultWas::Info:
        case ResultWas::Warning:
        case ResultWas::Unknown:
        case ResultWas::FailureBit:
        case ResultWas::Exception: break;
      }

      if(assertionStats.infoMessages.size() >= 1)
        msg << " with message(s):";
      for(auto it = assertionStats.infoMessages.begin(); it != assertionStats.infoMessages.end(); ++it)
        msg << "\n" << it->message;

      if(assertionStats.assertionResult.hasExpression())
      {
        msg << "\n  " << assertionStats.assertionResult.getExpressionInMacro()
            << "\nwith expansion:\n  " << assertionStats.assertionResult.getExpandedExpression()
            << "\n";
      }

      errorList += msg.str();
    }

    return true;
  }

  virtual void sectionEnded(Catch::SectionStats const &sectionStats) override
  {
    durationInSeconds += sectionStats.durationInSeconds;

    Catch::TestEventListenerBase::sectionEnded(sectionStats);
  }

  virtual void testCaseEnded(Catch::TestCaseStats const &testCaseStats) override
  {
    m_testcases.push_back({
        durationInSeconds, testCaseStats.totals.assertions.allOk(), errorList,
        testCaseStats.testInfo.name, testCaseStats.testInfo.lineInfo.file,
    });

    errorList.clear();
    durationInSeconds = 0.0;

    Catch::TestEventListenerBase::testCaseEnded(testCaseStats);
  }

  // we dump all the test data at the end, because appveyor can't be trusted to get it right
  // incrementally. This means if the program crashes mid-run we don't get partial test output, but
  // it should at least by identified as an issue.
  virtual void testRunEnded(Catch::TestRunStats const &testRunStats) override
  {
    const char *url = Process::GetEnvVariable("APPVEYOR_API_URL");

    if(url)
    {
      if(strncmp(url, "http://", 7))
        return;

      url += 7;

      const char *sep = strchr(url, ':');

      if(!sep)
        return;

      std::string hostname = std::string(url, sep);

      url = sep + 1;

      uint16_t port = 0;
      while(*url >= '0' && *url <= '9')
      {
        port *= 10;
        port += int((*url) - '0');
        url++;
      }

      Network::Socket *sock = Network::CreateClientSocket(hostname.c_str(), port, 10);

      if(sock)
      {
        std::string json;

        json += "[\n";
        for(size_t i = 0; i < m_testcases.size(); i++)
        {
          json += m_testcases[i].MakeJSON();

          if(i + 1 < m_testcases.size())
            json += ",";

          json += "\n";
        }
        json += "]";

        std::string http;
        http += StringFormat::Fmt("POST /api/tests/batch HTTP/1.1\r\n");
        http += StringFormat::Fmt("Host: %s\r\n", hostname.c_str());
        http += "Connection: close\r\n";
        http += "Content-Type: application/json\r\n";
        http += StringFormat::Fmt("Content-Length: %zu\r\n", json.size());
        http += "User-Agent: Catch.hpp appveyor updater\r\n";
        http += "\r\n";
        http += json;

        sock->SendDataBlocking(http.c_str(), (uint32_t)http.size());
      }

      SAFE_DELETE(sock);
    }
  }
};

static std::string escape(const std::string &input)
{
  std::string ret = input;
  size_t i = ret.find_first_of("\"\n\\", 0);
  while(i != std::string::npos)
  {
    if(ret[i] == '"')
      ret.replace(i, 1, "\\\"");
    else if(ret[i] == '\\')
      ret.replace(i, 1, "\\\\");
    else if(ret[i] == '\n')
      ret.replace(i, 1, "\\n");

    i = ret.find_first_of("\"\n\\", i + 2);
  }

  return ret;
}

std::string AppVeyorListener::TestCase::MakeJSON()
{
  std::string json;

  return StringFormat::Fmt(
      R"({
    "testName": "%s",
    "testFramework": "Catch.hpp",
    "fileName": "%s",
    "outcome": "%s",
    "durationMilliseconds": "%d",
    "ErrorMessage": "%s",
    "ErrorStackTrace": "",
    "StdOut": "",
    "StdErr": ""
})",
      escape(name).c_str(), escape(filename).c_str(), passed ? "Passed" : "Failed",
      (int)RDCMAX(durationInSeconds * 1000.0, 0.0), escape(trim(errorList)).c_str());
}

CATCH_REGISTER_LISTENER(AppVeyorListener)

class LogOutputter : public std::stringbuf
{
public:
  LogOutputter() {}
  virtual int sync() override
  {
    std::string msg = this->str();
    OSUtility::WriteOutput(OSUtility::Output_DebugMon, msg.c_str());
    OSUtility::WriteOutput(OSUtility::Output_StdOut, msg.c_str());
    this->str("");
    return 0;
  }

  // force a sync on every output
  virtual std::streamsize xsputn(const char *s, std::streamsize n) override
  {
    std::streamsize ret = std::stringbuf::xsputn(s, n);
    sync();
    return ret;
  }
};

std::ostream *catch_stream = NULL;

namespace Catch
{
std::ostream &cout()
{
  return *catch_stream;
}
std::ostream &cerr()
{
  return *catch_stream;
}
std::ostream &clog()
{
  return *catch_stream;
}
}

extern "C" RENDERDOC_API int RENDERDOC_CC RENDERDOC_RunUnitTests(const rdcstr &command,
                                                                 const rdcarray<rdcstr> &args)
{
  LogOutputter logbuf;
  std::ostream logstream(&logbuf);
  catch_stream = &logstream;

  Catch::Session session;

  session.configData().name = "RenderDoc";
  session.configData().shouldDebugBreak = OSUtility::DebuggerPresent();

  const char **argv = new const char *[args.size() + 1];
  argv[0] = command.c_str();
  for(size_t i = 0; i < args.size(); i++)
    argv[i + 1] = args[i].c_str();

  int ret = session.applyCommandLine(args.count() + 1, argv);

  delete[] argv;

  // command line error
  if(ret != 0)
    return ret;

  int numFailed = session.run();

  // Note that on unices only the lower 8 bits are usually used, clamping
  // the return value to 255 prevents false negative when some multiple
  // of 256 tests has failed
  return (numFailed < 0xff ? numFailed : 0xff);
}

#else

#include "api/replay/renderdoc_replay.h"

extern "C" RENDERDOC_API int RENDERDOC_CC RENDERDOC_RunUnitTests(const rdcstr &command,
                                                                 const rdcarray<rdcstr> &args)
{
  return 0;
}

#endif    // ENABLED(ENABLE_UNIT_TESTS)
<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include <gtest/gtest.h>

#include <map>

#include "logging.h"
#include "platform.h"
#include "util_concurrency.h"
#include "util/pointer.h"
#include "util/posix.h"

typedef std::map<file_watcher::Event, int> Counters;

class TestEventHandler : public file_watcher::EventHandler {
 public:
  explicit TestEventHandler(Counters* ctrs,
                            FifoChannel<bool>* chan)
      : counters_(ctrs)
      , chan_(chan)
      , clear_(true) {}

  virtual ~TestEventHandler() {}

  virtual bool Handle(const std::string& /*file_path*/,
                      file_watcher::Event event,
                      bool* clear_handler) {
    (*counters_)[event]++;
    *clear_handler = clear_;
    chan_->Enqueue(true);
    return true;
  }

  Counters* counters_;
  FifoChannel<bool>* chan_;
  bool clear_;
};

class T_FileWatcher : public ::testing::Test {
 protected:
  void SetUp() {
    counters_.clear();
    channel_ = new FifoChannel<bool>(10, 1);
  }

  Counters counters_;
  UniquePtr<FifoChannel<bool> > channel_;
};

TEST_F(T_FileWatcher, kModifiedEvent) {
  const std::string watched_file_name =
      GetCurrentWorkingDirectory() + "/file_watcher_test.txt";
  SafeWriteToFile("test", watched_file_name, 0600);

  UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());

  TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));
  watcher->RegisterHandler(watched_file_name, hd);

  EXPECT_TRUE(watcher->Start());

  SafeWriteToFile("test", watched_file_name, 0600);

  channel_->Dequeue();

  Counters::const_iterator it_mod = counters_.find(file_watcher::kModified);
  const int num_modifications = it_mod->second;
  EXPECT_EQ(1, num_modifications);

  watcher->Stop();
}

TEST_F(T_FileWatcher, kDeletedEvent) {
  const std::string watched_file_name =
      GetCurrentWorkingDirectory() + "/file_watcher_test2.txt";
  SafeWriteToFile("test", watched_file_name, 0600);

  UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());

  TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));
  watcher->RegisterHandler(watched_file_name, hd);

  EXPECT_TRUE(watcher->Start());

  unlink(watched_file_name.c_str());

  channel_->Dequeue();

  Counters::const_iterator it_del = counters_.find(file_watcher::kDeleted);
  const int num_deletions = it_del->second;
  EXPECT_EQ(1, num_deletions);

  watcher->Stop();
}

TEST_F(T_FileWatcher, kModifiedThenDeletedEvent) {
  const std::string watched_file_name =
      GetCurrentWorkingDirectory() + "/file_watcher_test.txt";
  SafeWriteToFile("test", watched_file_name, 0600);

  UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());

  TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));
  hd->clear_ = false;
  watcher->RegisterHandler(watched_file_name, hd);

  EXPECT_TRUE(watcher->Start());

  SafeWriteToFile("test", watched_file_name, 0600);

  channel_->Dequeue();

  hd->clear_ = true;

  Counters::const_iterator it_mod = counters_.find(file_watcher::kModified);
  const int num_modifications = it_mod->second;
  EXPECT_EQ(1, num_modifications);

  unlink(watched_file_name.c_str());

  channel_->Dequeue();

  Counters::const_iterator it_del = counters_.find(file_watcher::kDeleted);
  const int num_deletions = it_del->second;
  EXPECT_EQ(1, num_deletions);

  watcher->Stop();
}
<commit_msg>Disable FileWatcher tests on Linux until the inotify version is written<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include <gtest/gtest.h>

#include <map>

#include "logging.h"
#include "platform.h"
#include "util_concurrency.h"
#include "util/pointer.h"
#include "util/posix.h"

typedef std::map<file_watcher::Event, int> Counters;

class TestEventHandler : public file_watcher::EventHandler {
 public:
  explicit TestEventHandler(Counters* ctrs,
                            FifoChannel<bool>* chan)
      : counters_(ctrs)
      , chan_(chan)
      , clear_(true) {}

  virtual ~TestEventHandler() {}

  virtual bool Handle(const std::string& /*file_path*/,
                      file_watcher::Event event,
                      bool* clear_handler) {
    (*counters_)[event]++;
    *clear_handler = clear_;
    chan_->Enqueue(true);
    return true;
  }

  Counters* counters_;
  FifoChannel<bool>* chan_;
  bool clear_;
};

class T_FileWatcher : public ::testing::Test {
 protected:
  void SetUp() {
    counters_.clear();
    channel_ = new FifoChannel<bool>(10, 1);
  }

  Counters counters_;
  UniquePtr<FifoChannel<bool> > channel_;
};

TEST_F(T_FileWatcher, kModifiedEvent) {
  const std::string watched_file_name =
      GetCurrentWorkingDirectory() + "/file_watcher_test.txt";
  SafeWriteToFile("test", watched_file_name, 0600);

  UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());

  // TODO(radu): Remove this check when the Linux inotify version is added
  if (watcher.IsValid()) {
    TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));
    watcher->RegisterHandler(watched_file_name, hd);

    EXPECT_TRUE(watcher->Start());

    SafeWriteToFile("test", watched_file_name, 0600);

    channel_->Dequeue();

    Counters::const_iterator it_mod = counters_.find(file_watcher::kModified);
    const int num_modifications = it_mod->second;
    EXPECT_EQ(1, num_modifications);

    watcher->Stop();
  }
}

TEST_F(T_FileWatcher, kDeletedEvent) {
  const std::string watched_file_name =
      GetCurrentWorkingDirectory() + "/file_watcher_test2.txt";
  SafeWriteToFile("test", watched_file_name, 0600);

  UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());

  // TODO(radu): Remove this check when the Linux inotify version is added
  if (watcher.IsValid()) {
    TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));
    watcher->RegisterHandler(watched_file_name, hd);

    EXPECT_TRUE(watcher->Start());

    unlink(watched_file_name.c_str());

    channel_->Dequeue();

    Counters::const_iterator it_del = counters_.find(file_watcher::kDeleted);
    const int num_deletions = it_del->second;
    EXPECT_EQ(1, num_deletions);

    watcher->Stop();
  }
}

TEST_F(T_FileWatcher, kModifiedThenDeletedEvent) {
  const std::string watched_file_name =
      GetCurrentWorkingDirectory() + "/file_watcher_test.txt";
  SafeWriteToFile("test", watched_file_name, 0600);

  UniquePtr<file_watcher::FileWatcher> watcher(platform_file_watcher());

  // TODO(radu): Remove this check when the Linux inotify version is added
  if (watcher.IsValid()) {
    TestEventHandler* hd(new TestEventHandler(&counters_, channel_.weak_ref()));
    hd->clear_ = false;
    watcher->RegisterHandler(watched_file_name, hd);

    EXPECT_TRUE(watcher->Start());

    SafeWriteToFile("test", watched_file_name, 0600);

    channel_->Dequeue();

    hd->clear_ = true;

    Counters::const_iterator it_mod = counters_.find(file_watcher::kModified);
    const int num_modifications = it_mod->second;
    EXPECT_EQ(1, num_modifications);

    unlink(watched_file_name.c_str());

    channel_->Dequeue();

    Counters::const_iterator it_del = counters_.find(file_watcher::kDeleted);
    const int num_deletions = it_del->second;
    EXPECT_EQ(1, num_deletions);

    watcher->Stop();
  }
}
<|endoftext|>


<commit_before>#ifndef ELEKTRON_H__
#define ELEKTRON_H__

#include "WProgram.h"

#include <inttypes.h>

typedef struct machine_name_s {
  char name[11];
  uint8_t id;
} machine_name_t;

typedef struct model_param_name_s {
  char name[4];
  uint8_t id;
} model_param_name_t;

typedef struct model_to_param_names_s {
  uint8_t model;
  model_param_name_t *names;
} model_to_param_names_t;

class ElektronHelper {
public:
  static uint16_t MDSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len);
  static uint16_t MDDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len);
  static uint16_t MNMDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len, uint16_t maxLen);
  static uint16_t MNMSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len, uint16_t maxLen);
  static uint16_t to16Bit7(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t *b);
  static uint32_t to32Bit(uint8_t *b);
  static void from16Bit(uint16_t num, uint8_t *b);
  static void from32Bit(uint32_t num, uint8_t *b);
  static uint64_t to64Bit(uint8_t *b);
  static void from64Bit(uint64_t num, uint8_t *b);
};

class DataEncoder {
public:
  uint8_t *data;
  uint8_t *ptr;
  uint16_t maxLen;

  virtual void init(uint8_t *_data, uint16_t _maxLen) {
    data = _data;
    maxLen = _maxLen;
    ptr = data;
  }

  virtual bool pack(uint8_t inb) {
    return false;
  }
  virtual uint16_t finish() {
    return 0;
  }
#ifdef HOST_MIDIDUINO
  virtual ~DataEncoder() { };
#endif
};

class MNMDataToSysexEncoder : public DataEncoder {
  uint16_t retLen;
  uint16_t cnt7;

  uint8_t lastByte;
  uint8_t lastCnt;
  bool isFirstByte;

public:
  MNMDataToSysexEncoder(uint8_t *_sysex = NULL, uint16_t _sysexLen = 0) {
    init(_sysex, _sysexLen);
  }

  virtual void init(uint8_t *_sysex, uint16_t _sysexLen);
  bool encode7Bit(uint8_t inb);
  virtual bool pack(uint8_t inb);
  bool packLastByte();
  virtual uint16_t finish();
};

class MNMSysexToDataEncoder : public DataEncoder {
public:
  uint16_t retLen;
  uint8_t cnt7;
  uint8_t repeat;
  uint16_t cnt;
  uint8_t bits;
  uint8_t tmpData[7];

  MNMSysexToDataEncoder(uint8_t *_data = NULL, uint16_t _maxLen = 0) {
    init(_data, _maxLen);
  }

  virtual void init(uint8_t *_data, uint16_t _maxLen);
  virtual bool pack(uint8_t inb);
  bool unpack8Bit();
  virtual uint16_t finish();
};

#endif /* ELEKTRON_H__ */
<commit_msg>split md machine and mnm machine names to save some bytes<commit_after>#ifndef ELEKTRON_H__
#define ELEKTRON_H__

#include "WProgram.h"

#include <inttypes.h>

typedef struct mnm_machine_name_s {
  char name[11];
  uint8_t id;
} mnm_machine_name_t;

typedef struct md_machine_name_s {
  char name[7];
  uint8_t id;
} md_machine_name_t;

typedef struct model_param_name_s {
  char name[4];
  uint8_t id;
} model_param_name_t;

typedef struct model_to_param_names_s {
  uint8_t model;
  model_param_name_t *names;
} model_to_param_names_t;

class ElektronHelper {
public:
  static uint16_t MDSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len);
  static uint16_t MDDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len);
  static uint16_t MNMDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len, uint16_t maxLen);
  static uint16_t MNMSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len, uint16_t maxLen);
  static uint16_t to16Bit7(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t *b);
  static uint32_t to32Bit(uint8_t *b);
  static void from16Bit(uint16_t num, uint8_t *b);
  static void from32Bit(uint32_t num, uint8_t *b);
  static uint64_t to64Bit(uint8_t *b);
  static void from64Bit(uint64_t num, uint8_t *b);
};

class DataEncoder {
public:
  uint8_t *data;
  uint8_t *ptr;
  uint16_t maxLen;

  virtual void init(uint8_t *_data, uint16_t _maxLen) {
    data = _data;
    maxLen = _maxLen;
    ptr = data;
  }

  virtual bool pack(uint8_t inb) {
    return false;
  }
  virtual uint16_t finish() {
    return 0;
  }
#ifdef HOST_MIDIDUINO
  virtual ~DataEncoder() { };
#endif
};

class MNMDataToSysexEncoder : public DataEncoder {
  uint16_t retLen;
  uint16_t cnt7;

  uint8_t lastByte;
  uint8_t lastCnt;
  bool isFirstByte;

public:
  MNMDataToSysexEncoder(uint8_t *_sysex = NULL, uint16_t _sysexLen = 0) {
    init(_sysex, _sysexLen);
  }

  virtual void init(uint8_t *_sysex, uint16_t _sysexLen);
  bool encode7Bit(uint8_t inb);
  virtual bool pack(uint8_t inb);
  bool packLastByte();
  virtual uint16_t finish();
};

class MNMSysexToDataEncoder : public DataEncoder {
public:
  uint16_t retLen;
  uint8_t cnt7;
  uint8_t repeat;
  uint16_t cnt;
  uint8_t bits;
  uint8_t tmpData[7];

  MNMSysexToDataEncoder(uint8_t *_data = NULL, uint16_t _maxLen = 0) {
    init(_data, _maxLen);
  }

  virtual void init(uint8_t *_data, uint16_t _maxLen);
  virtual bool pack(uint8_t inb);
  bool unpack8Bit();
  virtual uint16_t finish();
};

#endif /* ELEKTRON_H__ */
<|endoftext|>


<commit_before>#ifndef ELEKTRON_H__
#define ELEKTRON_H__

#include "WProgram.h"

#include <inttypes.h>

typedef struct machine_name_s {
  char name[11];
  uint8_t id;
} machine_name_t;

typedef struct model_param_name_s {
  char name[4];
  uint8_t id;
} model_param_name_t;

typedef struct model_to_param_names_s {
  uint8_t model;
  model_param_name_t *names;
} model_to_param_names_t;

class ElektronHelper {
public:
  static uint16_t MDSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len);
  static uint16_t MDDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len);
  static uint16_t MNMDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len, uint16_t maxLen);
  static uint16_t MNMSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len, uint16_t maxLen);
  static uint16_t to16Bit7(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t *b);
  static uint32_t to32Bit(uint8_t *b);
  static void from16Bit(uint16_t num, uint8_t *b);
  static void from32Bit(uint32_t num, uint8_t *b);
  static uint64_t to64Bit(uint8_t *b);
  static void from64Bit(uint64_t num, uint8_t *b);
};

class DataEncoder {
public:
  uint8_t *data;
  uint8_t *ptr;
  uint16_t maxLen;

  virtual void init(uint8_t *_data, uint16_t _maxLen) {
    data = _data;
    maxLen = _maxLen;
    ptr = data;
  }

  virtual bool pack(uint8_t inb) = 0;
  virtual uint16_t finish() = 0;
#ifdef HOST_MIDIDUINO
  virtual ~DataEncoder() { };
#endif
};

class MNMDataToSysexEncoder : public DataEncoder {
  uint16_t retLen;
  uint16_t cnt7;

  uint8_t lastByte;
  uint8_t lastCnt;
  bool isFirstByte;

public:
  MNMDataToSysexEncoder(uint8_t *_sysex = NULL, uint16_t _sysexLen = 0) {
    init(_sysex, _sysexLen);
  }

  virtual void init(uint8_t *_sysex, uint16_t _sysexLen);
  bool encode7Bit(uint8_t inb);
  virtual bool pack(uint8_t inb);
  bool packLastByte();
  virtual uint16_t finish();
};

class MNMSysexToDataEncoder : public DataEncoder {
public:
  uint16_t retLen;
  uint8_t cnt7;
  uint8_t repeat;
  uint16_t cnt;
  uint8_t bits;
  uint8_t tmpData[7];

  MNMSysexToDataEncoder(uint8_t *_data = NULL, uint16_t _maxLen = 0) {
    init(_data, _maxLen);
  }

  virtual void init(uint8_t *_data, uint16_t _maxLen);
  virtual bool pack(uint8_t inb);
  bool unpack8Bit();
  virtual uint16_t finish();
};

#endif /* ELEKTRON_H__ */
<commit_msg>added virtual methods to Elektron<commit_after>#ifndef ELEKTRON_H__
#define ELEKTRON_H__

#include "WProgram.h"

#include <inttypes.h>

typedef struct machine_name_s {
  char name[11];
  uint8_t id;
} machine_name_t;

typedef struct model_param_name_s {
  char name[4];
  uint8_t id;
} model_param_name_t;

typedef struct model_to_param_names_s {
  uint8_t model;
  model_param_name_t *names;
} model_to_param_names_t;

class ElektronHelper {
public:
  static uint16_t MDSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len);
  static uint16_t MDDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len);
  static uint16_t MNMDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len, uint16_t maxLen);
  static uint16_t MNMSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len, uint16_t maxLen);
  static uint16_t to16Bit7(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t *b);
  static uint32_t to32Bit(uint8_t *b);
  static void from16Bit(uint16_t num, uint8_t *b);
  static void from32Bit(uint32_t num, uint8_t *b);
  static uint64_t to64Bit(uint8_t *b);
  static void from64Bit(uint64_t num, uint8_t *b);
};

class DataEncoder {
public:
  uint8_t *data;
  uint8_t *ptr;
  uint16_t maxLen;

  virtual void init(uint8_t *_data, uint16_t _maxLen) {
    data = _data;
    maxLen = _maxLen;
    ptr = data;
  }

  virtual bool pack(uint8_t inb) {
    return false;
  }
  virtual uint16_t finish() {
    return 0;
  }
#ifdef HOST_MIDIDUINO
  virtual ~DataEncoder() { };
#endif
};

class MNMDataToSysexEncoder : public DataEncoder {
  uint16_t retLen;
  uint16_t cnt7;

  uint8_t lastByte;
  uint8_t lastCnt;
  bool isFirstByte;

public:
  MNMDataToSysexEncoder(uint8_t *_sysex = NULL, uint16_t _sysexLen = 0) {
    init(_sysex, _sysexLen);
  }

  virtual void init(uint8_t *_sysex, uint16_t _sysexLen);
  bool encode7Bit(uint8_t inb);
  virtual bool pack(uint8_t inb);
  bool packLastByte();
  virtual uint16_t finish();
};

class MNMSysexToDataEncoder : public DataEncoder {
public:
  uint16_t retLen;
  uint8_t cnt7;
  uint8_t repeat;
  uint16_t cnt;
  uint8_t bits;
  uint8_t tmpData[7];

  MNMSysexToDataEncoder(uint8_t *_data = NULL, uint16_t _maxLen = 0) {
    init(_data, _maxLen);
  }

  virtual void init(uint8_t *_data, uint16_t _maxLen);
  virtual bool pack(uint8_t inb);
  bool unpack8Bit();
  virtual uint16_t finish();
};

#endif /* ELEKTRON_H__ */
<|endoftext|>