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

  Program:   Visualization Library
  Module:    Pixel.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "Pixel.hh"
#include "Quad.hh"
#include "Polygon.hh"
#include "Plane.hh"
#include "vlMath.hh"
#include "CellArr.hh"
#include "Line.hh"

static vlMath math;
static vlPlane plane;
static vlPolygon poly;

// Description:
// Deep copy of cell.
vlPixel::vlPixel(const vlPixel& p)
{
  this->Points = p.Points;
  this->PointIds = p.PointIds;
}

int vlPixel::EvaluatePosition(float x[3], float closestPoint[3],
                                  int& subId, float pcoords[3],
                                  float& dist2, float weights[MAX_CELL_SIZE])
{
  float *pt1, *pt2, *pt3;
  int i;
  float p[3], p21[3], p31[3];
  float l21, l31, n[3];

  subId = 0;
  pcoords[0] = pcoords[1] = pcoords[2] = 0.0;
//
// Get normal for pixel
//
  pt1 = this->Points.GetPoint(0);
  pt2 = this->Points.GetPoint(1);
  pt3 = this->Points.GetPoint(2);

  poly.ComputeNormal (pt1, pt2, pt3, n);
//
// Project point to plane
//
  plane.ProjectPoint(x,pt1,n,closestPoint);

  for (i=0; i<3; i++)
    {
    p21[i] = pt2[i] - pt1[i];
    p31[i] = pt3[i] - pt1[i];
    p[i] = x[i] - pt1[i];
    }

  if ( (l21=math.Norm(p21)) == 0.0 ) l21 = 1.0;
  if ( (l31=math.Norm(p31)) == 0.0 ) l31 = 1.0;

  pcoords[0] = math.Dot(p21,p) / (l21*l21);
  pcoords[1] = math.Dot(p31,p) / (l31*l31);

  if ( pcoords[0] >= 0.0 && pcoords[1] <= 1.0 &&
  pcoords[1] >= 0.0 && pcoords[1] <= 1.0 )
    {
    dist2 = math.Distance2BetweenPoints(closestPoint,x); //projection distance
    this->InterpolationFunctions(pcoords, weights);
    return 1;
    }
  else
    {
    for (i=0; i<2; i++)
      {
      if (pcoords[i] < 0.0) pcoords[i] = 0.0;
      if (pcoords[i] > 1.0) pcoords[i] = 1.0;
      }
    this->EvaluateLocation(subId, pcoords, closestPoint, weights);
    dist2 = math.Distance2BetweenPoints(closestPoint,x);
    return 0;
    }
}

void vlPixel::EvaluateLocation(int& subId, float pcoords[3], float x[3],
                                   float weights[MAX_CELL_SIZE])
{
  float *pt1, *pt2, *pt3;
  int i;

  pt1 = this->Points.GetPoint(0);
  pt2 = this->Points.GetPoint(1);
  pt3 = this->Points.GetPoint(2);

  for (i=0; i<3; i++)
    {
    x[i] = pt1[i] + pcoords[0]*(pt2[i] - pt1[i]) +
                    pcoords[1]*(pt3[i] - pt1[i]);
    }

  this->InterpolationFunctions(pcoords, weights);
}

int vlPixel::CellBoundary(int subId, float pcoords[3], vlIdList& pts)
{
  float t1=pcoords[0]-pcoords[1];
  float t2=1.0-pcoords[0]-pcoords[1];

  pts.Reset();

  // compare against two lines in parametric space that divide element
  // into four pieces.
  if ( t1 >= 0.0 && t2 >= 0.0 )
    {
    pts.SetId(0,this->PointIds.GetId(0));
    pts.SetId(1,this->PointIds.GetId(1));
    }

  else if ( t1 >= 0.0 && t2 < 0.0 )
    {
    pts.SetId(0,this->PointIds.GetId(1));
    pts.SetId(1,this->PointIds.GetId(3));
    }

  else if ( t1 < 0.0 && t2 < 0.0 )
    {
    pts.SetId(0,this->PointIds.GetId(3));
    pts.SetId(1,this->PointIds.GetId(2));
    }

  else //( t1 < 0.0 && t2 >= 0.0 )
    {
    pts.SetId(0,this->PointIds.GetId(2));
    pts.SetId(1,this->PointIds.GetId(0));
    }

  if ( pcoords[0] < 0.0 || pcoords[0] > 1.0 ||
  pcoords[1] < 0.0 || pcoords[1] > 1.0 )
    return 0;
  else
    return 1;
}

//
// Marching squares
//
static int edges[4][2] = { {0,1}, {1,3}, {3,2}, {2,0} };

typedef int EDGE_LIST;
typedef struct {
       EDGE_LIST edges[5];
} LINE_CASES;

static LINE_CASES lineCases[] = {
  {-1, -1, -1, -1, -1},
  {0, 3, -1, -1, -1},
  {1, 0, -1, -1, -1},
  {1, 3, -1, -1, -1},
  {2, 1, -1, -1, -1},
  {0, 3, 2, 1, -1},
  {2, 0, -1, -1, -1},
  {2, 3, -1, -1, -1},
  {3, 2, -1, -1, -1},
  {0, 2, -1, -1, -1},
  {1, 0, 3, 2, -1},
  {1, 2, -1, -1, -1},
  {3, 1, -1, -1, -1},
  {0, 1, -1, -1, -1},
  {3, 0, -1, -1, -1},
  {-1, -1, -1, -1, -1}
};

void vlPixel::Contour(float value, vlFloatScalars *cellScalars,
                     vlFloatPoints *points, vlCellArray *verts,
                     vlCellArray *lines, vlCellArray *polys,
                     vlFloatScalars *scalars)
{
  static int CASE_MASK[4] = {1,2,4,8};
  LINE_CASES *lineCase;
  EDGE_LIST  *edge;
  int i, j, index, *vert;
  int pts[2];
  float t, *x1, *x2, x[3];

  // Build the case table
  for ( i=0, index = 0; i < 4; i++)
      if (cellScalars->GetScalar(i) >= value)
          index |= CASE_MASK[i];

  lineCase = lineCases + index;
  edge = lineCase->edges;

  for ( ; edge[0] > -1; edge += 2 )
    {
    for (i=0; i<2; i++) // insert line
      {
      vert = edges[edge[i]];
      t = (value - cellScalars->GetScalar(vert[0])) /
          (cellScalars->GetScalar(vert[1]) - cellScalars->GetScalar(vert[0]));
      x1 = this->Points.GetPoint(vert[0]);
      x2 = this->Points.GetPoint(vert[1]);
      for (j=0; j<3; j++) x[j] = x1[j] + t * (x2[j] - x1[j]);
      pts[i] = points->InsertNextPoint(x);
      scalars->InsertNextScalar(value);
      }
    lines->InsertNextCell(2,pts);
    }
}

vlCell *vlPixel::GetEdge(int edgeId)
{
  static vlLine line;
  int *verts;

  verts = edges[edgeId];

  // load point id's
  line.PointIds.SetId(0,this->PointIds.GetId(verts[0]));
  line.PointIds.SetId(1,this->PointIds.GetId(verts[1]));

  // load coordinates
  line.Points.SetPoint(0,this->Points.GetPoint(verts[0]));
  line.Points.SetPoint(1,this->Points.GetPoint(verts[1]));

  return &line;
}
//
// Compute interpolation functions (similar but different than Quad interpolation functions)
//
void vlPixel::InterpolationFunctions(float pcoords[3], float sf[4])
{
  float rm, sm;

  rm = 1. - pcoords[0];
  sm = 1. - pcoords[1];

  sf[0] = rm * sm;
  sf[1] = pcoords[0] * sm;
  sf[2] = rm * pcoords[1];
  sf[3] = pcoords[0] * pcoords[1];
}

//
// Intersect plane; see whether point is inside.
//
int vlPixel::IntersectWithLine(float p1[3], float p2[3], float tol, float& t,
                               float x[3], float pcoords[3], int& subId)
{
  float *pt1, *pt2, *pt3, *pt4, n[3];
  float tol2 = tol*tol;
  float closestPoint[3];
  float dist2, weights[MAX_CELL_SIZE];
  int i;

  subId = 0;
  pcoords[0] = pcoords[1] = pcoords[2] = 0.0;
//
// Get normal for triangle
//
  pt1 = this->Points.GetPoint(0);
  pt2 = this->Points.GetPoint(1);
  pt3 = this->Points.GetPoint(2);
  pt4 = this->Points.GetPoint(3);

  n[0] = n[1] = n[2] = 0.0;
  for (i=0; i<3; i++)
    {
    if ( (pt4[i] - pt1[i]) <= 0.0 )
      {
      n[i] = 1.0;
      break;
      }
    }
//
// Intersect plane of pixel with line
//
  if ( ! plane.IntersectWithLine(p1,p2,n,pt1,t,x) ) return 0;
//
// Use evaluate position
//
  if ( this->EvaluatePosition(x, closestPoint, subId, pcoords, dist2, weights) )
    if ( dist2 <= tol2 ) return 1;

  return 0;
}
<commit_msg>*** empty log message ***<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    Pixel.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "Pixel.hh"
#include "Quad.hh"
#include "Polygon.hh"
#include "Plane.hh"
#include "vlMath.hh"
#include "CellArr.hh"
#include "Line.hh"

static vlMath math;
static vlPlane plane;
static vlPolygon poly;

// Description:
// Deep copy of cell.
vlPixel::vlPixel(const vlPixel& p)
{
  this->Points = p.Points;
  this->PointIds = p.PointIds;
}

int vlPixel::EvaluatePosition(float x[3], float closestPoint[3],
                                  int& subId, float pcoords[3],
                                  float& dist2, float weights[MAX_CELL_SIZE])
{
  float *pt1, *pt2, *pt3;
  int i;
  float p[3], p21[3], p31[3];
  float l21, l31, n[3];

  subId = 0;
  pcoords[0] = pcoords[1] = pcoords[2] = 0.0;
//
// Get normal for pixel
//
  pt1 = this->Points.GetPoint(0);
  pt2 = this->Points.GetPoint(1);
  pt3 = this->Points.GetPoint(2);

  poly.ComputeNormal (pt1, pt2, pt3, n);
//
// Project point to plane
//
  plane.ProjectPoint(x,pt1,n,closestPoint);

  for (i=0; i<3; i++)
    {
    p21[i] = pt2[i] - pt1[i];
    p31[i] = pt3[i] - pt1[i];
    p[i] = x[i] - pt1[i];
    }

  if ( (l21=math.Norm(p21)) == 0.0 ) l21 = 1.0;
  if ( (l31=math.Norm(p31)) == 0.0 ) l31 = 1.0;

  pcoords[0] = math.Dot(p21,p) / (l21*l21);
  pcoords[1] = math.Dot(p31,p) / (l31*l31);

  if ( pcoords[0] >= 0.0 && pcoords[1] <= 1.0 &&
  pcoords[1] >= 0.0 && pcoords[1] <= 1.0 )
    {
    dist2 = math.Distance2BetweenPoints(closestPoint,x); //projection distance
    this->InterpolationFunctions(pcoords, weights);
    return 1;
    }
  else
    {
    for (i=0; i<2; i++)
      {
      if (pcoords[i] < 0.0) pcoords[i] = 0.0;
      if (pcoords[i] > 1.0) pcoords[i] = 1.0;
      }
    this->EvaluateLocation(subId, pcoords, closestPoint, weights);
    dist2 = math.Distance2BetweenPoints(closestPoint,x);
    return 0;
    }
}

void vlPixel::EvaluateLocation(int& subId, float pcoords[3], float x[3],
                                   float weights[MAX_CELL_SIZE])
{
  float *pt1, *pt2, *pt3;
  int i;

  pt1 = this->Points.GetPoint(0);
  pt2 = this->Points.GetPoint(1);
  pt3 = this->Points.GetPoint(2);

  for (i=0; i<3; i++)
    {
    x[i] = pt1[i] + pcoords[0]*(pt2[i] - pt1[i]) +
                    pcoords[1]*(pt3[i] - pt1[i]);
    }

  this->InterpolationFunctions(pcoords, weights);
}

int vlPixel::CellBoundary(int subId, float pcoords[3], vlIdList& pts)
{
  float t1=pcoords[0]-pcoords[1];
  float t2=1.0-pcoords[0]-pcoords[1];

  pts.Reset();

  // compare against two lines in parametric space that divide element
  // into four pieces.
  if ( t1 >= 0.0 && t2 >= 0.0 )
    {
    pts.SetId(0,this->PointIds.GetId(0));
    pts.SetId(1,this->PointIds.GetId(1));
    }

  else if ( t1 >= 0.0 && t2 < 0.0 )
    {
    pts.SetId(0,this->PointIds.GetId(1));
    pts.SetId(1,this->PointIds.GetId(3));
    }

  else if ( t1 < 0.0 && t2 < 0.0 )
    {
    pts.SetId(0,this->PointIds.GetId(3));
    pts.SetId(1,this->PointIds.GetId(2));
    }

  else //( t1 < 0.0 && t2 >= 0.0 )
    {
    pts.SetId(0,this->PointIds.GetId(2));
    pts.SetId(1,this->PointIds.GetId(0));
    }

  if ( pcoords[0] < 0.0 || pcoords[0] > 1.0 ||
  pcoords[1] < 0.0 || pcoords[1] > 1.0 )
    return 0;
  else
    return 1;
}

//
// Marching squares
//
static int edges[4][2] = { {0,1}, {1,3}, {3,2}, {2,0} };

typedef int EDGE_LIST;
typedef struct {
       EDGE_LIST edges[5];
} LINE_CASES;

static LINE_CASES lineCases[] = {
  {-1, -1, -1, -1, -1},
  {0, 3, -1, -1, -1},
  {1, 0, -1, -1, -1},
  {1, 3, -1, -1, -1},
  {2, 1, -1, -1, -1},
  {0, 3, 2, 1, -1},
  {2, 0, -1, -1, -1},
  {2, 3, -1, -1, -1},
  {3, 2, -1, -1, -1},
  {0, 2, -1, -1, -1},
  {1, 0, 3, 2, -1},
  {1, 2, -1, -1, -1},
  {3, 1, -1, -1, -1},
  {0, 1, -1, -1, -1},
  {3, 0, -1, -1, -1},
  {-1, -1, -1, -1, -1}
};

void vlPixel::Contour(float value, vlFloatScalars *cellScalars,
                     vlFloatPoints *points, vlCellArray *verts,
                     vlCellArray *lines, vlCellArray *polys,
                     vlFloatScalars *scalars)
{
  static int CASE_MASK[4] = {1,2,8,4}; //note difference!
  LINE_CASES *lineCase;
  EDGE_LIST  *edge;
  int i, j, index, *vert;
  int pts[2];
  float t, *x1, *x2, x[3];

  // Build the case table
  for ( i=0, index = 0; i < 4; i++)
      if (cellScalars->GetScalar(i) >= value)
          index |= CASE_MASK[i];

  lineCase = lineCases + index;
  edge = lineCase->edges;

  for ( ; edge[0] > -1; edge += 2 )
    {
    for (i=0; i<2; i++) // insert line
      {
      vert = edges[edge[i]];
      t = (value - cellScalars->GetScalar(vert[0])) /
          (cellScalars->GetScalar(vert[1]) - cellScalars->GetScalar(vert[0]));
      x1 = this->Points.GetPoint(vert[0]);
      x2 = this->Points.GetPoint(vert[1]);
      for (j=0; j<3; j++) x[j] = x1[j] + t * (x2[j] - x1[j]);
      pts[i] = points->InsertNextPoint(x);
      scalars->InsertNextScalar(value);
      }
    lines->InsertNextCell(2,pts);
    }
}

vlCell *vlPixel::GetEdge(int edgeId)
{
  static vlLine line;
  int *verts;

  verts = edges[edgeId];

  // load point id's
  line.PointIds.SetId(0,this->PointIds.GetId(verts[0]));
  line.PointIds.SetId(1,this->PointIds.GetId(verts[1]));

  // load coordinates
  line.Points.SetPoint(0,this->Points.GetPoint(verts[0]));
  line.Points.SetPoint(1,this->Points.GetPoint(verts[1]));

  return &line;
}
//
// Compute interpolation functions (similar but different than Quad interpolation functions)
//
void vlPixel::InterpolationFunctions(float pcoords[3], float sf[4])
{
  float rm, sm;

  rm = 1. - pcoords[0];
  sm = 1. - pcoords[1];

  sf[0] = rm * sm;
  sf[1] = pcoords[0] * sm;
  sf[2] = rm * pcoords[1];
  sf[3] = pcoords[0] * pcoords[1];
}

//
// Intersect plane; see whether point is inside.
//
int vlPixel::IntersectWithLine(float p1[3], float p2[3], float tol, float& t,
                               float x[3], float pcoords[3], int& subId)
{
  float *pt1, *pt2, *pt3, *pt4, n[3];
  float tol2 = tol*tol;
  float closestPoint[3];
  float dist2, weights[MAX_CELL_SIZE];
  int i;

  subId = 0;
  pcoords[0] = pcoords[1] = pcoords[2] = 0.0;
//
// Get normal for triangle
//
  pt1 = this->Points.GetPoint(0);
  pt2 = this->Points.GetPoint(1);
  pt3 = this->Points.GetPoint(2);
  pt4 = this->Points.GetPoint(3);

  n[0] = n[1] = n[2] = 0.0;
  for (i=0; i<3; i++)
    {
    if ( (pt4[i] - pt1[i]) <= 0.0 )
      {
      n[i] = 1.0;
      break;
      }
    }
//
// Intersect plane of pixel with line
//
  if ( ! plane.IntersectWithLine(p1,p2,n,pt1,t,x) ) return 0;
//
// Use evaluate position
//
  if ( this->EvaluatePosition(x, closestPoint, subId, pcoords, dist2, weights) )
    if ( dist2 <= tol2 ) return 1;

  return 0;
}
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include <boost/algorithm/string.hpp>

#ifndef unix
#include <float.h>
#else
#include "CoreTypes.h"
#endif

#include "RexNetworkUtils.h"
#include "QuatUtils.h"
#include <QStringList>

namespace RexTypes
{
    bool ParseBool(const std::string &value)
    {
        std::string testedvalue = value;
        boost::algorithm::to_lower(testedvalue);
        return (boost::algorithm::starts_with(testedvalue,"true") || boost::algorithm::starts_with(testedvalue,"1"));
    }

    Quaternion GetProcessedQuaternion(const uint8_t* bytes)
    {
        uint16_t *rot = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);
        Quaternion rotation = UnpackQuaternionFromU16_4(rot);
        rotation.normalize();
        return rotation;
    }

    Vector3df GetProcessedScaledVectorFromUint16(const uint8_t* bytes, float scale)
    {
        uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);

        Vector3df resultvector;
        resultvector.x = scale * ((vec[0] / 32768.0f) - 1.0f);
        resultvector.y = scale * ((vec[1] / 32768.0f) - 1.0f);
        resultvector.z = scale * ((vec[2] / 32768.0f) - 1.0f);

        return resultvector;
    }

    Vector3df GetProcessedVectorFromUint16(const uint8_t* bytes)
    {
        uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);
        return Vector3df(vec[0],vec[1],vec[2]);
    }

    Vector3df GetProcessedVector(const uint8_t* bytes)
    {
        Vector3df resultvector = *reinterpret_cast<Vector3df*>((Vector3df*)&bytes[0]);
        return resultvector;
    }

    bool IsValidPositionVector(const Vector3df &pos)
    {
        // This is a heuristic check to guard against the OpenSim server sending us stupid positions.
        if (fabs(pos.x) > 1e6f || fabs(pos.y) > 1e6f || fabs(pos.z) > 1e6f)
            return false;
        if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z))
            return false;
        if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z))
            return false;

        return true;
    }

    bool IsValidVelocityVector(const Vector3df &pos)
    {
        // This is a heuristic check to guard against the OpenSim server sending us stupid velocity vectors.
        if (fabs(pos.x) > 1e3f || fabs(pos.y) > 1e3f || fabs(pos.z) > 1e3f)
            return false;
        if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z))
            return false;
        if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z))
            return false;

        return true;
    }

    bool ReadBoolFromBytes(const uint8_t* bytes, int& idx)
    {
        bool result = *(bool*)(&bytes[idx]);
        idx += sizeof(bool);

        return result;
    }

    uint8_t ReadUInt8FromBytes(const uint8_t* bytes, int& idx)
    {
        uint8_t result = bytes[idx];
        idx++;

        return result;
    }

    uint16_t ReadUInt16FromBytes(const uint8_t* bytes, int& idx)
    {
        uint16_t result = *(uint16_t*)(&bytes[idx]);
        idx += sizeof(uint16_t);

        return result;
    }

    uint32_t ReadUInt32FromBytes(const uint8_t* bytes, int& idx)
    {
        uint32_t result = *(uint32_t*)(&bytes[idx]);
        idx += sizeof(uint32_t);

        return result;
    }

    int16_t ReadSInt16FromBytes(const uint8_t* bytes, int& idx)
    {
        int16_t result = *(int16_t*)(&bytes[idx]);
        idx += sizeof(int16_t);

        return result;
    }

    int32_t ReadSInt32FromBytes(const uint8_t* bytes, int& idx)
    {
        int32_t result = *(int32_t*)(&bytes[idx]);
        idx += sizeof(int32_t);

        return result;
    }

    float ReadFloatFromBytes(const uint8_t* bytes, int& idx)
    {
        float result = *(float*)(&bytes[idx]);
        idx += sizeof(float);

        return result;
    }

    RexUUID ReadUUIDFromBytes(const uint8_t* bytes, int& idx)
    {
        RexUUID result = *(RexUUID*)(&bytes[idx]);
        idx += sizeof(RexUUID);

        return result;
    }

    Color ReadColorFromBytes(const uint8_t* bytes, int& idx)
    {
        uint8_t r = bytes[idx++];
        uint8_t g = bytes[idx++];
        uint8_t b = bytes[idx++];
        uint8_t a = bytes[idx++];

        return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
    }

    Color ReadColorFromBytesInverted(const uint8_t* bytes, int& idx)
    {
        uint8_t r = 255 - bytes[idx++];
        uint8_t g = 255 - bytes[idx++];
        uint8_t b = 255 - bytes[idx++];
        uint8_t a = 255 - bytes[idx++];

        return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
    }

    std::string ReadNullTerminatedStringFromBytes(const uint8_t* bytes, int& idx)
    {
        std::string result = "";

        uint8_t readbyte = bytes[idx];
        idx++;
        while(readbyte != 0)
        {
            result.push_back((char)readbyte);
            readbyte = bytes[idx];
            idx++;
        }

        return result;
    }

    void WriteBoolToBytes(bool value, uint8_t* bytes, int& idx)
    {
        bytes[idx] = (uint8_t)value;
        idx++;
    }

    void WriteUInt8ToBytes(uint8_t value, uint8_t* bytes, int& idx)
    {
        bytes[idx] = value;
        idx++;
    }

    void WriteUInt16ToBytes(uint16_t value, uint8_t* bytes, int& idx)
    {
        *(uint16_t*)(&bytes[idx]) = value;
        idx += sizeof(uint16_t);
    }

    void WriteUInt32ToBytes(uint32_t value, uint8_t* bytes, int& idx)
    {
        *(uint32_t*)(&bytes[idx]) = value;
        idx += sizeof(uint32_t);
    }

    void WriteFloatToBytes(float value, uint8_t* bytes, int& idx)
    {
        *(float*)(&bytes[idx]) = value;
        idx += sizeof(float);
    }

    void WriteUUIDToBytes(const RexUUID &value, uint8_t* bytes, int& idx)
    {
        *(RexUUID*)(&bytes[idx]) = value;
        idx += sizeof(RexUUID);
    }

    void WriteNullTerminatedStringToBytes(const std::string& value, uint8_t* bytes, int& idx)
    {
        const char* c_str = value.c_str();

        memcpy(&bytes[idx], c_str, value.length() + 1);
        idx += value.length() + 1;
    }

    NameValueMap ParseNameValueMap(const std::string& namevalue)
    {
        // NameValue contains: "FirstName STRING RW SV <firstName>\nLastName STRING RW SV <lastName>"
        // When using rex auth <firstName> contains both first and last name and <lastName> contains the auth server address

        // Split into lines
        NameValueMap map;
        StringVector lines = SplitString(namevalue, '\n');
        for (unsigned i = 0; i < lines.size(); ++i)
        {
            StringVector line = SplitString(lines[i], ' ');
            if (line.size() > 4)
            {
                // First element is the name
                const std::string& name = line[0];
                std::string value;
                // Skip over the STRING RW SV etc. (3 values)
                // Concatenate the rest of the values
                for (unsigned j = 4; j < line.size(); ++j)
                {
                    value += line[j];
                    if (j != line.size()-1)
                        value += " ";
                }
                map[name] = value;
            }
        }

        // Parse auth server address out from the NameValue if it exists
        QString fullname = QString(map["FirstName"].c_str()) + " " + QString(map["LastName"].c_str());

        // Rex auth has: <First Last> <rex auth url>
        if (fullname.count('@') == 1)
        {
            QStringList names;
            if (fullname.contains('@'))
            {
                names = fullname.split(" ");
                foreach(QString name, names)
                {
                    if (name.contains('@'))
                    {
                        map["RexAuth"] = name.toStdString();
                        names.removeOne(name);
                    }
                }
            }
            assert(names[0].size() >= 2);
            if (names.length() >= 1)
                map["FirstName"] = names[0].toStdString();
            if (names.length() >= 2)
                map["LastName"] = names[1].toStdString();
        }
        // Web auth has: <url> <url>
        else if (fullname.count('@') == 2)
        {
            QStringList names = fullname.split(" ");
            map["FirstName"] = names[0].toStdString();
            map["LastName"] = "";
        }

        return map;
    }

    bool ReadTextureEntryBits(uint32_t& bits, int& num_bits, const uint8_t* bytes, int& idx)
    {
        bits = 0;
        num_bits = 0;
        uint8_t byte;

        do
        {
            byte = bytes[idx++];
            bits <<= 7;
            bits |= byte & 0x7f;
            num_bits += 7;
        }
        while (byte & 0x80);

        return bits != 0;
    }
}
<commit_msg>Don't crash on 1 char first names, or malformed web auth lines<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include <boost/algorithm/string.hpp>

#ifndef unix
#include <float.h>
#else
#include "CoreTypes.h"
#endif

#include "RexNetworkUtils.h"
#include "QuatUtils.h"
#include <QStringList>

namespace RexTypes
{
    bool ParseBool(const std::string &value)
    {
        std::string testedvalue = value;
        boost::algorithm::to_lower(testedvalue);
        return (boost::algorithm::starts_with(testedvalue,"true") || boost::algorithm::starts_with(testedvalue,"1"));
    }

    Quaternion GetProcessedQuaternion(const uint8_t* bytes)
    {
        uint16_t *rot = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);
        Quaternion rotation = UnpackQuaternionFromU16_4(rot);
        rotation.normalize();
        return rotation;
    }

    Vector3df GetProcessedScaledVectorFromUint16(const uint8_t* bytes, float scale)
    {
        uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);

        Vector3df resultvector;
        resultvector.x = scale * ((vec[0] / 32768.0f) - 1.0f);
        resultvector.y = scale * ((vec[1] / 32768.0f) - 1.0f);
        resultvector.z = scale * ((vec[2] / 32768.0f) - 1.0f);

        return resultvector;
    }

    Vector3df GetProcessedVectorFromUint16(const uint8_t* bytes)
    {
        uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);
        return Vector3df(vec[0],vec[1],vec[2]);
    }

    Vector3df GetProcessedVector(const uint8_t* bytes)
    {
        Vector3df resultvector = *reinterpret_cast<Vector3df*>((Vector3df*)&bytes[0]);
        return resultvector;
    }

    bool IsValidPositionVector(const Vector3df &pos)
    {
        // This is a heuristic check to guard against the OpenSim server sending us stupid positions.
        if (fabs(pos.x) > 1e6f || fabs(pos.y) > 1e6f || fabs(pos.z) > 1e6f)
            return false;
        if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z))
            return false;
        if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z))
            return false;

        return true;
    }

    bool IsValidVelocityVector(const Vector3df &pos)
    {
        // This is a heuristic check to guard against the OpenSim server sending us stupid velocity vectors.
        if (fabs(pos.x) > 1e3f || fabs(pos.y) > 1e3f || fabs(pos.z) > 1e3f)
            return false;
        if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z))
            return false;
        if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z))
            return false;

        return true;
    }

    bool ReadBoolFromBytes(const uint8_t* bytes, int& idx)
    {
        bool result = *(bool*)(&bytes[idx]);
        idx += sizeof(bool);

        return result;
    }

    uint8_t ReadUInt8FromBytes(const uint8_t* bytes, int& idx)
    {
        uint8_t result = bytes[idx];
        idx++;

        return result;
    }

    uint16_t ReadUInt16FromBytes(const uint8_t* bytes, int& idx)
    {
        uint16_t result = *(uint16_t*)(&bytes[idx]);
        idx += sizeof(uint16_t);

        return result;
    }

    uint32_t ReadUInt32FromBytes(const uint8_t* bytes, int& idx)
    {
        uint32_t result = *(uint32_t*)(&bytes[idx]);
        idx += sizeof(uint32_t);

        return result;
    }

    int16_t ReadSInt16FromBytes(const uint8_t* bytes, int& idx)
    {
        int16_t result = *(int16_t*)(&bytes[idx]);
        idx += sizeof(int16_t);

        return result;
    }

    int32_t ReadSInt32FromBytes(const uint8_t* bytes, int& idx)
    {
        int32_t result = *(int32_t*)(&bytes[idx]);
        idx += sizeof(int32_t);

        return result;
    }

    float ReadFloatFromBytes(const uint8_t* bytes, int& idx)
    {
        float result = *(float*)(&bytes[idx]);
        idx += sizeof(float);

        return result;
    }

    RexUUID ReadUUIDFromBytes(const uint8_t* bytes, int& idx)
    {
        RexUUID result = *(RexUUID*)(&bytes[idx]);
        idx += sizeof(RexUUID);

        return result;
    }

    Color ReadColorFromBytes(const uint8_t* bytes, int& idx)
    {
        uint8_t r = bytes[idx++];
        uint8_t g = bytes[idx++];
        uint8_t b = bytes[idx++];
        uint8_t a = bytes[idx++];

        return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
    }

    Color ReadColorFromBytesInverted(const uint8_t* bytes, int& idx)
    {
        uint8_t r = 255 - bytes[idx++];
        uint8_t g = 255 - bytes[idx++];
        uint8_t b = 255 - bytes[idx++];
        uint8_t a = 255 - bytes[idx++];

        return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
    }

    std::string ReadNullTerminatedStringFromBytes(const uint8_t* bytes, int& idx)
    {
        std::string result = "";

        uint8_t readbyte = bytes[idx];
        idx++;
        while(readbyte != 0)
        {
            result.push_back((char)readbyte);
            readbyte = bytes[idx];
            idx++;
        }

        return result;
    }

    void WriteBoolToBytes(bool value, uint8_t* bytes, int& idx)
    {
        bytes[idx] = (uint8_t)value;
        idx++;
    }

    void WriteUInt8ToBytes(uint8_t value, uint8_t* bytes, int& idx)
    {
        bytes[idx] = value;
        idx++;
    }

    void WriteUInt16ToBytes(uint16_t value, uint8_t* bytes, int& idx)
    {
        *(uint16_t*)(&bytes[idx]) = value;
        idx += sizeof(uint16_t);
    }

    void WriteUInt32ToBytes(uint32_t value, uint8_t* bytes, int& idx)
    {
        *(uint32_t*)(&bytes[idx]) = value;
        idx += sizeof(uint32_t);
    }

    void WriteFloatToBytes(float value, uint8_t* bytes, int& idx)
    {
        *(float*)(&bytes[idx]) = value;
        idx += sizeof(float);
    }

    void WriteUUIDToBytes(const RexUUID &value, uint8_t* bytes, int& idx)
    {
        *(RexUUID*)(&bytes[idx]) = value;
        idx += sizeof(RexUUID);
    }

    void WriteNullTerminatedStringToBytes(const std::string& value, uint8_t* bytes, int& idx)
    {
        const char* c_str = value.c_str();

        memcpy(&bytes[idx], c_str, value.length() + 1);
        idx += value.length() + 1;
    }

    NameValueMap ParseNameValueMap(const std::string& namevalue)
    {
        // NameValue starts with: "FirstName STRING RW SV <firstName>\nLastName STRING RW SV <lastName>"
        // When using rex auth <firstName> contains both first and last name and <lastName> contains the auth server address

        // Split into lines
        NameValueMap map;
        StringVector lines = SplitString(namevalue, '\n');
        for (unsigned i = 0; i < lines.size(); ++i)
        {
            StringVector line = SplitString(lines[i], ' ');
            if (line.size() > 4)
            {
                // First element is the name
                const std::string& name = line[0];
                std::string value;
                // Skip over the STRING RW SV etc. (3 values)
                // Concatenate the rest of the values
                for (unsigned j = 4; j < line.size(); ++j)
                {
                    value += line[j];
                    if (j != line.size()-1)
                        value += " ";
                }
                map[name] = value;
            }
        }

        // Parse auth server address out from the NameValue if it exists
        QString fullname = QString(map["FirstName"].c_str()) + " " + QString(map["LastName"].c_str());

        // Rex auth has: <First Last> <rex auth url>
        if (fullname.count('@') == 1)
        {
            QStringList names;
            if (fullname.contains('@'))
            {
                names = fullname.split(" ");
                foreach(QString name, names)
                {
                    if (name.contains('@'))
                    {
                        map["RexAuth"] = name.toStdString();
                        names.removeOne(name);
                    }
                }
            }
            if (names.length() >= 1)
                map["FirstName"] = names[0].toStdString();
            if (names.length() >= 2)
                map["LastName"] = names[1].toStdString();
        }
        // Web auth has: <url> <url>
        else if (fullname.count('@') == 2)
        {
            QStringList names = fullname.split(" ");
            if (names.length() >= 1) {
                map["FirstName"] = names[0].toStdString();
                map["LastName"] = "";
            }
        }

        return map;
    }

    bool ReadTextureEntryBits(uint32_t& bits, int& num_bits, const uint8_t* bytes, int& idx)
    {
        bits = 0;
        num_bits = 0;
        uint8_t byte;

        do
        {
            byte = bytes[idx++];
            bits <<= 7;
            bits |= byte & 0x7f;
            num_bits += 7;
        }
        while (byte & 0x80);

        return bits != 0;
    }
}
<|endoftext|>


<commit_before>#include "PRINTOBJ.H"

#include "DRAW.H"
#include "SPECIFIC.H"
#include "MATHS.H"
#include "3D_GEN.H"
#include "CONTROL.H"
#include "SETUP.H"
#include "ITEMS.H"
#include "EFFECTS.H"
#include "LOAD_LEV.H"
#include "DELTAPAK.H"
#include "DRAWOBJ.H"

void CalcAllAnimatingItems_ASM()
{
	UNIMPLEMENTED();
}

void DrawEffect(short item_num)
{
	struct FX_INFO* fx = &effects[item_num];
	struct object_info* obj = &objects[fx->object_number];

	if (obj->draw_routine != NULL && obj->loaded)
	{
		mPushMatrix();
		mTranslateAbsXYZ(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos);

		if (Matrix->tz < 20480)
		{
			mRotYXZ(fx->pos.y_rot, fx->pos.x_rot, fx->pos.z_rot);

			S_CalculateLight(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos, fx->room_number, &duff_item.il);
			duff_item.il.Light[3].pad = 0;

			phd_PutPolygons(meshes[obj->nmeshes != 0 ? obj->mesh_index : fx->frame_number], -1);
		}

		mPopMatrix();
	}
}

void PrintAllOtherObjects_ASM(short room_num /*s3*/)//(F)
{
	struct room_info* r = &room[room_num];
	struct ITEM_INFO* item = NULL;
	struct object_info* object;
	short item_num;
	struct FX_INFO* effect;
	int mesh_num;
	short* mesh;
	int effect_num;

	r->bound_active = 0;
	mPushMatrix();
	mTranslateAbsXYZ(r->x, r->y, r->z);

	phd_right = 512;
	phd_bottom = 240;
	phd_left = 0;
	phd_top = 0;

	item_num = r->item_number;

	if (item_num != -1)
	{
		do
		{
			item = &items[item_num];
			object = &objects[item->object_number];

			if (item->status != 6)
			{
				if (!object->using_drawanimating_item && object->draw_routine != NULL)
				{
					object->draw_routine(item);
				}
			}
			//loc_8F5AC
			if (object->draw_routine_extra != NULL)
			{
				object->draw_routine_extra(item);
			}

			//loc_8F5C4
			if (item->after_death - 1 < 127)
			{
				item->after_death++;

				if (item->after_death == 128)
				{
					KillItem(r->item_number);
				}
			}//loc_8F5EC

			item_num = item->next_item;
		} while (item_num != -1);

	}//loc_8F5FC

	effect_num = r->fx_number;

	if (effect_num != -1)
	{
		//loc_8F608
		do
		{
			effect = &effect[effect_num];
			object = &objects[effect->object_number];

			if (object->draw_routine != NULL && object->loaded)
			{
				mPushMatrix();
				mTranslateAbsXYZ(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos);

				if (((int*)MatrixStack)[2] - 21 < 20459)
				{
					mRotYXZ(effect->pos.y_rot, effect->pos.x_rot, effect->pos.z_rot);

					duff_item.il.Light[3].pad = 0;
					S_CalculateLight(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos, effect->room_number, &duff_item.il);

					mesh_num = effect->frame_number;

					if (object->nmeshes != 0)
					{
						mesh_num = object->mesh_index;
					}//loc_8F6C0

					phd_PutPolygons(meshes[mesh_num], -1);
				}//loc_8F6D8

				mPopMatrix();

				//loc_8F6E0
				effect_num = effect->next_fx;
			}
		} while (effect_num != -1);//loc_8F6E0
	}//loc_8F6EC

	mPopMatrix();
	((int*)&r->left)[0] = 511;
	((int*)&r->top)[0] = 239;
}

void print_all_object_NOW()//8F474(<), 914B8(<) (F)
{
	CalcAllAnimatingItems_ASM();

	for (int i = 0; i < number_draw_rooms; i++)
	{
		PrintAllOtherObjects_ASM(draw_rooms[i]);
	}
}<commit_msg>[Specific-PSXPC_N] Implement init_scratchpad<commit_after>#include "PRINTOBJ.H"

#include "CAMERA.H"
#include "DRAW.H"
#include "SPECIFIC.H"
#include "MATHS.H"
#include "3D_GEN.H"
#include "CONTROL.H"
#include "SETUP.H"
#include "ITEMS.H"
#include "EFFECTS.H"
#include "LOAD_LEV.H"
#include "DELTAPAK.H"
#include "DRAWOBJ.H"

#include <GTEREG.H>

void init_scratchpad(int* fp)//8281C(<) (F)
{
	int t0;
	int t1;
	int t2;
	int t3;
	int t4;
	int t5;
	int t6;
	int t7;
	int* at = &fp[47];
	fp[20] = (int)at;

	t0 = R11 | (R12 << 16);
	t1 = R13 | (R21 << 16);
	t2 = R22 | (R23 << 16);
	t3 = R31 | (R32 << 16);
	t4 = R33;
	t5 = TRX;
	t6 = TRY;
	t7 = TRZ;

	at[0] = t0;
	at[1] = t1;
	at[2] = t2;
	at[3] = t3;
	at[4] = t4;
	at[5] = t5;
	at[6] = t6;
	at[7] = t7;
	//v0 = (int)&stashed_objects_list[0]
	//v1 = (int)&stashed_matrix_list[0]
	//a0 = (int)&items[0]
	//a1 = (int)&room[0]

	fp[16] = (int)stashed_objects_list;
	fp[17] = (int)stashed_matrix_list;
	fp[18] = 0;
	fp[24] = (int)items;
	fp[38] = (int)room;

	//v0 = camera.pos.room_number
	//v1 = anims
	//a0 = meshes
	//a1 = bones

	((short*)fp)[53] = camera.pos.room_number;
	fp[39] = (int)anims;
	fp[40] = (int)meshes;
	fp[41] = (int)bones;

	t0 = ((int*)MatrixStack)[5];
	t1 = ((int*)MatrixStack)[6];
	t2 = ((int*)MatrixStack)[7];

	fp[46] = BinocularRange;
	fp[27] = t0;
	fp[28] = t1;
	fp[29] = t2;

	/* Must be set in outer function */
	//s1 = number_draw_rooms
	//s0 = &draw_rooms[0];
}

void CalcAllAnimatingItems_ASM()
{
	int scratchPad[256];
	int* fp;

	fp = &scratchPad[0];
	init_scratchpad(fp);
#if 0
		blez    $s1, loc_827DC

		loc_82658 :
		lh      $a0, 0($s0)
		lw      $v1, 0x80 + arg_18($fp)
		sll     $v0, $a0, 2
		addu    $v0, $a0
		sll     $v0, 4
		addu    $s2, $v1, $v0
		sh      $a0, 0x80 + var_18($fp)
		jal     sub_81BBC
		sw      $s2, 0x80 + var_1C($fp)
		lh      $s3, 0x32($s2)
		lw      $s4, 0x10($s2)
		blez    $s3, loc_8275C
		lw      $v0, 0x38($s2)
		lw      $v1, 0x3C($s2)
		sw      $v0, 0x80 + arg_10($fp)
		sw      $v1, 0x80 + arg_14($fp)

		loc_82698:
	lh      $v0, 0x12($s4)
		lh      $v1, 0x10($s4)
		li      $s5, 0x1F9780//static objects?
		sll     $at, $v0, 3
		subu    $at, $v0
		sll     $at, 2
		andi    $v0, $v1, 1
		beqz    $v0, loc_82750
		addu    $s5, $at
		jal     sub_81BBC
		lw      $a1, 4($s4)
		lw      $a0, 0($s4)
		jal     sub_81A8C
		lw      $a2, 8($s4)
		lh      $a0, 0xC($s4)
		jal     sub_81858
		nop
		lhu     $v1, 2($s5)
		cfc2    $at, $7
		srl     $v1, 2
		sll     $v1, 10
		beqz    $v1, loc_82704
		slt     $at, $v1, $at
		beqz    $at, loc_82704
		nop
		addiu   $s5, 0x1C

		loc_82704:
	jal     sub_811FC
		addiu   $a0, $s5, 4
		beqz    $v0, loc_8274C
		lw      $a3, 0x80 + var_38($fp)
		lw      $a2, 0x80 + var_40($fp)
		addiu   $a3, 1
		sw      $a3, 0x80 + var_38($fp)
		sh      $v0, 0($a2)
		sw      $s4, 4($a2)
		sh      $zero, 2($a2)
		addiu   $a2, 0xC
		sw      $a2, 0x80 + var_40($fp)
		lh      $v1, 0($s5)
		lw      $v0, 0x80 + arg_20($fp)
		sll     $v1, 2
		addu    $v0, $v1
		jal     sub_81750
		lw      $a0, 0($v0)

		loc_8274C:
	jal     sub_81C0C

		loc_82750 :
	addiu   $s3, -1
		bgtz    $s3, loc_82698
		addiu   $s4, 0x14

		loc_8275C :
		lh      $s2, 0x48($s2)
		li      $v1, 0xFFFFFFFF
		beq     $s2, $v1, loc_827CC
		sll     $v0, $s2, 7

		loc_8276C :
		sll     $v1, $s2, 4
		lw      $s3, 0x80 + var_20($fp)
		addu    $v0, $v1
		addu    $s3, $v0
		lh      $v1, 0xC($s3)
		li      $s6, 0x1F2480//objects?
		sll     $v1, 6
		addu    $s6, $v1
		lhu     $v0, 0x32($s6)
		lw      $a1, 0x84($s3)
		andi    $v0, 0x200
		beqz    $v0, loc_827BC
		li      $v1, 6
		andi    $a1, 6
		beq     $a1, $v1, loc_827BC
		nop
		jal     sub_81504
		move    $s2, $s3
		move    $s3, $s2

		loc_827BC :
	lh      $s2, 0x1A($s3)
		li      $v0, 0xFFFFFFFF
		bne     $s2, $v0, loc_8276C
		sll     $v0, $s2, 7

		loc_827CC :
		jal     sub_81C0C
		addiu   $s1, -1
		bnez    $s1, loc_82658
		addiu   $s0, 2

		loc_827DC :
		lw      $s4, 0x80 + var_38($fp)
		lui     $gp, 0xA
		jal     sub_82900
		la      $gp, aTwat       # "TWAT"
		lw      $ra, 0x80 + var_44($sp)
		lw      $fp, 0x80 + var_48($sp)
		lw      $s7, 0x80 + var_4C($sp)
		lw      $s6, 0x80 + var_50($sp)
		lw      $s5, 0x80 + var_54($sp)
		lw      $s4, 0x80 + var_58($sp)
		lw      $s3, 0x80 + var_5C($sp)
		lw      $s2, 0x80 + var_60($sp)
		lw      $s1, 0x80 + var_64($sp)
		lw      $s0, 0x80 + var_68($sp)
		jr      $ra
		addiu   $sp, 0x80
#endif
}

void DrawEffect(short item_num)
{
	struct FX_INFO* fx = &effects[item_num];
	struct object_info* obj = &objects[fx->object_number];

	if (obj->draw_routine != NULL && obj->loaded)
	{
		mPushMatrix();
		mTranslateAbsXYZ(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos);

		if (Matrix->tz < 20480)
		{
			mRotYXZ(fx->pos.y_rot, fx->pos.x_rot, fx->pos.z_rot);

			S_CalculateLight(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos, fx->room_number, &duff_item.il);
			duff_item.il.Light[3].pad = 0;

			phd_PutPolygons(meshes[obj->nmeshes != 0 ? obj->mesh_index : fx->frame_number], -1);
		}

		mPopMatrix();
	}
}

void PrintAllOtherObjects_ASM(short room_num /*s3*/)//(F)
{
	struct room_info* r = &room[room_num];
	struct ITEM_INFO* item = NULL;
	struct object_info* object;
	short item_num;
	struct FX_INFO* effect;
	int mesh_num;
	short* mesh;
	int effect_num;

	r->bound_active = 0;
	mPushMatrix();
	mTranslateAbsXYZ(r->x, r->y, r->z);

	phd_right = 512;
	phd_bottom = 240;
	phd_left = 0;
	phd_top = 0;

	item_num = r->item_number;

	if (item_num != -1)
	{
		do
		{
			item = &items[item_num];
			object = &objects[item->object_number];

			if (item->status != 6)
			{
				if (!object->using_drawanimating_item && object->draw_routine != NULL)
				{
					object->draw_routine(item);
				}
			}
			//loc_8F5AC
			if (object->draw_routine_extra != NULL)
			{
				object->draw_routine_extra(item);
			}

			//loc_8F5C4
			if (item->after_death - 1 < 127)
			{
				item->after_death++;

				if (item->after_death == 128)
				{
					KillItem(r->item_number);
				}
			}//loc_8F5EC

			item_num = item->next_item;
		} while (item_num != -1);

	}//loc_8F5FC

	effect_num = r->fx_number;

	if (effect_num != -1)
	{
		//loc_8F608
		do
		{
			effect = &effect[effect_num];
			object = &objects[effect->object_number];

			if (object->draw_routine != NULL && object->loaded)
			{
				mPushMatrix();
				mTranslateAbsXYZ(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos);

				if (((int*)MatrixStack)[2] - 21 < 20459)
				{
					mRotYXZ(effect->pos.y_rot, effect->pos.x_rot, effect->pos.z_rot);

					duff_item.il.Light[3].pad = 0;
					S_CalculateLight(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos, effect->room_number, &duff_item.il);

					mesh_num = effect->frame_number;

					if (object->nmeshes != 0)
					{
						mesh_num = object->mesh_index;
					}//loc_8F6C0

					phd_PutPolygons(meshes[mesh_num], -1);
				}//loc_8F6D8

				mPopMatrix();

				//loc_8F6E0
				effect_num = effect->next_fx;
			}
		} while (effect_num != -1);//loc_8F6E0
	}//loc_8F6EC

	mPopMatrix();
	((int*)&r->left)[0] = 511;
	((int*)&r->top)[0] = 239;
}

void print_all_object_NOW()//8F474(<), 914B8(<) (F)
{
	CalcAllAnimatingItems_ASM();

	for (int i = 0; i < number_draw_rooms; i++)
	{
		PrintAllOtherObjects_ASM(draw_rooms[i]);
	}
}<|endoftext|>


<commit_before>#include "xUnitAssert.h"

namespace
{
    std::string AssembleWhat(const std::string &call, const std::vector<std::string> &userMsg, const std::string &customMsg,
                             const std::string &expected, const std::string &actual)
    {
        std::string msg = call + "() failure";
        if (!userMsg.empty())
        {
            msg += ": ";

            for (const auto &s : userMsg)
            {
                msg += s;
            }

            if (!customMsg.empty())
            {
                msg += "\n     " + customMsg;
            }
        }
        else
        {
            if (!customMsg.empty())
            {
                msg += ": " + customMsg;
            }
        }

        if (!expected.empty())
        {
            msg += "\n     Expected: " + expected;
            msg += "\n       Actual: " + actual;
        }

        return msg;
    }
}

namespace xUnitpp
{

const xUnitAssert &xUnitAssert::None()
{
    static xUnitAssert none("", xUnitpp::LineInfo());
    return none;
}

xUnitAssert::xUnitAssert(std::string &&call, xUnitpp::LineInfo &&lineInfo)
    : lineInfo(std::move(lineInfo))
    , call(std::move(call))
{
}

xUnitAssert &xUnitAssert::CustomMessage(std::string &&message)
{
    customMessage = std::move(message);
    return *this;
}

xUnitAssert &xUnitAssert::Expected(std::string &&str)
{
    expected = std::move(str);
    return *this;
}

xUnitAssert &xUnitAssert::Actual(std::string &&str)
{
    actual = std::move(str);
    return *this;
}

const LineInfo &xUnitAssert::LineInfo() const
{
    return lineInfo;
}

const char *xUnitAssert::what() const noexcept(true)
{
    if (whatMessage.empty())
    {
        whatMessage = AssembleWhat(call, userMessage, customMessage, expected, actual);
    }

    return whatMessage.c_str();
}

xUnitFailure::xUnitFailure()
    : OnFailureComplete([](const xUnitAssert &){})
    , assert(xUnitAssert::None())
    , refCount(*(new int(0)))
{
}

xUnitFailure::xUnitFailure(xUnitAssert &&assert, std::function<void(const xUnitAssert &)> onFailureComplete)
    : OnFailureComplete(onFailureComplete)
    , assert(std::move(assert))
    , refCount(*(new int(1)))
{
}

xUnitFailure::xUnitFailure(const xUnitFailure &other)
    : OnFailureComplete(other.OnFailureComplete)
    , assert(other.assert)
    , refCount(other.refCount)
{
    refCount++;
}

xUnitFailure::~xUnitFailure() noexcept(false)
{
    if (!--refCount)
    {
        delete &refCount;

        // http://cpp-next.com/archive/2012/08/evil-or-just-misunderstood/
        // http://akrzemi1.wordpress.com/2011/09/21/destructors-that-throw/
        // throwing destructors aren't Evil, just misunderstood
        OnFailureComplete(assert);
    }
}

xUnitFailure xUnitFailure::None()
{
    return xUnitFailure();
}

xUnitFailure Assert::OnFailure(xUnitAssert &&assert) const
{
    return xUnitFailure(std::move(assert), handleFailure);
}

xUnitFailure Assert::OnSuccess() const
{
    return xUnitFailure::None();
}

double Assert::round(double value, size_t precision)
{
    if (value < 0)
    {
        return std::ceil((value - 0.5) * std::pow(10, precision)) / std::pow(10, precision);
    }
    else
    {
        return std::floor((value + 0.5) * std::pow(10, precision)) / std::pow(10, precision);
    }
}

xUnitFailure Assert::Equal(const std::string &expected, const std::string &actual, LineInfo &&lineInfo) const
{
    if (expected != actual)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "Equal", std::move(lineInfo))
            .Expected(std::string(expected))    // can't assume expected or actual are allowed to be moved
            .Actual(std::string(actual))));
    }

    return OnSuccess();
}

xUnitFailure Assert::Equal(const char *expected, const char *actual, LineInfo &&lineInfo) const
{
    return Equal(std::string(expected), std::string(actual), std::move(lineInfo));
}

xUnitFailure Assert::Equal(const char *expected, const std::string &actual, LineInfo &&lineInfo) const
{
    return Equal(std::string(expected), actual, std::move(lineInfo));
}

xUnitFailure Assert::Equal(const std::string &expected, const char *actual, LineInfo &&lineInfo) const
{
    return Equal(expected, std::string(actual), std::move(lineInfo));
}

xUnitFailure Assert::Equal(float expected, float actual, int precision, LineInfo &&lineInfo) const
{
    return Equal((double)expected, (double)actual, precision, std::move(lineInfo));
}

xUnitFailure Assert::Equal(double expected, double actual, int precision, LineInfo &&lineInfo) const
{
    auto er = round(expected, precision);
    auto ar = round(actual, precision);

    return Equal(er, ar, [](double er, double ar) { return er == ar; }, std::move(lineInfo));
}

xUnitFailure Assert::NotEqual(const std::string &expected, const std::string &actual, LineInfo &&lineInfo) const
{
    if (expected == actual)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "NotEqual", std::move(lineInfo))
            .Expected(std::string(expected))    // can't assume expected or actual are allowed to be moved
            .Actual(std::string(actual))));
    }

    return OnSuccess();
}

xUnitFailure Assert::NotEqual(const char *expected, const char *actual, LineInfo &&lineInfo) const
{
    return NotEqual(std::string(expected), std::string(actual), std::move(lineInfo));
}

xUnitFailure Assert::NotEqual(const char *expected, const std::string &actual, LineInfo &&lineInfo) const
{
    return NotEqual(std::string(expected), actual, std::move(lineInfo));
}

xUnitFailure Assert::NotEqual(const std::string &expected, const char *actual, LineInfo &&lineInfo) const
{
    return NotEqual(expected, std::string(actual), std::move(lineInfo));
}

xUnitFailure Assert::Fail(LineInfo &&lineInfo) const
{
    return OnFailure(std::move(xUnitAssert(callPrefix + "Fail", std::move(lineInfo))));
}

xUnitFailure Assert::False(bool b, LineInfo &&lineInfo) const
{
    if (b)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "False", std::move(lineInfo)).Expected("false").Actual("true")));
    }

    return OnSuccess();
}

xUnitFailure Assert::True(bool b, LineInfo &&lineInfo) const
{
    if (!b)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "True", std::move(lineInfo)).Expected("true").Actual("false")));
    }

    return OnSuccess();
}

xUnitFailure Assert::DoesNotContain(const char *actualString, const char *value, LineInfo &&lineInfo) const
{
    const auto a = std::string(actualString);
    const auto v = std::string(value);
    return DoesNotContain(a, v, std::move(lineInfo));
}

xUnitFailure Assert::DoesNotContain(const char *actualString, const std::string &value, LineInfo &&lineInfo) const
{
    const auto a = std::string(actualString);
    return DoesNotContain(a, value, std::move(lineInfo));
}

xUnitFailure Assert::DoesNotContain(const std::string &actualString, const char *value, LineInfo &&lineInfo) const
{
    const auto v = std::string(value);
    return DoesNotContain(actualString, v, std::move(lineInfo));
}

xUnitFailure Assert::DoesNotContain(const std::string &actualString, const std::string &value, LineInfo &&lineInfo) const
{
    auto found = actualString.find(value);
    if (found != std::string::npos)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "DoesNotContain", std::move(lineInfo))
            .CustomMessage("Found: \"" + value + "\" at position " + ToString(found) + ".")));
    }

    return OnSuccess();
}

xUnitFailure Assert::Contains(const char *actualString, const char *value, LineInfo &&lineInfo) const
{
    const auto a = std::string(actualString);
    const auto v = std::string(value);
    return Contains(a, v, std::move(lineInfo));
}

xUnitFailure Assert::Contains(const char *actualString, const std::string &value, LineInfo &&lineInfo) const
{
    const auto a = std::string(actualString);
    return Contains(a, value, std::move(lineInfo));
}

xUnitFailure Assert::Contains(const std::string &actualString, const char *value, LineInfo &&lineInfo) const
{
    const auto v = std::string(value);
    return Contains(actualString, v, std::move(lineInfo));
}

xUnitFailure Assert::Contains(const std::string &actualString, const std::string &value, LineInfo &&lineInfo) const
{
    if (actualString.find(value) == std::string::npos)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "Contains", std::move(lineInfo))
            .Expected(std::string(actualString))    // can't assume actualString or value can be moved
            .Actual(std::string(value))));
    }

    return OnSuccess();
}

Assert::Assert(std::string &&callPrefix, std::function<void (const xUnitAssert &)> &&onFailure)
    : callPrefix(std::move(callPrefix))
    , handleFailure(std::move(onFailure))
{
}

}
<commit_msg>xUnitAssert.cpp needs <cmath> to compile properly with OS X clang++<commit_after>#include "xUnitAssert.h"
#include <cmath>

namespace
{
    std::string AssembleWhat(const std::string &call, const std::vector<std::string> &userMsg, const std::string &customMsg,
                             const std::string &expected, const std::string &actual)
    {
        std::string msg = call + "() failure";
        if (!userMsg.empty())
        {
            msg += ": ";

            for (const auto &s : userMsg)
            {
                msg += s;
            }

            if (!customMsg.empty())
            {
                msg += "\n     " + customMsg;
            }
        }
        else
        {
            if (!customMsg.empty())
            {
                msg += ": " + customMsg;
            }
        }

        if (!expected.empty())
        {
            msg += "\n     Expected: " + expected;
            msg += "\n       Actual: " + actual;
        }

        return msg;
    }
}

namespace xUnitpp
{

const xUnitAssert &xUnitAssert::None()
{
    static xUnitAssert none("", xUnitpp::LineInfo());
    return none;
}

xUnitAssert::xUnitAssert(std::string &&call, xUnitpp::LineInfo &&lineInfo)
    : lineInfo(std::move(lineInfo))
    , call(std::move(call))
{
}

xUnitAssert &xUnitAssert::CustomMessage(std::string &&message)
{
    customMessage = std::move(message);
    return *this;
}

xUnitAssert &xUnitAssert::Expected(std::string &&str)
{
    expected = std::move(str);
    return *this;
}

xUnitAssert &xUnitAssert::Actual(std::string &&str)
{
    actual = std::move(str);
    return *this;
}

const LineInfo &xUnitAssert::LineInfo() const
{
    return lineInfo;
}

const char *xUnitAssert::what() const noexcept(true)
{
    if (whatMessage.empty())
    {
        whatMessage = AssembleWhat(call, userMessage, customMessage, expected, actual);
    }

    return whatMessage.c_str();
}

xUnitFailure::xUnitFailure()
    : OnFailureComplete([](const xUnitAssert &){})
    , assert(xUnitAssert::None())
    , refCount(*(new int(0)))
{
}

xUnitFailure::xUnitFailure(xUnitAssert &&assert, std::function<void(const xUnitAssert &)> onFailureComplete)
    : OnFailureComplete(onFailureComplete)
    , assert(std::move(assert))
    , refCount(*(new int(1)))
{
}

xUnitFailure::xUnitFailure(const xUnitFailure &other)
    : OnFailureComplete(other.OnFailureComplete)
    , assert(other.assert)
    , refCount(other.refCount)
{
    refCount++;
}

xUnitFailure::~xUnitFailure() noexcept(false)
{
    if (!--refCount)
    {
        delete &refCount;

        // http://cpp-next.com/archive/2012/08/evil-or-just-misunderstood/
        // http://akrzemi1.wordpress.com/2011/09/21/destructors-that-throw/
        // throwing destructors aren't Evil, just misunderstood
        OnFailureComplete(assert);
    }
}

xUnitFailure xUnitFailure::None()
{
    return xUnitFailure();
}

xUnitFailure Assert::OnFailure(xUnitAssert &&assert) const
{
    return xUnitFailure(std::move(assert), handleFailure);
}

xUnitFailure Assert::OnSuccess() const
{
    return xUnitFailure::None();
}

double Assert::round(double value, size_t precision)
{
    if (value < 0)
    {
        return std::ceil((value - 0.5) * std::pow(10, precision)) / std::pow(10, precision);
    }
    else
    {
        return std::floor((value + 0.5) * std::pow(10, precision)) / std::pow(10, precision);
    }
}

xUnitFailure Assert::Equal(const std::string &expected, const std::string &actual, LineInfo &&lineInfo) const
{
    if (expected != actual)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "Equal", std::move(lineInfo))
            .Expected(std::string(expected))    // can't assume expected or actual are allowed to be moved
            .Actual(std::string(actual))));
    }

    return OnSuccess();
}

xUnitFailure Assert::Equal(const char *expected, const char *actual, LineInfo &&lineInfo) const
{
    return Equal(std::string(expected), std::string(actual), std::move(lineInfo));
}

xUnitFailure Assert::Equal(const char *expected, const std::string &actual, LineInfo &&lineInfo) const
{
    return Equal(std::string(expected), actual, std::move(lineInfo));
}

xUnitFailure Assert::Equal(const std::string &expected, const char *actual, LineInfo &&lineInfo) const
{
    return Equal(expected, std::string(actual), std::move(lineInfo));
}

xUnitFailure Assert::Equal(float expected, float actual, int precision, LineInfo &&lineInfo) const
{
    return Equal((double)expected, (double)actual, precision, std::move(lineInfo));
}

xUnitFailure Assert::Equal(double expected, double actual, int precision, LineInfo &&lineInfo) const
{
    auto er = round(expected, precision);
    auto ar = round(actual, precision);

    return Equal(er, ar, [](double er, double ar) { return er == ar; }, std::move(lineInfo));
}

xUnitFailure Assert::NotEqual(const std::string &expected, const std::string &actual, LineInfo &&lineInfo) const
{
    if (expected == actual)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "NotEqual", std::move(lineInfo))
            .Expected(std::string(expected))    // can't assume expected or actual are allowed to be moved
            .Actual(std::string(actual))));
    }

    return OnSuccess();
}

xUnitFailure Assert::NotEqual(const char *expected, const char *actual, LineInfo &&lineInfo) const
{
    return NotEqual(std::string(expected), std::string(actual), std::move(lineInfo));
}

xUnitFailure Assert::NotEqual(const char *expected, const std::string &actual, LineInfo &&lineInfo) const
{
    return NotEqual(std::string(expected), actual, std::move(lineInfo));
}

xUnitFailure Assert::NotEqual(const std::string &expected, const char *actual, LineInfo &&lineInfo) const
{
    return NotEqual(expected, std::string(actual), std::move(lineInfo));
}

xUnitFailure Assert::Fail(LineInfo &&lineInfo) const
{
    return OnFailure(std::move(xUnitAssert(callPrefix + "Fail", std::move(lineInfo))));
}

xUnitFailure Assert::False(bool b, LineInfo &&lineInfo) const
{
    if (b)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "False", std::move(lineInfo)).Expected("false").Actual("true")));
    }

    return OnSuccess();
}

xUnitFailure Assert::True(bool b, LineInfo &&lineInfo) const
{
    if (!b)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "True", std::move(lineInfo)).Expected("true").Actual("false")));
    }

    return OnSuccess();
}

xUnitFailure Assert::DoesNotContain(const char *actualString, const char *value, LineInfo &&lineInfo) const
{
    const auto a = std::string(actualString);
    const auto v = std::string(value);
    return DoesNotContain(a, v, std::move(lineInfo));
}

xUnitFailure Assert::DoesNotContain(const char *actualString, const std::string &value, LineInfo &&lineInfo) const
{
    const auto a = std::string(actualString);
    return DoesNotContain(a, value, std::move(lineInfo));
}

xUnitFailure Assert::DoesNotContain(const std::string &actualString, const char *value, LineInfo &&lineInfo) const
{
    const auto v = std::string(value);
    return DoesNotContain(actualString, v, std::move(lineInfo));
}

xUnitFailure Assert::DoesNotContain(const std::string &actualString, const std::string &value, LineInfo &&lineInfo) const
{
    auto found = actualString.find(value);
    if (found != std::string::npos)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "DoesNotContain", std::move(lineInfo))
            .CustomMessage("Found: \"" + value + "\" at position " + ToString(found) + ".")));
    }

    return OnSuccess();
}

xUnitFailure Assert::Contains(const char *actualString, const char *value, LineInfo &&lineInfo) const
{
    const auto a = std::string(actualString);
    const auto v = std::string(value);
    return Contains(a, v, std::move(lineInfo));
}

xUnitFailure Assert::Contains(const char *actualString, const std::string &value, LineInfo &&lineInfo) const
{
    const auto a = std::string(actualString);
    return Contains(a, value, std::move(lineInfo));
}

xUnitFailure Assert::Contains(const std::string &actualString, const char *value, LineInfo &&lineInfo) const
{
    const auto v = std::string(value);
    return Contains(actualString, v, std::move(lineInfo));
}

xUnitFailure Assert::Contains(const std::string &actualString, const std::string &value, LineInfo &&lineInfo) const
{
    if (actualString.find(value) == std::string::npos)
    {
        return OnFailure(std::move(xUnitAssert(callPrefix + "Contains", std::move(lineInfo))
            .Expected(std::string(actualString))    // can't assume actualString or value can be moved
            .Actual(std::string(value))));
    }

    return OnSuccess();
}

Assert::Assert(std::string &&callPrefix, std::function<void (const xUnitAssert &)> &&onFailure)
    : callPrefix(std::move(callPrefix))
    , handleFailure(std::move(onFailure))
{
}

}
<|endoftext|>


<commit_before>/**
 * Exercise 5 : Read in a gph-file, computes the longest (with respect to the edge weights) shortest path from any vertex to the vertex with index 1.
 *
 * @author FirstSanny
 */

#include <iostream>
#include <fstream>
#include <utility>
#include <vector>
#include <climits>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/named_function_params.hpp>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>
#include "Dijkstra.h"

// Constants
namespace {

const char* FILEEND = ".gph";

}

// declaring print
using std::cout;
using std::endl;
using std::cerr;
using std::string;

// declaring types
namespace po = boost::program_options;
using Graph = boost::adjacency_list<boost::listS, boost::vecS,
  boost::undirectedS, boost::no_property,
  boost::property<boost::edge_weight_t, int>> ;
using VertexDescriptor = boost::graph_traits < Graph >::vertex_descriptor;
using Directions = std::vector<VertexDescriptor >;
using Edge = std::pair<int, int>;
using Edges = std::vector<Edge >;
using Weights = std::vector<int >;

po::variables_map parseCommandLine(po::options_description desc, int argn,
		char* argv[]) {
	desc.add_options()("help", "produce help message")("algo,m",
			po::value<int>(),
			"algorithm to solve shortest Path. \n 1 - libary (boost)\n 2 - own Algo")(
			"input-file", po::value<string>(), "input file");
	po::positional_options_description p;
	p.add("input-file", -1);
	po::variables_map vm;
	po::store(
			po::command_line_parser(argn, argv).options(desc).positional(p).run(),
			vm);
	po::notify(vm);
	return vm;
}

char parseAlgoOption(const po::variables_map& vm, char useOwnAlgo) {
	if (vm.count("algo")) {
		useOwnAlgo = vm["algo"].as<int>();
		if (useOwnAlgo == 2) {
			useOwnAlgo = 0;
		}
		if (useOwnAlgo != 1 && useOwnAlgo != 0) {
			cout
					<< "No valid Option was given for Algorithm! Fallback: algo from libary"
					<< endl;
		}
	}
	if (useOwnAlgo) {
		cout << "Using own algorithm..." << endl;
	} else {
		cout << "Using algorithm from boost-libary..." << endl;
	}
	return useOwnAlgo;
}

/** Reading in a Graphfile, computes the longest shortest path */
int main(int argn, char *argv[]) {
	boost::timer::auto_cpu_timer t;
	if (argn <= 1) {
		cerr << "ERROR : There was no filename" << endl;
		return 1;
	}

	po::options_description desc("Allowed options");
	po::variables_map vm = parseCommandLine(desc, argn, argv);

	if (vm.count("help")) {
	    cout << desc << "\n";
	    return 1;
	}
	char useOwnAlgo = 0;
	useOwnAlgo = parseAlgoOption(vm, useOwnAlgo);

	std::ifstream fileStream;
	if(vm.count("input-file") == 0){
		cerr << "No input-file was given!" << endl;
		return 1;
	}

	string filename = vm["input-file"].as<string >();
	filename += FILEEND;
	cout << "Going to parse the file " << filename << endl;
	fileStream.open(filename.c_str(), std::ios::in);

	if ( (fileStream.rdstate()) != 0 ){
		std::perror("ERROR : Encoutered Problem opening file");
		return 1;
	}

	string line;

	unsigned int edgeCount;
	unsigned int vertexCount;

	if(std::getline(fileStream, line)){
		sscanf(line.c_str(), "%d %d", &vertexCount, &edgeCount);
		cout << "Vertexcount: " << vertexCount << endl;
		cout << "Edgecount: " << edgeCount << endl;
		line.clear();
		vertexCount++;
	} else {
		cerr << "ERROR : File was empty" << endl;
		return 1;
	}

	Edges* edges = new Edges(edgeCount);
	Weights* weights = new Weights(edgeCount);

	cout << "Reading edges..." << endl;
	while (getline(fileStream, line)) {
		int start;
		int end;
		int weight;
		int count = sscanf(line.c_str(), "%d %d %d", &start, &end, &weight);
		if (count != 3) {
			line.clear();
			continue;
		}
		edges->push_back(std::make_pair(start, end));
		weights->push_back(weight);
		line.clear();
	}

	Weights weightsForShortestpath;

	if(useOwnAlgo){
		cout << "Compute shortest paths via Dijkstra(own)..." << endl;
		Dijkstra* d = new Dijkstra();
		weightsForShortestpath = d->dijkstra(vertexCount, *edges, *weights, 1);
	} else {

		cout << "Creating graph..." << endl;
		Graph g{edges->begin(), edges->end(), weights->begin(), vertexCount};

		Directions* directions = new std::vector<VertexDescriptor>(vertexCount);
		cout << "Compute shortest paths via Dijkstra(boost)..." << endl;
		std::vector<int>* weightMapPointer = new std::vector<int>(vertexCount);
		boost::dijkstra_shortest_paths(g, 1,
			boost::predecessor_map(//
					boost::make_iterator_property_map(directions->begin(), boost::get(boost::vertex_index, g))) //
				.distance_map(//
					boost::make_iterator_property_map(weightMapPointer->begin(), boost::get(boost::vertex_index, g))));
		weightsForShortestpath = *weightMapPointer;
		delete weightMapPointer;
		delete directions;
	}

	cout << "Search longest shortest path..." << endl;
	int vertex = 1;
	int distance = 0;

	for(unsigned int i=2; i<vertexCount; i++){
		if(weightsForShortestpath[i]>distance){
			distance = weightsForShortestpath[i];
			vertex = i;
		}
	}

	cout << "RESULT VERTEX " << vertex << endl;
	cout << "RESULT DIST " << distance << endl;

	delete edges;
	delete weights;

	return 0;
}
<commit_msg>getting m1 and m2 right<commit_after>/**
 * Exercise 5 : Read in a gph-file, computes the longest (with respect to the edge weights) shortest path from any vertex to the vertex with index 1.
 *
 * @author FirstSanny
 */

#include <iostream>
#include <fstream>
#include <utility>
#include <vector>
#include <climits>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/named_function_params.hpp>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>
#include "Dijkstra.h"

// Constants
namespace {

const char* FILEEND = ".gph";

}

// declaring print
using std::cout;
using std::endl;
using std::cerr;
using std::string;

// declaring types
namespace po = boost::program_options;
using Graph = boost::adjacency_list<boost::listS, boost::vecS,
  boost::undirectedS, boost::no_property,
  boost::property<boost::edge_weight_t, int>> ;
using VertexDescriptor = boost::graph_traits < Graph >::vertex_descriptor;
using Directions = std::vector<VertexDescriptor >;
using Edge = std::pair<int, int>;
using Edges = std::vector<Edge >;
using Weights = std::vector<int >;

po::variables_map parseCommandLine(po::options_description desc, int argn,
		char* argv[]) {
	desc.add_options()("help", "produce help message")("algo,m",
			po::value<int>(),
			"algorithm to solve shortest Path. \n 1 - libary (boost)\n 2 - own Algo")(
			"input-file", po::value<string>(), "input file");
	po::positional_options_description p;
	p.add("input-file", -1);
	po::variables_map vm;
	po::store(
			po::command_line_parser(argn, argv).options(desc).positional(p).run(),
			vm);
	po::notify(vm);
	return vm;
}

char parseAlgoOption(const po::variables_map& vm, char useOwnAlgo) {
	if (vm.count("algo")) {
		useOwnAlgo = vm["algo"].as<int>();
		useOwnAlgo--;
		if (useOwnAlgo != 1 && useOwnAlgo != 0) {
			cout << "No valid Option was given for Algorithm! Fallback: algo from libary" << endl;
			useOwnAlgo = 0;
		}
	}
	if (useOwnAlgo) {
		cout << "Using own algorithm..." << endl;
	} else {
		cout << "Using algorithm from boost-libary..." << endl;
	}
	return useOwnAlgo;
}

/** Reading in a Graphfile, computes the longest shortest path */
int main(int argn, char *argv[]) {
	boost::timer::auto_cpu_timer t;
	if (argn <= 1) {
		cerr << "ERROR : There was no filename" << endl;
		return 1;
	}

	po::options_description desc("Allowed options");
	po::variables_map vm = parseCommandLine(desc, argn, argv);

	if (vm.count("help")) {
	    cout << desc << "\n";
	    return 1;
	}
	char useOwnAlgo = 0;
	useOwnAlgo = parseAlgoOption(vm, useOwnAlgo);

	std::ifstream fileStream;
	if(vm.count("input-file") == 0){
		cerr << "No input-file was given!" << endl;
		return 1;
	}

	string filename = vm["input-file"].as<string >();
	filename += FILEEND;
	cout << "Going to parse the file " << filename << endl;
	fileStream.open(filename.c_str(), std::ios::in);

	if ( (fileStream.rdstate()) != 0 ){
		std::perror("ERROR : Encoutered Problem opening file");
		return 1;
	}

	string line;

	unsigned int edgeCount;
	unsigned int vertexCount;

	if(std::getline(fileStream, line)){
		sscanf(line.c_str(), "%d %d", &vertexCount, &edgeCount);
		cout << "Vertexcount: " << vertexCount << endl;
		cout << "Edgecount: " << edgeCount << endl;
		line.clear();
		vertexCount++;
	} else {
		cerr << "ERROR : File was empty" << endl;
		return 1;
	}

	Edges* edges = new Edges(edgeCount);
	Weights* weights = new Weights(edgeCount);

	cout << "Reading edges..." << endl;
	while (getline(fileStream, line)) {
		int start;
		int end;
		int weight;
		int count = sscanf(line.c_str(), "%d %d %d", &start, &end, &weight);
		if (count != 3) {
			line.clear();
			continue;
		}
		edges->push_back(std::make_pair(start, end));
		weights->push_back(weight);
		line.clear();
	}

	Weights weightsForShortestpath;

	if(useOwnAlgo){
		cout << "Compute shortest paths via Dijkstra(own)..." << endl;
		Dijkstra* d = new Dijkstra();
		weightsForShortestpath = d->dijkstra(vertexCount, *edges, *weights, 1);
	} else {

		cout << "Creating graph..." << endl;
		Graph g{edges->begin(), edges->end(), weights->begin(), vertexCount};

		Directions* directions = new std::vector<VertexDescriptor>(vertexCount);
		cout << "Compute shortest paths via Dijkstra(boost)..." << endl;
		std::vector<int>* weightMapPointer = new std::vector<int>(vertexCount);
		boost::dijkstra_shortest_paths(g, 1,
			boost::predecessor_map(//
					boost::make_iterator_property_map(directions->begin(), boost::get(boost::vertex_index, g))) //
				.distance_map(//
					boost::make_iterator_property_map(weightMapPointer->begin(), boost::get(boost::vertex_index, g))));
		weightsForShortestpath = *weightMapPointer;
		delete weightMapPointer;
		delete directions;
	}

	cout << "Search longest shortest path..." << endl;
	int vertex = 1;
	int distance = 0;

	for(unsigned int i=2; i<vertexCount; i++){
		if(weightsForShortestpath[i]>distance){
			distance = weightsForShortestpath[i];
			vertex = i;
		}
	}

	cout << "RESULT VERTEX " << vertex << endl;
	cout << "RESULT DIST " << distance << endl;

	delete edges;
	delete weights;

	return 0;
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   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.
*/

//!    File   : Scripting.cpp
//!    Author : Jens Krueger
//!             SCI Institute
//!             University of Utah
//!    Date   : January 2009
//
//!    Copyright (C) 2008 SCI Institute

#include "Scripting.h"
#include <Controller/MasterController.h>
#include <Basics/SysTools.h>

#include <sstream>

using namespace std;

ScriptableListElement::ScriptableListElement(Scriptable* source, const std::string& strCommand, const std::string& strParameters, const std::string& strDescription) :
      m_source(source),
      m_strCommand(strCommand),
      m_strDescription(strDescription)
{
  m_vParameters = SysTools::Tokenize(strParameters, false);

  m_iMaxParam = UINT32(m_vParameters.size());
  m_iMinParam = 0;

  bool bFoundOptional = false;
  for (UINT32 i = 0;i<m_iMaxParam;i++) {
    if (m_vParameters[i][0] == '[' && m_vParameters[i][m_vParameters[i].size()-1] == ']') {
      bFoundOptional = true;
      m_vParameters[i] = string(m_vParameters[i].begin()+1, m_vParameters[i].end()-1);
    } else {
      if (!bFoundOptional)
        m_iMinParam++;
      // else // this else would be an syntax error case but lets just assume all parameters after the first optional parameter are also optional
    }
  }
}

Scripting::Scripting(MasterController* pMasterController) :
  m_pMasterController(pMasterController),
  m_bEcho(false)
{
  RegisterCalls(this);
}

Scripting::~Scripting() {
  for (size_t i = 0;i<m_ScriptableList.size();i++) delete m_ScriptableList[i];
}

bool Scripting::RegisterCommand(Scriptable* source, const std::string& strCommand, const std::string& strParameters, const std::string& strDescription) {
  // commands may not contain whitespaces
  vector<string> strTest = SysTools::Tokenize(strCommand, false);
  if (strTest.size() != 1) return false;

  // commands must be unique
  for (size_t i = 0;i<m_ScriptableList.size();i++) {
    if (m_ScriptableList[i]->m_strCommand == strCommand) return false;
  }

  // ok, all seems fine: add the command to the list
  ScriptableListElement* elem = new ScriptableListElement(source, strCommand, strParameters, strDescription);
  m_ScriptableList.push_back(elem);
  return true;
}

bool Scripting::ParseLine(const string& strLine) {
  // tokenize string
  vector<string> vParameters = SysTools::Tokenize(strLine);

  string strMessage = "";
  bool bResult = ParseCommand(vParameters, strMessage);

  if (!bResult) {
    if (strMessage == "")
      m_pMasterController->DebugOut()->printf("Input \"%s\" not understood, try \"help\"!", strLine.c_str());
    else
      m_pMasterController->DebugOut()->printf(strMessage.c_str());
  } else
    if (m_bEcho) m_pMasterController->DebugOut()->printf("OK (%s)", strLine.c_str());

  return bResult;
}

bool Scripting::ParseCommand(const vector<string>& strTokenized, string& strMessage) {

  if (strTokenized.size() == 0) return false;
  string strCommand = strTokenized[0];
  vector<string> strParams(strTokenized.begin()+1, strTokenized.end());

  strMessage = "";
  for (size_t i = 0;i<m_ScriptableList.size();i++) {
    if (m_ScriptableList[i]->m_strCommand == strCommand) {
      if (strParams.size() >= m_ScriptableList[i]->m_iMinParam &&
          strParams.size() <= m_ScriptableList[i]->m_iMaxParam) {
        return m_ScriptableList[i]->m_source->Execute(strCommand, strParams, strMessage);
      } else {
         strMessage = "Parameter mismatch for command \""+strCommand+"\"";
         return false;
      }
    }
  }

  return false;
}

bool Scripting::ParseFile(const std::string& strFilename) {
  string line;
  ifstream fileData(strFilename.c_str());

  UINT32 iLine=0;
  if (fileData.is_open())
  {
    while (! fileData.eof() )
    {
      getline (fileData,line);
      iLine++;
      SysTools::RemoveLeadingWhitespace(line);
      if (line.size() == 0) continue;     // skip empty lines
      if (line[0] == '#') continue;       // skip comments

      if (!ParseLine(line)) {
        m_pMasterController->DebugOut()->Error("Scripting::ParseFile:","Error reading line %i in file %s (%s)", iLine, strFilename.c_str(), line.c_str());
        fileData.close();
        return false;
      }
    }
  } else {
    m_pMasterController->DebugOut()->Error("Scripting::ParseFile:","Error opening script file %s", strFilename.c_str());
    return false;
  }

  fileData.close();
  return true;
}

void Scripting::RegisterCalls(Scripting* pScriptEngine) {
  pScriptEngine->RegisterCommand(this, "help", "", "show all commands");
  pScriptEngine->RegisterCommand(this, "echo", "on/off", "turn feedback on succesfull command execution on or off");
}

bool Scripting::Execute(const std::string& strCommand, const std::vector< std::string >& strParams, std::string& strMessage) {
  strMessage = "";
  if (strCommand == "echo") {
    m_bEcho = SysTools::ToLowerCase(strParams[0]) == "on";
    return true;
  } else
  if (strCommand == "help") {
    m_pMasterController->DebugOut()->printf("Command Listing:");
    m_pMasterController->DebugOut()->printf("\"help\" : this help screen");
    for (size_t i = 0;i<m_ScriptableList.size();i++) {
      string strParams = "";
      for (size_t j = 0;j<m_ScriptableList[i]->m_iMinParam;j++) {
        strParams = strParams + m_ScriptableList[i]->m_vParameters[j];
        if (j != m_ScriptableList[i]->m_vParameters.size()-1) strParams = strParams + " ";
      }
      for (size_t j = m_ScriptableList[i]->m_iMinParam;j<m_ScriptableList[i]->m_iMaxParam;j++) {
        strParams = strParams + "["+m_ScriptableList[i]->m_vParameters[j]+"]";
        if (j != m_ScriptableList[i]->m_vParameters.size()-1) strParams = strParams + " ";
      }

      m_pMasterController->DebugOut()->printf("\"%s\" %s: %s", m_ScriptableList[i]->m_strCommand.c_str(), strParams.c_str(), m_ScriptableList[i]->m_strDescription.c_str());
    }
    return true;
  }

  return false;

}<commit_msg>Handle blank lines correctly.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   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.
*/

//!    File   : Scripting.cpp
//!    Author : Jens Krueger
//!             SCI Institute
//!             University of Utah
//!    Date   : January 2009
//
//!    Copyright (C) 2008 SCI Institute

#include "Scripting.h"
#include <Controller/MasterController.h>
#include <Basics/SysTools.h>

#include <sstream>

using namespace std;

ScriptableListElement::ScriptableListElement(Scriptable* source, const std::string& strCommand, const std::string& strParameters, const std::string& strDescription) :
      m_source(source),
      m_strCommand(strCommand),
      m_strDescription(strDescription)
{
  m_vParameters = SysTools::Tokenize(strParameters, false);

  m_iMaxParam = UINT32(m_vParameters.size());
  m_iMinParam = 0;

  bool bFoundOptional = false;
  for (UINT32 i = 0;i<m_iMaxParam;i++) {
    if (m_vParameters[i][0] == '[' && m_vParameters[i][m_vParameters[i].size()-1] == ']') {
      bFoundOptional = true;
      m_vParameters[i] = string(m_vParameters[i].begin()+1, m_vParameters[i].end()-1);
    } else {
      if (!bFoundOptional)
        m_iMinParam++;
      // else // this else would be an syntax error case but lets just assume all parameters after the first optional parameter are also optional
    }
  }
}

Scripting::Scripting(MasterController* pMasterController) :
  m_pMasterController(pMasterController),
  m_bEcho(false)
{
  RegisterCalls(this);
}

Scripting::~Scripting() {
  for (size_t i = 0;i<m_ScriptableList.size();i++) delete m_ScriptableList[i];
}

bool Scripting::RegisterCommand(Scriptable* source, const std::string& strCommand, const std::string& strParameters, const std::string& strDescription) {
  // commands may not contain whitespaces
  vector<string> strTest = SysTools::Tokenize(strCommand, false);
  if (strTest.size() != 1) return false;

  // commands must be unique
  for (size_t i = 0;i<m_ScriptableList.size();i++) {
    if (m_ScriptableList[i]->m_strCommand == strCommand) return false;
  }

  // ok, all seems fine: add the command to the list
  ScriptableListElement* elem = new ScriptableListElement(source, strCommand, strParameters, strDescription);
  m_ScriptableList.push_back(elem);
  return true;
}

bool Scripting::ParseLine(const string& strLine) {
  // tokenize string
  vector<string> vParameters = SysTools::Tokenize(strLine);
  if(vParameters.empty()) { return true; }

  string strMessage = "";
  bool bResult = ParseCommand(vParameters, strMessage);

  if (!bResult) {
    if (strMessage == "")
      m_pMasterController->DebugOut()->printf("Input \"%s\" not understood, try \"help\"!", strLine.c_str());
    else
      m_pMasterController->DebugOut()->printf(strMessage.c_str());
  } else
    if (m_bEcho) m_pMasterController->DebugOut()->printf("OK (%s)", strLine.c_str());

  return bResult;
}

bool Scripting::ParseCommand(const vector<string>& strTokenized, string& strMessage) {

  if (strTokenized.empty()) return false;
  string strCommand = strTokenized[0];
  vector<string> strParams(strTokenized.begin()+1, strTokenized.end());

  strMessage = "";
  for (size_t i = 0;i<m_ScriptableList.size();i++) {
    if (m_ScriptableList[i]->m_strCommand == strCommand) {
      if (strParams.size() >= m_ScriptableList[i]->m_iMinParam &&
          strParams.size() <= m_ScriptableList[i]->m_iMaxParam) {
        return m_ScriptableList[i]->m_source->Execute(strCommand, strParams, strMessage);
      } else {
         strMessage = "Parameter mismatch for command \""+strCommand+"\"";
         return false;
      }
    }
  }

  return false;
}

bool Scripting::ParseFile(const std::string& strFilename) {
  string line;
  ifstream fileData(strFilename.c_str());

  UINT32 iLine=0;
  if (fileData.is_open())
  {
    while (! fileData.eof() )
    {
      getline (fileData,line);
      iLine++;
      SysTools::RemoveLeadingWhitespace(line);
      if (line.size() == 0) continue;     // skip empty lines
      if (line[0] == '#') continue;       // skip comments

      if (!ParseLine(line)) {
        m_pMasterController->DebugOut()->Error("Scripting::ParseFile:","Error reading line %i in file %s (%s)", iLine, strFilename.c_str(), line.c_str());
        fileData.close();
        return false;
      }
    }
  } else {
    m_pMasterController->DebugOut()->Error("Scripting::ParseFile:","Error opening script file %s", strFilename.c_str());
    return false;
  }

  fileData.close();
  return true;
}

void Scripting::RegisterCalls(Scripting* pScriptEngine) {
  pScriptEngine->RegisterCommand(this, "help", "", "show all commands");
  pScriptEngine->RegisterCommand(this, "echo", "on/off", "turn feedback on succesfull command execution on or off");
}

bool Scripting::Execute(const std::string& strCommand, const std::vector< std::string >& strParams, std::string& strMessage) {
  strMessage = "";
  if (strCommand == "echo") {
    m_bEcho = SysTools::ToLowerCase(strParams[0]) == "on";
    return true;
  } else
  if (strCommand == "help") {
    m_pMasterController->DebugOut()->printf("Command Listing:");
    m_pMasterController->DebugOut()->printf("\"help\" : this help screen");
    for (size_t i = 0;i<m_ScriptableList.size();i++) {
      string strParams = "";
      for (size_t j = 0;j<m_ScriptableList[i]->m_iMinParam;j++) {
        strParams = strParams + m_ScriptableList[i]->m_vParameters[j];
        if (j != m_ScriptableList[i]->m_vParameters.size()-1) strParams = strParams + " ";
      }
      for (size_t j = m_ScriptableList[i]->m_iMinParam;j<m_ScriptableList[i]->m_iMaxParam;j++) {
        strParams = strParams + "["+m_ScriptableList[i]->m_vParameters[j]+"]";
        if (j != m_ScriptableList[i]->m_vParameters.size()-1) strParams = strParams + " ";
      }

      m_pMasterController->DebugOut()->printf("\"%s\" %s: %s", m_ScriptableList[i]->m_strCommand.c_str(), strParams.c_str(), m_ScriptableList[i]->m_strDescription.c_str());
    }
    return true;
  }

  return false;

}
<|endoftext|>


<commit_before>#include "TexManagementGL.h"

std::string TexManagementGL::fetchTexPath(TextureId texId)
{
	std::string pathComplete = texPath;
	switch(texId)
	{
	case TEXTURE_PACMAN:
		pathComplete += texPacman;
		break;
	case TEXTURE_WALL:
		pathComplete += texWall;
		break;
	case TEXTURE_PILL:
		pathComplete += texPill;
		break;
	case TEXTURE_PILL_BLOODY:
		pathComplete += texPillBloody;
		break;
	case TEXTURE_PILL_CONSUME:
		pathComplete += texConsume;
		break;
	default:
		pathComplete += texPlaceHolder;
		break;
	}
	return pathComplete;
}

void TexManagementGL::init()
{
	std::vector<TextureId>* loadTex = new std::vector<TextureId>();
	loadTex->push_back(TEXTURE_PACMAN);
	loadTex->push_back(TEXTURE_PILL);
	loadTex->push_back(TEXTURE_PILL_BLOODY);
	loadTex->push_back(TEXTURE_GHOST);
	loadTex->push_back(TEXTURE_WALL);
	loadTex->push_back(TEXTURE_PLACEHOLDER);
	loadTex->push_back(TEXTURE_CONSUME);

	std::string completePath;
	for(unsigned int i = 0; i < loadTex->size(); i++)
	{
		completePath = fetchTexPath(loadTex->at(i));
		Texture* tex = loadTexture(loadTex->at(i), completePath);

		textures->push_back(tex);
	}

	delete loadTex;
}
Texture* TexManagementGL::loadTexture(TextureId id, std::string completePath)
{
	Texture* texture = new Texture();
	texture->textureId = id;

	bool textureLoaded = LoadTGA(texture, completePath.c_str());
	if(textureLoaded)
	{
		//Creates a texture and put it's ID in the given integer variable
		glGenTextures(1, &(texture->texID));

		//Setting as active texture
		glBindTexture(GL_TEXTURE_2D, texture->texID);

		//Load texture into memory
		glTexImage2D(
			GL_TEXTURE_2D,
			0,
			texture->bpp / 8,
			texture->width,
			texture->height,
			0,
			texture->type,
			GL_UNSIGNED_BYTE,
			texture->imageData);
	}
	else
	{
		throw 0;
	}

	return texture;
}

Texture* TexManagementGL::getTexture(TextureId textureId)
{
	Texture* texture = NULL;

	bool textureFound = false;
	for(unsigned int i = 0; i < textures->size() && !textureFound; i++)
	{
		if(textures->at(i)->textureId == textureId)
		{
			texture = textures->at(i);
			textureFound = true;
		}
	}

	return texture;
}

TexManagementGL::TexManagementGL()
{
	textures = new std::vector<Texture*>();
}
TexManagementGL::~TexManagementGL()
{
	if(textures)
	{
		for(unsigned int i = 0; i < textures->size(); i++)
		{
			if(textures->at(i))
			{
				free(textures->at(i)->imageData); //Free raw image data
				if(textures->at(i))
				{
					delete textures->at(i);
					textures->at(i) = NULL;
				}
			}
		}
		delete textures;
	}
}<commit_msg>redundant<commit_after>#include "TexManagementGL.h"

std::string TexManagementGL::fetchTexPath(TextureId texId)
{
	std::string pathComplete = texPath;
	switch(texId)
	{
	case TEXTURE_PACMAN:
		pathComplete += texPacman;
		break;
	case TEXTURE_WALL:
		pathComplete += texWall;
		break;
	case TEXTURE_PILL:
		pathComplete += texPill;
		break;
	case TEXTURE_PILL_BLOODY:
		pathComplete += texPillBloody;
		break;
	case TEXTURE_CONSUME:
		pathComplete += texConsume;
		break;
	default:
		pathComplete += texPlaceHolder;
		break;
	}
	return pathComplete;
}

void TexManagementGL::init()
{
	std::vector<TextureId>* loadTex = new std::vector<TextureId>();
	loadTex->push_back(TEXTURE_PACMAN);
	loadTex->push_back(TEXTURE_PILL);
	loadTex->push_back(TEXTURE_PILL_BLOODY);
	loadTex->push_back(TEXTURE_GHOST);
	loadTex->push_back(TEXTURE_WALL);
	loadTex->push_back(TEXTURE_PLACEHOLDER);
	loadTex->push_back(TEXTURE_CONSUME);

	std::string completePath;
	for(unsigned int i = 0; i < loadTex->size(); i++)
	{
		completePath = fetchTexPath(loadTex->at(i));
		Texture* tex = loadTexture(loadTex->at(i), completePath);

		textures->push_back(tex);
	}

	delete loadTex;
}
Texture* TexManagementGL::loadTexture(TextureId id, std::string completePath)
{
	Texture* texture = new Texture();
	texture->textureId = id;

	bool textureLoaded = LoadTGA(texture, completePath.c_str());
	if(textureLoaded)
	{
		//Creates a texture and put it's ID in the given integer variable
		glGenTextures(1, &(texture->texID));

		//Setting as active texture
		glBindTexture(GL_TEXTURE_2D, texture->texID);

		//Load texture into memory
		glTexImage2D(
			GL_TEXTURE_2D,
			0,
			texture->bpp / 8,
			texture->width,
			texture->height,
			0,
			texture->type,
			GL_UNSIGNED_BYTE,
			texture->imageData);
	}
	else
	{
		throw 0;
	}

	return texture;
}

Texture* TexManagementGL::getTexture(TextureId textureId)
{
	Texture* texture = NULL;

	bool textureFound = false;
	for(unsigned int i = 0; i < textures->size() && !textureFound; i++)
	{
		if(textures->at(i)->textureId == textureId)
		{
			texture = textures->at(i);
			textureFound = true;
		}
	}

	return texture;
}

TexManagementGL::TexManagementGL()
{
	textures = new std::vector<Texture*>();
}
TexManagementGL::~TexManagementGL()
{
	if(textures)
	{
		for(unsigned int i = 0; i < textures->size(); i++)
		{
			if(textures->at(i))
			{
				free(textures->at(i)->imageData); //Free raw image data
				if(textures->at(i))
				{
					delete textures->at(i);
					textures->at(i) = NULL;
				}
			}
		}
		delete textures;
	}
}<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/math_function.h"
#include "paddle/fluid/operators/math/softmax.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;

template <typename T>
class SequenceSoftmaxCUDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* x = ctx.Input<LoDTensor>("X");
    auto* out = ctx.Output<LoDTensor>("Out");

    auto& lod = x->lod();
    auto& dims = x->dims();

    const size_t level = lod.size() - 1;
    PADDLE_ENFORCE_EQ(dims[0], static_cast<int64_t>(lod[level].back()),
                      "The first dimension of Input(X) should be equal to the "
                      "sum of all sequences' lengths.");
    PADDLE_ENFORCE_EQ(dims[0], x->numel(),
                      "The width of each timestep in Input(X) of "
                      "SequenceSoftmaxOp should be 1.");

    out->mutable_data<T>(ctx.GetPlace());
    for (int i = 0; i < static_cast<int>(lod[level].size()) - 1; ++i) {
      int start_pos = static_cast<int>(lod[level][i]);
      int end_pos = static_cast<int>(lod[level][i + 1]);
      Tensor x_i = x->Slice(start_pos, end_pos);
      Tensor out_i = out->Slice(start_pos, end_pos);

      // Reshape from (end_pos - start_pos) x 1UL to 1UL x (end_pos - start_pos)
      framework::DDim dims_i =
          // framework::make_ddim({1UL, end_pos - start_pos, 1UL, 1UL});
          framework::make_ddim({1UL, end_pos - start_pos});
      x_i.Resize(dims_i);
      out_i.Resize(dims_i);
      math::SoftmaxCUDNNFunctor<T>()(
          ctx.template device_context<platform::CUDADeviceContext>(), &x_i,
          &out_i);
    }
  }
};

template <typename T>
class SequenceSoftmaxGradCUDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* out = ctx.Input<LoDTensor>("Out");
    auto* out_grad = ctx.Input<LoDTensor>(framework::GradVarName("Out"));
    auto* x = ctx.Input<LoDTensor>("X");
    auto* x_grad = ctx.Output<LoDTensor>(framework::GradVarName("X"));
    if (x_grad) {
      x_grad->set_lod(x->lod());
    }
    auto& lod = x->lod();
    const size_t level = lod.size() - 1;

    x_grad->mutable_data<T>(ctx.GetPlace());
    for (int i = 0; i < static_cast<int>(lod[level].size()) - 1; ++i) {
      int start_pos = static_cast<int>(lod[level][i]);
      int end_pos = static_cast<int>(lod[level][i + 1]);

      Tensor out_i = out->Slice(start_pos, end_pos);
      Tensor out_grad_i = out_grad->Slice(start_pos, end_pos);
      Tensor x_grad_i = x_grad->Slice(start_pos, end_pos);

      // Reshape from (end_pos - start_pos) x 1UL to 1UL x (end_pos - start_pos)
      framework::DDim dims_i = framework::make_ddim({1UL, end_pos - start_pos});
      out_i.Resize(dims_i);
      out_grad_i.Resize(dims_i);
      x_grad_i.Resize(dims_i);
      math::SoftmaxGradCUDNNFunctor<T>()(
          ctx.template device_context<platform::CUDADeviceContext>(), &out_i,
          &out_grad_i, &x_grad_i);
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_KERNEL(sequence_softmax, CUDNN, ::paddle::platform::CUDAPlace,
                   ops::SequenceSoftmaxCUDNNKernel<float>,
                   ops::SequenceSoftmaxCUDNNKernel<double>);
REGISTER_OP_KERNEL(sequence_softmax_grad, CUDNN, ::paddle::platform::CUDAPlace,
                   ops::SequenceSoftmaxGradCUDNNKernel<float>,
                   ops::SequenceSoftmaxGradCUDNNKernel<double>);
<commit_msg>polish two error message, test=develop (#24778)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/math_function.h"
#include "paddle/fluid/operators/math/softmax.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;

template <typename T>
class SequenceSoftmaxCUDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* x = ctx.Input<LoDTensor>("X");
    auto* out = ctx.Output<LoDTensor>("Out");

    auto& lod = x->lod();
    auto& dims = x->dims();

    const size_t level = lod.size() - 1;
    PADDLE_ENFORCE_EQ(
        dims[0], static_cast<int64_t>(lod[level].back()),
        platform::errors::InvalidArgument(
            "The first dimension of Input(X) should be equal to the sum of all "
            "sequences' lengths. But received first dimension of Input(X) is "
            "%d, the sum of all sequences' lengths is %d.",
            dims[0], static_cast<int64_t>(lod[level].back())));
    PADDLE_ENFORCE_EQ(dims[0], x->numel(),
                      platform::errors::InvalidArgument(
                          "The width of each timestep in Input(X) of "
                          "SequenceSoftmaxOp should be 1."));

    out->mutable_data<T>(ctx.GetPlace());
    for (int i = 0; i < static_cast<int>(lod[level].size()) - 1; ++i) {
      int start_pos = static_cast<int>(lod[level][i]);
      int end_pos = static_cast<int>(lod[level][i + 1]);
      Tensor x_i = x->Slice(start_pos, end_pos);
      Tensor out_i = out->Slice(start_pos, end_pos);

      // Reshape from (end_pos - start_pos) x 1UL to 1UL x (end_pos - start_pos)
      framework::DDim dims_i =
          // framework::make_ddim({1UL, end_pos - start_pos, 1UL, 1UL});
          framework::make_ddim({1UL, end_pos - start_pos});
      x_i.Resize(dims_i);
      out_i.Resize(dims_i);
      math::SoftmaxCUDNNFunctor<T>()(
          ctx.template device_context<platform::CUDADeviceContext>(), &x_i,
          &out_i);
    }
  }
};

template <typename T>
class SequenceSoftmaxGradCUDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* out = ctx.Input<LoDTensor>("Out");
    auto* out_grad = ctx.Input<LoDTensor>(framework::GradVarName("Out"));
    auto* x = ctx.Input<LoDTensor>("X");
    auto* x_grad = ctx.Output<LoDTensor>(framework::GradVarName("X"));
    if (x_grad) {
      x_grad->set_lod(x->lod());
    }
    auto& lod = x->lod();
    const size_t level = lod.size() - 1;

    x_grad->mutable_data<T>(ctx.GetPlace());
    for (int i = 0; i < static_cast<int>(lod[level].size()) - 1; ++i) {
      int start_pos = static_cast<int>(lod[level][i]);
      int end_pos = static_cast<int>(lod[level][i + 1]);

      Tensor out_i = out->Slice(start_pos, end_pos);
      Tensor out_grad_i = out_grad->Slice(start_pos, end_pos);
      Tensor x_grad_i = x_grad->Slice(start_pos, end_pos);

      // Reshape from (end_pos - start_pos) x 1UL to 1UL x (end_pos - start_pos)
      framework::DDim dims_i = framework::make_ddim({1UL, end_pos - start_pos});
      out_i.Resize(dims_i);
      out_grad_i.Resize(dims_i);
      x_grad_i.Resize(dims_i);
      math::SoftmaxGradCUDNNFunctor<T>()(
          ctx.template device_context<platform::CUDADeviceContext>(), &out_i,
          &out_grad_i, &x_grad_i);
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_KERNEL(sequence_softmax, CUDNN, ::paddle::platform::CUDAPlace,
                   ops::SequenceSoftmaxCUDNNKernel<float>,
                   ops::SequenceSoftmaxCUDNNKernel<double>);
REGISTER_OP_KERNEL(sequence_softmax_grad, CUDNN, ::paddle::platform::CUDAPlace,
                   ops::SequenceSoftmaxGradCUDNNKernel<float>,
                   ops::SequenceSoftmaxGradCUDNNKernel<double>);
<|endoftext|>