<commit_before>/**************************************************************************/
/**
**  @file tStorm.cpp
**  @brief Functions for class tStorm.
**
**  A tStorm object generates random storms assuming an exponential
**  distribution of rainfall intensity, storm duration, and time to the
**  next storm. It is essentially an implementation of the model of
**  P. Eagleson, 1978b, Water Resources Research. Its services include
**  reading the necessary parameters from a tInputFile, generating a new
**  storm, and reporting its various values.
**
**  $Id: tStorm.cpp,v 1.33 2004-01-30 15:00:14 childcvs Exp $
*/
/**************************************************************************/

#include <math.h>
#include <string.h>
#include "../Mathutil/mathutil.h"
#include "tStorm.h"
#if !defined(HAVE_NO_NAMESPACE)
# include <iostream>
using namespace std;
#else
# include <iostream.h>
#endif

/**************************************************************************\
**
**  tStorm::tStorm:  Constructor for storms. The default constructor
**                   assigns a value of unity to storm depth, duration,
**                   and interstorm duration. (Note:
**                   this constructor does not allow option for sinusoidal
**                   variation in means).
**
\**************************************************************************/
tStorm::tStorm( bool optvar )
  :
  rand(0),
  p(1.0),
  stdur(1.0),
  istdur(1.0),
  endtm(1.0e9),
  optVariable(optvar)
{
   //srand( 0 );
}

/**************************************************************************\
**
**  tStorm::tStorm
**
**  Alternative constructor that reads parameters directly from a tInputFile
**  object. Reads option for variable storms (normally this is "yes"---that's
**  the point of these objects---but a user may wish to switch off variation
**  as a test), mean values for rainfall intensity, duration, and interstorm
**  period, and a random seed to initialize the random number generator.
**    Also reads an option for long-term sinusoidal variations in the mean
**  values, and if the option is selected, reads the relevant parameters.
**  Variables p0, stdur0, and istdur0 are the mean values of the means;
**  pdev, stdurdev, and istdurdev are the range of variation (e.g., if pMean
**  were to fluctuate between 5 and 10, p0 would be 7.5 and pdev 2.5).
**
**  Modifications:
**   - 3/00 initialization now includes creation of ".storm" file for storm
**     history (GT)
**
\**************************************************************************/
tStorm::tStorm( const tInputFile &infile, tRand *rand_ ) :
  rand(rand_)
{
   // Read + set parameters for storm intensity, duration, and spacing
   {
     int tmp_;
     tmp_ = infile.ReadItem( tmp_, "OPTVAR" );
     optVariable = BOOL(tmp_ != 0);
   }
   infile.ReadItem( p_ts, "ST_PMEAN");
   infile.ReadItem( stdur_ts, "ST_STDUR");
   infile.ReadItem( istdur_ts, "ST_ISTDUR");

   infile.WarnObsoleteKeyword("PMEAN", "ST_PMEAN");
   infile.WarnObsoleteKeyword("STDUR", "ST_STDUR");
   infile.WarnObsoleteKeyword("ISTDUR", "ST_ISTDUR");

   p = p_ts.calc(0.);
   stdur = stdur_ts.calc(0.);
   istdur = istdur_ts.calc(0.);

   endtm = infile.ReadItem( endtm, "RUNTIME" );
   double help;

   help = infile.ReadItem( help, "OPTREADINPUT" );
   if(help>0){
      help = infile.ReadItem( help, "INPUTTIME" );
      endtm += help;
   }

   infile.WarnObsoleteKeyword("OPTSINVAR", "ST_PMEAN");
   infile.WarnObsoleteKeyword("PERIOD", "ST_PMEAN");
   infile.WarnObsoleteKeyword("START_CYCLE_TIME", "ST_PMEAN");
   infile.WarnObsoleteKeyword("MAXPMEAN", "ST_PMEAN");
   infile.WarnObsoleteKeyword("MAXSTDURMN", "ST_STDUR");
   infile.WarnObsoleteKeyword("MAXISTDURMN", "ST_ISTDUR");

   // If variable storms used, create a file for writing them
   if( optVariable )
   {
      char fname[87];
#define THEEXT ".storm"
      infile.ReadItem( fname, sizeof(fname)-sizeof(THEEXT), "OUTFILENAME" );
      strcat( fname, THEEXT );
#undef THEEXT
      stormfile.open( fname );
      if( !stormfile.good() )
          cerr << "Warning: unable to create storm data file '"
               << fname << "'\n";
   }
}

/**************************************************************************\
**
**  tStorm::GenerateStorm
**
**  Generates a new storm by drawing new values of p, stdur, and istdur from
**  an exponential distribution and updating the random seed.
**    If the minp parameter is greater than zero, the function will keep
**  picking storms until it finds one with p>minp. The total elapsed time,
**  including the rejected storms and their associated interstorm periods,
**  is stored istdur.
**
**  Inputs:      minp -- minimum value of rainfall rate p (default 0)
**               mind -- minimum storm depth to produce runoff (default 0)
**               tm -- current time in simulation
**  Members updated:  p, stdur, istdur take on new random values (if optVar)
**                    pMean, stdurMean, istdurMean adjusted (if optSinVar)
**  Assumptions:  pMean > 0
**
**  Modifications:
**   - changed AND to OR in while loop, GT 5/99
**   - added to while loop an additional check to see if time has run out,
**     NG 2/00
**   - added output of time, storm intensity, & duration to ".storm" file
**     GT 3/00
**
\**************************************************************************/
void tStorm::GenerateStorm( double tm, double minp, double mind )
{

   p = p_ts.calc(tm);
   stdur = stdur_ts.calc(tm);
   istdur = istdur_ts.calc(tm);

   // If option for random storms is on, pick a storm at random.
   // Keep picking and accumulating time until the storm depth or intensity
   // is greater than the minimum value needed to produce runoff.

   if( optVariable )
   {
      const double pMean = p;
      const double stdurMean = stdur;
      const double istdurMean = istdur;

      stdur = 0;
      istdur = 0;
      do
      {
         p = pMean*ExpDev();
         istdur += istdurMean*ExpDev() + stdur;
         stdur = stdurMean*ExpDev();
	 if(0) { // Debug
	   cout << "P " << p << "  ST " << stdur << "  IST " << istdur
		<< "  DP " << p*stdur << " minp " << minp << " mind " <<mind <<
	     endl;
	 }
      } while( (p<=minp || (p*stdur)<=mind) && (tm+istdur+stdur<endtm) );
      stormfile << istdur << " " << p << " " << stdur << endl;
   }
}

/**************************************************************************\
**
**  tStorm::ExpDev:  Finds a random number with an exponential distribution
**                   (adapted from Numerical Recipes).
**
\**************************************************************************/
double tStorm::ExpDev() const
{
    double dum;

    do
        dum = rand->ran3();
    while( dum==0.0 );
    return -log(dum);
}

/**************************************************************************\
**
**  tStorm "get" routines: return various variables
**
\**************************************************************************/

double tStorm::getStormDuration() const { return stdur; }
double tStorm::interstormDur() const { return istdur; }
double tStorm::getRainrate() const { return p; }

/**************************************************************************\
**
**  GammaDev
**
**  Returns a random variable drawn from a Gamma distribution with parameter m.
**
**  (Note: not actually called; provided for future use).
**
\**************************************************************************/
double tStorm::GammaDev(double m) const
{
  double x, y,z, c,t,b,u,w,v;

  if (m<1)
    {
      c = 1/m;
      t = 0.07 + 0.75*sqrt(1-m);
      b = 1 + exp(-t)*m/t;
      int accept = 0;
      while (accept == 0)
        {
          u = rand->ran3();
          w = rand->ran3();
          v = b *u;
          if (v<=1)
            {
              x  = t * pow(v, c);
              accept = ((w<=((2-x)/(2+x))) || (w<=exp(-x)));
            }
          else
            {
              x = -log(c*t*(b-v));
              y = x/t;
              accept = (((w*(m + y - m*y)) <= 1) || (w<= ( pow(y, (m-1)))));
            }
        }
    }
  else
    {
      b = m-1;
      c = 3*m - 0.75;
      int accept = 0;
      while (accept == 0)
        {
          u = rand->ran3(); v = rand->ran3();
          w = u* ( 1-u);
          y = sqrt(c/w) * (u - 0.5);
          x = b + y;
          if ( x>= 0)
            {
              z = 64*( pow(w,3.))*v*v;
              accept = (z <= ( 1 - 2*y*y/x)) || ( log(z) <= (2*(b*log(x/b) - y)));
            }
        }
    }
  return x;
}

<commit_msg>(Arnaud) Warn about obsolete keywords before reading their modern equivalent.<commit_after>/**************************************************************************/
/**
**  @file tStorm.cpp
**  @brief Functions for class tStorm.
**
**  A tStorm object generates random storms assuming an exponential
**  distribution of rainfall intensity, storm duration, and time to the
**  next storm. It is essentially an implementation of the model of
**  P. Eagleson, 1978b, Water Resources Research. Its services include
**  reading the necessary parameters from a tInputFile, generating a new
**  storm, and reporting its various values.
**
**  $Id: tStorm.cpp,v 1.34 2004-02-27 11:14:22 childcvs Exp $
*/
/**************************************************************************/

#include <math.h>
#include <string.h>
#include "../Mathutil/mathutil.h"
#include "tStorm.h"
#if !defined(HAVE_NO_NAMESPACE)
# include <iostream>
using namespace std;
#else
# include <iostream.h>
#endif

/**************************************************************************\
**
**  tStorm::tStorm:  Constructor for storms. The default constructor
**                   assigns a value of unity to storm depth, duration,
**                   and interstorm duration. (Note:
**                   this constructor does not allow option for sinusoidal
**                   variation in means).
**
\**************************************************************************/
tStorm::tStorm( bool optvar )
  :
  rand(0),
  p(1.0),
  stdur(1.0),
  istdur(1.0),
  endtm(1.0e9),
  optVariable(optvar)
{
   //srand( 0 );
}

/**************************************************************************\
**
**  tStorm::tStorm
**
**  Alternative constructor that reads parameters directly from a tInputFile
**  object. Reads option for variable storms (normally this is "yes"---that's
**  the point of these objects---but a user may wish to switch off variation
**  as a test), mean values for rainfall intensity, duration, and interstorm
**  period, and a random seed to initialize the random number generator.
**    Also reads an option for long-term sinusoidal variations in the mean
**  values, and if the option is selected, reads the relevant parameters.
**  Variables p0, stdur0, and istdur0 are the mean values of the means;
**  pdev, stdurdev, and istdurdev are the range of variation (e.g., if pMean
**  were to fluctuate between 5 and 10, p0 would be 7.5 and pdev 2.5).
**
**  Modifications:
**   - 3/00 initialization now includes creation of ".storm" file for storm
**     history (GT)
**
\**************************************************************************/
tStorm::tStorm( const tInputFile &infile, tRand *rand_ ) :
  rand(rand_)
{
   // Read + set parameters for storm intensity, duration, and spacing
   {
     int tmp_;
     tmp_ = infile.ReadItem( tmp_, "OPTVAR" );
     optVariable = BOOL(tmp_ != 0);
   }
   infile.WarnObsoleteKeyword("PMEAN", "ST_PMEAN");
   infile.WarnObsoleteKeyword("STDUR", "ST_STDUR");
   infile.WarnObsoleteKeyword("ISTDUR", "ST_ISTDUR");
   infile.WarnObsoleteKeyword("OPTSINVAR", "ST_PMEAN");
   infile.WarnObsoleteKeyword("PERIOD", "ST_PMEAN");
   infile.WarnObsoleteKeyword("START_CYCLE_TIME", "ST_PMEAN");
   infile.WarnObsoleteKeyword("MAXPMEAN", "ST_PMEAN");
   infile.WarnObsoleteKeyword("MAXSTDURMN", "ST_STDUR");
   infile.WarnObsoleteKeyword("MAXISTDURMN", "ST_ISTDUR");

   infile.ReadItem( p_ts, "ST_PMEAN");
   infile.ReadItem( stdur_ts, "ST_STDUR");
   infile.ReadItem( istdur_ts, "ST_ISTDUR");

   p = p_ts.calc(0.);
   stdur = stdur_ts.calc(0.);
   istdur = istdur_ts.calc(0.);

   endtm = infile.ReadItem( endtm, "RUNTIME" );
   double help;

   help = infile.ReadItem( help, "OPTREADINPUT" );
   if(help>0){
      help = infile.ReadItem( help, "INPUTTIME" );
      endtm += help;
   }

   // If variable storms used, create a file for writing them
   if( optVariable )
   {
      char fname[87];
#define THEEXT ".storm"
      infile.ReadItem( fname, sizeof(fname)-sizeof(THEEXT), "OUTFILENAME" );
      strcat( fname, THEEXT );
#undef THEEXT
      stormfile.open( fname );
      if( !stormfile.good() )
          cerr << "Warning: unable to create storm data file '"
               << fname << "'\n";
   }
}

/**************************************************************************\
**
**  tStorm::GenerateStorm
**
**  Generates a new storm by drawing new values of p, stdur, and istdur from
**  an exponential distribution and updating the random seed.
**    If the minp parameter is greater than zero, the function will keep
**  picking storms until it finds one with p>minp. The total elapsed time,
**  including the rejected storms and their associated interstorm periods,
**  is stored istdur.
**
**  Inputs:      minp -- minimum value of rainfall rate p (default 0)
**               mind -- minimum storm depth to produce runoff (default 0)
**               tm -- current time in simulation
**  Members updated:  p, stdur, istdur take on new random values (if optVar)
**                    pMean, stdurMean, istdurMean adjusted (if optSinVar)
**  Assumptions:  pMean > 0
**
**  Modifications:
**   - changed AND to OR in while loop, GT 5/99
**   - added to while loop an additional check to see if time has run out,
**     NG 2/00
**   - added output of time, storm intensity, & duration to ".storm" file
**     GT 3/00
**
\**************************************************************************/
void tStorm::GenerateStorm( double tm, double minp, double mind )
{

   p = p_ts.calc(tm);
   stdur = stdur_ts.calc(tm);
   istdur = istdur_ts.calc(tm);

   // If option for random storms is on, pick a storm at random.
   // Keep picking and accumulating time until the storm depth or intensity
   // is greater than the minimum value needed to produce runoff.

   if( optVariable )
   {
      const double pMean = p;
      const double stdurMean = stdur;
      const double istdurMean = istdur;

      stdur = 0;
      istdur = 0;
      do
      {
         p = pMean*ExpDev();
         istdur += istdurMean*ExpDev() + stdur;
         stdur = stdurMean*ExpDev();
	 if(0) { // Debug
	   cout << "P " << p << "  ST " << stdur << "  IST " << istdur
		<< "  DP " << p*stdur << " minp " << minp << " mind " <<mind <<
	     endl;
	 }
      } while( (p<=minp || (p*stdur)<=mind) && (tm+istdur+stdur<endtm) );
      stormfile << istdur << " " << p << " " << stdur << endl;
   }
}

/**************************************************************************\
**
**  tStorm::ExpDev:  Finds a random number with an exponential distribution
**                   (adapted from Numerical Recipes).
**
\**************************************************************************/
double tStorm::ExpDev() const
{
    double dum;

    do
        dum = rand->ran3();
    while( dum==0.0 );
    return -log(dum);
}

/**************************************************************************\
**
**  tStorm "get" routines: return various variables
**
\**************************************************************************/

double tStorm::getStormDuration() const { return stdur; }
double tStorm::interstormDur() const { return istdur; }
double tStorm::getRainrate() const { return p; }

/**************************************************************************\
**
**  GammaDev
**
**  Returns a random variable drawn from a Gamma distribution with parameter m.
**
**  (Note: not actually called; provided for future use).
**
\**************************************************************************/
double tStorm::GammaDev(double m) const
{
  double x, y,z, c,t,b,u,w,v;

  if (m<1)
    {
      c = 1/m;
      t = 0.07 + 0.75*sqrt(1-m);
      b = 1 + exp(-t)*m/t;
      int accept = 0;
      while (accept == 0)
        {
          u = rand->ran3();
          w = rand->ran3();
          v = b *u;
          if (v<=1)
            {
              x  = t * pow(v, c);
              accept = ((w<=((2-x)/(2+x))) || (w<=exp(-x)));
            }
          else
            {
              x = -log(c*t*(b-v));
              y = x/t;
              accept = (((w*(m + y - m*y)) <= 1) || (w<= ( pow(y, (m-1)))));
            }
        }
    }
  else
    {
      b = m-1;
      c = 3*m - 0.75;
      int accept = 0;
      while (accept == 0)
        {
          u = rand->ran3(); v = rand->ran3();
          w = u* ( 1-u);
          y = sqrt(c/w) * (u - 0.5);
          x = b + y;
          if ( x>= 0)
            {
              z = 64*( pow(w,3.))*v*v;
              accept = (z <= ( 1 - 2*y*y/x)) || ( log(z) <= (2*(b*log(x/b) - y)));
            }
        }
    }
  return x;
}

<|endoftext|>


<commit_before>/**********************************************************************
 * $Id$
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <geos/geomgraph.h>
//#include "../headers/util.h"

#ifndef DEBUG
#define DEBUG 0
#endif
#ifndef COMPUTE_Z
#define COMPUTE_Z 0
#endif

namespace geos {

Node::Node(Coordinate& newCoord, EdgeEndStar* newEdges): GraphComponent(new Label(0,Location::UNDEF)) {
	coord=newCoord;
#if DEBUG
	cerr<<"Node::Node("<<newCoord.toString()<<")"<<endl;
#endif
#if COMPUTE_Z
	z=0;
	validz=0;
#endif
	edges=newEdges;
}

Node::~Node(){
	delete edges;
}

const Coordinate& Node::getCoordinate() const {
	return coord;
}

EdgeEndStar* Node::getEdges() {
	return edges;
}

bool Node::isIsolated() {
	return (label->getGeometryCount()==1);
}

void Node::add(EdgeEnd *e) {
#if DEBUG
	cerr<<"Node::add("<<e->print()<<")"<<endl;
#endif
	// Assert: start pt of e is equal to node point
	if (edges==NULL)
		edges=new EdgeEndStar();
	edges->insert(e);
	e->setNode(this);
#if COMPUTE_Z
	Coordinate &ec = e->getCoordinate();
	if ( ec.z != DoubleNotANumber )
	{
		z+=ec.z;
		validz++;
	}
	coord.z=z/validz;
#if DEBUG
	cerr<<" z=="<<z<<endl;
	cerr<<" validz=="<<validz<<endl;
	cerr<<" coord.z=="<<coord.z<<endl;
#endif // DEBUG
#endif
}

void Node::mergeLabel(const Node* n) {
	mergeLabel(n->label);
}

void Node::mergeLabel(const Label* label2) {
	for (int i=0; i<2; i++) {
		int loc=computeMergedLocation(label2, i);
		int thisLoc=label->getLocation(i);
		if (thisLoc==Location::UNDEF) label->setLocation(i,loc);
	}
}

void Node::setLabel(int argIndex, int onLocation) {
	if (label==NULL) {
		label=new Label(argIndex, onLocation);
	} else
		label->setLocation(argIndex, onLocation);
}

void Node::setLabelBoundary(int argIndex) {
	int loc=Location::UNDEF;
	if (label!=NULL)
		loc=label->getLocation(argIndex);
	// flip the loc
	int newLoc;
	switch (loc){
		case Location::BOUNDARY: newLoc=Location::INTERIOR; break;
		case Location::INTERIOR: newLoc=Location::BOUNDARY; break;
		default: newLoc=Location::BOUNDARY;  break;
	}
	label->setLocation(argIndex, newLoc);
}

int Node::computeMergedLocation(const Label* label2, int eltIndex){
	int loc=Location::UNDEF;
	loc=label->getLocation(eltIndex);
	if (!label2->isNull(eltIndex)) {
		int nLoc=label2->getLocation(eltIndex);
		if (loc!=Location::BOUNDARY) loc=nLoc;
	}
	return loc;
}

string Node::print(){
	string out="node "+coord.toString()+" lbl: "+label->toString();
	return out;
}

}

/**********************************************************************
 * $Log$
 * Revision 1.5  2004/11/17 15:09:08  strk
 * Changed COMPUTE_Z defaults to be more conservative
 *
 * Revision 1.4  2004/11/17 08:13:16  strk
 * Indentation changes.
 * Some Z_COMPUTATION activated by default.
 *
 * Revision 1.3  2004/10/21 22:29:54  strk
 * Indentation changes and some more COMPUTE_Z rules
 *
 * Revision 1.2  2004/07/02 13:28:26  strk
 * Fixed all #include lines to reflect headers layout change.
 * Added client application build tips in README.
 *
 * Revision 1.1  2004/03/19 09:48:45  ybychkov
 * "geomgraph" and "geomgraph/indexl" upgraded to JTS 1.4
 *
 * Revision 1.12  2003/11/07 01:23:42  pramsey
 * Add standard CVS headers licence notices and copyrights to all cpp and h
 * files.
 *
 *
 **********************************************************************/

<commit_msg>COMPUTE_Z re-enabled by default<commit_after>/**********************************************************************
 * $Id$
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <geos/geomgraph.h>
//#include "../headers/util.h"

#ifndef DEBUG
#define DEBUG 0
#endif
#ifndef COMPUTE_Z
#define COMPUTE_Z 1
#endif

namespace geos {

Node::Node(Coordinate& newCoord, EdgeEndStar* newEdges): GraphComponent(new Label(0,Location::UNDEF)) {
	coord=newCoord;
#if DEBUG
	cerr<<"Node::Node("<<newCoord.toString()<<")"<<endl;
#endif
#if COMPUTE_Z
	z=0;
	validz=0;
#endif
	edges=newEdges;
}

Node::~Node(){
	delete edges;
}

const Coordinate& Node::getCoordinate() const {
	return coord;
}

EdgeEndStar* Node::getEdges() {
	return edges;
}

bool Node::isIsolated() {
	return (label->getGeometryCount()==1);
}

void Node::add(EdgeEnd *e) {
#if DEBUG
	cerr<<"Node::add("<<e->print()<<")"<<endl;
#endif
	// Assert: start pt of e is equal to node point
	if (edges==NULL)
		edges=new EdgeEndStar();
	edges->insert(e);
	e->setNode(this);
#if COMPUTE_Z
	Coordinate &ec = e->getCoordinate();
	if ( ec.z != DoubleNotANumber )
	{
		z+=ec.z;
		validz++;
	}
	coord.z=z/validz;
#if DEBUG
	cerr<<" z=="<<z<<endl;
	cerr<<" validz=="<<validz<<endl;
	cerr<<" coord.z=="<<coord.z<<endl;
#endif // DEBUG
#endif
}

void Node::mergeLabel(const Node* n) {
	mergeLabel(n->label);
}

void Node::mergeLabel(const Label* label2) {
	for (int i=0; i<2; i++) {
		int loc=computeMergedLocation(label2, i);
		int thisLoc=label->getLocation(i);
		if (thisLoc==Location::UNDEF) label->setLocation(i,loc);
	}
}

void Node::setLabel(int argIndex, int onLocation) {
	if (label==NULL) {
		label=new Label(argIndex, onLocation);
	} else
		label->setLocation(argIndex, onLocation);
}

void Node::setLabelBoundary(int argIndex) {
	int loc=Location::UNDEF;
	if (label!=NULL)
		loc=label->getLocation(argIndex);
	// flip the loc
	int newLoc;
	switch (loc){
		case Location::BOUNDARY: newLoc=Location::INTERIOR; break;
		case Location::INTERIOR: newLoc=Location::BOUNDARY; break;
		default: newLoc=Location::BOUNDARY;  break;
	}
	label->setLocation(argIndex, newLoc);
}

int Node::computeMergedLocation(const Label* label2, int eltIndex){
	int loc=Location::UNDEF;
	loc=label->getLocation(eltIndex);
	if (!label2->isNull(eltIndex)) {
		int nLoc=label2->getLocation(eltIndex);
		if (loc!=Location::BOUNDARY) loc=nLoc;
	}
	return loc;
}

string Node::print(){
	string out="node "+coord.toString()+" lbl: "+label->toString();
	return out;
}

}

/**********************************************************************
 * $Log$
 * Revision 1.6  2004/11/19 10:10:23  strk
 * COMPUTE_Z re-enabled by default
 *
 * Revision 1.5  2004/11/17 15:09:08  strk
 * Changed COMPUTE_Z defaults to be more conservative
 *
 * Revision 1.4  2004/11/17 08:13:16  strk
 * Indentation changes.
 * Some Z_COMPUTATION activated by default.
 *
 * Revision 1.3  2004/10/21 22:29:54  strk
 * Indentation changes and some more COMPUTE_Z rules
 *
 * Revision 1.2  2004/07/02 13:28:26  strk
 * Fixed all #include lines to reflect headers layout change.
 * Added client application build tips in README.
 *
 * Revision 1.1  2004/03/19 09:48:45  ybychkov
 * "geomgraph" and "geomgraph/indexl" upgraded to JTS 1.4
 *
 * Revision 1.12  2003/11/07 01:23:42  pramsey
 * Add standard CVS headers licence notices and copyrights to all cpp and h
 * files.
 *
 *
 **********************************************************************/

<|endoftext|>


<commit_before>#include <fstream>
#include <sys/stat.h>

#include "project/entity.h"
#include "project/record.h"
#include "project/project.h"
#include "project/schema.h"

#include "pixelboost/data/json/reader.h"
#include "pixelboost/data/json/writer.h"
#include "pixelboost/external/lua/lua.hpp"

extern "C" {
#include "pixelboost/external/lua/lapi.h"
#include "pixelboost/external/lua/lobject.h"
#include "pixelboost/external/lua/lundump.h"
}

#include "pixelboost/file/fileHelpers.h"

using namespace pixeleditor;

ProjectRecord::ProjectRecord(Project* project)
    : ProjectStruct(project)
    , _IsOpen(false)
{

}

ProjectRecord::ProjectRecord(Project* project, const SchemaRecord* type, const std::string& name)
    : ProjectStruct(project, type)
    , _IsOpen(true)
{
    SetName(name);
}

ProjectRecord::~ProjectRecord()
{
    if (_IsOpen)
        Close();
}

bool ProjectRecord::Open(const std::string& filename)
{
    std::string file = pb::FileHelpers::FileToString(pb::kFileLocationUser, filename.c_str());

    json::Object record;

    json::Reader::Read(record, file);

    bool status = ProjectStruct::Open(record);

    // Entities
    json::Array& entities = record["Entities"];

    for (json::Array::iterator it = entities.Begin(); it != entities.End(); ++it)
    {
        json::Object& entity = *it;

        ProjectEntity* newEntity = new ProjectEntity(this);

        newEntity->Open(entity);

        if (!AddEntity(newEntity))
        {
            status = false;
            delete newEntity;
        }
    }

    _IsOpen = true;

    return status;
}

bool ProjectRecord::Close()
{
    if (!_IsOpen)
        return false;

    EntityMap::iterator it = _Entities.begin();
    while (it != _Entities.end())
    {
        RemoveEntity(it->second);
        it = _Entities.begin();
    }

    _IsOpen = false;

    return true;
}

bool ProjectRecord::Save()
{
    // TODO: Make OS independant
    char cmd[2048];
    std::string outputDir = GetProject()->GetLocation() + "records/";
    sprintf(cmd, "mkdir -p %s", outputDir.c_str());
    system(cmd);

    char location[1024];
    sprintf(location, "%s%X.txt", outputDir.c_str(), GetUid());

    json::Object record;

    bool status = ProjectStruct::Save(record);

    json::Array entities;

    for (EntityMap::iterator it = _Entities.begin(); it != _Entities.end(); ++it)
    {
        json::Object entity;
        if (!it->second->Save(entity))
            status = false;

        entities.Insert(entity);
    }

    record["Entities"] = entities;

    std::fstream file(location, std::fstream::out | std::fstream::trunc);
    json::Writer::Write(record, file);

    file.close();

    return status;
}

bool ProjectRecord::ExportJson()
{
    // TODO: Make OS independant
    char cmd[2048];
    std::string outputDir = GetProject()->GetConfig().exportDir + "records/";
    sprintf(cmd, "mkdir -p %s", outputDir.c_str());
    system(cmd);

    char location[1024];
    sprintf(location, "%s%X.pbr", outputDir.c_str(), GetUid());

    json::Object record;

    bool status = ExportJson(record);

    std::fstream file(location, std::fstream::out | std::fstream::trunc);
    json::Writer::Write(record, file);

    file.close();

    return status;
}

static int writeLua(lua_State*, const void* p, size_t size, void* u)
{
    return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0);
}

bool ProjectRecord::ExportLua(bool exportByteCode)
{
    // TODO: Make OS independant
    char cmd[2048];
    std::string outputDir = GetProject()->GetConfig().exportDir + "records/";
    sprintf(cmd, "mkdir -p %s", outputDir.c_str());
    system(cmd);

    char location[1024];
    sprintf(location, "%s%X.lua", outputDir.c_str(), GetUid());

    std::fstream file(location, std::fstream::out | std::fstream::trunc);

    bool status = ExportLua(file);

    file.close();

    if (exportByteCode)
    {
        lua_State* state = luaL_newstate();
        luaL_openlibs(state);
        luaL_loadfile(state, location);
        sprintf(location, "%sc", location);
        FILE* compiledFile = fopen(location, "wb");
        TValue *o;
        lua_lock(state);
        api_checknelems(state, 1);
        o = state->top - 1;
        if (isLfunction(o))
            luaU_dump(state, getproto(o), writeLua, compiledFile, true);
        lua_unlock(state);
        fclose(compiledFile);
        lua_close(state);
    }

    return status;
}

bool ProjectRecord::ExportJson(json::Object& record)
{
    bool status = ProjectStruct::ExportJson(record);

    json::Array entities;

    for (EntityMap::iterator it = _Entities.begin(); it != _Entities.end(); ++it)
    {
        json::Object entity;
        if (!it->second->ExportJson(entity))
            status = false;

        entities.Insert(entity);
    }

    record["Entities"] = entities;

    return status;
}

bool ProjectRecord::ExportLua(std::iostream& output)
{
    char record[64];
    sprintf(record, "r%X", GetUid());

    output << record << " = {" << std::endl;
    bool status = ProjectStruct::ExportLua(output);
    output << "}" << std::endl << std::endl;

    output << record << ".entities = {}" << std::endl << std::endl;

    int i=0;
    for (EntityMap::iterator it = _Entities.begin(); it != _Entities.end(); ++it)
    {
        output << record << ".entities[" << (++i) << "] = {" << std::endl;
        if (!it->second->ExportLua(output))
            status = false;
        output << std::endl << "}" << std::endl << std::endl;
    }

    return status;
}

ProjectRecord* ProjectRecord::GetRecord()
{
    return this;
}

const ProjectRecord* ProjectRecord::GetRecord() const
{
    return this;
}

bool ProjectRecord::AddEntity(ProjectEntity* entity)
{
    Uid uid = entity->GetUid();

    EntityMap::iterator it = _Entities.find(uid);

    if (it == _Entities.end())
    {
        _Entities[uid] = entity;

        entityAdded(this, entity);

        return true;
    }

    return false;
}

bool ProjectRecord::RemoveEntity(ProjectEntity* entity, bool erase)
{
    EntityMap::iterator it = _Entities.find(entity->GetUid());

    if (it != _Entities.end())
    {
        _Entities.erase(it);

        entityRemoved(this, entity);

        if (erase)
            delete entity;

        return true;
    }

    return false;
}

ProjectEntity* ProjectRecord::GetEntity(Uid uid) const
{
    EntityMap::const_iterator it = _Entities.find(uid);

    if (it != _Entities.end())
        return it->second;

    return 0;
}

const ProjectRecord::EntityMap& ProjectRecord::GetEntities() const
{
    return _Entities;
}
<commit_msg>Fix lua include<commit_after>#include <fstream>
#include <sys/stat.h>

#include "lua.hpp"

#include "pixelboost/data/json/reader.h"
#include "pixelboost/data/json/writer.h"

extern "C" {
#include "pixelboost/external/lua/lapi.h"
#include "pixelboost/external/lua/lobject.h"
#include "pixelboost/external/lua/lundump.h"
}

#include "pixelboost/file/fileHelpers.h"

#include "project/entity.h"
#include "project/record.h"
#include "project/project.h"
#include "project/schema.h"

using namespace pixeleditor;

ProjectRecord::ProjectRecord(Project* project)
    : ProjectStruct(project)
    , _IsOpen(false)
{

}

ProjectRecord::ProjectRecord(Project* project, const SchemaRecord* type, const std::string& name)
    : ProjectStruct(project, type)
    , _IsOpen(true)
{
    SetName(name);
}

ProjectRecord::~ProjectRecord()
{
    if (_IsOpen)
        Close();
}

bool ProjectRecord::Open(const std::string& filename)
{
    std::string file = pb::FileHelpers::FileToString(pb::kFileLocationUser, filename.c_str());

    json::Object record;

    json::Reader::Read(record, file);

    bool status = ProjectStruct::Open(record);

    // Entities
    json::Array& entities = record["Entities"];

    for (json::Array::iterator it = entities.Begin(); it != entities.End(); ++it)
    {
        json::Object& entity = *it;

        ProjectEntity* newEntity = new ProjectEntity(this);

        newEntity->Open(entity);

        if (!AddEntity(newEntity))
        {
            status = false;
            delete newEntity;
        }
    }

    _IsOpen = true;

    return status;
}

bool ProjectRecord::Close()
{
    if (!_IsOpen)
        return false;

    EntityMap::iterator it = _Entities.begin();
    while (it != _Entities.end())
    {
        RemoveEntity(it->second);
        it = _Entities.begin();
    }

    _IsOpen = false;

    return true;
}

bool ProjectRecord::Save()
{
    // TODO: Make OS independant
    char cmd[2048];
    std::string outputDir = GetProject()->GetLocation() + "records/";
    sprintf(cmd, "mkdir -p %s", outputDir.c_str());
    system(cmd);

    char location[1024];
    sprintf(location, "%s%X.txt", outputDir.c_str(), GetUid());

    json::Object record;

    bool status = ProjectStruct::Save(record);

    json::Array entities;

    for (EntityMap::iterator it = _Entities.begin(); it != _Entities.end(); ++it)
    {
        json::Object entity;
        if (!it->second->Save(entity))
            status = false;

        entities.Insert(entity);
    }

    record["Entities"] = entities;

    std::fstream file(location, std::fstream::out | std::fstream::trunc);
    json::Writer::Write(record, file);

    file.close();

    return status;
}

bool ProjectRecord::ExportJson()
{
    // TODO: Make OS independant
    char cmd[2048];
    std::string outputDir = GetProject()->GetConfig().exportDir + "records/";
    sprintf(cmd, "mkdir -p %s", outputDir.c_str());
    system(cmd);

    char location[1024];
    sprintf(location, "%s%X.pbr", outputDir.c_str(), GetUid());

    json::Object record;

    bool status = ExportJson(record);

    std::fstream file(location, std::fstream::out | std::fstream::trunc);
    json::Writer::Write(record, file);

    file.close();

    return status;
}

static int writeLua(lua_State*, const void* p, size_t size, void* u)
{
    return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0);
}

bool ProjectRecord::ExportLua(bool exportByteCode)
{
    // TODO: Make OS independant
    char cmd[2048];
    std::string outputDir = GetProject()->GetConfig().exportDir + "records/";
    sprintf(cmd, "mkdir -p %s", outputDir.c_str());
    system(cmd);

    char location[1024];
    sprintf(location, "%s%X.lua", outputDir.c_str(), GetUid());

    std::fstream file(location, std::fstream::out | std::fstream::trunc);

    bool status = ExportLua(file);

    file.close();

    if (exportByteCode)
    {
        lua_State* state = luaL_newstate();
        luaL_openlibs(state);
        luaL_loadfile(state, location);
        sprintf(location, "%sc", location);
        FILE* compiledFile = fopen(location, "wb");
        TValue *o;
        lua_lock(state);
        api_checknelems(state, 1);
        o = state->top - 1;
        if (isLfunction(o))
            luaU_dump(state, getproto(o), writeLua, compiledFile, true);
        lua_unlock(state);
        fclose(compiledFile);
        lua_close(state);
    }

    return status;
}

bool ProjectRecord::ExportJson(json::Object& record)
{
    bool status = ProjectStruct::ExportJson(record);

    json::Array entities;

    for (EntityMap::iterator it = _Entities.begin(); it != _Entities.end(); ++it)
    {
        json::Object entity;
        if (!it->second->ExportJson(entity))
            status = false;

        entities.Insert(entity);
    }

    record["Entities"] = entities;

    return status;
}

bool ProjectRecord::ExportLua(std::iostream& output)
{
    char record[64];
    sprintf(record, "r%X", GetUid());

    output << record << " = {" << std::endl;
    bool status = ProjectStruct::ExportLua(output);
    output << "}" << std::endl << std::endl;

    output << record << ".entities = {}" << std::endl << std::endl;

    int i=0;
    for (EntityMap::iterator it = _Entities.begin(); it != _Entities.end(); ++it)
    {
        output << record << ".entities[" << (++i) << "] = {" << std::endl;
        if (!it->second->ExportLua(output))
            status = false;
        output << std::endl << "}" << std::endl << std::endl;
    }

    return status;
}

ProjectRecord* ProjectRecord::GetRecord()
{
    return this;
}

const ProjectRecord* ProjectRecord::GetRecord() const
{
    return this;
}

bool ProjectRecord::AddEntity(ProjectEntity* entity)
{
    Uid uid = entity->GetUid();

    EntityMap::iterator it = _Entities.find(uid);

    if (it == _Entities.end())
    {
        _Entities[uid] = entity;

        entityAdded(this, entity);

        return true;
    }

    return false;
}

bool ProjectRecord::RemoveEntity(ProjectEntity* entity, bool erase)
{
    EntityMap::iterator it = _Entities.find(entity->GetUid());

    if (it != _Entities.end())
    {
        _Entities.erase(it);

        entityRemoved(this, entity);

        if (erase)
            delete entity;

        return true;
    }

    return false;
}

ProjectEntity* ProjectRecord::GetEntity(Uid uid) const
{
    EntityMap::const_iterator it = _Entities.find(uid);

    if (it != _Entities.end())
        return it->second;

    return 0;
}

const ProjectRecord::EntityMap& ProjectRecord::GetEntities() const
{
    return _Entities;
}
<|endoftext|>


<commit_before>//====================================================================================================================//
// File:          qcan_defs.hpp                                                                                //
// Description:   QCAN classes - Definitions                                                                          //
//                                                                                //
// Copyright (C) MicroControl GmbH & Co. KG                                                                           //
// 53844 Troisdorf - Germany                                                                                //
// www.microcontrol.net                                                                                //
//                                                                                //
//--------------------------------------------------------------------------------------------------------------------//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the   //
// following conditions are met:                                                                                //
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions, the following   //
//    disclaimer and the referenced file 'LICENSE'.                                                                   //
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       //
//    following disclaimer in the documentation and/or other materials provided with the distribution.                //
// 3. Neither the name of MicroControl nor the names of its contributors may be used to endorse or promote products   //
//    derived from this software without specific prior written permission.                                           //
//                                                                                //
// 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.                                     //
//                                                                                //
//====================================================================================================================//

#ifndef QCAN_DEFS_HPP_
#define QCAN_DEFS_HPP_

//------------------------------------------------------------------------------------------------------
/*!
** \file    qcan_defs.hpp
** \brief   Global QCan definitions
**
** This file holds global definitions for the QCanServer and QCanInterface classes.
**
*/

/*--------------------------------------------------------------------------------------------------------------------*\
** Definitions                                                                                **
**                                                                                **
\*--------------------------------------------------------------------------------------------------------------------*/

//------------------------------------------------------------------------------------------------------
/*!
** \defgroup QCAN_NW QCan network definitions
**
**
*/

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_WEB_SOCKET_DEFAULT_PORT
** \ingroup QCAN_NW
** \brief   Default port for WebSocket server
**
** This symbol defines the default WebSocket port for the server.
*/
#define  QCAN_WEB_SOCKET_DEFAULT_PORT       55660

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_WEB_SOCKET_MAX
** \ingroup QCAN_NW
** \brief   Maximum number of WebSockets
**
** This symbol defines the maximum number of sockets connected to the WebSocket server.
*/
#define  QCAN_WEB_SOCKET_MAX                64

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_LOCAL_SOCKET_MAX
** \ingroup QCAN_NW
** \brief   Maximum number of local sockets
**
** This symbol defines the maximum number of local sockets connected to the server.
*/
#define  QCAN_LOCAL_SOCKET_MAX              64

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_NETWORK_MAX
** \ingroup QCAN_NW
** \brief   Maximum number of networks
**
** This symbol defines the maximum number of networks.
*/
#define  QCAN_NETWORK_MAX                   8

//------------------------------------------------------------------------------------------------------
/*!
** \defgroup QCAN_IF QCan interface definitions
**
** The QCan interface definitions are used by the method QCanInterface::supportedFeatures().
*/

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_IF_SUPPORT_ERROR_FRAMES
** \ingroup QCAN_IF
** \brief   Support error frames
**
** The bit-mask value defines if error frames are supported by
** a CAN interface.
*/
#define  QCAN_IF_SUPPORT_ERROR_FRAMES     ((uint32_t) (0x00000001))

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_IF_SUPPORT_LISTEN_ONLY
** \ingroup QCAN_IF
** \brief   Support listen-only mode
**
** The bit-mask value defines if the listen-only mode is supported by
** a CAN interface.
*/
#define  QCAN_IF_SUPPORT_LISTEN_ONLY      ((uint32_t) (0x00000002))

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_IF_SUPPORT_CAN_FD
** \ingroup QCAN_IF
** \brief   Support CAN FD
**
** The bit-mask value defines if CAN FD is supported by
** a CAN interface.
*/
#define  QCAN_IF_SUPPORT_CAN_FD           ((uint32_t) (0x00000004))

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_IF_SUPPORT_SPECIFIC_CONFIG
** \ingroup QCAN_IF
** \brief   Support device specific configuration
**
** The bit-mask value defines if CAN interface supports
** device specific configuration.
*/
#define  QCAN_IF_SUPPORT_SPECIFIC_CONFIG  ((uint32_t) (0x00000008))

#define  QCAN_IF_SUPPORT_MASK             ((uint32_t) (0x0000000F))
#endif // QCAN_DEFS_HPP_
<commit_msg>Introduce QCAN_VERSION_ number<commit_after>//====================================================================================================================//
// File:          qcan_defs.hpp                                                                                //
// Description:   QCAN classes - Definitions                                                                          //
//                                                                                //
// Copyright (C) MicroControl GmbH & Co. KG                                                                           //
// 53844 Troisdorf - Germany                                                                                //
// www.microcontrol.net                                                                                //
//                                                                                //
//--------------------------------------------------------------------------------------------------------------------//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the   //
// following conditions are met:                                                                                //
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions, the following   //
//    disclaimer and the referenced file 'LICENSE'.                                                                   //
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       //
//    following disclaimer in the documentation and/or other materials provided with the distribution.                //
// 3. Neither the name of MicroControl nor the names of its contributors may be used to endorse or promote products   //
//    derived from this software without specific prior written permission.                                           //
//                                                                                //
// 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.                                     //
//                                                                                //
//====================================================================================================================//

#ifndef QCAN_DEFS_HPP_
#define QCAN_DEFS_HPP_

//------------------------------------------------------------------------------------------------------
/*!
** \file    qcan_defs.hpp
** \brief   Global QCan definitions
**
** This file holds global definitions for the QCanServer and QCanInterface classes.
**
*/

/*--------------------------------------------------------------------------------------------------------------------*\
** Definitions                                                                                **
**                                                                                **
\*--------------------------------------------------------------------------------------------------------------------*/

//------------------------------------------------------------------------------------------------------
/*!
** \defgroup QCAN_NW QCan network definitions
**
**
*/

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_WEB_SOCKET_DEFAULT_PORT
** \ingroup QCAN_NW
** \brief   Default port for WebSocket server
**
** This symbol defines the default WebSocket port for the server.
*/
#define  QCAN_WEB_SOCKET_DEFAULT_PORT       55660

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_WEB_SOCKET_MAX
** \ingroup QCAN_NW
** \brief   Maximum number of WebSockets
**
** This symbol defines the maximum number of sockets connected to the WebSocket server.
*/
#define  QCAN_WEB_SOCKET_MAX                64

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_LOCAL_SOCKET_MAX
** \ingroup QCAN_NW
** \brief   Maximum number of local sockets
**
** This symbol defines the maximum number of local sockets connected to the server.
*/
#define  QCAN_LOCAL_SOCKET_MAX              64

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_NETWORK_MAX
** \ingroup QCAN_NW
** \brief   Maximum number of networks
**
** This symbol defines the maximum number of networks.
*/
#define  QCAN_NETWORK_MAX                   8

//------------------------------------------------------------------------------------------------------
/*!
** \defgroup QCAN_IF QCan interface definitions
**
** The QCan interface definitions are used by the method QCanInterface::supportedFeatures().
*/

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_IF_SUPPORT_ERROR_FRAMES
** \ingroup QCAN_IF
** \brief   Support error frames
**
** The bit-mask value defines if error frames are supported by a CAN interface.
*/
#define  QCAN_IF_SUPPORT_ERROR_FRAMES     ((uint32_t) (0x00000001))

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_IF_SUPPORT_LISTEN_ONLY
** \ingroup QCAN_IF
** \brief   Support listen-only mode
**
** The bit-mask value defines if the listen-only mode is supported by a CAN interface.
*/
#define  QCAN_IF_SUPPORT_LISTEN_ONLY      ((uint32_t) (0x00000002))

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_IF_SUPPORT_CAN_FD
** \ingroup QCAN_IF
** \brief   Support CAN FD
**
** The bit-mask value defines if CAN FD is supported by a CAN interface.
*/
#define  QCAN_IF_SUPPORT_CAN_FD           ((uint32_t) (0x00000004))

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_IF_SUPPORT_SPECIFIC_CONFIG
** \ingroup QCAN_IF
** \brief   Support device specific configuration
**
** The bit-mask value defines if CAN interface supports device specific configuration.
*/
#define  QCAN_IF_SUPPORT_SPECIFIC_CONFIG  ((uint32_t) (0x00000008))

#define  QCAN_IF_SUPPORT_MASK             ((uint32_t) (0x0000000F))

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_VERSION_MAJOR
** \ingroup QCAN_VERSION
**
** This symbol defines the major version number.
*/
#define  QCAN_VERSION_MAJOR                 0

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_VERSION_MINOR
** \ingroup QCAN_VERSION
**
** This symbol defines the minor version number.
*/
#define  QCAN_VERSION_MINOR                 99

//------------------------------------------------------------------------------------------------------
/*!
** \def     QCAN_VERSION_BUILD
** \ingroup QCAN_VERSION
**
** This symbol defines the build version number.
*/
#define  QCAN_VERSION_BUILD                 8

#endif // QCAN_DEFS_HPP_
<|endoftext|>


<commit_before>#include <Arduino.h>
#include "HaskinoComm.h"
#include "HaskinoConfig.h"

#undef  DEBUG

bool runCodeBlock(int blockSize, const byte * block, CONTEXT *context)
    {
    int currPos = 0;
    TASK *task = context->task;
    bool taskRescheduled;
    int16_t thisBlockLevel;
#ifdef DEBUG
    sendStringf("Run Block %d %d %d",task->rescheduled,context->recallBlockLevel,context->currBlockLevel);
#endif

    if (task && task->rescheduled)
        {
        // A task is running, and has been rescheduled.
        // Increase the block level as we return to the level at which we
        // rescheduled.
        context->recallBlockLevel++;
        // Go to the position in the block at which we were interrupted.
        currPos = context->blockStatus[context->recallBlockLevel].currPos;
        // Set the block level we are executing at.
        thisBlockLevel = context->recallBlockLevel;
        // If we have reached the level at which we were rescheduled, then
        // the rescheduling process is complete, and we can resume normal
        // operation.
        if (context->recallBlockLevel == context->currBlockLevel)
            {
            task->rescheduled = false;
            }
        }
    else
        {
        // Increase the current context block level
        context->currBlockLevel++;
        // Start execution at the start of the code block
        context->blockStatus[context->currBlockLevel].currPos = 0;
        thisBlockLevel = context->currBlockLevel;
        }
#ifdef DEBUG
    sendStringf("Run Block Lvl %d",thisBlockLevel);
#endif

    while (currPos < blockSize)
        {
#ifdef DEBUG
        sendStringf("Block %d",currPos);
#endif
        const byte *msg = &block[currPos];
        byte cmdSize;
        const byte *cmd;

        if (msg[0] != 0xFF)
            {
            cmdSize = msg[0];
            cmd = &msg[1];
            }
        else
            {
            cmdSize = ((uint16_t) msg[2]) << 8 |
                      ((uint16_t) msg[1]);
            cmd = &msg[3];
            }

        taskRescheduled = parseMessage(cmdSize, cmd, context);

        if (!taskRescheduled || thisBlockLevel == context->currBlockLevel)
            {
            // If we weren't rescheduled, or we are running, then
            // move to the next command in the command block.
            currPos += cmdSize + 1;
            context->blockStatus[context->currBlockLevel].currPos = currPos;
            }
        if (task && taskRescheduled)
            {
            if (!task->rescheduled)
                {
                // Reset the recallBlockLevel for when task is reactivated.
                context->recallBlockLevel = -1;
                task->rescheduled = true;
                }
#ifdef DEBUG
            sendStringf("Resched Exit Block Lvl %d",thisBlockLevel);
#endif
            return true;
            }
        }

    context->currBlockLevel--;
#ifdef DEBUG
    sendStringf("Normal Exit Block Lvl %d",thisBlockLevel);
#endif
    return false;
    }
<commit_msg>Correct size cmdSize variable<commit_after>#include <Arduino.h>
#include "HaskinoComm.h"
#include "HaskinoConfig.h"

#undef  DEBUG

bool runCodeBlock(int blockSize, const byte * block, CONTEXT *context)
    {
    int currPos = 0;
    TASK *task = context->task;
    bool taskRescheduled;
    int16_t thisBlockLevel;
#ifdef DEBUG
    sendStringf("Run Block %d %d %d",task->rescheduled,context->recallBlockLevel,context->currBlockLevel);
#endif

    if (task && task->rescheduled)
        {
        // A task is running, and has been rescheduled.
        // Increase the block level as we return to the level at which we
        // rescheduled.
        context->recallBlockLevel++;
        // Go to the position in the block at which we were interrupted.
        currPos = context->blockStatus[context->recallBlockLevel].currPos;
        // Set the block level we are executing at.
        thisBlockLevel = context->recallBlockLevel;
        // If we have reached the level at which we were rescheduled, then
        // the rescheduling process is complete, and we can resume normal
        // operation.
        if (context->recallBlockLevel == context->currBlockLevel)
            {
            task->rescheduled = false;
            }
        }
    else
        {
        // Increase the current context block level
        context->currBlockLevel++;
        // Start execution at the start of the code block
        context->blockStatus[context->currBlockLevel].currPos = 0;
        thisBlockLevel = context->currBlockLevel;
        }
#ifdef DEBUG
    sendStringf("Run Block Lvl %d",thisBlockLevel);
#endif

    while (currPos < blockSize)
        {
#ifdef DEBUG
        sendStringf("Block %d",currPos);
#endif
        const byte *msg = &block[currPos];
        uint16_t cmdSize;
        const byte *cmd;

        if (msg[0] != 0xFF)
            {
            cmdSize = msg[0];
            cmd = &msg[1];
            }
        else
            {
            cmdSize = ((uint16_t) msg[2]) << 8 |
                      ((uint16_t) msg[1]);
            cmd = &msg[3];
            }

        taskRescheduled = parseMessage(cmdSize, cmd, context);

        if (!taskRescheduled || thisBlockLevel == context->currBlockLevel)
            {
            // If we weren't rescheduled, or we are running, then
            // move to the next command in the command block.
            currPos += cmdSize + 1;
            context->blockStatus[context->currBlockLevel].currPos = currPos;
            }
        if (task && taskRescheduled)
            {
            if (!task->rescheduled)
                {
                // Reset the recallBlockLevel for when task is reactivated.
                context->recallBlockLevel = -1;
                task->rescheduled = true;
                }
#ifdef DEBUG
            sendStringf("Resched Exit Block Lvl %d",thisBlockLevel);
#endif
            return true;
            }
        }

    context->currBlockLevel--;
#ifdef DEBUG
    sendStringf("Normal Exit Block Lvl %d",thisBlockLevel);
#endif
    return false;
    }
<|endoftext|>


<commit_before>#include <aerial_autonomy/estimators/tracking_vector_estimator.h>
#include <aerial_autonomy/log/log.h>
#include <glog/logging.h>

TrackingVectorEstimator::TrackingVectorEstimator(
    TrackingVectorEstimatorConfig config,
    std::chrono::duration<double> propagation_step)
    : config_(config), filter_(3, 3, 3, CV_64F), zero_tolerance_(1e-6),
      initial_state_initialized_(false) {
  // Assuming x = [Marker direction] and u = [velocity]
  // Transition matrix
  filter_.transitionMatrix = cv::Mat_<double>::eye(3, 3);
  filter_.controlMatrix =
      -propagation_step.count() * cv::Mat_<double>::eye(3, 3);
  // Measurement matrix
  filter_.measurementMatrix = cv::Mat_<double>::eye(3, 3);
  // Check stdeviation vectors
  checkStdVector(config_.marker_process_stdev());
  checkStdVector(config_.marker_meas_stdev());
  checkStdVector(config_.marker_initial_stdev());
  checkStdVector(config_.marker_dilation_stdev());
  // Noise matrices
  setCovarianceMatrix(filter_.processNoiseCov, config_.marker_process_stdev());
  setCovarianceMatrix(filter_.measurementNoiseCov, config_.marker_meas_stdev());
  // Save variables
  marker_dilation_stdev_ = tf::Vector3(config_.marker_dilation_stdev().x(),
                                       config_.marker_dilation_stdev().y(),
                                       config_.marker_dilation_stdev().z());
  marker_meas_stdev_ = tf::Vector3(config_.marker_meas_stdev().x(),
                                   config_.marker_meas_stdev().y(),
                                   config_.marker_meas_stdev().z());
  // Set initial state
  initializeState(tf::Vector3(0, 0, 0));
  DATA_HEADER("tracking_vector_estimator") << "Measured_Marker_x"
                                           << "Measured_Marker_y"
                                           << "Measured_Marker_z"
                                           << "Marker_x"
                                           << "Marker_y"
                                           << "Marker_z"
                                           << "Meas_noise_x"
                                           << "Meas_noise_y"
                                           << "Meas_noise_z"
                                           << "Noise_x"
                                           << "Noise_y"
                                           << "Noise_z" << DataStream::endl;
}

void TrackingVectorEstimator::initializeState(tf::Vector3 marker_direction) {
  VLOG(1) << "Initializing KF with Marker dirxn: " << marker_direction.x()
          << marker_direction.y() << marker_direction.z();
  filter_.statePre = (cv::Mat_<double>(3, 1) << marker_direction.x(),
                      marker_direction.y(), marker_direction.z());
  setCovarianceMatrix(filter_.errorCovPost, config_.marker_initial_stdev());
  filter_.statePre.copyTo(filter_.statePost);
  initial_state_initialized_ = true;
}

void TrackingVectorEstimator::predict(tf::Vector3 velocity) {
  cv::Mat_<double> control =
      (cv::Mat_<double>(3, 1) << velocity.x(), velocity.y(), velocity.z());
  filter_.predict(control);
}

void TrackingVectorEstimator::setMeasurementCovariance(
    cv::Mat &covariance_mat,
    std::chrono::time_point<std::chrono::high_resolution_clock>
        marker_time_stamp) {
  double dt = std::chrono::duration<double>(
                  std::chrono::high_resolution_clock::now() - marker_time_stamp)
                  .count();
  dt = std::max(dt, 0.0);
  tf::Vector3 current_meas_stdev =
      marker_meas_stdev_ + dt * marker_dilation_stdev_;
  setCovarianceMatrix(covariance_mat, current_meas_stdev);
}

void TrackingVectorEstimator::correct(
    tf::Vector3 marker_direction,
    std::chrono::time_point<std::chrono::high_resolution_clock>
        marker_time_stamp) {
  if (!initial_state_initialized_) {
    initializeState(marker_direction);
    return;
  }
  cv::Mat_<double> measurement =
      (cv::Mat_<double>(3, 1) << marker_direction.x(), marker_direction.y(),
       marker_direction.z());
  setMeasurementCovariance(filter_.measurementNoiseCov, marker_time_stamp);
  filter_.correct(measurement);
  // Log data
  tf::Vector3 marker_noise = getMarkerNoise();
  auto state = filter_.statePost;
  auto &data_stream = Log::instance()["tracking_vector_estimator"];
  data_stream << DataStream::startl;
  for (int i = 0; i < 3; ++i) {
    data_stream << measurement.at<double>(i);
  }
  for (int i = 0; i < 3; ++i) {
    data_stream << state.at<double>(i);
  }
  for (int i = 0; i < 3; ++i) {
    data_stream << sqrt(filter_.measurementNoiseCov.at<double>(i, i));
  }
  for (int i = 0; i < 3; ++i) {
    data_stream << marker_noise[i];
  }
  data_stream << DataStream::endl;
}
<commit_msg>Check dt is above 0 and warn if not.<commit_after>#include <aerial_autonomy/estimators/tracking_vector_estimator.h>
#include <aerial_autonomy/log/log.h>
#include <glog/logging.h>

TrackingVectorEstimator::TrackingVectorEstimator(
    TrackingVectorEstimatorConfig config,
    std::chrono::duration<double> propagation_step)
    : config_(config), filter_(3, 3, 3, CV_64F), zero_tolerance_(1e-6),
      initial_state_initialized_(false) {
  // Assuming x = [Marker direction] and u = [velocity]
  // Transition matrix
  filter_.transitionMatrix = cv::Mat_<double>::eye(3, 3);
  filter_.controlMatrix =
      -propagation_step.count() * cv::Mat_<double>::eye(3, 3);
  // Measurement matrix
  filter_.measurementMatrix = cv::Mat_<double>::eye(3, 3);
  // Check stdeviation vectors
  checkStdVector(config_.marker_process_stdev());
  checkStdVector(config_.marker_meas_stdev());
  checkStdVector(config_.marker_initial_stdev());
  checkStdVector(config_.marker_dilation_stdev());
  // Noise matrices
  setCovarianceMatrix(filter_.processNoiseCov, config_.marker_process_stdev());
  setCovarianceMatrix(filter_.measurementNoiseCov, config_.marker_meas_stdev());
  // Save variables
  marker_dilation_stdev_ = tf::Vector3(config_.marker_dilation_stdev().x(),
                                       config_.marker_dilation_stdev().y(),
                                       config_.marker_dilation_stdev().z());
  marker_meas_stdev_ = tf::Vector3(config_.marker_meas_stdev().x(),
                                   config_.marker_meas_stdev().y(),
                                   config_.marker_meas_stdev().z());
  // Set initial state
  initializeState(tf::Vector3(0, 0, 0));
  DATA_HEADER("tracking_vector_estimator") << "Measured_Marker_x"
                                           << "Measured_Marker_y"
                                           << "Measured_Marker_z"
                                           << "Marker_x"
                                           << "Marker_y"
                                           << "Marker_z"
                                           << "Meas_noise_x"
                                           << "Meas_noise_y"
                                           << "Meas_noise_z"
                                           << "Noise_x"
                                           << "Noise_y"
                                           << "Noise_z" << DataStream::endl;
}

void TrackingVectorEstimator::initializeState(tf::Vector3 marker_direction) {
  VLOG(1) << "Initializing KF with Marker dirxn: " << marker_direction.x()
          << marker_direction.y() << marker_direction.z();
  filter_.statePre = (cv::Mat_<double>(3, 1) << marker_direction.x(),
                      marker_direction.y(), marker_direction.z());
  setCovarianceMatrix(filter_.errorCovPost, config_.marker_initial_stdev());
  filter_.statePre.copyTo(filter_.statePost);
  initial_state_initialized_ = true;
}

void TrackingVectorEstimator::predict(tf::Vector3 velocity) {
  cv::Mat_<double> control =
      (cv::Mat_<double>(3, 1) << velocity.x(), velocity.y(), velocity.z());
  filter_.predict(control);
}

void TrackingVectorEstimator::setMeasurementCovariance(
    cv::Mat &covariance_mat,
    std::chrono::time_point<std::chrono::high_resolution_clock>
        marker_time_stamp) {
  double dt = std::chrono::duration<double>(
                  std::chrono::high_resolution_clock::now() - marker_time_stamp)
                  .count();
  if (dt < 0) {
    LOG(WARNING) << "dt negative: " << dt;
    dt = 0;
  }
  tf::Vector3 current_meas_stdev =
      marker_meas_stdev_ + dt * marker_dilation_stdev_;
  setCovarianceMatrix(covariance_mat, current_meas_stdev);
}

void TrackingVectorEstimator::correct(
    tf::Vector3 marker_direction,
    std::chrono::time_point<std::chrono::high_resolution_clock>
        marker_time_stamp) {
  if (!initial_state_initialized_) {
    initializeState(marker_direction);
    return;
  }
  cv::Mat_<double> measurement =
      (cv::Mat_<double>(3, 1) << marker_direction.x(), marker_direction.y(),
       marker_direction.z());
  setMeasurementCovariance(filter_.measurementNoiseCov, marker_time_stamp);
  filter_.correct(measurement);
  // Log data
  tf::Vector3 marker_noise = getMarkerNoise();
  auto state = filter_.statePost;
  auto &data_stream = Log::instance()["tracking_vector_estimator"];
  data_stream << DataStream::startl;
  for (int i = 0; i < 3; ++i) {
    data_stream << measurement.at<double>(i);
  }
  for (int i = 0; i < 3; ++i) {
    data_stream << state.at<double>(i);
  }
  for (int i = 0; i < 3; ++i) {
    data_stream << sqrt(filter_.measurementNoiseCov.at<double>(i, i));
  }
  for (int i = 0; i < 3; ++i) {
    data_stream << marker_noise[i];
  }
  data_stream << DataStream::endl;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 "stdafx.h"

#include <cstddef>
#include "api/functionimpl.h"
#include "api/zorbaimpl.h"
#include "api/unmarshaller.h"

#include "functions/function.h"
#include "diagnostics/xquery_diagnostics.h"
#include "annotations/annotations.h"
#include "api/annotationimpl.h"

namespace zorba {

///////////////////////////////////////////////////////////////////////////////

bool FunctionImpl::isUpdating() const
{
  return theFunction->isUpdating();
}

bool FunctionImpl::isPrivate() const
{
  return theFunction->isPrivate();
}

bool FunctionImpl::isDeterministic() const
{
  return theFunction->isDeterministic();
}

bool FunctionImpl::isSequential() const
{
  return theFunction->isSequential();
}

void FunctionImpl::getAnnotations(std::vector<Annotation_t>& annotations) const
{
  annotations.clear();

  const AnnotationList* ann_list = theFunction->getAnnotationList();
  if (ann_list == NULL)
    return;

  try
  {
    for (unsigned int i = 0; i < ann_list->size(); ++i)
      annotations.push_back(new AnnotationImpl(ann_list->get(i)));
  }
  catch (ZorbaException const& e)
  {
    ZorbaImpl::notifyError(theDiagnosticHandler, e);
  }
}

Item FunctionImpl::getQName() const
{
  try
  {
    return theFunction->getName();
  }
  catch (ZorbaException const& e)
  {
    ZorbaImpl::notifyError(theDiagnosticHandler, e);
  }
  return Item();
}

String FunctionImpl::getURI() const
{
  try
  {
    return Unmarshaller::newString(theFunction->getName()->getNamespace());
  }
  catch (ZorbaException const& e)
  {
    ZorbaImpl::notifyError(theDiagnosticHandler, e);
  }
  return String();
}

String FunctionImpl::getLocalName() const
{
  try
  {
    return Unmarshaller::newString(theFunction->getName()->getLocalName());
  }
  catch (ZorbaException const& e)
  {
    ZorbaImpl::notifyError(theDiagnosticHandler, e);
  }
  return String();
}

size_t FunctionImpl::getArity() const
{
  return theFunction->getArity();
}

bool FunctionImpl::isVariadic() const
{
  return theFunction->isVariadic();
}

bool FunctionImpl::isExternal() const
{
  return static_cast<function*>(theFunction)->isExternal();
}

bool FunctionImpl::isXQuery() const
{
  return static_cast<function*>(theFunction)->isUdf();
}

bool FunctionImpl::isBuiltin() const
{
  return static_cast<function*>(theFunction)->isBuiltin();
}

///////////////////////////////////////////////////////////////////////////////

Item ExternalFunction::getItem( Arguments_t const &args, unsigned pos ) const {
  Iterator_t i = args[ pos ]->getIterator();
  Item item;
  i->open();
  i->next( item );
  i->close();
  return item;
}

///////////////////////////////////////////////////////////////////////////////

} // namespace zorba
/* vim:set et sw=2 ts=2: */
<commit_msg>Added missing header.<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 "stdafx.h"

#include <cstddef>

#include <zorba/item_sequence.h>

#include "api/functionimpl.h"
#include "api/zorbaimpl.h"
#include "api/unmarshaller.h"

#include "functions/function.h"
#include "diagnostics/xquery_diagnostics.h"
#include "annotations/annotations.h"
#include "api/annotationimpl.h"

namespace zorba {

///////////////////////////////////////////////////////////////////////////////

bool FunctionImpl::isUpdating() const
{
  return theFunction->isUpdating();
}

bool FunctionImpl::isPrivate() const
{
  return theFunction->isPrivate();
}

bool FunctionImpl::isDeterministic() const
{
  return theFunction->isDeterministic();
}

bool FunctionImpl::isSequential() const
{
  return theFunction->isSequential();
}

void FunctionImpl::getAnnotations(std::vector<Annotation_t>& annotations) const
{
  annotations.clear();

  const AnnotationList* ann_list = theFunction->getAnnotationList();
  if (ann_list == NULL)
    return;

  try
  {
    for (unsigned int i = 0; i < ann_list->size(); ++i)
      annotations.push_back(new AnnotationImpl(ann_list->get(i)));
  }
  catch (ZorbaException const& e)
  {
    ZorbaImpl::notifyError(theDiagnosticHandler, e);
  }
}

Item FunctionImpl::getQName() const
{
  try
  {
    return theFunction->getName();
  }
  catch (ZorbaException const& e)
  {
    ZorbaImpl::notifyError(theDiagnosticHandler, e);
  }
  return Item();
}

String FunctionImpl::getURI() const
{
  try
  {
    return Unmarshaller::newString(theFunction->getName()->getNamespace());
  }
  catch (ZorbaException const& e)
  {
    ZorbaImpl::notifyError(theDiagnosticHandler, e);
  }
  return String();
}

String FunctionImpl::getLocalName() const
{
  try
  {
    return Unmarshaller::newString(theFunction->getName()->getLocalName());
  }
  catch (ZorbaException const& e)
  {
    ZorbaImpl::notifyError(theDiagnosticHandler, e);
  }
  return String();
}

size_t FunctionImpl::getArity() const
{
  return theFunction->getArity();
}

bool FunctionImpl::isVariadic() const
{
  return theFunction->isVariadic();
}

bool FunctionImpl::isExternal() const
{
  return static_cast<function*>(theFunction)->isExternal();
}

bool FunctionImpl::isXQuery() const
{
  return static_cast<function*>(theFunction)->isUdf();
}

bool FunctionImpl::isBuiltin() const
{
  return static_cast<function*>(theFunction)->isBuiltin();
}

///////////////////////////////////////////////////////////////////////////////

Item ExternalFunction::getItem( Arguments_t const &args, unsigned pos ) const {
  Iterator_t i = args[ pos ]->getIterator();
  Item item;
  i->open();
  i->next( item );
  i->close();
  return item;
}

///////////////////////////////////////////////////////////////////////////////

} // namespace zorba
/* vim:set et sw=2 ts=2: */
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2009 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__

#include "base/bitunion.hh"

namespace ArmISA
{
    enum ConditionCode {
        COND_EQ  =   0,
        COND_NE, //  1
        COND_CS, //  2
        COND_CC, //  3
        COND_MI, //  4
        COND_PL, //  5
        COND_VS, //  6
        COND_VC, //  7
        COND_HI, //  8
        COND_LS, //  9
        COND_GE, // 10
        COND_LT, // 11
        COND_GT, // 12
        COND_LE, // 13
        COND_AL, // 14
        COND_UC  // 15
    };

    enum MiscRegIndex {
        MISCREG_CPSR = 0,
        MISCREG_SPSR,
        MISCREG_SPSR_FIQ,
        MISCREG_SPSR_IRQ,
        MISCREG_SPSR_SVC,
        MISCREG_SPSR_MON,
        MISCREG_SPSR_UND,
        MISCREG_SPSR_ABT,
        MISCREG_FPSR,
        MISCREG_FPSID,
        MISCREG_FPSCR,
        MISCREG_FPEXC,

        // CP15 registers
        MISCREG_CP15_START,
        MISCREG_SCTLR = MISCREG_CP15_START,
        MISCREG_DCCISW,
        MISCREG_CONTEXTIDR,
        MISCREG_CP15_UNIMP_START,
        MISCREG_CTR = MISCREG_CP15_UNIMP_START,
        MISCREG_TCMTR,
        MISCREG_MPUIR,
        MISCREG_MPIDR,
        MISCREG_MIDR,
        MISCREG_ID_PFR0,
        MISCREG_ID_PFR1,
        MISCREG_ID_DFR0,
        MISCREG_ID_AFR0,
        MISCREG_ID_MMFR0,
        MISCREG_ID_MMFR1,
        MISCREG_ID_MMFR2,
        MISCREG_ID_MMFR3,
        MISCREG_ID_ISAR0,
        MISCREG_ID_ISAR1,
        MISCREG_ID_ISAR2,
        MISCREG_ID_ISAR3,
        MISCREG_ID_ISAR4,
        MISCREG_ID_ISAR5,
        MISCREG_CCSIDR,
        MISCREG_CLIDR,
        MISCREG_AIDR,
        MISCREG_CSSELR,
        MISCREG_ACTLR,
        MISCREG_CPACR,
        MISCREG_DFSR,
        MISCREG_IFSR,
        MISCREG_ADFSR,
        MISCREG_AIFSR,
        MISCREG_DFAR,
        MISCREG_IFAR,
        MISCREG_DRBAR,
        MISCREG_IRBAR,
        MISCREG_DRSR,
        MISCREG_IRSR,
        MISCREG_DRACR,
        MISCREG_IRACR,
        MISCREG_RGNR,
        MISCREG_ICIALLUIS,
        MISCREG_BPIALLIS,
        MISCREG_ICIALLU,
        MISCREG_ICIMVAU,
        MISCREG_CP15ISB,
        MISCREG_BPIALL,
        MISCREG_BPIMVA,
        MISCREG_DCIMVAC,
        MISCREG_DCISW,
        MISCREG_DCCMVAC,
        MISCREG_MCCSW,
        MISCREG_CP15DSB,
        MISCREG_CP15DMB,
        MISCREG_DCCMVAU,
        MISCREG_DCCIMVAC,
        MISCREG_TPIDRURW,
        MISCREG_TPIDRURO,
        MISCREG_TPIDRPRW,

        MISCREG_CP15_END,

        // Dummy indices
        MISCREG_NOP = MISCREG_CP15_END,
        MISCREG_RAZ,

        NUM_MISCREGS
    };

    MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
                               unsigned crm, unsigned opc2);

    const char * const miscRegName[NUM_MISCREGS] = {
        "cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
        "spsr_mon", "spsr_und", "spsr_abt",
        "fpsr", "fpsid", "fpscr", "fpexc",
        "sctlr", "dccisw", "contextidr", "ctr", "tcmtr", "mpuir", "mpidr", "midr",
        "id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
        "id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
        "id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
        "ccsidr", "clidr", "aidr", "csselr", "actlr", "cpacr",
        "dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
        "drbar", "irbar", "drsr", "irsr", "dracr", "iracr",
        "rgnr", "icialluis", "bpiallis", "iciallu", "icimvau",
        "cp15isb", "bpiall", "bpimva", "dcimvac", "dcisw", "dccmvac", "mccsw",
        "cp15dsb", "cp15dmb", "dccmvau", "dccimvac",
        "tpidrurw", "tpidruro", "tpidrprw",
        "nop", "raz"
    };

    BitUnion32(CPSR)
        Bitfield<31> n;
        Bitfield<30> z;
        Bitfield<29> c;
        Bitfield<28> v;
        Bitfield<27> q;
        Bitfield<26,25> it1;
        Bitfield<24> j;
        Bitfield<19, 16> ge;
        Bitfield<15,10> it2;
        Bitfield<9> e;
        Bitfield<8> a;
        Bitfield<7> i;
        Bitfield<6> f;
        Bitfield<5> t;
        Bitfield<4, 0> mode;
    EndBitUnion(CPSR)

    // This mask selects bits of the CPSR that actually go in the CondCodes
    // integer register to allow renaming.
    static const uint32_t CondCodesMask = 0xF80F0000;

    // These otherwise unused bits of the PC are used to select a mode
    // like the J and T bits of the CPSR.
    static const Addr PcJBitShift = 33;
    static const Addr PcTBitShift = 34;
    static const Addr PcModeMask = (ULL(1) << PcJBitShift) |
                                   (ULL(1) << PcTBitShift);

    BitUnion32(SCTLR)
        Bitfield<30> te;  // Thumb Exception Enable
        Bitfield<29> afe; // Access flag enable
        Bitfield<28> tre; // TEX Remap bit
        Bitfield<27> nmfi;// Non-maskable fast interrupts enable
        Bitfield<25> ee;  // Exception Endianness bit
        Bitfield<24> ve;  // Interrupt vectors enable
        Bitfield<23> rao1;// Read as one
        Bitfield<22> u;   // Alignment (now unused)
        Bitfield<21> fi;  // Fast interrupts configuration enable
        Bitfield<18> rao2;// Read as one
        Bitfield<17> ha;  // Hardware access flag enable
        Bitfield<16> rao3;// Read as one
        Bitfield<14> rr;  // Round robin cache replacement
        Bitfield<13> v;   // Base address for exception vectors
        Bitfield<12> i;   // instruction cache enable
        Bitfield<11> z;   // branch prediction enable bit
        Bitfield<10> sw;  // Enable swp/swpb
        Bitfield<6,3> rao4;// Read as one
        Bitfield<7>  b;   // Endianness support (unused)
        Bitfield<2>  c;   // Cache enable bit
        Bitfield<1>  a;   // Alignment fault checking
        Bitfield<0>  m;   // MMU enable bit
    EndBitUnion(SCTLR)
};

#endif // __ARCH_ARM_MISCREGS_HH__
<commit_msg>ARM: Allow accesses to the software thread id registers.<commit_after>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2009 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__

#include "base/bitunion.hh"

namespace ArmISA
{
    enum ConditionCode {
        COND_EQ  =   0,
        COND_NE, //  1
        COND_CS, //  2
        COND_CC, //  3
        COND_MI, //  4
        COND_PL, //  5
        COND_VS, //  6
        COND_VC, //  7
        COND_HI, //  8
        COND_LS, //  9
        COND_GE, // 10
        COND_LT, // 11
        COND_GT, // 12
        COND_LE, // 13
        COND_AL, // 14
        COND_UC  // 15
    };

    enum MiscRegIndex {
        MISCREG_CPSR = 0,
        MISCREG_SPSR,
        MISCREG_SPSR_FIQ,
        MISCREG_SPSR_IRQ,
        MISCREG_SPSR_SVC,
        MISCREG_SPSR_MON,
        MISCREG_SPSR_UND,
        MISCREG_SPSR_ABT,
        MISCREG_FPSR,
        MISCREG_FPSID,
        MISCREG_FPSCR,
        MISCREG_FPEXC,

        // CP15 registers
        MISCREG_CP15_START,
        MISCREG_SCTLR = MISCREG_CP15_START,
        MISCREG_DCCISW,
        MISCREG_CONTEXTIDR,
        MISCREG_TPIDRURW,
        MISCREG_TPIDRURO,
        MISCREG_TPIDRPRW,
        MISCREG_CP15_UNIMP_START,
        MISCREG_CTR = MISCREG_CP15_UNIMP_START,
        MISCREG_TCMTR,
        MISCREG_MPUIR,
        MISCREG_MPIDR,
        MISCREG_MIDR,
        MISCREG_ID_PFR0,
        MISCREG_ID_PFR1,
        MISCREG_ID_DFR0,
        MISCREG_ID_AFR0,
        MISCREG_ID_MMFR0,
        MISCREG_ID_MMFR1,
        MISCREG_ID_MMFR2,
        MISCREG_ID_MMFR3,
        MISCREG_ID_ISAR0,
        MISCREG_ID_ISAR1,
        MISCREG_ID_ISAR2,
        MISCREG_ID_ISAR3,
        MISCREG_ID_ISAR4,
        MISCREG_ID_ISAR5,
        MISCREG_CCSIDR,
        MISCREG_CLIDR,
        MISCREG_AIDR,
        MISCREG_CSSELR,
        MISCREG_ACTLR,
        MISCREG_CPACR,
        MISCREG_DFSR,
        MISCREG_IFSR,
        MISCREG_ADFSR,
        MISCREG_AIFSR,
        MISCREG_DFAR,
        MISCREG_IFAR,
        MISCREG_DRBAR,
        MISCREG_IRBAR,
        MISCREG_DRSR,
        MISCREG_IRSR,
        MISCREG_DRACR,
        MISCREG_IRACR,
        MISCREG_RGNR,
        MISCREG_ICIALLUIS,
        MISCREG_BPIALLIS,
        MISCREG_ICIALLU,
        MISCREG_ICIMVAU,
        MISCREG_CP15ISB,
        MISCREG_BPIALL,
        MISCREG_BPIMVA,
        MISCREG_DCIMVAC,
        MISCREG_DCISW,
        MISCREG_DCCMVAC,
        MISCREG_MCCSW,
        MISCREG_CP15DSB,
        MISCREG_CP15DMB,
        MISCREG_DCCMVAU,
        MISCREG_DCCIMVAC,

        MISCREG_CP15_END,

        // Dummy indices
        MISCREG_NOP = MISCREG_CP15_END,
        MISCREG_RAZ,

        NUM_MISCREGS
    };

    MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
                               unsigned crm, unsigned opc2);

    const char * const miscRegName[NUM_MISCREGS] = {
        "cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
        "spsr_mon", "spsr_und", "spsr_abt",
        "fpsr", "fpsid", "fpscr", "fpexc",
        "sctlr", "dccisw", "contextidr", "tpidrurw", "tpidruro", "tpidrprw",
        "ctr", "tcmtr", "mpuir", "mpidr", "midr",
        "id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
        "id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
        "id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
        "ccsidr", "clidr", "aidr", "csselr", "actlr", "cpacr",
        "dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
        "drbar", "irbar", "drsr", "irsr", "dracr", "iracr",
        "rgnr", "icialluis", "bpiallis", "iciallu", "icimvau",
        "cp15isb", "bpiall", "bpimva", "dcimvac", "dcisw", "dccmvac", "mccsw",
        "cp15dsb", "cp15dmb", "dccmvau", "dccimvac",
        "nop", "raz"
    };

    BitUnion32(CPSR)
        Bitfield<31> n;
        Bitfield<30> z;
        Bitfield<29> c;
        Bitfield<28> v;
        Bitfield<27> q;
        Bitfield<26,25> it1;
        Bitfield<24> j;
        Bitfield<19, 16> ge;
        Bitfield<15,10> it2;
        Bitfield<9> e;
        Bitfield<8> a;
        Bitfield<7> i;
        Bitfield<6> f;
        Bitfield<5> t;
        Bitfield<4, 0> mode;
    EndBitUnion(CPSR)

    // This mask selects bits of the CPSR that actually go in the CondCodes
    // integer register to allow renaming.
    static const uint32_t CondCodesMask = 0xF80F0000;

    // These otherwise unused bits of the PC are used to select a mode
    // like the J and T bits of the CPSR.
    static const Addr PcJBitShift = 33;
    static const Addr PcTBitShift = 34;
    static const Addr PcModeMask = (ULL(1) << PcJBitShift) |
                                   (ULL(1) << PcTBitShift);

    BitUnion32(SCTLR)
        Bitfield<30> te;  // Thumb Exception Enable
        Bitfield<29> afe; // Access flag enable
        Bitfield<28> tre; // TEX Remap bit
        Bitfield<27> nmfi;// Non-maskable fast interrupts enable
        Bitfield<25> ee;  // Exception Endianness bit
        Bitfield<24> ve;  // Interrupt vectors enable
        Bitfield<23> rao1;// Read as one
        Bitfield<22> u;   // Alignment (now unused)
        Bitfield<21> fi;  // Fast interrupts configuration enable
        Bitfield<18> rao2;// Read as one
        Bitfield<17> ha;  // Hardware access flag enable
        Bitfield<16> rao3;// Read as one
        Bitfield<14> rr;  // Round robin cache replacement
        Bitfield<13> v;   // Base address for exception vectors
        Bitfield<12> i;   // instruction cache enable
        Bitfield<11> z;   // branch prediction enable bit
        Bitfield<10> sw;  // Enable swp/swpb
        Bitfield<6,3> rao4;// Read as one
        Bitfield<7>  b;   // Endianness support (unused)
        Bitfield<2>  c;   // Cache enable bit
        Bitfield<1>  a;   // Alignment fault checking
        Bitfield<0>  m;   // MMU enable bit
    EndBitUnion(SCTLR)
};

#endif // __ARCH_ARM_MISCREGS_HH__
<|endoftext|>