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

  Program:   Visualization Toolkit
  Module:    vtkConnectivityFilter.cc
  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 "vtkConnectivityFilter.hh"

// Description:
// Construct with default extraction mode to extract largest regions.
vtkConnectivityFilter::vtkConnectivityFilter()
{
  this->ExtractionMode = VTK_EXTRACT_LARGEST_REGION;
  this->ColorRegions = 0;
  this->MaxRecursionDepth = 10000;
}

static NumExceededMaxDepth;
static int *Visited, *PointMap;
static vtkFloatScalars *NewScalars;
static int RecursionDepth;
static int RegionNumber, PointNumber;
static int NumCellsInRegion;
static  vtkIdList *RecursionSeeds;

void vtkConnectivityFilter::Execute()
{
  int cellId, i, j, pt;
  int numPts, numCells;
  vtkFloatPoints *newPts;
  vtkIdList cellIds(VTK_CELL_SIZE), ptIds(VTK_CELL_SIZE);
  vtkPointData *pd;
  int id;
  int maxCellsInRegion, largestRegionId;
  vtkUnstructuredGrid *output = this->GetOutput();
  vtkPointData *outputPD = output->GetPointData();

  vtkDebugMacro(<<"Executing connectivity filter.");
  //
  //  Check input/allocate storage
  //
  if ( (numPts=this->Input->GetNumberOfPoints()) < 1 ||
  (numCells=this->Input->GetNumberOfCells()) < 1 )
    {
    vtkDebugMacro(<<"No data to connect!");
    return;
    }
  output->Allocate(numCells,numCells);
  //
  // Initialize.  Keep track of points and cells visited.
  //
  this->RegionSizes.Reset();
  Visited = new int[numCells];
  for ( i=0; i < numCells; i++ ) Visited[i] = -1;
  PointMap = new int[numPts];
  for ( i=0; i < numPts; i++ ) PointMap[i] = -1;

  NewScalars = new vtkFloatScalars(numPts);
  newPts = new vtkFloatPoints(numPts);
  //
  // Traverse all cells marking those visited.  Each new search
  // starts a new connected region.  Note: have to truncate recursion
  // and keep track of seeds to start up again.
  //
  RecursionSeeds = new vtkIdList(1000,10000);

  NumExceededMaxDepth = 0;
  PointNumber = 0;
  RegionNumber = 0;
  maxCellsInRegion = 0;

  if ( this->ExtractionMode != VTK_EXTRACT_POINT_SEEDED_REGIONS &&
  this->ExtractionMode != VTK_EXTRACT_CELL_SEEDED_REGIONS )
    { //visit all cells marking with region number
    for (cellId=0; cellId < numCells; cellId++)
      {
      if ( Visited[cellId] < 0 )
        {
        NumCellsInRegion = 0;
        RecursionDepth = 0;
        this->TraverseAndMark (cellId);

        for (i=0; i < RecursionSeeds->GetNumberOfIds(); i++)
          {
          RecursionDepth = 0;
          this->TraverseAndMark (RecursionSeeds->GetId(i));
          }

        if ( NumCellsInRegion > maxCellsInRegion )
          {
          maxCellsInRegion = NumCellsInRegion;
          largestRegionId = RegionNumber;
          }

        this->RegionSizes.InsertValue(RegionNumber++,NumCellsInRegion);
        RecursionSeeds->Reset();
        }
      }
    }
  else // regions have been seeded, everything considered in same region
    {
    NumCellsInRegion = 0;

    if ( this->ExtractionMode == VTK_EXTRACT_POINT_SEEDED_REGIONS )
      {
      for (i=0; i < this->Seeds.GetNumberOfIds(); i++)
        {
        pt = this->Seeds.GetId(i);
        if ( pt >= 0 )
          {
          this->Input->GetPointCells(pt,cellIds);
          for (j=0; j < cellIds.GetNumberOfIds(); j++)
            RecursionSeeds->InsertNextId(cellIds.GetId(j));
          }
        }
      }
    else if ( this->ExtractionMode == VTK_EXTRACT_CELL_SEEDED_REGIONS )
      {
      for (i=0; i < this->Seeds.GetNumberOfIds(); i++)
        {
        cellId = this->Seeds.GetId(i);
        if ( cellId >= 0 ) RecursionSeeds->InsertNextId(cellId);
        }
      }

    //mark all seeded regions
    for (i=0; i < RecursionSeeds->GetNumberOfIds(); i++)
      {
      RecursionDepth = 0;
      this->TraverseAndMark (RecursionSeeds->GetId(i));
      }
    this->RegionSizes.InsertValue(RegionNumber,NumCellsInRegion);
    }

  vtkDebugMacro (<<"Extracted " << RegionNumber << " region(s)");
  vtkDebugMacro (<<"Exceeded recursion depth " << NumExceededMaxDepth
                << " times\n");

  RecursionSeeds->Delete();
//
// Now that points and cells have been marked, traverse these lists pulling
// everything that has been visited.
//
  //Pass through point data that has been visited
  pd = this->Input->GetPointData();
  if ( this->ColorRegions ) outputPD->CopyScalarsOff();
  outputPD->CopyAllocate(pd);

  for (i=0; i < numPts; i++)
    {
    if ( PointMap[i] > -1 )
      {
      newPts->SetPoint(PointMap[i],this->Input->GetPoint(i));
      outputPD->CopyData(pd,i,PointMap[i]);
      }
    }

  // if coloring regions; send down new scalar data
  if ( this->ColorRegions ) outputPD->SetScalars(NewScalars);
  NewScalars->Delete();

  output->SetPoints(newPts);
  newPts->Delete();
//
// Create output cells
//
  if ( this->ExtractionMode == VTK_EXTRACT_POINT_SEEDED_REGIONS ||
  this->ExtractionMode == VTK_EXTRACT_CELL_SEEDED_REGIONS )
    { // extract any cell that's been visited
    for (cellId=0; cellId < numCells; cellId++)
      {
      if ( Visited[cellId] >= 0 )
        {
        this->Input->GetCellPoints(cellId, ptIds);
        for (i=0; i < ptIds.GetNumberOfIds(); i++)
          {
          id = PointMap[ptIds.GetId(i)];
          ptIds.InsertId(i,id);
          }
        output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);
        }
      }
    }
  else if ( this->ExtractionMode == VTK_EXTRACT_SPECIFIED_REGIONS )
    {
    for (cellId=0; cellId < numCells; cellId++)
      {
      int inReg, regionId;
      if ( (regionId=Visited[cellId]) >= 0 )
        {
        for (inReg=0,i=0; i<this->SpecifiedRegionIds.GetNumberOfIds(); i++)
          {
          if ( regionId == this->SpecifiedRegionIds.GetId(i) )
            {
            inReg = 1;
            break;
            }
          }
        if ( inReg )
          {
          this->Input->GetCellPoints(cellId, ptIds);
          for (i=0; i < ptIds.GetNumberOfIds(); i++)
            {
            id = PointMap[ptIds.GetId(i)];
            ptIds.InsertId(i,id);
            }
          output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);
          }
        }
      }
    }
  else //extract largest region
    {
    for (cellId=0; cellId < numCells; cellId++)
      {
      if ( Visited[cellId] == largestRegionId )
        {
        this->Input->GetCellPoints(cellId, ptIds);
        for (i=0; i < ptIds.GetNumberOfIds(); i++)
          {
          id = PointMap[ptIds.GetId(i)];
          ptIds.InsertId(i,id);
          }
        output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);
        }
      }
   }

  delete [] Visited;
  delete [] PointMap;

  vtkDebugMacro (<<"Extracted " << output->GetNumberOfCells() << " cells");

  return;
}

//
// Mark current cell as visited and assign region number.  Note:
// traversal occurs across shared vertices.
//
void vtkConnectivityFilter::TraverseAndMark (int cellId)
{
  int j, k, ptId;
  vtkIdList ptIds, cellIds;

  Visited[cellId] = RegionNumber;
  NumCellsInRegion++;

  if ( RecursionDepth++ > this->MaxRecursionDepth )
    {
    RecursionSeeds->InsertNextId(cellId);
    NumExceededMaxDepth++;
    return;
    }

  this->Input->GetCellPoints(cellId, ptIds);

  for (j=0; j < ptIds.GetNumberOfIds(); j++)
    {
    if ( PointMap[ptId=ptIds.GetId(j)] < 0 )
      {
      PointMap[ptId] = PointNumber++;
      NewScalars->SetScalar(PointMap[ptId], RegionNumber);
      }

    this->Input->GetPointCells(ptId,cellIds);

    for (k=0; k < cellIds.GetNumberOfIds(); k++)
      if ( Visited[cellIds.GetId(k)] < 0 )
         TraverseAndMark (cellIds.GetId(k));

    } // for all cells of this element

  RecursionDepth--;
  return;
}

// Description:
// Obtain the number of connected regions.
int vtkConnectivityFilter::GetNumberOfExtractedRegions()
{
  return this->RegionSizes.GetSize();
}

// Description:
// Set the extraction mode to extract regions sharing specified point ids.
void vtkConnectivityFilter::ExtractPointSeededRegions()
{
  if ( this->ExtractionMode != VTK_EXTRACT_POINT_SEEDED_REGIONS )
    {
    this->Modified();
    this->ExtractionMode = VTK_EXTRACT_POINT_SEEDED_REGIONS;
    }
}

// Description:
// Set the extraction mode to extract regions sharing specified cell ids.
void vtkConnectivityFilter::ExtractCellSeededRegions()
{
  if ( this->ExtractionMode != VTK_EXTRACT_CELL_SEEDED_REGIONS )
    {
    this->Modified();
    this->ExtractionMode = VTK_EXTRACT_CELL_SEEDED_REGIONS;
    }
}

// Description:
// Set the extraction mode to extract regions of specified id. You may
// have to execute filter first (with debug turned on) to determine region ids.
void vtkConnectivityFilter::ExtractSpecifiedRegions()
{
  if ( this->ExtractionMode != VTK_EXTRACT_SPECIFIED_REGIONS )
    {
    this->Modified();
    this->ExtractionMode = VTK_EXTRACT_SPECIFIED_REGIONS;
    }
}

// Description:
// Set the extraction mode to extract the largest region found.
void vtkConnectivityFilter::ExtractLargestRegion()
{
  if ( this->ExtractionMode != VTK_EXTRACT_LARGEST_REGION )
    {
    this->Modified();
    this->ExtractionMode = VTK_EXTRACT_LARGEST_REGION;
    }
}

// Description:
// Initialize list of point ids/cell ids used to seed regions.
void vtkConnectivityFilter::InitializeSeedList()
{
  this->Modified();
  this->Seeds.Reset();
}

// Description:
// Add a seed id (point or cell id). Note: ids are 0-offset.
void vtkConnectivityFilter::AddSeed(int id)
{
  this->Modified();
  this->Seeds.InsertNextId(id);
}

// Description:
// Delete a seed id (point or cell id). Note: ids are 0-offset.
void vtkConnectivityFilter::DeleteSeed(int id)
{
  this->Modified();
  this->Seeds.DeleteId(id);
}

// Description:
// Initialize list of region ids to extract.
void vtkConnectivityFilter::InitializeSpecifiedRegionList()
{
  this->Modified();
  this->SpecifiedRegionIds.Reset();
}

// Description:
// Add a region id to extract. Note: ids are 0-offset.
void vtkConnectivityFilter::AddSpecifiedRegion(int id)
{
  this->Modified();
  this->SpecifiedRegionIds.InsertNextId(id);
}

// Description:
// Delete a region id to extract. Note: ids are 0-offset.
void vtkConnectivityFilter::DeleteSpecifiedRegion(int id)
{
  this->Modified();
  this->SpecifiedRegionIds.DeleteId(id);
}

void vtkConnectivityFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkDataSetToUnstructuredGridFilter::PrintSelf(os,indent);

  os << indent << "Extraction Mode: ";
  switch (this->ExtractionMode)
    {
    case VTK_EXTRACT_POINT_SEEDED_REGIONS:
      os << "(Extract point seeded regions)\n";
      break;
    case VTK_EXTRACT_CELL_SEEDED_REGIONS:
      os << "(Extract cell seeded regions)\n";
      break;
    case VTK_EXTRACT_SPECIFIED_REGIONS:
      os << "(Extract specified regions)\n";
      break;
    case VTK_EXTRACT_LARGEST_REGION:
      os << "(Extract largest region)\n";
      break;
    }

    os << indent << "Color Regions: " << (this->ColorRegions ? "On\n" : "Off\n");
    os << indent << "Maximum Recursion Depth: " << this->MaxRecursionDepth << "\n";
}

<commit_msg>minor fix<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkConnectivityFilter.cc
  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 "vtkConnectivityFilter.hh"

// Description:
// Construct with default extraction mode to extract largest regions.
vtkConnectivityFilter::vtkConnectivityFilter()
{
  this->ExtractionMode = VTK_EXTRACT_LARGEST_REGION;
  this->ColorRegions = 0;
  this->MaxRecursionDepth = 10000;
}

static int NumExceededMaxDepth;
static int *Visited, *PointMap;
static vtkFloatScalars *NewScalars;
static int RecursionDepth;
static int RegionNumber, PointNumber;
static int NumCellsInRegion;
static  vtkIdList *RecursionSeeds;

void vtkConnectivityFilter::Execute()
{
  int cellId, i, j, pt;
  int numPts, numCells;
  vtkFloatPoints *newPts;
  vtkIdList cellIds(VTK_CELL_SIZE), ptIds(VTK_CELL_SIZE);
  vtkPointData *pd;
  int id;
  int maxCellsInRegion, largestRegionId;
  vtkUnstructuredGrid *output = this->GetOutput();
  vtkPointData *outputPD = output->GetPointData();

  vtkDebugMacro(<<"Executing connectivity filter.");
  //
  //  Check input/allocate storage
  //
  if ( (numPts=this->Input->GetNumberOfPoints()) < 1 ||
  (numCells=this->Input->GetNumberOfCells()) < 1 )
    {
    vtkDebugMacro(<<"No data to connect!");
    return;
    }
  output->Allocate(numCells,numCells);
  //
  // Initialize.  Keep track of points and cells visited.
  //
  this->RegionSizes.Reset();
  Visited = new int[numCells];
  for ( i=0; i < numCells; i++ ) Visited[i] = -1;
  PointMap = new int[numPts];
  for ( i=0; i < numPts; i++ ) PointMap[i] = -1;

  NewScalars = new vtkFloatScalars(numPts);
  newPts = new vtkFloatPoints(numPts);
  //
  // Traverse all cells marking those visited.  Each new search
  // starts a new connected region.  Note: have to truncate recursion
  // and keep track of seeds to start up again.
  //
  RecursionSeeds = new vtkIdList(1000,10000);

  NumExceededMaxDepth = 0;
  PointNumber = 0;
  RegionNumber = 0;
  maxCellsInRegion = 0;

  if ( this->ExtractionMode != VTK_EXTRACT_POINT_SEEDED_REGIONS &&
  this->ExtractionMode != VTK_EXTRACT_CELL_SEEDED_REGIONS )
    { //visit all cells marking with region number
    for (cellId=0; cellId < numCells; cellId++)
      {
      if ( Visited[cellId] < 0 )
        {
        NumCellsInRegion = 0;
        RecursionDepth = 0;
        this->TraverseAndMark (cellId);

        for (i=0; i < RecursionSeeds->GetNumberOfIds(); i++)
          {
          RecursionDepth = 0;
          this->TraverseAndMark (RecursionSeeds->GetId(i));
          }

        if ( NumCellsInRegion > maxCellsInRegion )
          {
          maxCellsInRegion = NumCellsInRegion;
          largestRegionId = RegionNumber;
          }

        this->RegionSizes.InsertValue(RegionNumber++,NumCellsInRegion);
        RecursionSeeds->Reset();
        }
      }
    }
  else // regions have been seeded, everything considered in same region
    {
    NumCellsInRegion = 0;

    if ( this->ExtractionMode == VTK_EXTRACT_POINT_SEEDED_REGIONS )
      {
      for (i=0; i < this->Seeds.GetNumberOfIds(); i++)
        {
        pt = this->Seeds.GetId(i);
        if ( pt >= 0 )
          {
          this->Input->GetPointCells(pt,cellIds);
          for (j=0; j < cellIds.GetNumberOfIds(); j++)
            RecursionSeeds->InsertNextId(cellIds.GetId(j));
          }
        }
      }
    else if ( this->ExtractionMode == VTK_EXTRACT_CELL_SEEDED_REGIONS )
      {
      for (i=0; i < this->Seeds.GetNumberOfIds(); i++)
        {
        cellId = this->Seeds.GetId(i);
        if ( cellId >= 0 ) RecursionSeeds->InsertNextId(cellId);
        }
      }

    //mark all seeded regions
    for (i=0; i < RecursionSeeds->GetNumberOfIds(); i++)
      {
      RecursionDepth = 0;
      this->TraverseAndMark (RecursionSeeds->GetId(i));
      }
    this->RegionSizes.InsertValue(RegionNumber,NumCellsInRegion);
    }

  vtkDebugMacro (<<"Extracted " << RegionNumber << " region(s)");
  vtkDebugMacro (<<"Exceeded recursion depth " << NumExceededMaxDepth
                << " times\n");

  RecursionSeeds->Delete();
//
// Now that points and cells have been marked, traverse these lists pulling
// everything that has been visited.
//
  //Pass through point data that has been visited
  pd = this->Input->GetPointData();
  if ( this->ColorRegions ) outputPD->CopyScalarsOff();
  outputPD->CopyAllocate(pd);

  for (i=0; i < numPts; i++)
    {
    if ( PointMap[i] > -1 )
      {
      newPts->SetPoint(PointMap[i],this->Input->GetPoint(i));
      outputPD->CopyData(pd,i,PointMap[i]);
      }
    }

  // if coloring regions; send down new scalar data
  if ( this->ColorRegions ) outputPD->SetScalars(NewScalars);
  NewScalars->Delete();

  output->SetPoints(newPts);
  newPts->Delete();
//
// Create output cells
//
  if ( this->ExtractionMode == VTK_EXTRACT_POINT_SEEDED_REGIONS ||
  this->ExtractionMode == VTK_EXTRACT_CELL_SEEDED_REGIONS )
    { // extract any cell that's been visited
    for (cellId=0; cellId < numCells; cellId++)
      {
      if ( Visited[cellId] >= 0 )
        {
        this->Input->GetCellPoints(cellId, ptIds);
        for (i=0; i < ptIds.GetNumberOfIds(); i++)
          {
          id = PointMap[ptIds.GetId(i)];
          ptIds.InsertId(i,id);
          }
        output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);
        }
      }
    }
  else if ( this->ExtractionMode == VTK_EXTRACT_SPECIFIED_REGIONS )
    {
    for (cellId=0; cellId < numCells; cellId++)
      {
      int inReg, regionId;
      if ( (regionId=Visited[cellId]) >= 0 )
        {
        for (inReg=0,i=0; i<this->SpecifiedRegionIds.GetNumberOfIds(); i++)
          {
          if ( regionId == this->SpecifiedRegionIds.GetId(i) )
            {
            inReg = 1;
            break;
            }
          }
        if ( inReg )
          {
          this->Input->GetCellPoints(cellId, ptIds);
          for (i=0; i < ptIds.GetNumberOfIds(); i++)
            {
            id = PointMap[ptIds.GetId(i)];
            ptIds.InsertId(i,id);
            }
          output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);
          }
        }
      }
    }
  else //extract largest region
    {
    for (cellId=0; cellId < numCells; cellId++)
      {
      if ( Visited[cellId] == largestRegionId )
        {
        this->Input->GetCellPoints(cellId, ptIds);
        for (i=0; i < ptIds.GetNumberOfIds(); i++)
          {
          id = PointMap[ptIds.GetId(i)];
          ptIds.InsertId(i,id);
          }
        output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);
        }
      }
   }

  delete [] Visited;
  delete [] PointMap;

  vtkDebugMacro (<<"Extracted " << output->GetNumberOfCells() << " cells");

  return;
}

//
// Mark current cell as visited and assign region number.  Note:
// traversal occurs across shared vertices.
//
void vtkConnectivityFilter::TraverseAndMark (int cellId)
{
  int j, k, ptId;
  vtkIdList ptIds, cellIds;

  Visited[cellId] = RegionNumber;
  NumCellsInRegion++;

  if ( RecursionDepth++ > this->MaxRecursionDepth )
    {
    RecursionSeeds->InsertNextId(cellId);
    NumExceededMaxDepth++;
    return;
    }

  this->Input->GetCellPoints(cellId, ptIds);

  for (j=0; j < ptIds.GetNumberOfIds(); j++)
    {
    if ( PointMap[ptId=ptIds.GetId(j)] < 0 )
      {
      PointMap[ptId] = PointNumber++;
      NewScalars->SetScalar(PointMap[ptId], RegionNumber);
      }

    this->Input->GetPointCells(ptId,cellIds);

    for (k=0; k < cellIds.GetNumberOfIds(); k++)
      if ( Visited[cellIds.GetId(k)] < 0 )
         TraverseAndMark (cellIds.GetId(k));

    } // for all cells of this element

  RecursionDepth--;
  return;
}

// Description:
// Obtain the number of connected regions.
int vtkConnectivityFilter::GetNumberOfExtractedRegions()
{
  return this->RegionSizes.GetSize();
}

// Description:
// Set the extraction mode to extract regions sharing specified point ids.
void vtkConnectivityFilter::ExtractPointSeededRegions()
{
  if ( this->ExtractionMode != VTK_EXTRACT_POINT_SEEDED_REGIONS )
    {
    this->Modified();
    this->ExtractionMode = VTK_EXTRACT_POINT_SEEDED_REGIONS;
    }
}

// Description:
// Set the extraction mode to extract regions sharing specified cell ids.
void vtkConnectivityFilter::ExtractCellSeededRegions()
{
  if ( this->ExtractionMode != VTK_EXTRACT_CELL_SEEDED_REGIONS )
    {
    this->Modified();
    this->ExtractionMode = VTK_EXTRACT_CELL_SEEDED_REGIONS;
    }
}

// Description:
// Set the extraction mode to extract regions of specified id. You may
// have to execute filter first (with debug turned on) to determine region ids.
void vtkConnectivityFilter::ExtractSpecifiedRegions()
{
  if ( this->ExtractionMode != VTK_EXTRACT_SPECIFIED_REGIONS )
    {
    this->Modified();
    this->ExtractionMode = VTK_EXTRACT_SPECIFIED_REGIONS;
    }
}

// Description:
// Set the extraction mode to extract the largest region found.
void vtkConnectivityFilter::ExtractLargestRegion()
{
  if ( this->ExtractionMode != VTK_EXTRACT_LARGEST_REGION )
    {
    this->Modified();
    this->ExtractionMode = VTK_EXTRACT_LARGEST_REGION;
    }
}

// Description:
// Initialize list of point ids/cell ids used to seed regions.
void vtkConnectivityFilter::InitializeSeedList()
{
  this->Modified();
  this->Seeds.Reset();
}

// Description:
// Add a seed id (point or cell id). Note: ids are 0-offset.
void vtkConnectivityFilter::AddSeed(int id)
{
  this->Modified();
  this->Seeds.InsertNextId(id);
}

// Description:
// Delete a seed id (point or cell id). Note: ids are 0-offset.
void vtkConnectivityFilter::DeleteSeed(int id)
{
  this->Modified();
  this->Seeds.DeleteId(id);
}

// Description:
// Initialize list of region ids to extract.
void vtkConnectivityFilter::InitializeSpecifiedRegionList()
{
  this->Modified();
  this->SpecifiedRegionIds.Reset();
}

// Description:
// Add a region id to extract. Note: ids are 0-offset.
void vtkConnectivityFilter::AddSpecifiedRegion(int id)
{
  this->Modified();
  this->SpecifiedRegionIds.InsertNextId(id);
}

// Description:
// Delete a region id to extract. Note: ids are 0-offset.
void vtkConnectivityFilter::DeleteSpecifiedRegion(int id)
{
  this->Modified();
  this->SpecifiedRegionIds.DeleteId(id);
}

void vtkConnectivityFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkDataSetToUnstructuredGridFilter::PrintSelf(os,indent);

  os << indent << "Extraction Mode: ";
  switch (this->ExtractionMode)
    {
    case VTK_EXTRACT_POINT_SEEDED_REGIONS:
      os << "(Extract point seeded regions)\n";
      break;
    case VTK_EXTRACT_CELL_SEEDED_REGIONS:
      os << "(Extract cell seeded regions)\n";
      break;
    case VTK_EXTRACT_SPECIFIED_REGIONS:
      os << "(Extract specified regions)\n";
      break;
    case VTK_EXTRACT_LARGEST_REGION:
      os << "(Extract largest region)\n";
      break;
    }

    os << indent << "Color Regions: " << (this->ColorRegions ? "On\n" : "Off\n");
    os << indent << "Maximum Recursion Depth: " << this->MaxRecursionDepth << "\n";
}

<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <af/version.h>
#include <platform.hpp>
#include <driver.h>
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <stdexcept>
#include <cstdio>
#include <cstring>
#include <err_cuda.hpp>

//Macro for checking cuda errors following a cuda launch or api call
#define CUDA(call)                                                  \
do {                                                                \
    cudaError_t err = call;                                         \
    if (cudaSuccess != err) {                                       \
        fprintf (stderr, "CUDA Error in %s:%d : %s.",               \
                 __FILE__, __LINE__, cudaGetErrorString(err));      \
        exit(EXIT_FAILURE);                                         \
    }                                                               \
} while (0);                                                        \

using namespace std;

namespace cuda
{

///////////////////////////////////////////////////////////////////////////
// HELPERS
///////////////////////////////////////////////////////////////////////////
// pulled from CUTIL from CUDA SDK
static inline int compute2cores(int major, int minor)
{
    struct {
        int compute; // 0xMm (hex), M = major version, m = minor version
        int cores;
    } gpus[] = {
        { 0x10,  8 },
        { 0x11,  8 },
        { 0x12,  8 },
        { 0x13,  8 },
        { 0x20, 32 },
        { 0x21, 48 },
        { 0x30, 192 },
        { 0x35, 192 },
        { 0x50, 128 },
        {   -1, -1  },
    };

    for (int i = 0; gpus[i].compute != -1; ++i) {
        if (gpus[i].compute == (major << 4) + minor)
            return gpus[i].cores;
    }
    return 0;
}

// compare two cards based on (in order):
//   1. flops (theoretical)
//   2. total memory

#define COMPARE(a,b,f) do {                     \
        return ((a)->f >= (b)->f);              \
    } while (0);

static inline bool card_compare_compute(const cudaDevice_t &l, const cudaDevice_t &r)
{
    const cudaDevice_t *lc = &l;
    const cudaDevice_t *rc = &r;

    COMPARE(lc, rc, prop.major);
    COMPARE(lc, rc, prop.minor);
    COMPARE(lc, rc, flops);
    COMPARE(lc, rc, prop.totalGlobalMem);
    COMPARE(lc, rc, nativeId);
    return 0;
}

static inline bool card_compare_flops(const cudaDevice_t &l, const cudaDevice_t &r)
{
    const cudaDevice_t *lc = &l;
    const cudaDevice_t *rc = &r;

    COMPARE(lc, rc, flops);
    COMPARE(lc, rc, prop.totalGlobalMem);
    COMPARE(lc, rc, prop.major);
    COMPARE(lc, rc, prop.minor);
    COMPARE(lc, rc, nativeId);
    return 0;
}

static inline bool card_compare_mem(const cudaDevice_t &l, const cudaDevice_t &r)
{
    const cudaDevice_t *lc = &l;
    const cudaDevice_t *rc = &r;

    COMPARE(lc, rc, prop.totalGlobalMem);
    COMPARE(lc, rc, flops);
    COMPARE(lc, rc, prop.major);
    COMPARE(lc, rc, prop.minor);
    COMPARE(lc, rc, nativeId);
    return 0;
}

static inline bool card_compare_num(const cudaDevice_t &l, const cudaDevice_t &r)
{
    const cudaDevice_t *lc = &l;
    const cudaDevice_t *rc = &r;

    COMPARE(lc, rc, nativeId);
    return 0;
}

static const char *get_system(void)
{
    return
#if defined(ARCH_32)
    "32-bit "
#elif defined(ARCH_64)
    "64-bit "
#endif

#if defined(OS_LNX)
    "Linux";
#elif defined(OS_WIN)
    "Windows";
#elif defined(OS_MAC)
    "Mac OSX";
#endif
}

template <typename T>
static inline string toString(T val)
{
    stringstream s;
    s << val;
    return s.str();
}

///////////////////////////////////////////////////////////////////////////
// Wrapper Functions
///////////////////////////////////////////////////////////////////////////
string getInfo()
{
    ostringstream info;
    info << "ArrayFire v" << AF_VERSION
         << " (CUDA, " << get_system() << ", build " << AF_REVISION << ")" << std::endl;
    info << getPlatformInfo();
    for (int i = 0; i < getDeviceCount(); ++i) {
        info << getDeviceInfo(i);
    }
    return info.str();
}

string getDeviceInfo(int device)
{
    cudaDeviceProp dev = getDeviceProp(device);

    size_t mem_gpu_total = dev.totalGlobalMem;
    //double cc = double(dev.major) + double(dev.minor) / 10;

    bool show_braces = getActiveDeviceId() == device;

    string id = (show_braces ? string("[") : "-") + toString(device) +
                (show_braces ? string("]") : "-");
    string name(dev.name);
    string memory = toString((mem_gpu_total / (1024 * 1024))
                          + !!(mem_gpu_total % (1024 * 1024)))
                    + string(" MB");
    string compute = string("CUDA Compute ") + toString(dev.major) + string(".") + toString(dev.minor);

    string info = id + string(" ")  +
                name + string(", ") +
              memory + string(", ") +
             compute + string("\n");
    return info;
}

string getPlatformInfo()
{
    string driverVersion = getDriverVersion();
    std::string cudaRuntime = getCUDARuntimeVersion();
    string platform = "Platform: CUDA Toolkit " + cudaRuntime;
    if (!driverVersion.empty()) {
        platform.append(", Driver: ");
        platform.append(driverVersion);
    }
    platform.append("\n");
    return platform;
}

bool isDoubleSupported(int device)
{
    return true;
}

void devprop(char* d_name, char* d_platform, char *d_toolkit, char* d_compute)
{
    if (getDeviceCount() <= 0) {
        printf("No CUDA-capable devices detected.\n");
        return;
    }

    cudaDeviceProp dev = getDeviceProp(getActiveDeviceId());

    // Name
    snprintf(d_name, 32, "%s", dev.name);

    //Platform
    std::string cudaRuntime = getCUDARuntimeVersion();
    snprintf(d_platform, 10, "CUDA");
    snprintf(d_toolkit, 64, "v%s", cudaRuntime.c_str());

    // Compute Version
    snprintf(d_compute, 10, "%d.%d", dev.major, dev.minor);

    // Sanitize input
    for (int i = 0; i < 31; i++) {
        if (d_name[i] == ' ') {
            if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') d_name[i] = 0;
            else d_name[i] = '_';
        }
    }
}

string getDriverVersion()
{
    char driverVersion[1024] = {" ",};
    int x = nvDriverVersion(driverVersion, sizeof(driverVersion));
    if (x != 1) {
        #if !defined(OS_MAC) && !defined(__arm__)  // HACK Mac OSX 10.7 needs new method for fetching driver
        throw runtime_error("Invalid driver");
        #endif
        int driver = 0;
        CUDA(cudaDriverGetVersion(&driver));
        return string("CUDA Driver Version: ") + toString(driver);
    } else {
        return string(driverVersion);
    }
}

string getCUDARuntimeVersion()
{
    int runtime = 0;
    CUDA(cudaRuntimeGetVersion(&runtime));
    if(runtime / 100.f > 0)
        return toString((runtime / 1000) + (runtime % 1000)/ 100.);
    else
        return toString(runtime / 1000) + string(".0");

}

int getDeviceCount()
{
    return DeviceManager::getInstance().nDevices;
}

int getActiveDeviceId()
{
    return DeviceManager::getInstance().activeDev;
}

int getDeviceNativeId(int device)
{
    if(device < (int)DeviceManager::getInstance().cuDevices.size())
        return DeviceManager::getInstance().cuDevices[device].nativeId;
    return -1;
}

int setDevice(int device)
{
    return DeviceManager::getInstance().setActiveDevice(device);
}

cudaDeviceProp getDeviceProp(int device)
{
    if(device < (int)DeviceManager::getInstance().cuDevices.size())
        return DeviceManager::getInstance().cuDevices[device].prop;
    return DeviceManager::getInstance().cuDevices[0].prop;
}

///////////////////////////////////////////////////////////////////////////
// DeviceManager Class Functions
///////////////////////////////////////////////////////////////////////////
DeviceManager& DeviceManager::getInstance()
{
    static DeviceManager my_instance;
    return my_instance;
}

DeviceManager::DeviceManager()
    : cuDevices(0), activeDev(0), nDevices(0)
{
    CUDA(cudaGetDeviceCount(&nDevices));
    if (nDevices == 0)
        throw runtime_error("No CUDA-Capable devices found");

    cuDevices.reserve(nDevices);

    for(int i = 0; i < nDevices; i++) {
        cudaDevice_t dev;
        cudaGetDeviceProperties(&dev.prop, i);
        dev.flops = dev.prop.multiProcessorCount * compute2cores(dev.prop.major, dev.prop.minor) * dev.prop.clockRate;
        dev.nativeId = i;
        cuDevices.push_back(dev);
    }

    sortDevices();

    const char* deviceENV = getenv("AF_CUDA_DEFAULT_DEVICE");
    if(!deviceENV) {
        setActiveDevice(0, cuDevices[0].nativeId);
    } else {
        stringstream s(deviceENV);
        int def_device = -1;
        s >> def_device;
        if(def_device < 0 || def_device >= nDevices) {
            printf("WARNING: AF_CUDA_DEFAULT_DEVICE is out of range\n");
            printf("Setting default device as 0\n");
            setActiveDevice(0, cuDevices[0].nativeId);
        } else {
            setActiveDevice(def_device, cuDevices[def_device].nativeId);
        }
    }
}

void DeviceManager::sortDevices(sort_mode mode)
{
    switch(mode) {
        case memory :
            sort(cuDevices.begin(), cuDevices.end(), card_compare_mem);
            break;
        case flops :
            sort(cuDevices.begin(), cuDevices.end(), card_compare_flops);
            break;
        case compute :
            sort(cuDevices.begin(), cuDevices.end(), card_compare_compute);
            break;
        case none : default :
            sort(cuDevices.begin(), cuDevices.end(), card_compare_num);
            break;
    }
}

int DeviceManager::setActiveDevice(int device, int nId)
{
    if(device > (int)cuDevices.size()) {
        return -1;
    } else {
        int old = activeDev;
        if(nId == -1) nId = getDeviceNativeId(device);
        CUDA(cudaSetDevice(nId));
        activeDev = device;
        return old;
    }
}

void sync(int device)
{
    int currDevice = getActiveDeviceId();
    setDevice(device);
    CUDA_CHECK(cudaDeviceSynchronize());
    setDevice(currDevice);
}

}
<commit_msg>Fixing the cuda error check in cuda/platform.cpp<commit_after>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <af/version.h>
#include <platform.hpp>
#include <driver.h>
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <stdexcept>
#include <cstdio>
#include <cstring>
#include <err_cuda.hpp>

using namespace std;

namespace cuda
{

///////////////////////////////////////////////////////////////////////////
// HELPERS
///////////////////////////////////////////////////////////////////////////
// pulled from CUTIL from CUDA SDK
static inline int compute2cores(int major, int minor)
{
    struct {
        int compute; // 0xMm (hex), M = major version, m = minor version
        int cores;
    } gpus[] = {
        { 0x10,  8 },
        { 0x11,  8 },
        { 0x12,  8 },
        { 0x13,  8 },
        { 0x20, 32 },
        { 0x21, 48 },
        { 0x30, 192 },
        { 0x35, 192 },
        { 0x50, 128 },
        {   -1, -1  },
    };

    for (int i = 0; gpus[i].compute != -1; ++i) {
        if (gpus[i].compute == (major << 4) + minor)
            return gpus[i].cores;
    }
    return 0;
}

// compare two cards based on (in order):
//   1. flops (theoretical)
//   2. total memory

#define COMPARE(a,b,f) do {                     \
        return ((a)->f >= (b)->f);              \
    } while (0);

static inline bool card_compare_compute(const cudaDevice_t &l, const cudaDevice_t &r)
{
    const cudaDevice_t *lc = &l;
    const cudaDevice_t *rc = &r;

    COMPARE(lc, rc, prop.major);
    COMPARE(lc, rc, prop.minor);
    COMPARE(lc, rc, flops);
    COMPARE(lc, rc, prop.totalGlobalMem);
    COMPARE(lc, rc, nativeId);
    return 0;
}

static inline bool card_compare_flops(const cudaDevice_t &l, const cudaDevice_t &r)
{
    const cudaDevice_t *lc = &l;
    const cudaDevice_t *rc = &r;

    COMPARE(lc, rc, flops);
    COMPARE(lc, rc, prop.totalGlobalMem);
    COMPARE(lc, rc, prop.major);
    COMPARE(lc, rc, prop.minor);
    COMPARE(lc, rc, nativeId);
    return 0;
}

static inline bool card_compare_mem(const cudaDevice_t &l, const cudaDevice_t &r)
{
    const cudaDevice_t *lc = &l;
    const cudaDevice_t *rc = &r;

    COMPARE(lc, rc, prop.totalGlobalMem);
    COMPARE(lc, rc, flops);
    COMPARE(lc, rc, prop.major);
    COMPARE(lc, rc, prop.minor);
    COMPARE(lc, rc, nativeId);
    return 0;
}

static inline bool card_compare_num(const cudaDevice_t &l, const cudaDevice_t &r)
{
    const cudaDevice_t *lc = &l;
    const cudaDevice_t *rc = &r;

    COMPARE(lc, rc, nativeId);
    return 0;
}

static const char *get_system(void)
{
    return
#if defined(ARCH_32)
    "32-bit "
#elif defined(ARCH_64)
    "64-bit "
#endif

#if defined(OS_LNX)
    "Linux";
#elif defined(OS_WIN)
    "Windows";
#elif defined(OS_MAC)
    "Mac OSX";
#endif
}

template <typename T>
static inline string toString(T val)
{
    stringstream s;
    s << val;
    return s.str();
}

///////////////////////////////////////////////////////////////////////////
// Wrapper Functions
///////////////////////////////////////////////////////////////////////////
string getInfo()
{
    ostringstream info;
    info << "ArrayFire v" << AF_VERSION
         << " (CUDA, " << get_system() << ", build " << AF_REVISION << ")" << std::endl;
    info << getPlatformInfo();
    for (int i = 0; i < getDeviceCount(); ++i) {
        info << getDeviceInfo(i);
    }
    return info.str();
}

string getDeviceInfo(int device)
{
    cudaDeviceProp dev = getDeviceProp(device);

    size_t mem_gpu_total = dev.totalGlobalMem;
    //double cc = double(dev.major) + double(dev.minor) / 10;

    bool show_braces = getActiveDeviceId() == device;

    string id = (show_braces ? string("[") : "-") + toString(device) +
                (show_braces ? string("]") : "-");
    string name(dev.name);
    string memory = toString((mem_gpu_total / (1024 * 1024))
                          + !!(mem_gpu_total % (1024 * 1024)))
                    + string(" MB");
    string compute = string("CUDA Compute ") + toString(dev.major) + string(".") + toString(dev.minor);

    string info = id + string(" ")  +
                name + string(", ") +
              memory + string(", ") +
             compute + string("\n");
    return info;
}

string getPlatformInfo()
{
    string driverVersion = getDriverVersion();
    std::string cudaRuntime = getCUDARuntimeVersion();
    string platform = "Platform: CUDA Toolkit " + cudaRuntime;
    if (!driverVersion.empty()) {
        platform.append(", Driver: ");
        platform.append(driverVersion);
    }
    platform.append("\n");
    return platform;
}

bool isDoubleSupported(int device)
{
    return true;
}

void devprop(char* d_name, char* d_platform, char *d_toolkit, char* d_compute)
{
    if (getDeviceCount() <= 0) {
        printf("No CUDA-capable devices detected.\n");
        return;
    }

    cudaDeviceProp dev = getDeviceProp(getActiveDeviceId());

    // Name
    snprintf(d_name, 32, "%s", dev.name);

    //Platform
    std::string cudaRuntime = getCUDARuntimeVersion();
    snprintf(d_platform, 10, "CUDA");
    snprintf(d_toolkit, 64, "v%s", cudaRuntime.c_str());

    // Compute Version
    snprintf(d_compute, 10, "%d.%d", dev.major, dev.minor);

    // Sanitize input
    for (int i = 0; i < 31; i++) {
        if (d_name[i] == ' ') {
            if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') d_name[i] = 0;
            else d_name[i] = '_';
        }
    }
}

string getDriverVersion()
{
    char driverVersion[1024] = {" ",};
    int x = nvDriverVersion(driverVersion, sizeof(driverVersion));
    if (x != 1) {
        #if !defined(OS_MAC) && !defined(__arm__)  // HACK Mac OSX 10.7 needs new method for fetching driver
        throw runtime_error("Invalid driver");
        #endif
        int driver = 0;
        CUDA_CHECK(cudaDriverGetVersion(&driver));
        return string("CUDA Driver Version: ") + toString(driver);
    } else {
        return string(driverVersion);
    }
}

string getCUDARuntimeVersion()
{
    int runtime = 0;
    CUDA_CHECK(cudaRuntimeGetVersion(&runtime));
    if(runtime / 100.f > 0)
        return toString((runtime / 1000) + (runtime % 1000)/ 100.);
    else
        return toString(runtime / 1000) + string(".0");

}

int getDeviceCount()
{
    return DeviceManager::getInstance().nDevices;
}

int getActiveDeviceId()
{
    return DeviceManager::getInstance().activeDev;
}

int getDeviceNativeId(int device)
{
    if(device < (int)DeviceManager::getInstance().cuDevices.size())
        return DeviceManager::getInstance().cuDevices[device].nativeId;
    return -1;
}

int setDevice(int device)
{
    return DeviceManager::getInstance().setActiveDevice(device);
}

cudaDeviceProp getDeviceProp(int device)
{
    if(device < (int)DeviceManager::getInstance().cuDevices.size())
        return DeviceManager::getInstance().cuDevices[device].prop;
    return DeviceManager::getInstance().cuDevices[0].prop;
}

///////////////////////////////////////////////////////////////////////////
// DeviceManager Class Functions
///////////////////////////////////////////////////////////////////////////
DeviceManager& DeviceManager::getInstance()
{
    static DeviceManager my_instance;
    return my_instance;
}

DeviceManager::DeviceManager()
    : cuDevices(0), activeDev(0), nDevices(0)
{
    CUDA_CHECK(cudaGetDeviceCount(&nDevices));
    if (nDevices == 0)
        throw runtime_error("No CUDA-Capable devices found");

    cuDevices.reserve(nDevices);

    for(int i = 0; i < nDevices; i++) {
        cudaDevice_t dev;
        cudaGetDeviceProperties(&dev.prop, i);
        dev.flops = dev.prop.multiProcessorCount * compute2cores(dev.prop.major, dev.prop.minor) * dev.prop.clockRate;
        dev.nativeId = i;
        cuDevices.push_back(dev);
    }

    sortDevices();

    const char* deviceENV = getenv("AF_CUDA_DEFAULT_DEVICE");
    if(!deviceENV) {
        setActiveDevice(0, cuDevices[0].nativeId);
    } else {
        stringstream s(deviceENV);
        int def_device = -1;
        s >> def_device;
        if(def_device < 0 || def_device >= nDevices) {
            printf("WARNING: AF_CUDA_DEFAULT_DEVICE is out of range\n");
            printf("Setting default device as 0\n");
            setActiveDevice(0, cuDevices[0].nativeId);
        } else {
            setActiveDevice(def_device, cuDevices[def_device].nativeId);
        }
    }
}

void DeviceManager::sortDevices(sort_mode mode)
{
    switch(mode) {
        case memory :
            sort(cuDevices.begin(), cuDevices.end(), card_compare_mem);
            break;
        case flops :
            sort(cuDevices.begin(), cuDevices.end(), card_compare_flops);
            break;
        case compute :
            sort(cuDevices.begin(), cuDevices.end(), card_compare_compute);
            break;
        case none : default :
            sort(cuDevices.begin(), cuDevices.end(), card_compare_num);
            break;
    }
}

int DeviceManager::setActiveDevice(int device, int nId)
{
    if(device > (int)cuDevices.size()) {
        return -1;
    } else {
        int old = activeDev;
        if(nId == -1) nId = getDeviceNativeId(device);
        CUDA_CHECK(cudaSetDevice(nId));
        activeDev = device;
        return old;
    }
}

void sync(int device)
{
    int currDevice = getActiveDeviceId();
    setDevice(device);
    CUDA_CHECK(cudaDeviceSynchronize());
    setDevice(currDevice);
}

}
<|endoftext|>


<commit_before>/*!
@file

@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_SEQUENCES_RANGE_HPP
#define BOOST_BRIGAND_SEQUENCES_RANGE_HPP

#include <brigand/config.hpp>
#include <brigand/sequences/list.hpp>
#include <brigand/types/integral_constant.hpp>

namespace brigand
{
namespace detail
{
    template <class T, class, class, T>
    struct range_cat;

#ifdef BRIGAND_COMP_MSVC
    template <class T, T Start, T Int>
    struct int_plus
    {
        using type = brigand::integral_constant<T, Start + Int>;
    };
#endif

    template <class T, class... Ts, T... Ints, T Start>
    struct range_cat<T, list<Ts...>, list<brigand::integral_constant<T, Ints>...>, Start>
    {
#ifdef BRIGAND_COMP_MSVC
        using type = list<Ts..., typename int_plus<T, Start, Ints>::type...>;
#else
        using type = list<Ts..., brigand::integral_constant<T, Start + Ints>...>;
#endif
    };

    template <class T, T Start, unsigned int N>
    struct range_impl : range_cat<T, typename range_impl<T, Start, N / 2>::type,
                                  typename range_impl<T, Start, N - N / 2>::type, N / 2>
    {
    };

    template <class T, T Start>
    struct range_impl<T, Start, 1>
    {
        using type = list<brigand::integral_constant<T, Start>>;
    };

    template <class T, T Start>
    struct range_impl<T, Start, 0>
    {
        using type = list<>;
    };

    template <class T, class, class, T>
    struct reverse_range_cat;

#ifdef BRIGAND_COMP_MSVC
    template <class T, T Start, T Int>
    struct int_minus
    {
        using type = brigand::integral_constant<T, Int - Start>;
    };
#endif

    template <class T, class... Ts, T... Ints, T Start>
    struct reverse_range_cat<T, list<Ts...>, list<brigand::integral_constant<T, Ints>...>, Start>
    {
#ifdef BRIGAND_COMP_MSVC
        using type = list<Ts..., typename int_minus<T, Start, Ints>::type...>;
#else
        using type = list<Ts..., brigand::integral_constant<T, Ints - Start>...>;
#endif
    };

    template <class T, T Start, unsigned int N>
    struct reverse_range_impl
        : reverse_range_cat<T, typename reverse_range_impl<T, Start, N / 2>::type,
                            typename reverse_range_impl<T, Start, N - N / 2>::type, N / 2>
    {
    };

    template <class T, T Start>
    struct reverse_range_impl<T, Start, 1>
    {
        using type = list<brigand::integral_constant<T, Start>>;
    };

    template <class T, T Start>
    struct reverse_range_impl<T, Start, 0>
    {
        using type = list<>;
    };

    template <class T, T Start, T Stop>
    struct reverse_range_safe
    {
        static_assert(
            Start >= Stop,
            "Invalid parameters. reverse_range<> syntax is reverse_range<type, from, down_to>");
        using type = typename reverse_range_impl<T, Start, Start - Stop>::type;
    };
}

template <class T, T Start, T Stop>
using range = typename detail::range_impl<T, Start, Stop - Start>::type;

template <class T, T Start, T Stop>
using reverse_range = typename detail::reverse_range_safe<T, Start, Stop>::type;
}
#endif
<commit_msg>Delete range.hpp<commit_after><|endoftext|>


<commit_before>#include "walrus_joystick_controller/joystick_controller.h"
#include "geometry_msgs/Twist.h"
#include "std_msgs/Float64.h"

namespace walrus_joystick_controller {

JoystickController::JoystickController(ros::NodeHandle& nh, ros::NodeHandle& pnh)
{
  pnh.param<int>("axis_linear", axis_linear_, 1);
  pnh.param<double>("scale_linear", scale_linear_, 0.5);

  pnh.param<int>("axis_angular", axis_angular_, 0);
  pnh.param<double>("scale_angular", scale_angular_, 1.0);

  pnh.param<int>("button_pods_up", button_pods_up_, 0);
  pnh.param<int>("button_pods_toes", button_pods_toes_, 1);
  pnh.param<int>("button_pods_flat", button_pods_flat_, 2);

  joy_sub_ = nh.subscribe<sensor_msgs::Joy>("joy", 1, &JoystickController::joyCallback, this);
  enabled_sub_ = nh.subscribe<std_msgs::Bool>("enabled", 1, &JoystickController::enabledCallback, this);

  cmd_vel_pub_ = nh.advertise<geometry_msgs::Twist>("cmd_vel", 1);

  back_left_pod_pub_ = nh.advertise<std_msgs::Float64>("back_left_pod_joint_controller/command", 1);
  back_right_pod_pub_ = nh.advertise<std_msgs::Float64>("back_right_pod_joint_controller/command", 1);
  front_left_pod_pub_ = nh.advertise<std_msgs::Float64>("front_left_pod_joint_controller/command", 1);
  front_right_pod_pub_ = nh.advertise<std_msgs::Float64>("front_right_pod_joint_controller/command", 1);
}

void JoystickController::joyCallback(const sensor_msgs::Joy::ConstPtr& joy_msg)
{
  if(enabled_)
  {
    geometry_msgs::Twist twist_msg;

    twist_msg.linear.x = joy_msg->axes[axis_linear_] * scale_linear_;
    twist_msg.angular.z = joy_msg->axes[axis_angular_] * scale_angular_;
    cmd_vel_pub_.publish(twist_msg);

    if(joy_msg->buttons[button_pods_up_]) {
      publishPodAngles(0.3);
    }
    else if(joy_msg->buttons[button_pods_toes_]) {
      publishPodAngles(-0.3);
    }
    else if(joy_msg->buttons[button_pods_flat_]) {
      publishPodAngles(0.0);
    }
  }
}

void JoystickController::publishPodAngles(double angle) {
  std_msgs::Float64 angle_msg;
  angle_msg.data = angle;
  std_msgs::Float64 negated_angle_msg;
  negated_angle_msg.data = -angle;

  back_left_pod_pub_.publish(angle_msg);
  back_right_pod_pub_.publish(angle_msg);

  front_left_pod_pub_.publish(negated_angle_msg);
  front_right_pod_pub_.publish(negated_angle_msg);
}

void JoystickController::enabledCallback(const std_msgs::Bool::ConstPtr& bool_msg)
{
  enabled_ = bool_msg->data;

  if(enabled_)
  {
    // Publish zero twist
    geometry_msgs::Twist twist_msg;
    cmd_vel_pub_.publish(twist_msg);
  }
}

}

<commit_msg>Move pods more when using joystick<commit_after>#include "walrus_joystick_controller/joystick_controller.h"
#include "geometry_msgs/Twist.h"
#include "std_msgs/Float64.h"

namespace walrus_joystick_controller {

JoystickController::JoystickController(ros::NodeHandle& nh, ros::NodeHandle& pnh)
{
  pnh.param<int>("axis_linear", axis_linear_, 1);
  pnh.param<double>("scale_linear", scale_linear_, 0.5);

  pnh.param<int>("axis_angular", axis_angular_, 0);
  pnh.param<double>("scale_angular", scale_angular_, 1.0);

  pnh.param<int>("button_pods_up", button_pods_up_, 0);
  pnh.param<int>("button_pods_toes", button_pods_toes_, 1);
  pnh.param<int>("button_pods_flat", button_pods_flat_, 2);

  joy_sub_ = nh.subscribe<sensor_msgs::Joy>("joy", 1, &JoystickController::joyCallback, this);
  enabled_sub_ = nh.subscribe<std_msgs::Bool>("enabled", 1, &JoystickController::enabledCallback, this);

  cmd_vel_pub_ = nh.advertise<geometry_msgs::Twist>("cmd_vel", 1);

  back_left_pod_pub_ = nh.advertise<std_msgs::Float64>("back_left_pod_joint_controller/command", 1);
  back_right_pod_pub_ = nh.advertise<std_msgs::Float64>("back_right_pod_joint_controller/command", 1);
  front_left_pod_pub_ = nh.advertise<std_msgs::Float64>("front_left_pod_joint_controller/command", 1);
  front_right_pod_pub_ = nh.advertise<std_msgs::Float64>("front_right_pod_joint_controller/command", 1);
}

void JoystickController::joyCallback(const sensor_msgs::Joy::ConstPtr& joy_msg)
{
  if(enabled_)
  {
    geometry_msgs::Twist twist_msg;

    twist_msg.linear.x = joy_msg->axes[axis_linear_] * scale_linear_;
    twist_msg.angular.z = joy_msg->axes[axis_angular_] * scale_angular_;
    cmd_vel_pub_.publish(twist_msg);

    if(joy_msg->buttons[button_pods_up_]) {
      publishPodAngles(0.6);
    }
    else if(joy_msg->buttons[button_pods_toes_]) {
      publishPodAngles(-0.6);
    }
    else if(joy_msg->buttons[button_pods_flat_]) {
      publishPodAngles(0.0);
    }
  }
}

void JoystickController::publishPodAngles(double angle) {
  std_msgs::Float64 angle_msg;
  angle_msg.data = angle;
  std_msgs::Float64 negated_angle_msg;
  negated_angle_msg.data = -angle;

  back_left_pod_pub_.publish(angle_msg);
  back_right_pod_pub_.publish(angle_msg);

  front_left_pod_pub_.publish(negated_angle_msg);
  front_right_pod_pub_.publish(negated_angle_msg);
}

void JoystickController::enabledCallback(const std_msgs::Bool::ConstPtr& bool_msg)
{
  enabled_ = bool_msg->data;

  if(enabled_)
  {
    // Publish zero twist
    geometry_msgs::Twist twist_msg;
    cmd_vel_pub_.publish(twist_msg);
  }
}

}

<|endoftext|>


<commit_before>#include <vector>
#include <memory>
#include <iostream>
#include <utility>
#include <string>
#include <uv.h>

#include "worker_thread.h"
#include "worker_platform.h"
#include "../log.h"
#include "../queue.h"
#include "../message.h"
#include "../result.h"

using std::endl;
using std::vector;
using std::unique_ptr;
using std::move;
using std::string;

WorkerThread::WorkerThread(uv_async_t *main_callback) :
  Thread(this, &WorkerThread::listen, "worker thread", main_callback),
  platform{WorkerPlatform::for_worker(this)}
{
  //
}

WorkerThread::~WorkerThread()
{
  // Necessary so that unique_ptr can see the full definition of WorkerPlatform
}

Result<> WorkerThread::wake()
{
  return platform->wake();
}

void WorkerThread::listen()
{
  // Handle any commands that were enqueued while the thread was starting.
  Result<> cr = handle_commands();
  if (cr.is_error()) {
    LOGGER << "Unable to handle initially enqueued commands: " << cr << endl;
  }

  Result<> lr = platform->listen();
  if (lr.is_error()) {
    LOGGER << "Unable to listen: " << lr << endl;
    report_error(string(lr.get_error()));
  } else {
    LOGGER << "listen unexpectedly returned without reporting an error." << endl;
  }
}

Result<> WorkerThread::handle_commands()
{
  Result< unique_ptr<vector<Message>> > pr = process_all();
  if (pr.is_error()) {
    return error_result(string(pr.get_error()));
  }

  unique_ptr<vector<Message>> &accepted = pr.get_value();
  if (!accepted) {
    // No command messages to accept.
    return ok_result();
  }

  vector<Message> acks;
  acks.reserve(accepted->size());

  for (auto it = accepted->begin(); it != accepted->end(); ++it) {
    const CommandPayload *command = it->as_command();
    if (!command) {
      LOGGER << "Received unexpected message " << *it << "." << endl;
      continue;
    }

    bool success = true;
    string message = "";

    switch (command->get_action()) {
      case COMMAND_ADD:
        {
          Result<> r = platform->handle_add_command(command->get_channel_id(), command->get_root());
          if (r.is_error()) {
            success = false;
            message = r.get_error();
          }
        }
        break;

      case COMMAND_REMOVE:
        {
          Result<> r = platform->handle_remove_command(command->get_channel_id());
          if (r.is_error()) {
            success = false;
            message = r.get_error();
          }
        }
        break;

      case COMMAND_LOG_FILE:
        Logger::to_file(command->get_root().c_str());
        break;

      case COMMAND_LOG_DISABLE:
        LOGGER << "Disabling logger." << endl;
        Logger::disable();
        break;

      default:
        LOGGER << "Received command with unexpected action " << *it << "." << endl;
        break;
    }

    AckPayload ack(command->get_id(), command->get_channel_id(), success, move(message));
    Message response(move(ack));
    acks.push_back(move(response));
  }

  return emit_all(acks.begin(), acks.end());
}

void WorkerThread::collect_status(Status &status)
{
  status.worker_thread_ok = get_error();
  status.worker_in_size = get_in_queue_size();
  status.worker_in_ok = get_in_queue_error();
  status.worker_out_size = get_out_queue_size();
  status.worker_out_ok = get_out_queue_error();
}
<commit_msg>Log errors in the worker loop before returning them<commit_after>#include <vector>
#include <memory>
#include <iostream>
#include <utility>
#include <string>
#include <uv.h>

#include "worker_thread.h"
#include "worker_platform.h"
#include "../log.h"
#include "../queue.h"
#include "../message.h"
#include "../result.h"

using std::endl;
using std::vector;
using std::unique_ptr;
using std::move;
using std::string;

WorkerThread::WorkerThread(uv_async_t *main_callback) :
  Thread(this, &WorkerThread::listen, "worker thread", main_callback),
  platform{WorkerPlatform::for_worker(this)}
{
  //
}

WorkerThread::~WorkerThread()
{
  // Necessary so that unique_ptr can see the full definition of WorkerPlatform
}

Result<> WorkerThread::wake()
{
  return platform->wake();
}

void WorkerThread::listen()
{
  // Handle any commands that were enqueued while the thread was starting.
  Result<> cr = handle_commands();
  if (cr.is_error()) {
    LOGGER << "Unable to handle initially enqueued commands: " << cr << endl;
  }

  Result<> lr = platform->listen();
  if (lr.is_error()) {
    LOGGER << "Unable to listen: " << lr << endl;
    report_error(string(lr.get_error()));
  } else {
    LOGGER << "listen unexpectedly returned without reporting an error." << endl;
  }
}

Result<> WorkerThread::handle_commands()
{
  Result< unique_ptr<vector<Message>> > pr = process_all();
  if (pr.is_error()) {
    return error_result(string(pr.get_error()));
  }

  unique_ptr<vector<Message>> &accepted = pr.get_value();
  if (!accepted) {
    // No command messages to accept.
    return ok_result();
  }

  vector<Message> acks;
  acks.reserve(accepted->size());

  for (auto it = accepted->begin(); it != accepted->end(); ++it) {
    const CommandPayload *command = it->as_command();
    if (!command) {
      LOGGER << "Received unexpected message " << *it << "." << endl;
      continue;
    }

    bool success = true;
    string message = "";

    switch (command->get_action()) {
      case COMMAND_ADD:
        {
          Result<> r = platform->handle_add_command(command->get_channel_id(), command->get_root());
          if (r.is_error()) {
            success = false;
            message = r.get_error();
          }
        }
        break;

      case COMMAND_REMOVE:
        {
          Result<> r = platform->handle_remove_command(command->get_channel_id());
          if (r.is_error()) {
            success = false;
            message = r.get_error();
          }
        }
        break;

      case COMMAND_LOG_FILE:
        Logger::to_file(command->get_root().c_str());
        break;

      case COMMAND_LOG_DISABLE:
        LOGGER << "Disabling logger." << endl;
        Logger::disable();
        break;

      default:
        LOGGER << "Received command with unexpected action " << *it << "." << endl;
        break;
    }

    if (!message.empty()) {
      LOGGER << "Reporting platform error: " << message << "." << endl;
    }

    AckPayload ack(command->get_id(), command->get_channel_id(), success, move(message));
    Message response(move(ack));
    acks.push_back(move(response));
  }

  return emit_all(acks.begin(), acks.end());
}

void WorkerThread::collect_status(Status &status)
{
  status.worker_thread_ok = get_error();
  status.worker_in_size = get_in_queue_size();
  status.worker_in_ok = get_in_queue_error();
  status.worker_out_size = get_out_queue_size();
  status.worker_out_ok = get_out_queue_error();
}
<|endoftext|>


<commit_before>/*
 * AscEmu Framework based on ArcEmu MMORPG Server
 * Copyright (C) 2014-2016 AscEmu Team <http://www.ascemu.org/>
 * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
 * Copyright (C) 2005-2007 Ascent Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "CObjectFactory.h"
#include "ObjectStorage.h"

GameObject* CObjectFactory::CreateGameObject(uint32 Id, uint32 LowGUID)
{
    GameObjectInfo* gameobject_info = GameObjectNameStorage.LookupEntry(Id);
    if (gameobject_info == NULL)
        return NULL;

    GameObject* gameobject = nullptr;

    uint64 GUID = uint64((uint64(HIGHGUID_TYPE_GAMEOBJECT) << 32) | LowGUID);

    switch (gameobject_info->type)
    {

        case GAMEOBJECT_TYPE_DOOR:
            gameobject = new GameObject_Door(GUID);
            break;

        case GAMEOBJECT_TYPE_BUTTON:
            gameobject = new GameObject_Button(GUID);
            break;

        case GAMEOBJECT_TYPE_QUESTGIVER:
            gameobject = new GameObject_QuestGiver(GUID);
            break;

        case GAMEOBJECT_TYPE_CHEST:
            gameobject = new GameObject_Chest(GUID);
            break;

        case GAMEOBJECT_TYPE_TRAP:
            gameobject = new GameObject_Trap(GUID);
            break;

        case GAMEOBJECT_TYPE_SPELL_FOCUS:
            gameobject = new GameObject_SpellFocus(GUID);
            break;

        case GAMEOBJECT_TYPE_GOOBER:
            gameobject = new GameObject_Goober(GUID);
            break;

        case GAMEOBJECT_TYPE_FISHINGNODE:
            gameobject = new GameObject_FishingNode(GUID);
            break;

        case GAMEOBJECT_TYPE_RITUAL:
            gameobject = new GameObject_Ritual(GUID);
            break;

        case GAMEOBJECT_TYPE_SPELLCASTER:
            gameobject = new GameObject_SpellCaster(GUID);
            break;

        case GAMEOBJECT_TYPE_FISHINGHOLE:
            gameobject = new GameObject_FishingHole(GUID);
            break;

        case GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING:
            gameobject = new GameObject_Destructible(GUID);
            break;

        default:
            gameobject = new GameObject(GUID);
            break;
    }

    gameobject->SetInfo(gameobject_info);

    return gameobject;
}

void CObjectFactory::DisposeOf(Object* obj)
{
    delete obj;
}
<commit_msg>no message<commit_after>/*
 * AscEmu Framework based on ArcEmu MMORPG Server
 * Copyright (C) 2014-2016 AscEmu Team <http://www.ascemu.org/>
 * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
 * Copyright (C) 2005-2007 Ascent Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "CObjectFactory.h"
#include "Object.h"
#include "ObjectStorage.h"

GameObject* CObjectFactory::CreateGameObject(uint32 Id, uint32 LowGUID)
{
    GameObjectInfo* gameobject_info = GameObjectNameStorage.LookupEntry(Id);
    if (gameobject_info == NULL)
        return NULL;

    GameObject* gameobject = nullptr;

    uint64 GUID = uint64((uint64(HIGHGUID_TYPE_GAMEOBJECT) << 32) | LowGUID);

    switch (gameobject_info->type)
    {

        case GAMEOBJECT_TYPE_DOOR:
            gameobject = new GameObject_Door(GUID);
            break;

        case GAMEOBJECT_TYPE_BUTTON:
            gameobject = new GameObject_Button(GUID);
            break;

        case GAMEOBJECT_TYPE_QUESTGIVER:
            gameobject = new GameObject_QuestGiver(GUID);
            break;

        case GAMEOBJECT_TYPE_CHEST:
            gameobject = new GameObject_Chest(GUID);
            break;

        case GAMEOBJECT_TYPE_TRAP:
            gameobject = new GameObject_Trap(GUID);
            break;

        case GAMEOBJECT_TYPE_SPELL_FOCUS:
            gameobject = new GameObject_SpellFocus(GUID);
            break;

        case GAMEOBJECT_TYPE_GOOBER:
            gameobject = new GameObject_Goober(GUID);
            break;

        case GAMEOBJECT_TYPE_FISHINGNODE:
            gameobject = new GameObject_FishingNode(GUID);
            break;

        case GAMEOBJECT_TYPE_RITUAL:
            gameobject = new GameObject_Ritual(GUID);
            break;

        case GAMEOBJECT_TYPE_SPELLCASTER:
            gameobject = new GameObject_SpellCaster(GUID);
            break;

        case GAMEOBJECT_TYPE_FISHINGHOLE:
            gameobject = new GameObject_FishingHole(GUID);
            break;

        case GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING:
            gameobject = new GameObject_Destructible(GUID);
            break;

        default:
            gameobject = new GameObject(GUID);
            break;
    }

    gameobject->SetInfo(gameobject_info);

    return gameobject;
}

void CObjectFactory::DisposeOf(Object* obj)
{
    delete obj;
}
<|endoftext|>


<commit_before>#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>
#include <Adafruit_L3GD20_U.h>
#include <Adafruit_9DOF.h>

#include "Arduino.h"
#include "RadioFunctions.h"
/* Assign a unique ID to the sensors */
void initSensors();
void setup(void);
void loop(void);

Adafruit_9DOF                dof   = Adafruit_9DOF();
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);
Adafruit_L3GD20_Unified      gyr   = Adafruit_L3GD20_Unified(30303);

/* Update this with the correct SLP for accurate altitude measurements */
float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;

float p_roll;
float p_pitch;
float p_gyro_x;
float p_gyro_y;
float p_gyro_z;
float p_heading;
char buf[100];
char *char_ptr;

/**************************************************************************/
/*!
    @brief  Initialises all the sensors used by this example
*/
/**************************************************************************/
void initSensors()
{
  if(!accel.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  if(!gyr.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no L3GD20 detected ... Check your wiring!");
    while(1);
  }
}

/**************************************************************************/
/*!

*/
/**************************************************************************/
void setup(void)
{
  Serial.begin(115200);

  rfBegin(11);

  /* Initialise the sensors */
  initSensors();
}

/**************************************************************************/
/*!
    @brief  Constantly check the roll/pitch/heading/altitude/temperature
*/
/**************************************************************************/
void loop(void)
  {

    sensors_event_t accel_event;
    sensors_event_t mag_event;
    sensors_event_t gyr_event;
    sensors_vec_t   orientation;

    /* Calculate pitch and roll from the raw accelerometer data */
    if(!accel.getEvent(&accel_event)) return;
    if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation))
    {
      /* 'orientation' should have valid .roll and .pitch fields */
      p_roll = orientation.roll; //roll
      //    if(orientation.roll<=0){
      //      Serial.print(-orientation.roll); //roll
      //    }
      //    else{
      //      Serial.print(360-orientation.roll); //roll
      //    }
      p_pitch = orientation.pitch; //pitch
      //    if(orientation.pitch<0){
      //      Serial.print(-orientation.pitch); //pitch
      //    }
      //    else{
      //      Serial.print(360-orientation.pitch); //pitch
      //    }
    }

    /* Calculate x y z from gyroscope */
    if (!gyr.getEvent(&gyr_event)) return;
    else {
      /* 'orientation' should have valid .roll and .pitch fields */
      p_gyro_x = gyr_event.gyro.x; //gyr x
      p_gyro_y = gyr_event.gyro.y; //gyr y
      p_gyro_z = gyr_event.gyro.z; //gyr z

    }

    /* Calculate the heading using the magnetometer */
    if(!mag.getEvent(&mag_event)) return;
    //  dof.magTiltCompensation(SENSOR_AXIS_Z, &mag_event, &accel_event);
    if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation)) {
      /* 'orientation' should have valid .heading data now */
      p_heading = orientation.heading;
    }

    char_ptr = buf;
    *char_ptr = '\n';
    char_ptr++;

    dtostrf(p_roll, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    dtostrf(p_pitch, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    dtostrf(p_gyro_x, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    dtostrf(p_gyro_y, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    dtostrf(p_gyro_z, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    dtostrf(p_heading, 1, 2, char_ptr);
    strcat(buf, "\n");

    rfPrint(buf);
    //Serial.print(buf);

    delay(100);
}
<commit_msg>Added button code for PCB<commit_after>#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>
#include <Adafruit_L3GD20_U.h>
#include <Adafruit_9DOF.h>

#include "Arduino.h"
#include "RadioFunctions.h"
/* Assign a unique ID to the sensors */
void initSensors();
void setup(void);
void loop(void);

Adafruit_9DOF                dof   = Adafruit_9DOF();
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);
Adafruit_L3GD20_Unified      gyr   = Adafruit_L3GD20_Unified(30303);

/* Update this with the correct SLP for accurate altitude measurements */
float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;

float p_roll;
float p_pitch;
float p_gyro_x;
float p_gyro_y;
float p_gyro_z;
float p_heading;
char buf[100];
char *char_ptr;

/**************************************************************************/
/*!
    @brief  Initialises all the sensors used by this example
*/
/**************************************************************************/
void initSensors()
{
  if(!accel.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  if(!gyr.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no L3GD20 detected ... Check your wiring!");
    while(1);
  }
}

/**************************************************************************/
/*!

*/
/**************************************************************************/
void setup(void)
{
  Serial.begin(115200);

  rfBegin(11);

  /* Initialise the sensors */
  initSensors();
}

/**************************************************************************/
/*!
    @brief  Constantly check the roll/pitch/heading/altitude/temperature
*/
/**************************************************************************/
void loop(void)
  {

    sensors_event_t accel_event;
    sensors_event_t mag_event;
    sensors_event_t gyr_event;
    sensors_vec_t   orientation;

    /* Calculate pitch and roll from the raw accelerometer data */
    if(!accel.getEvent(&accel_event)) return;
    if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation))
    {
      /* 'orientation' should have valid .roll and .pitch fields */
      p_roll = orientation.roll; //roll
      //    if(orientation.roll<=0){
      //      Serial.print(-orientation.roll); //roll
      //    }
      //    else{
      //      Serial.print(360-orientation.roll); //roll
      //    }
      p_pitch = orientation.pitch; //pitch
      //    if(orientation.pitch<0){
      //      Serial.print(-orientation.pitch); //pitch
      //    }
      //    else{
      //      Serial.print(360-orientation.pitch); //pitch
      //    }
    }

    /* Calculate x y z from gyroscope */
    if (!gyr.getEvent(&gyr_event)) return;
    else {
      /* 'orientation' should have valid .roll and .pitch fields */
      p_gyro_x = gyr_event.gyro.x; //gyr x
      p_gyro_y = gyr_event.gyro.y; //gyr y
      p_gyro_z = gyr_event.gyro.z; //gyr z

    }

    /* Calculate the heading using the magnetometer */
    if(!mag.getEvent(&mag_event)) return;
    //  dof.magTiltCompensation(SENSOR_AXIS_Z, &mag_event, &accel_event);
    if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation)) {
      /* 'orientation' should have valid .heading data now */
      p_heading = orientation.heading;
    }

    char_ptr = buf;
    *char_ptr = '\n';
    char_ptr++;

    dtostrf(p_roll, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    dtostrf(p_pitch, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    dtostrf(p_gyro_x, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    dtostrf(p_gyro_y, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    dtostrf(p_gyro_z, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    dtostrf(p_heading, 1, 2, char_ptr);
    char_ptr += strlen(char_ptr);
    *char_ptr = ',';
    char_ptr++;

    char pt1 = analogRead(2) > 255 ? '1' : '0';
    char pt2 = analogRead(3) > 255 ? '1' : '0';
    char pt3 = analogRead(4) > 255 ? '1' : '0';

    char_ptr[0] = pt1;
    char_ptr[1] = ',';
    char_ptr[2] = pt2;
    char_ptr[3] = ',';
    char_ptr[4] = pt3;
    char_ptr[5] = '\n';
    char_ptr[6] = '\0';

    rfPrint(buf);
    //Serial.print(buf);

    delay(100);
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

#if !defined(XMEMORY_HPP)
#define XMEMORY_HPP

#include <xercesc/util/XercesDefs.hpp>
#include <stdlib.h>

XERCES_CPP_NAMESPACE_BEGIN

class MemoryManager;

/**
 *  This class makes it possible to override the C++ memory management by
 *  adding new/delete operators to this base class.
 *
 *  This class is used in conjuction with the pluggable memory manager. It
 *  allows applications to control Xerces memory management.
 */

class XMLUTIL_EXPORT XMemory
{
public :
    // -----------------------------------------------------------------------
    //  The C++ memory management
    // -----------------------------------------------------------------------
    /** @name The C++ memory management */
    //@{

    /**
      * This method overrides operator new
      *
      * @param size The requested memory size
      */
    void* operator new(size_t size);

    /**
      * This method overrides placement operator new
      *
      * @param size   The requested memory size
      * @param memMgr An application's memory manager
      */
    void* operator new(size_t size, MemoryManager* memMgr);

    /**
      * This method overrides operator delete
      *
      * @param p The pointer to the allocated memory
      */
    void operator delete(void* p);

     //The HP compiler is complaining about duplicate overloading of delete
#if !defined(XML_HPUX)
    /**
      * This method provide a matching delete for the placement new
      *
      * @param p      The pointer to the allocated memory
      * @param memMgr An appliation's memory manager
      */
    void operator delete(void* p, MemoryManager* memMgr);
#endif

    //@}

protected :
    // -----------------------------------------------------------------------
    //  Hidden Constructors
    // -----------------------------------------------------------------------
    /** @name Constructor */
    //@{

    /**
      * Protected default constructor
      */
    XMemory()
    {
    }
    //@}

private:
    // -----------------------------------------------------------------------
    //  Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    XMemory(const XMemory&);
    XMemory& operator=(const XMemory&);
};

XERCES_CPP_NAMESPACE_END

#endif
<commit_msg>for build on WinXP.NET and Intel Electron<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

#if !defined(XMEMORY_HPP)
#define XMEMORY_HPP

#include <xercesc/util/XercesDefs.hpp>
#include <stdlib.h>

XERCES_CPP_NAMESPACE_BEGIN

class MemoryManager;

/**
 *  This class makes it possible to override the C++ memory management by
 *  adding new/delete operators to this base class.
 *
 *  This class is used in conjuction with the pluggable memory manager. It
 *  allows applications to control Xerces memory management.
 */

class XMLUTIL_EXPORT XMemory
{
public :
    // -----------------------------------------------------------------------
    //  The C++ memory management
    // -----------------------------------------------------------------------
    /** @name The C++ memory management */
    //@{

    /**
      * This method overrides operator new
      *
      * @param size The requested memory size
      */
    void* operator new(size_t size);

    /**
      * This method overrides placement operator new
      *
      * @param size   The requested memory size
      * @param memMgr An application's memory manager
      */
    void* operator new(size_t size, MemoryManager* memMgr);

    /**
      * This method overrides operator delete
      *
      * @param p The pointer to the allocated memory
      */
    void operator delete(void* p);

     //The HP compiler is complaining about duplicate overloading of delete
#if !defined(XML_HPUX)
    /**
      * This method provide a matching delete for the placement new
      *
      * @param p      The pointer to the allocated memory
      * @param memMgr An appliation's memory manager
      */
    void operator delete(void* p, MemoryManager* memMgr);
#endif

    //@}

protected :
    // -----------------------------------------------------------------------
    //  Hidden Constructors
    // -----------------------------------------------------------------------
    /** @name Constructor */
    //@{

    /**
      * Protected default constructor and copy constructor
      */
    XMemory()
    {
    }

    XMemory(const XMemory&)
    {
    }
    //@}

private:
    // -----------------------------------------------------------------------
    //  Unimplemented operators
    // -----------------------------------------------------------------------
    XMemory& operator=(const XMemory&);
};

XERCES_CPP_NAMESPACE_END

#endif
<|endoftext|>