<commit_before>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *        Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen         *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *                                                                           *
 *                                License                                    *
 *                                                                           *
 *  This library is free software; you can redistribute it and/or modify it  *
 *  under the terms of the GNU Lesser General Public License as published    *
 *  by the Free Software Foundation, version 2.1.                            *
 *                                                                           *
 *  This library is distributed in the hope that it will be useful, but      *
 *  WITHOUT ANY WARRANTY; without even the implied warranty of               *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
 *  Lesser General Public License for more details.                          *
 *                                                                           *
 *  You should have received a copy of the GNU Lesser General Public         *
 *  License along with this library; if not, write to the Free Software      *
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                *
 *                                                                           *
\*===========================================================================*/

//== INCLUDES =================================================================

//STL
#include <fstream>

// OpenMesh
#include <OpenMesh/Core/System/config.h>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/writer/OBJWriter.hh>
#include <OpenMesh/Core/IO/IOManager.hh>
#include <OpenMesh/Core/System/omstream.hh>
#include <OpenMesh/Core/Utils/color_cast.hh>

//=== NAMESPACES ==============================================================

namespace OpenMesh {
namespace IO {

//=== INSTANCIATE =============================================================

// register the OBJLoader singleton with MeshLoader
_OBJWriter_  __OBJWriterinstance;
_OBJWriter_& OBJWriter() { return __OBJWriterinstance; }

//=== IMPLEMENTATION ==========================================================

_OBJWriter_::_OBJWriter_() { IOManager().register_module(this); }

//-----------------------------------------------------------------------------

bool
_OBJWriter_::
write(const std::string& _filename, BaseExporter& _be, Options _opt) const
{
  std::fstream out(_filename.c_str(), std::ios_base::out );

  if (!out)
  {
    omerr() << "[OBJWriter] : cannot open file "
	  << _filename << std::endl;
    return false;
  }

  {
#if defined(WIN32)
    std::string::size_type dot = _filename.find_last_of("\\/");
#else
    std::string::size_type dot = _filename.rfind("/");
#endif

    if (dot == std::string::npos){
      path_ = "./";
      objName_ = _filename;
    }else{
      path_ = _filename.substr(0,dot+1);
      objName_ = _filename.substr(dot+1);
    }

    //remove the file extension
    dot = _filename.find_last_of(".");

    if(dot != std::string::npos)
      objName_ = objName_.substr(0,dot-1);
  }

  bool result = write(out, _be, _opt);

  out.close();
  return result;
}

//-----------------------------------------------------------------------------

int _OBJWriter_::getMaterial(OpenMesh::Vec3f _color) const
{
  for (uint i=0; i < material_.size(); i++)
    if(material_[i] == _color)
      return i;

  //not found add new material
  material_.push_back( _color );
  return material_.size()-1;
}

//-----------------------------------------------------------------------------

int _OBJWriter_::getMaterial(OpenMesh::Vec4f _color) const
{
  for (uint i=0; i < materialA_.size(); i++)
    if(materialA_[i] == _color)
      return i;

  //not found add new material
  materialA_.push_back( _color );
  return materialA_.size()-1;
}

//-----------------------------------------------------------------------------

bool
_OBJWriter_::
writeMaterial(std::fstream& _out, BaseExporter& _be, Options _opt) const
{
  OpenMesh::Vec3f c;
  OpenMesh::Vec4f cA;

  material_.clear();
  materialA_.clear();

  //iterate over faces
  for (int i=0, nF=_be.n_faces(); i<nF; ++i)
  {
    //color with alpha
    if ( _opt.color_has_alpha() ){
      cA  = color_cast<OpenMesh::Vec4f> (_be.colorA( FaceHandle(i) ));
      getMaterial(cA);
    }else{
    //and without alpha
      c  = color_cast<OpenMesh::Vec3f> (_be.color( FaceHandle(i) ));
      getMaterial(c);
    }
  }

  //write the materials
  if ( _opt.color_has_alpha() )
    for (uint i=0; i < materialA_.size(); i++){
      _out << "newmtl " << "mat" << i << std::endl;
      _out << "Ka 0.5000 0.5000 0.5000" << std::endl;
      _out << "Kd " << materialA_[i][0] << materialA_[i][1] << materialA_[i][2] << std::endl;;
      _out << "Tr " << materialA_[i][3] << std::endl;
      _out << "illum 1" << std::endl;
    }
  else
    for (uint i=0; i < material_.size(); i++){
      _out << "newmtl " << "mat" << i << std::endl;
      _out << "Ka 0.5000 0.5000 0.5000" << std::endl;
      _out << "Kd " << material_[i][0] << material_[i][1] << material_[i][2] << std::endl;;
      _out << "illum 1" << std::endl;
    }

  return true;
}

//-----------------------------------------------------------------------------

bool
_OBJWriter_::
write(std::fstream& _out, BaseExporter& _be, Options _opt) const
{
  unsigned int i, j, nV, nF, idx;
  Vec3f v, n;
  Vec2f t;
  VertexHandle vh;
  std::vector<VertexHandle> vhandles;
  bool useMatrial = false;
  OpenMesh::Vec3f c;
  OpenMesh::Vec4f cA;

  omlog() << "[OBJWriter] : write file\n";

  // check exporter features
  if (!check( _be, _opt))
     return false;

  // check writer features
  if ( _opt.check(Options::Binary)     || // not supported by format
       _opt.check(Options::FaceNormal) ||
       _opt.check(Options::FaceColor))
     return false;

  //create material file if needed
  if ( _opt.check(Options::FaceColor) ){

    std::string matFile = path_ + objName_ + ".mat";

    std::fstream matStream(matFile.c_str(), std::ios_base::out );

    if (!_out)
    {
      omerr() << "[OBJWriter] : cannot write material file " << matFile << std::endl;

    }else{
      useMatrial = writeMaterial(matStream, _be, _opt);

      matStream.close();
    }
  }

  // header
  _out << "# " << _be.n_vertices() << " vertices, ";
  _out << _be.n_faces() << " faces" << std::endl;

  // material file
  if (useMatrial &&  _opt.check(Options::FaceColor) )
    _out << "mtllib " << objName_ << ".mat" << std::endl;

  // vertex data (point, normals, texcoords)
  for (i=0, nV=_be.n_vertices(); i<nV; ++i)
  {
    vh = VertexHandle(i);
    v  = _be.point(vh);
    n  = _be.normal(vh);
    t  = _be.texcoord(vh);

    _out << "v " << v[0] <<" "<< v[1] <<" "<< v[2] << std::endl;

    if (_opt.check(Options::VertexNormal))
      _out << "n " << n[0] <<" "<< n[1] <<" "<< n[2] << std::endl;

    if (_opt.check(Options::VertexTexCoord))
      _out << "vt " << t[0] <<" "<< t[1] << std::endl;
  }

  int lastMat = -1;

  // faces (indices starting at 1 not 0)
  for (i=0, nF=_be.n_faces(); i<nF; ++i)
  {

    if (useMatrial &&  _opt.check(Options::FaceColor) ){
      int i;
      //color with alpha
      if ( _opt.color_has_alpha() ){
        cA  = color_cast<OpenMesh::Vec4f> (_be.colorA( FaceHandle(i) ));
        i = getMaterial(cA);
      }else{
      //and without alpha
        c  = color_cast<OpenMesh::Vec3f> (_be.color( FaceHandle(i) ));
        i = getMaterial(c);
      }

      if(lastMat != i)
        _out << "usemtl mat" << i << std::endl;
    }

    _out << "f";

    _be.get_vhandles(FaceHandle(i), vhandles);

    for (j=0; j< vhandles.size(); ++j)
    {
      idx = vhandles[j].idx() + 1;
      _out << " " << idx;

      if (_opt.check(Options::VertexTexCoord))
        _out << "/" << idx;

      if ( _opt.check(Options::VertexNormal) )
        _out << "/" << idx;
    }

    _out << std::endl;
  }

  material_.clear();
  materialA_.clear();

  return true;
}

//=============================================================================
} // namespace IO
} // namespace OpenMesh
//=============================================================================
<commit_msg>Fixed obj writer working on wrong material blocks, double definition of variable<commit_after>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *        Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen         *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *                                                                           *
 *                                License                                    *
 *                                                                           *
 *  This library is free software; you can redistribute it and/or modify it  *
 *  under the terms of the GNU Lesser General Public License as published    *
 *  by the Free Software Foundation, version 2.1.                            *
 *                                                                           *
 *  This library is distributed in the hope that it will be useful, but      *
 *  WITHOUT ANY WARRANTY; without even the implied warranty of               *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
 *  Lesser General Public License for more details.                          *
 *                                                                           *
 *  You should have received a copy of the GNU Lesser General Public         *
 *  License along with this library; if not, write to the Free Software      *
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                *
 *                                                                           *
\*===========================================================================*/

//== INCLUDES =================================================================

//STL
#include <fstream>

// OpenMesh
#include <OpenMesh/Core/System/config.h>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/writer/OBJWriter.hh>
#include <OpenMesh/Core/IO/IOManager.hh>
#include <OpenMesh/Core/System/omstream.hh>
#include <OpenMesh/Core/Utils/color_cast.hh>

//=== NAMESPACES ==============================================================

namespace OpenMesh {
namespace IO {

//=== INSTANCIATE =============================================================

// register the OBJLoader singleton with MeshLoader
_OBJWriter_  __OBJWriterinstance;
_OBJWriter_& OBJWriter() { return __OBJWriterinstance; }

//=== IMPLEMENTATION ==========================================================

_OBJWriter_::_OBJWriter_() { IOManager().register_module(this); }

//-----------------------------------------------------------------------------

bool
_OBJWriter_::
write(const std::string& _filename, BaseExporter& _be, Options _opt) const
{
  std::fstream out(_filename.c_str(), std::ios_base::out );

  if (!out)
  {
    omerr() << "[OBJWriter] : cannot open file "
	  << _filename << std::endl;
    return false;
  }

  {
#if defined(WIN32)
    std::string::size_type dot = _filename.find_last_of("\\/");
#else
    std::string::size_type dot = _filename.rfind("/");
#endif

    if (dot == std::string::npos){
      path_ = "./";
      objName_ = _filename;
    }else{
      path_ = _filename.substr(0,dot+1);
      objName_ = _filename.substr(dot+1);
    }

    //remove the file extension
    dot = _filename.find_last_of(".");

    if(dot != std::string::npos)
      objName_ = objName_.substr(0,dot-1);
  }

  bool result = write(out, _be, _opt);

  out.close();
  return result;
}

//-----------------------------------------------------------------------------

int _OBJWriter_::getMaterial(OpenMesh::Vec3f _color) const
{
  for (uint i=0; i < material_.size(); i++)
    if(material_[i] == _color)
      return i;

  //not found add new material
  material_.push_back( _color );
  return material_.size()-1;
}

//-----------------------------------------------------------------------------

int _OBJWriter_::getMaterial(OpenMesh::Vec4f _color) const
{
  for (uint i=0; i < materialA_.size(); i++)
    if(materialA_[i] == _color)
      return i;

  //not found add new material
  materialA_.push_back( _color );
  return materialA_.size()-1;
}

//-----------------------------------------------------------------------------

bool
_OBJWriter_::
writeMaterial(std::fstream& _out, BaseExporter& _be, Options _opt) const
{
  OpenMesh::Vec3f c;
  OpenMesh::Vec4f cA;

  material_.clear();
  materialA_.clear();

  //iterate over faces
  for (int i=0, nF=_be.n_faces(); i<nF; ++i)
  {
    //color with alpha
    if ( _opt.color_has_alpha() ){
      cA  = color_cast<OpenMesh::Vec4f> (_be.colorA( FaceHandle(i) ));
      getMaterial(cA);
    }else{
    //and without alpha
      c  = color_cast<OpenMesh::Vec3f> (_be.color( FaceHandle(i) ));
      getMaterial(c);
    }
  }

  //write the materials
  if ( _opt.color_has_alpha() )
    for (uint i=0; i < materialA_.size(); i++){
      _out << "newmtl " << "mat" << i << std::endl;
      _out << "Ka 0.5000 0.5000 0.5000" << std::endl;
      _out << "Kd " << materialA_[i][0] << materialA_[i][1] << materialA_[i][2] << std::endl;;
      _out << "Tr " << materialA_[i][3] << std::endl;
      _out << "illum 1" << std::endl;
    }
  else
    for (uint i=0; i < material_.size(); i++){
      _out << "newmtl " << "mat" << i << std::endl;
      _out << "Ka 0.5000 0.5000 0.5000" << std::endl;
      _out << "Kd " << material_[i][0] << material_[i][1] << material_[i][2] << std::endl;;
      _out << "illum 1" << std::endl;
    }

  return true;
}

//-----------------------------------------------------------------------------

bool
_OBJWriter_::
write(std::fstream& _out, BaseExporter& _be, Options _opt) const
{
  unsigned int i, j, nV, nF, idx;
  Vec3f v, n;
  Vec2f t;
  VertexHandle vh;
  std::vector<VertexHandle> vhandles;
  bool useMatrial = false;
  OpenMesh::Vec3f c;
  OpenMesh::Vec4f cA;

  omlog() << "[OBJWriter] : write file\n";

  // check exporter features
  if (!check( _be, _opt))
     return false;

  // check writer features
  if ( _opt.check(Options::Binary)     || // not supported by format
       _opt.check(Options::FaceNormal) ||
       _opt.check(Options::FaceColor))
     return false;

  //create material file if needed
  if ( _opt.check(Options::FaceColor) ){

    std::string matFile = path_ + objName_ + ".mat";

    std::fstream matStream(matFile.c_str(), std::ios_base::out );

    if (!_out)
    {
      omerr() << "[OBJWriter] : cannot write material file " << matFile << std::endl;

    }else{
      useMatrial = writeMaterial(matStream, _be, _opt);

      matStream.close();
    }
  }

  // header
  _out << "# " << _be.n_vertices() << " vertices, ";
  _out << _be.n_faces() << " faces" << std::endl;

  // material file
  if (useMatrial &&  _opt.check(Options::FaceColor) )
    _out << "mtllib " << objName_ << ".mat" << std::endl;

  // vertex data (point, normals, texcoords)
  for (i=0, nV=_be.n_vertices(); i<nV; ++i)
  {
    vh = VertexHandle(i);
    v  = _be.point(vh);
    n  = _be.normal(vh);
    t  = _be.texcoord(vh);

    _out << "v " << v[0] <<" "<< v[1] <<" "<< v[2] << std::endl;

    if (_opt.check(Options::VertexNormal))
      _out << "n " << n[0] <<" "<< n[1] <<" "<< n[2] << std::endl;

    if (_opt.check(Options::VertexTexCoord))
      _out << "vt " << t[0] <<" "<< t[1] << std::endl;
  }

  int lastMat = -1;

  // faces (indices starting at 1 not 0)
  for (i=0, nF=_be.n_faces(); i<nF; ++i)
  {

    if (useMatrial &&  _opt.check(Options::FaceColor) ){
      int material = -1;

      //color with alpha
      if ( _opt.color_has_alpha() ){
        cA  = color_cast<OpenMesh::Vec4f> (_be.colorA( FaceHandle(i) ));
        material = getMaterial(cA);
      } else{
      //and without alpha
        c  = color_cast<OpenMesh::Vec3f> (_be.color( FaceHandle(i) ));
        material = getMaterial(c);
      }

      if(lastMat != material) {
        _out << "usemtl mat" << material << std::endl;
	lastMat = material;
      }
    }

    _out << "f";

    _be.get_vhandles(FaceHandle(i), vhandles);

    for (j=0; j< vhandles.size(); ++j)
    {
      idx = vhandles[j].idx() + 1;
      _out << " " << idx;

      if (_opt.check(Options::VertexTexCoord))
        _out << "/" << idx;

      if ( _opt.check(Options::VertexNormal) )
        _out << "/" << idx;
    }

    _out << std::endl;
  }

  material_.clear();
  materialA_.clear();

  return true;
}

//=============================================================================
} // namespace IO
} // namespace OpenMesh
//=============================================================================
<|endoftext|>


<commit_before>#include "RN_Class.h"

// Static members should be initialize as:
// and static function?

boost::random::mt19937 randomNb::rng;

randomNb::randomNb(){
	randomNb::rng.seed(time(NULL));
}

double randomNb::sampleCauchy(double c){
	cauchy_distribution <> nd(c, 1);
	return nd(randomNb::rng);
}

double randomNb::sampleChiSqr(int c){
	chi_squared_distribution <> nd(c);
	return nd(randomNb::rng);
}

double randomNb::sampleUniform(double c){
	uniform_real_distribution <> nd(0, 1);
  return nd(randomNb::rng);
}

double randomNb::varCovRg(double c){
	if (c == 0){
		return randomNb::sampleCauchy(c);
	}
	else{
		return randomNb::sampleChiSqr(c);
	}
}

double multivariateNormal_density(const MatrixXd &x,
	const MatrixXd &Mu, const MatrixXd &Sigma){
	double expTerm, o;
	using namespace std;
	MatrixXd err;
	if ( x.cols() != 1)
		cerr << "X must be a column vector" << endl;
	if ( Mu.cols() != 1)
		cerr << "Mu must be a column vector" << endl;
	err = x - Mu;
	expTerm = exp((err.transpose()*Sigma.inverse()*err)(0,0));
	o = 1/sqrt(pow(2*M_PI, Mu.rows())*Sigma.determinant());
	return o*expTerm;
}
<commit_msg>Multivariate normal function only accepts row matrices<commit_after>#include "RN_Class.h"

// Static members should be initialize as:
// and static function?

boost::random::mt19937 randomNb::rng;

randomNb::randomNb(){
	randomNb::rng.seed(time(NULL));
}

double randomNb::sampleCauchy(double c){
	cauchy_distribution <> nd(c, 1);
	return nd(randomNb::rng);
}

double randomNb::sampleChiSqr(int c){
	chi_squared_distribution <> nd(c);
	return nd(randomNb::rng);
}

double randomNb::sampleUniform(double c){
	uniform_real_distribution <> nd(0, 1);
  return nd(randomNb::rng);
}

double randomNb::varCovRg(double c){
	if (c == 0){
		return randomNb::sampleCauchy(c);
	}
	else{
		return randomNb::sampleChiSqr(c);
	}
}

double multivariateNormal_density(const MatrixXd &x,
	const MatrixXd &Mu, const MatrixXd &Sigma){
	double expTerm, o;
	using namespace std;
	MatrixXd err;
	if ( x.rows() != 1)
		cerr << "X must be a row vector" << endl;
	if ( Mu.rows() != 1)
		cerr << "Mu must be a row vector" << endl;
	err = x - Mu;
	expTerm = exp((err*Sigma.inverse()*err.transpose())(0,0));
	o = 1/sqrt(pow(2*M_PI, Mu.rows())*Sigma.determinant());
	return o*expTerm;
}
<|endoftext|>


<commit_before>#include "qmljslink.h"

#include "parser/qmljsast_p.h"
#include "qmljsdocument.h"
#include "qmljsbind.h"

#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QDebug>

using namespace QmlJS;
using namespace QmlJS::Interpreter;
using namespace QmlJS::AST;

static QString componentName(const QString &fileName)
{
    QString componentName = fileName;
    int dotIndex = componentName.indexOf(QLatin1Char('.'));
    if (dotIndex != -1)
        componentName.truncate(dotIndex);
    componentName[0] = componentName[0].toUpper();
    return componentName;
}

void LinkImports::linkImports(Bind *bind, const QList<Bind *> &binds)
{
    // ### TODO: remove all properties from _typeEnv

    Document::Ptr doc = bind->_doc;
    if (! (doc->qmlProgram() && doc->qmlProgram()->imports))
        return;

    QFileInfo fileInfo(doc->fileName());
    const QString absolutePath = fileInfo.absolutePath();

    // implicit imports
    foreach (Bind *otherBind, binds) {
        if (otherBind == bind)
            continue;

        Document::Ptr otherDoc = otherBind->_doc;
        QFileInfo otherFileInfo(otherDoc->fileName());
        const QString otherAbsolutePath = otherFileInfo.absolutePath();

        if (otherAbsolutePath.size() < absolutePath.size()
            || otherAbsolutePath.left(absolutePath.size()) != absolutePath)
            continue;

        // ### TODO: implicit directory access not implemented
        if (otherAbsolutePath != absolutePath)
            continue;

        bind->_typeEnvironment->setProperty(componentName(otherFileInfo.fileName()), otherBind->_rootObjectValue);
    }

    // explicit imports, whether directories or files
    for (UiImportList *it = doc->qmlProgram()->imports; it; it = it->next) {
        if (! (it->import && it->import->fileName))
            continue;

        QString path = absolutePath;
        path += QLatin1Char('/');
        path += it->import->fileName->asString();
        path = QDir::cleanPath(path);

        foreach (Bind *otherBind, binds) {
            Document::Ptr otherDoc = otherBind->_doc;
            QFileInfo otherFileInfo(otherDoc->fileName());
            const QString otherAbsolutePath = otherFileInfo.absolutePath();

            if (path != otherDoc->fileName() && path != otherAbsolutePath)
                continue;

            bool directoryImport = (path == otherAbsolutePath);
            bool fileImport = (path == otherDoc->fileName());
            if (!directoryImport && !fileImport)
                continue;

            ObjectValue *importInto = bind->_typeEnvironment;
            if (directoryImport && it->import->importId) {
                // ### TODO: set importInto to a namespace object value
            }

            QString targetName;
            if (fileImport && it->import->importId) {
                targetName = it->import->importId->asString();
            } else {
                targetName = componentName(otherFileInfo.fileName());
            }

            importInto->setProperty(targetName, otherBind->_rootObjectValue);
        }
    }
}

static const ObjectValue *lookupType(ObjectValue *env, UiQualifiedId *id)
{
    const ObjectValue *objectValue = env;

    for (UiQualifiedId *iter = id; objectValue && iter; iter = iter->next) {
        if (! iter->name)
            return 0;

        const Value *value = objectValue->property(iter->name->asString());
        if (!value)
            return 0;

        objectValue = value->asObjectValue();
    }

    return objectValue;
}

void LinkImports::operator()(const QList<Bind *> &binds)
{
    foreach (Bind *bind, binds) {
        // Populate the _typeEnvironment with imports.
        linkImports(bind, binds);

        // Set the prototypes.
        {
            QHash<UiObjectDefinition *, ObjectValue *>::iterator it = bind->_qmlObjectDefinitions.begin();
            QHash<UiObjectDefinition *, ObjectValue *>::iterator end = bind->_qmlObjectDefinitions.end();
            for (; it != end; ++it) {
                UiObjectDefinition *key = it.key();
                ObjectValue *value = it.value();
                if (!key->qualifiedTypeNameId)
                    continue;

                value->setPrototype(lookupType(bind->_typeEnvironment, key->qualifiedTypeNameId));
            }
        }
        {
            QHash<UiObjectBinding *, ObjectValue *>::iterator it = bind->_qmlObjectBindings.begin();
            QHash<UiObjectBinding *, ObjectValue *>::iterator end = bind->_qmlObjectBindings.end();
            for (; it != end; ++it) {
                UiObjectBinding *key = it.key();
                ObjectValue *value = it.value();
                if (!key->qualifiedTypeNameId)
                    continue;

                value->setPrototype(lookupType(bind->_typeEnvironment, key->qualifiedTypeNameId));
            }
        }
    }
}

ObjectValue *Link::operator()(const QList<Bind *> &binds, Bind *currentBind, UiObjectMember *currentObject)
{
    ObjectValue *scopeObject;
    if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(currentObject))
        scopeObject = currentBind->_qmlObjectDefinitions.value(definition);
    else if (UiObjectBinding *binding = cast<UiObjectBinding *>(currentObject))
        scopeObject = currentBind->_qmlObjectBindings.value(binding);
    else
        return 0;

    if (!scopeObject)
        return 0;

    // Build the scope chain.
    currentBind->_typeEnvironment->setScope(currentBind->_idEnvironment);
    currentBind->_idEnvironment->setScope(currentBind->_functionEnvironment);
    currentBind->_functionEnvironment->setScope(scopeObject);
    if (scopeObject != currentBind->_rootObjectValue) {
        scopeObject->setScope(currentBind->_rootObjectValue);
        currentBind->_rootObjectValue->setScope(currentBind->_interp->globalObject());
    } else {
        scopeObject->setScope(currentBind->_interp->globalObject());
    }
    // May want to link to instantiating components from here.

    return currentBind->_typeEnvironment;
}
<commit_msg>Always return a valid scope from Link.<commit_after>#include "qmljslink.h"

#include "parser/qmljsast_p.h"
#include "qmljsdocument.h"
#include "qmljsbind.h"

#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QDebug>

using namespace QmlJS;
using namespace QmlJS::Interpreter;
using namespace QmlJS::AST;

static QString componentName(const QString &fileName)
{
    QString componentName = fileName;
    int dotIndex = componentName.indexOf(QLatin1Char('.'));
    if (dotIndex != -1)
        componentName.truncate(dotIndex);
    componentName[0] = componentName[0].toUpper();
    return componentName;
}

void LinkImports::linkImports(Bind *bind, const QList<Bind *> &binds)
{
    // ### TODO: remove all properties from _typeEnv

    Document::Ptr doc = bind->_doc;
    if (! (doc->qmlProgram() && doc->qmlProgram()->imports))
        return;

    QFileInfo fileInfo(doc->fileName());
    const QString absolutePath = fileInfo.absolutePath();

    // implicit imports
    foreach (Bind *otherBind, binds) {
        if (otherBind == bind)
            continue;

        Document::Ptr otherDoc = otherBind->_doc;
        QFileInfo otherFileInfo(otherDoc->fileName());
        const QString otherAbsolutePath = otherFileInfo.absolutePath();

        if (otherAbsolutePath.size() < absolutePath.size()
            || otherAbsolutePath.left(absolutePath.size()) != absolutePath)
            continue;

        // ### TODO: implicit directory access not implemented
        if (otherAbsolutePath != absolutePath)
            continue;

        bind->_typeEnvironment->setProperty(componentName(otherFileInfo.fileName()), otherBind->_rootObjectValue);
    }

    // explicit imports, whether directories or files
    for (UiImportList *it = doc->qmlProgram()->imports; it; it = it->next) {
        if (! (it->import && it->import->fileName))
            continue;

        QString path = absolutePath;
        path += QLatin1Char('/');
        path += it->import->fileName->asString();
        path = QDir::cleanPath(path);

        foreach (Bind *otherBind, binds) {
            Document::Ptr otherDoc = otherBind->_doc;
            QFileInfo otherFileInfo(otherDoc->fileName());
            const QString otherAbsolutePath = otherFileInfo.absolutePath();

            if (path != otherDoc->fileName() && path != otherAbsolutePath)
                continue;

            bool directoryImport = (path == otherAbsolutePath);
            bool fileImport = (path == otherDoc->fileName());
            if (!directoryImport && !fileImport)
                continue;

            ObjectValue *importInto = bind->_typeEnvironment;
            if (directoryImport && it->import->importId) {
                // ### TODO: set importInto to a namespace object value
            }

            QString targetName;
            if (fileImport && it->import->importId) {
                targetName = it->import->importId->asString();
            } else {
                targetName = componentName(otherFileInfo.fileName());
            }

            importInto->setProperty(targetName, otherBind->_rootObjectValue);
        }
    }
}

static const ObjectValue *lookupType(ObjectValue *env, UiQualifiedId *id)
{
    const ObjectValue *objectValue = env;

    for (UiQualifiedId *iter = id; objectValue && iter; iter = iter->next) {
        if (! iter->name)
            return 0;

        const Value *value = objectValue->property(iter->name->asString());
        if (!value)
            return 0;

        objectValue = value->asObjectValue();
    }

    return objectValue;
}

void LinkImports::operator()(const QList<Bind *> &binds)
{
    foreach (Bind *bind, binds) {
        // Populate the _typeEnvironment with imports.
        linkImports(bind, binds);

        // Set the prototypes.
        {
            QHash<UiObjectDefinition *, ObjectValue *>::iterator it = bind->_qmlObjectDefinitions.begin();
            QHash<UiObjectDefinition *, ObjectValue *>::iterator end = bind->_qmlObjectDefinitions.end();
            for (; it != end; ++it) {
                UiObjectDefinition *key = it.key();
                ObjectValue *value = it.value();
                if (!key->qualifiedTypeNameId)
                    continue;

                value->setPrototype(lookupType(bind->_typeEnvironment, key->qualifiedTypeNameId));
            }
        }
        {
            QHash<UiObjectBinding *, ObjectValue *>::iterator it = bind->_qmlObjectBindings.begin();
            QHash<UiObjectBinding *, ObjectValue *>::iterator end = bind->_qmlObjectBindings.end();
            for (; it != end; ++it) {
                UiObjectBinding *key = it.key();
                ObjectValue *value = it.value();
                if (!key->qualifiedTypeNameId)
                    continue;

                value->setPrototype(lookupType(bind->_typeEnvironment, key->qualifiedTypeNameId));
            }
        }
    }
}

ObjectValue *Link::operator()(const QList<Bind *> &binds, Bind *currentBind, UiObjectMember *currentObject)
{
    ObjectValue *scopeObject;
    if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(currentObject))
        scopeObject = currentBind->_qmlObjectDefinitions.value(definition);
    else if (UiObjectBinding *binding = cast<UiObjectBinding *>(currentObject))
        scopeObject = currentBind->_qmlObjectBindings.value(binding);
    else
        return currentBind->_interp->globalObject();

    if (!scopeObject)
        return currentBind->_interp->globalObject();

    // Build the scope chain.
    currentBind->_typeEnvironment->setScope(currentBind->_idEnvironment);
    currentBind->_idEnvironment->setScope(currentBind->_functionEnvironment);
    currentBind->_functionEnvironment->setScope(scopeObject);
    if (scopeObject != currentBind->_rootObjectValue) {
        scopeObject->setScope(currentBind->_rootObjectValue);
        currentBind->_rootObjectValue->setScope(currentBind->_interp->globalObject());
    } else {
        scopeObject->setScope(currentBind->_interp->globalObject());
    }
    // May want to link to instantiating components from here.

    return currentBind->_typeEnvironment;
}
<|endoftext|>


<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include "util.h"

#include <GL/glew.h>

#ifdef _WIN32
#include <Windows.h>
#endif

#include <stdio.h>
#include <stdarg.h>

namespace gl = virvo::gl;

#ifndef APIENTRY
#define APIENTRY
#endif

#ifndef NDEBUG

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#if defined(GL_KHR_debug)
static char const* GetDebugTypeString(GLenum type)
{
    switch (type)
    {
    case GL_DEBUG_TYPE_ERROR:
        return "error";
    case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
        return "deprecated behavior detected";
    case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
        return "undefined behavior detected";
    case GL_DEBUG_TYPE_PORTABILITY:
        return "portablility warning";
    case GL_DEBUG_TYPE_PERFORMANCE:
        return "performance warning";
    case GL_DEBUG_TYPE_OTHER:
        return "other";
    case GL_DEBUG_TYPE_MARKER:
        return "marker";
    }

    return "{unknown type}";
}
#endif

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#ifdef _WIN32
static void OutputDebugStringAF(char const* format, ...)
{
    char text[1024] = {0};

    va_list args;
    va_start(args, format);

    _vsnprintf_s(text, _TRUNCATE, format, args);

    va_end(args);

    OutputDebugStringA(text);
}
#endif

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#if defined(GL_KHR_debug)
static void APIENTRY DebugCallback( GLenum /*source*/,
                                    GLenum type,
                                    GLuint /*id*/,
                                    GLenum /*severity*/,
                                    GLsizei /*length*/,
                                    const GLchar* message,
                                    GLvoid* /*userParam*/
                                    )
{
    if (type != GL_DEBUG_TYPE_ERROR)
        return;

#ifdef _WIN32
    if (IsDebuggerPresent())
    {
        OutputDebugStringAF("GL %s: %s\n", GetDebugTypeString(type), message);
        DebugBreak();
    }
#endif

    fprintf(stderr, "GL %s: %s\n", GetDebugTypeString(type), message);
}
#endif

#endif // !NDEBUG

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::enableDebugCallback()
{
#if !defined(NDEBUG) && defined(GL_KHR_debug)
    if (GLEW_KHR_debug)
    {
        glEnable(GL_DEBUG_OUTPUT);
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);

        glDebugMessageCallback(DebugCallback, 0);
    }
#endif // !NDEBUG
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
GLenum gl::getError(char const* file, int line)
{
    GLenum err = glGetError();

    if (err != GL_NO_ERROR)
        fprintf(stderr, "%s(%d) : GL error: %s\n", file, line, gluErrorString(err));

    return err;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
static char const* GetFramebufferStatusString(GLenum status)
{
    switch (status)
    {
    case GL_FRAMEBUFFER_COMPLETE:
        return "framebuffer complete";
    case GL_FRAMEBUFFER_UNDEFINED:
        return "framebuffer undefined";
    case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
        return "framebuffer incomplete attachment";
    case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
        return "framebuffer incomplete missing attachment";
    case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
        return "framebuffer incomplete draw buffer";
    case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
        return "framebuffer incomplete read buffer";
    case GL_FRAMEBUFFER_UNSUPPORTED:
        return "framebuffer unsupported";
    case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
        return "framebuffer incomplete multisample";
#ifdef GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS
    case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
        return "framebuffer incomplete layer targets";
#endif
    default:
        return "{unknown status}";
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
GLenum gl::getFramebufferStatus(GLenum target, char const* file, int line)
{
    GLenum status = glCheckFramebufferStatus(target);

    if (status != GL_FRAMEBUFFER_COMPLETE)
        fprintf(stderr, "%s(%d) : GL framebuffer error: %s\n", file, line, GetFramebufferStatusString(status));

    return status;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
static void DrawFullScreenQuad()
{
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);
    glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);
    glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f,  1.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f,  1.0f);
    glEnd();

    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendTexture(GLuint texture, GLenum sfactor, GLenum dfactor)
{
    glPushAttrib(GL_ALL_ATTRIB_BITS);

    glActiveTexture(GL_TEXTURE0);

    glEnable(GL_BLEND);
    glBlendFunc(sfactor, dfactor);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);

    glDepthMask(GL_FALSE);

    DrawFullScreenQuad();

    glPopAttrib();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendTexture(GLuint texture)
{
    blendTexture(texture, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels, GLenum sfactor, GLenum dfactor)
{
    glPushAttrib(GL_COLOR_BUFFER_BIT);

    GLint viewport[4];

    glGetIntegerv(GL_VIEWPORT, &viewport[0]);

    glWindowPos2i(viewport[0], viewport[1]);

    GLfloat scaleX = static_cast<GLfloat>(viewport[2]) / srcW;
    GLfloat scaleY = static_cast<GLfloat>(viewport[3]) / srcH;

    glPixelZoom(scaleX, scaleY);

    glEnable(GL_BLEND);
    glBlendFunc(sfactor, dfactor);

    glDrawPixels(srcW, srcH, format, type, pixels);

    glPopAttrib();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels)
{
    blendPixels(srcW, srcH, format, type, pixels, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::renderInterlacedStereoStencilBuffer(bool lines)
{
    static const GLubyte kPatternLines[32*(32/8)] = {
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
    };

    static const GLubyte kPatternCheckerBoard[32*(32/8)] = {
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
    };

    glPushAttrib(GL_ALL_ATTRIB_BITS);
    glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);

    glDisable(GL_DEPTH_TEST);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_LIGHTING);

    glColorMask(0, 0, 0, 0);
    glDepthMask(0);

    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glEnable(GL_POLYGON_STIPPLE);
    if (lines)
        glPolygonStipple(kPatternLines);
    else
        glPolygonStipple(kPatternCheckerBoard);

    glEnable(GL_STENCIL_TEST);
    glStencilMask(0xFFFFFFFF);
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
    glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);

    DrawFullScreenQuad();

    glPopAttrib();
    glPopClientAttrib();
}
<commit_msg>mingw compile fix<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include "util.h"

#include <GL/glew.h>

#ifdef _WIN32
#include <Windows.h>
#endif

#include <stdio.h>
#include <stdarg.h>

namespace gl = virvo::gl;

#ifndef APIENTRY
#define APIENTRY
#endif

#ifndef NDEBUG

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#if defined(GL_KHR_debug)
static char const* GetDebugTypeString(GLenum type)
{
    switch (type)
    {
    case GL_DEBUG_TYPE_ERROR:
        return "error";
    case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
        return "deprecated behavior detected";
    case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
        return "undefined behavior detected";
    case GL_DEBUG_TYPE_PORTABILITY:
        return "portablility warning";
    case GL_DEBUG_TYPE_PERFORMANCE:
        return "performance warning";
    case GL_DEBUG_TYPE_OTHER:
        return "other";
    case GL_DEBUG_TYPE_MARKER:
        return "marker";
    }

    return "{unknown type}";
}
#endif

#if defined(GL_KHR_debug)
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#ifdef _WIN32
static void OutputDebugStringAF(char const* format, ...)
{
    char text[1024] = {0};

    va_list args;
    va_start(args, format);

    _vsnprintf_s(text, _TRUNCATE, format, args);

    va_end(args);

    OutputDebugStringA(text);
}
#endif

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
static void APIENTRY DebugCallback( GLenum /*source*/,
                                    GLenum type,
                                    GLuint /*id*/,
                                    GLenum /*severity*/,
                                    GLsizei /*length*/,
                                    const GLchar* message,
                                    GLvoid* /*userParam*/
                                    )
{
    if (type != GL_DEBUG_TYPE_ERROR)
        return;

#ifdef _WIN32
    if (IsDebuggerPresent())
    {
        OutputDebugStringAF("GL %s: %s\n", GetDebugTypeString(type), message);
        DebugBreak();
    }
#endif

    fprintf(stderr, "GL %s: %s\n", GetDebugTypeString(type), message);
}
#endif

#endif // !NDEBUG

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::enableDebugCallback()
{
#if !defined(NDEBUG) && defined(GL_KHR_debug)
    if (GLEW_KHR_debug)
    {
        glEnable(GL_DEBUG_OUTPUT);
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);

        glDebugMessageCallback(DebugCallback, 0);
    }
#endif // !NDEBUG
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
GLenum gl::getError(char const* file, int line)
{
    GLenum err = glGetError();

    if (err != GL_NO_ERROR)
        fprintf(stderr, "%s(%d) : GL error: %s\n", file, line, gluErrorString(err));

    return err;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
static char const* GetFramebufferStatusString(GLenum status)
{
    switch (status)
    {
    case GL_FRAMEBUFFER_COMPLETE:
        return "framebuffer complete";
    case GL_FRAMEBUFFER_UNDEFINED:
        return "framebuffer undefined";
    case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
        return "framebuffer incomplete attachment";
    case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
        return "framebuffer incomplete missing attachment";
    case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
        return "framebuffer incomplete draw buffer";
    case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
        return "framebuffer incomplete read buffer";
    case GL_FRAMEBUFFER_UNSUPPORTED:
        return "framebuffer unsupported";
    case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
        return "framebuffer incomplete multisample";
#ifdef GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS
    case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
        return "framebuffer incomplete layer targets";
#endif
    default:
        return "{unknown status}";
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
GLenum gl::getFramebufferStatus(GLenum target, char const* file, int line)
{
    GLenum status = glCheckFramebufferStatus(target);

    if (status != GL_FRAMEBUFFER_COMPLETE)
        fprintf(stderr, "%s(%d) : GL framebuffer error: %s\n", file, line, GetFramebufferStatusString(status));

    return status;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
static void DrawFullScreenQuad()
{
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);
    glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);
    glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f,  1.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f,  1.0f);
    glEnd();

    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendTexture(GLuint texture, GLenum sfactor, GLenum dfactor)
{
    glPushAttrib(GL_ALL_ATTRIB_BITS);

    glActiveTexture(GL_TEXTURE0);

    glEnable(GL_BLEND);
    glBlendFunc(sfactor, dfactor);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);

    glDepthMask(GL_FALSE);

    DrawFullScreenQuad();

    glPopAttrib();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendTexture(GLuint texture)
{
    blendTexture(texture, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels, GLenum sfactor, GLenum dfactor)
{
    glPushAttrib(GL_COLOR_BUFFER_BIT);

    GLint viewport[4];

    glGetIntegerv(GL_VIEWPORT, &viewport[0]);

    glWindowPos2i(viewport[0], viewport[1]);

    GLfloat scaleX = static_cast<GLfloat>(viewport[2]) / srcW;
    GLfloat scaleY = static_cast<GLfloat>(viewport[3]) / srcH;

    glPixelZoom(scaleX, scaleY);

    glEnable(GL_BLEND);
    glBlendFunc(sfactor, dfactor);

    glDrawPixels(srcW, srcH, format, type, pixels);

    glPopAttrib();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels)
{
    blendPixels(srcW, srcH, format, type, pixels, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::renderInterlacedStereoStencilBuffer(bool lines)
{
    static const GLubyte kPatternLines[32*(32/8)] = {
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
    };

    static const GLubyte kPatternCheckerBoard[32*(32/8)] = {
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
    };

    glPushAttrib(GL_ALL_ATTRIB_BITS);
    glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);

    glDisable(GL_DEPTH_TEST);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_LIGHTING);

    glColorMask(0, 0, 0, 0);
    glDepthMask(0);

    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glEnable(GL_POLYGON_STIPPLE);
    if (lines)
        glPolygonStipple(kPatternLines);
    else
        glPolygonStipple(kPatternCheckerBoard);

    glEnable(GL_STENCIL_TEST);
    glStencilMask(0xFFFFFFFF);
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
    glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);

    DrawFullScreenQuad();

    glPopAttrib();
    glPopClientAttrib();
}
<|endoftext|>


<commit_before>/*
 * G-Code command interpreter
 *
 * This does not attempt to be a complete or even correct G-Code interpreter.
 * It implements G-Code only as needed to support the pano functionality, without
 * ruling out future additions.
 *
 * Codes reference: https://www.tormach.com/machine_codes_gcodes.html
 *
 * Copyright (C)2017 Laurentiu Badea
 *
 * This file may be redistributed under the terms of the MIT license.
 * A copy of this license has been included with this distribution in the file LICENSE.
 */
#include "gcode.h"

#define d(x) serial.print(x)

/*
 * Parse and execute a G-code command
 * Example program line
 * G1 G91 A5.3 C-0.5 (rotation by 5.3° horiz and -0.5° vert)
 */
void GCode::execute(char buffer[], const char* eob){
    /*
     * Parse the command line
     */
    // reset the parameters
    cmd.target.a = 0;
    cmd.target.c = 0;
    cmd.p = 0;
    cmd.lineno = 0;
    cmd.nonmodal = NONE;

    while (buffer < eob){
        char* next = buffer;
        float value;
        char letter = toupper(*buffer++);
        if (letter == ' ') continue;
        value = strtod(buffer, &next);

        switch (letter){
        case 'N': cmd.lineno = int(value); continue;
        case ';':
        case '%': break;
        case 'O': break; // program name

        case 'G':
            switch (int(value)){
            case 0: cmd.motion = Motion::G0; break; // rapid move
            case 1: cmd.motion = Motion::G1; break; // linear interpolation move
            case 4: cmd.nonmodal |= NonModal::G4; break; // dwell
            case 28: cmd.nonmodal |= NonModal::G28; break; // go to origin
            case 80: cmd.motion = NO_MOTION; break; // cancel modal mode
            case 90: cmd.coords = Coords::ABSOLUTE; break;
            case 91: cmd.coords = Coords::RELATIVE; break;
            case 92: cmd.nonmodal |= (value == 92.1) ? NonModal::G92_1 : NonModal::G92; break;
            };
            break;

        case 'M':
            switch (int(value)){
            case 0: cmd.wait = Wait::M0; break; // pause, wait for user
            case 1: cmd.wait = Wait::M1; break; // stop if button pressed
            case 2: cmd.wait = Wait::M2; break; // end program
            case 114: cmd.nonmodal |= NonModal::M114; break; // get current position
            case 115: cmd.nonmodal |= NonModal::M115; break; // get firmware version and capabilities
            case 116: cmd.nonmodal |= NonModal::M116; break; // zero-motion wait
            case 117: cmd.nonmodal |= NonModal::M117; break; // get origin position
            case 240: cmd.nonmodal |= NonModal::M240; break; // shutter
            case 320: cmd.speed = Speed::ACCEL; break;
            case 321: cmd.speed = Speed::CONSTANT; break;
            case 503: cmd.nonmodal |= NonModal::M503; break; // get current settings

            case 17:
                motors.enable();
                // assume new origin since motors could have been moved
                cmd.origin.a = cmd.origin.c = 0;
                break;
            case 18:
                motors.disable();
                break;
            };
            break;

        /* Variables */
        case 'A': cmd.target.a = value; break;
        case 'C': cmd.target.c = value; break;
        case 'P': cmd.p = value; break;
        case 'Q': cmd.q = value; break;
        case 'R': cmd.r = value; break;
        case 'F': cmd.f = value; break;
        };
    }

    /*
     * Execute the command
     * order of execution table (just as reference, we do not actually need all of it)
     * https://www.tormach.com/order_execution_table.html
     */

    // messages
    if (cmd.nonmodal & NonModal::M114){
        // current position
        Serial.print("ok current A");Serial.print(cmd.current.a);
        Serial.print(" C");Serial.print(cmd.current.c);
        Serial.println();
    }
    if (cmd.nonmodal & NonModal::M115){
        // firmware version and capabilities
        Serial.println("ok PanoController 1.0");
        Serial.println("axis A360 C175");
        Serial.println("origin A0 C15");
    }
    if (cmd.nonmodal & NonModal::M117){
        // print origin
        Serial.print("ok origin A");Serial.print(cmd.origin.a);
        Serial.print(" C");Serial.print(cmd.origin.c);
        Serial.println();
    }
    if (cmd.nonmodal & NonModal::M503){
        // current settings
        Serial.println("ok");
    }

    // acceleration ("feed rate")
    if (cmd.speed == Speed::CONSTANT){
        // motors.setSpeedProfile(MultiDriver::CONSTANT_SPEED);
    } else {
        // motors.setSpeedProfile(MultiDriver::LINEAR_SPEED, accel, decel);
    }

    // Camera operations
    if (cmd.nonmodal & NonModal::M116){
        // Zero-Motion wait
        int start = millis();
        bool success = mpu.zeroMotionWait(100 * cmd.q, 1000 * cmd.p);
        d("ZM="); d(millis()-start);
        d((success) ? "\n" : " (failed)\n");
    }
    if (cmd.nonmodal & NonModal::M240){
        // Shutter
        d("SHUTTER="); d(cmd.p); d("\n");
        camera.shutter(1000 * cmd.p, bool(cmd.q));
        if (cmd.r > 0){
            delay(1000 * cmd.r);
        }
    }

    // dwell
    if (cmd.nonmodal & NonModal::G4){
        delay(1000 * cmd.p);
    }

    // units

    // distance mode

    // set offsets (origin)
    if (cmd.nonmodal & NonModal::G92_1){
        // reset origin
        cmd.origin.a = cmd.target.a = cmd.current.a = 0;
        cmd.origin.c = cmd.target.c = cmd.current.c = 0;
    }
    if (cmd.nonmodal & NonModal::G92){
        // origin moves so current coordinates match target
        cmd.origin.a -= cmd.target.a + cmd.current.a;
        cmd.origin.c -= cmd.target.c + cmd.current.c;
        cmd.current.a = cmd.target.a;
        cmd.current.c = cmd.target.c;
        cmd.target.a = 0;
        cmd.target.c = 0;
    }

    // motion

    if (cmd.nonmodal & NonModal::G28){
        // move to origin via another point (incremental)
        if (cmd.target.a != 0 || cmd.target.c != 0){
            move(cmd.motion, Coords::RELATIVE, cmd.current, cmd.target);
        }
        cmd.target.a = cmd.origin.a;
        cmd.target.c = cmd.origin.c;
        move(cmd.motion, Coords::ABSOLUTE, cmd.current, cmd.target);
        cmd.target.a = cmd.target.c = 0;
    }

    switch (cmd.motion){
    case Motion::G0:
    case Motion::G1:
        if (cmd.target.a != 0 || cmd.target.c != 0){
            move(cmd.motion, cmd.coords, cmd.current, cmd.target);
        }
    }

    // pause
    switch (cmd.wait){
    case Wait::M0:
        d("STOP\n");
        break;
    case Wait::M1:
        if (false){ // FIXME: replace w/ check button
            d("STOP\n");
        }
        break;
    case Wait::M2:
        d("END\n");
        break;
    }
}

void GCode::move(Motion motion, Coords coords, Position& current, Position& target){
    d("MOVE ");d(target.a);d(" ");d(target.c);d("\n");
    if (coords == Coords::RELATIVE){
        motors.rotate(target.a * horiz_gear_ratio, target.c * vert_gear_ratio);
        current.a += target.a;
        current.c += target.c;
    } else {
        motors.rotate((target.a - current.a) * horiz_gear_ratio,
                      (target.c - current.c) * vert_gear_ratio);
        current.a = target.a;
        current.c = target.c;
    };
    d("AT ");d(cmd.current.a);d(" ");d(cmd.current.c);d("\n");
}
<commit_msg>Updated data queries, removed some debugging<commit_after>/*
 * G-Code command interpreter
 *
 * This does not attempt to be a complete or even correct G-Code interpreter.
 * It implements G-Code only as needed to support the pano functionality, without
 * ruling out future additions.
 *
 * Codes reference: https://www.tormach.com/machine_codes_gcodes.html
 *
 * Copyright (C)2017 Laurentiu Badea
 *
 * This file may be redistributed under the terms of the MIT license.
 * A copy of this license has been included with this distribution in the file LICENSE.
 */
#include "gcode.h"

#define d(x) serial.print(x)

/*
 * Parse and execute a G-code command
 * Example program line
 * G1 G91 A5.3 C-0.5 (rotation by 5.3° horiz and -0.5° vert)
 */
void GCode::execute(char buffer[], const char* eob){
    /*
     * Parse the command line
     */
    // reset the parameters
    cmd.target.a = 0;
    cmd.target.c = 0;
    cmd.p = 0;
    cmd.lineno = 0;
    cmd.nonmodal = NONE;

    while (buffer < eob){
        char* next = buffer;
        float value;
        char letter = toupper(*buffer++);
        if (letter == ' ') continue;
        value = strtod(buffer, &next);

        switch (letter){
        case 'N': cmd.lineno = int(value); continue;
        case ';':
        case '%': break;
        case 'O': break; // program name

        case 'G':
            switch (int(value)){
            case 0: cmd.motion = Motion::G0; break; // rapid move
            case 1: cmd.motion = Motion::G1; break; // linear interpolation move
            case 4: cmd.nonmodal |= NonModal::G4; break; // dwell
            case 28: cmd.nonmodal |= NonModal::G28; break; // go to origin
            case 80: cmd.motion = NO_MOTION; break; // cancel modal mode
            case 90: cmd.coords = Coords::ABSOLUTE; break;
            case 91: cmd.coords = Coords::RELATIVE; break;
            case 92: cmd.nonmodal |= (value == 92.1) ? NonModal::G92_1 : NonModal::G92; break;
            };
            break;

        case 'M':
            switch (int(value)){
            case 0: cmd.wait = Wait::M0; break; // pause, wait for user
            case 1: cmd.wait = Wait::M1; break; // stop if button pressed
            case 2: cmd.wait = Wait::M2; break; // end program
            case 114: cmd.nonmodal |= NonModal::M114; break; // get current position
            case 115: cmd.nonmodal |= NonModal::M115; break; // get firmware version and capabilities
            case 116: cmd.nonmodal |= NonModal::M116; break; // zero-motion wait
            case 117: cmd.nonmodal |= NonModal::M117; break; // get origin position
            case 240: cmd.nonmodal |= NonModal::M240; break; // shutter
            case 320: cmd.speed = Speed::ACCEL; break;
            case 321: cmd.speed = Speed::CONSTANT; break;
            case 503: cmd.nonmodal |= NonModal::M503; break; // get current settings

            case 17:
                motors.enable();
                // assume new origin since motors could have been moved
                cmd.origin.a = cmd.origin.c = 0;
                break;
            case 18:
                motors.disable();
                break;
            };
            break;

        /* Variables */
        case 'A': cmd.target.a = value; break;
        case 'C': cmd.target.c = value; break;
        case 'P': cmd.p = value; break;
        case 'Q': cmd.q = value; break;
        case 'R': cmd.r = value; break;
        case 'F': cmd.f = value; break;
        };
    }

    /*
     * Execute the command
     * order of execution table (just as reference, we do not actually need all of it)
     * https://www.tormach.com/order_execution_table.html
     */

    // acceleration ("feed rate")
    if (cmd.speed == Speed::CONSTANT){
        // motors.setSpeedProfile(MultiDriver::CONSTANT_SPEED);
    } else {
        // motors.setSpeedProfile(MultiDriver::LINEAR_SPEED, accel, decel);
    }

    // Camera operations
    if (cmd.nonmodal & NonModal::M116){
        // Zero-Motion wait
        int start = millis();
        bool success = mpu.zeroMotionWait(100 * cmd.q, 1000 * cmd.p);
        d("ZM="); d(millis()-start);
        d((success) ? "\n" : " (failed)\n");
    }
    if (cmd.nonmodal & NonModal::M240){
        // Shutter
        camera.shutter(1000 * cmd.p, bool(cmd.q));
        if (cmd.r > 0){
            delay(1000 * cmd.r);
        }
    }

    // dwell
    if (cmd.nonmodal & NonModal::G4){
        delay(1000 * cmd.p);
    }

    // units

    // distance mode

    // set offsets (origin)
    if (cmd.nonmodal & NonModal::G92_1){
        // reset origin
        cmd.origin.a = cmd.target.a = cmd.current.a = 0;
        cmd.origin.c = cmd.target.c = cmd.current.c = 0;
    }
    if (cmd.nonmodal & NonModal::G92){
        // origin moves so current coordinates match target
        cmd.origin.a -= cmd.target.a + cmd.current.a;
        cmd.origin.c -= cmd.target.c + cmd.current.c;
        cmd.current.a = cmd.target.a;
        cmd.current.c = cmd.target.c;
        cmd.target.a = 0;
        cmd.target.c = 0;
    }

    // motion

    if (cmd.nonmodal & NonModal::G28){
        // move to origin via another point (incremental)
        if (cmd.target.a != 0 || cmd.target.c != 0){
            move(cmd.motion, Coords::RELATIVE, cmd.current, cmd.target);
        }
        cmd.target.a = cmd.origin.a;
        cmd.target.c = cmd.origin.c;
        move(cmd.motion, Coords::ABSOLUTE, cmd.current, cmd.target);
        cmd.target.a = cmd.target.c = 0;
    }

    switch (cmd.motion){
    case Motion::G0:
    case Motion::G1:
        if (cmd.target.a != 0 || cmd.target.c != 0){
            move(cmd.motion, cmd.coords, cmd.current, cmd.target);
        }
    }

    // Data Query. These are here so we can read the final state of a move.
    if (cmd.nonmodal & NonModal::M115){
        // firmware version and capabilities
        d("PanoController 2.2beta build "  __DATE__ " " __TIME__ "\n");
        d("Options CAMERA BATT ZM\n");
        d("Axis A C\n");
    }
    if (cmd.nonmodal & NonModal::M503){
        // current settings
        d("GearRatioA=1:");d(horiz_gear_ratio);d("\n");
        d("GearRatioC=1:");d(vert_gear_ratio);d("\n");
        d("Battery=");d(battery.voltage());d("\n");
    }
    if (cmd.nonmodal & NonModal::M117){
        // print origin
        d("OriginA=");d(cmd.origin.a);d("\n");
        d("OriginC=");d(cmd.origin.c);d("\n");
    }
    if (cmd.nonmodal & NonModal::M114){
        // current position
        d("CurrentA=");d(cmd.current.a);d("\n");
        d("CurrentC=");d(cmd.current.c);d("\n");
    }

    // pause
    switch (cmd.wait){
    case Wait::M0:
        d("STOP\n");
        break;
    case Wait::M1:
        if (false){ // FIXME: replace w/ check button
            d("STOP\n");
        }
        break;
    case Wait::M2:
        d("END\n");
        break;
    }
}

void GCode::move(Motion motion, Coords coords, Position& current, Position& target){
    if (coords == Coords::RELATIVE){
        motors.rotate(target.a * horiz_gear_ratio, target.c * vert_gear_ratio);
        current.a += target.a;
        current.c += target.c;
    } else {
        motors.rotate((target.a - current.a) * horiz_gear_ratio,
                      (target.c - current.c) * vert_gear_ratio);
        current.a = target.a;
        current.c = target.c;
    };
}
<|endoftext|>


<commit_before>/*
** Copyright 1986, 1987, 1988, 1989, 1990, 1991 by the Condor Design Team
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the Condor Design Team not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission.  The University of Wisconsin and the Condor
** Design Team make no representations about the suitability of this
** software for any purpose.  It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE CONDOR DESIGN TEAM DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE CONDOR DESIGN TEAM BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Authors:  Allan Bricker and Michael J. Litzkow,
** 	         University of Wisconsin, Computer Sciences Dept.
**
*/

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "errno.h"
#include <sys/types.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <signal.h>
#include "condor_constants.h"

#if defined(AIX32)
#	include  <sys/statfs.h>
#	include  <sys/utsname.h>
#	include "condor_fdset.h"
#endif

#if defined(IRIX331)
#include <sys/statfs.h>
#elif !defined(ULTRIX42) && !defined(ULTRIX43) && !defined(OSF1) && !defined(IRIX53)
#include <sys/vfs.h>
#endif

#if 0
#if !defined(ultrix)
#ifdef IRIX331
#include <sys/statfs.h>
#else
#include <sys/vfs.h>
#endif
#endif !defined(ultrix)
#endif

#if defined(HPUX9)
#include <sys/ustat.h>
#endif

#include <sys/wait.h>
#include <sys/ioctl.h>

#if	defined(SUNOS40) || defined(SUNOS41) || defined(CMOS)
#include <sys/core.h>
#endif defined(SUNOS40) || defined(SUNOS41) || defined(CMOS)

#undef _POSIX_SOURCE
#include "condor_types.h"

#include "condor_sys.h"
#include "condor_rsc.h"
#include "trace.h"
#include "condor_debug.h"
#include "except.h"
#include "debug.h"
#include "fileno.h"
#include "condor_io.h"
#include "clib.h"
#include "shadow.h"

FILE	*fdopen();

static char *_FileName_ = __FILE__;		/* Used by EXCEPT (see except.h)     */

static int RSCSock;
static int LogSock;
extern int	PipeToParent;
extern int	LogPipe;
extern int	LockFd;
extern int	ImageSize;
extern int	ClientUid;
extern int	ClientGid;
extern struct rusage AccumRusage;

extern int UsePipes;

extern int free_fs_blocks();

extern V2_PROC *Proc;

/* XDR xdr_RSC, *xdr_syscall = &xdr_RSC; */
ReliSock *syscall_sock;

ReliSock *
RSC_ShadowInit( int rscsock, int errsock )
{
	RSCSock = rscsock;
	syscall_sock = new ReliSock();
	syscall_sock->attach_to_file_desc(RSCSock);

/*	xdrrec_create( xdr_syscall, XDR_BUFSIZE, XDR_BUFSIZE, (caddr_t)&RSCSock,
			(void*)XDR_ShadowRead, (void*)XDR_ShadowWrite ); */

	syscall_sock->encode();

	LogSock = errsock;
	// Now set LogSock to be posix-style non-blocking
	fcntl(LogSock,F_SETFL,O_NONBLOCK);

	return( syscall_sock );
}

#ifdef CARMI_OPS
XDR *
RSC_MyShadowInit( int *rscsock, int *errsock )
{
   XDR* xdrs;
/* AT --- have added this line here to make the streams dynamically
   allocated, rather than being a single statoc stream */
	xdrs = (XDR *) malloc(sizeof(XDR));

	xdrrec_create( xdrs, XDR_BUFSIZE, XDR_BUFSIZE, (caddr_t)rscsock,
			XDR_ShadowRead, XDR_ShadowWrite );
/*        xdrrec_skiprecord( xdrs ); */     /* flush input buffer */
	xdrs->x_op = XDR_ENCODE;
	return( xdrs );
}
#endif

#if 0
char MsgBuf[ BUFSIZ ];
HandleChildLog( log_fp )
FILE	*log_fp;
{
	register char *nlp;
	char *strchr();
	char buf[ BUFSIZ ];

	for(;;) {
		memset(buf,0, sizeof(buf));

		if( fgets(buf, sizeof(buf), log_fp) == NULL ) {
			return -1;
		}

		nlp = strchr(buf, '\n');
		if( nlp != NULL ) {
			*nlp = '\0';
		}

		dprintf(D_ALWAYS|D_NOHEADER, "%s\n", buf );
		if( strncmp("ERROR",buf,5) == 0 ) {
			(void)strcpy( MsgBuf, buf );
		}

		/*
		**	If there is more to read, read it, otherwise just return...
		*/
#if defined(LINUX)
		return 0;	/*Don't know how to handle this yet		*/
#else
		if( log_fp->_cnt == 0 ) {
			return 0;
		}
#endif
	}
}
#endif

HandleLog()
{
	char *nlp;
	char buf[ BUFSIZ ];
	int len,i,done;
	static char oldbuf[ BUFSIZ ];

	for(;;) {
		errno = 0;

		len=read(LogSock,buf,sizeof(buf)-1);
		if ( len < 0 ) {
			if ( errno == EINTR )
				continue;	// interrupted by signal; just continue
			if ( errno == EAGAIN )
				return 0;	// no more data to read

			dprintf(D_FULLDEBUG,"HandleLog() read FAILED, errno=%d\n",errno );
			return -1; 		// anything other than EINTR or EAGAIN is error
		}
		if ( len == 0 ) {
			return 0;
		}

		nlp = buf;
		done = 1;
		for (i=0;i<len;i++) {
			switch ( buf[i] ) {
				case '\n' :
					buf[i] = '\0';
					// NOTICE: no break here, we fall thru....
				case '\0' :
					if ( nlp[0] != '\0' ) {
						dprintf(D_ALWAYS,"Read: %s%s\n",oldbuf,nlp);
					}
					nlp = &(buf[i+1]);
					oldbuf[0] = '\0';
					done = 1;
					break;
				default :
					done = 0;
			}
		}

		if ( !done ) {
			/* we did not receive the entire line - store the first part */
			buf[ BUFSIZ - 1 ]  = '\0';  /* make certain strcpy does not SEGV */
			strcpy(oldbuf,buf);
		}

	}
}

#if 0
/*
Pseudo system call reporting virtual image size, to be used in calculating
future disk requirements.
*/
condor_image_size(d)
int d;
{
	if( d > ImageSize ) {
		ImageSize = d;
		write_to_parent( SIZE, &ImageSize, sizeof(ImageSize) );
	}
	return 0;
}
#endif

#if 0
/*
**	Make sure that they are not trying to
**	close a reserved descriptor.
*/
condor_close(d)
int d;
{
	if( d == RSC_SOCK || d == CLIENT_LOG ||
					d == PipeToParent || d == LogPipe ) {
		errno = EINVAL;
		return( -1 );
	}

	return( close(d) );
}
#endif

#if 0
/*
**	Make sure that they are not trying to
**	dup to a reserved descriptor.
*/
condor_dup2(oldd, newd)
int oldd, newd;
{
	if( newd == RSC_SOCK || newd == CLIENT_LOG ||
					newd == PipeToParent || newd == LogPipe ) {
		errno = EINVAL;
		return( -1 );
	}

	return( dup2(oldd, newd) );
}
#endif

#if 0
/*
**	We don't really want the shadow to exit here because the
**	starter may want to make a new checkpoint file.  So, just
**	respond with an error-free return code and hang out; the
**	shadow will (should) go away when (if) the starter closes
**	the LogSock.
*/
/* ARGSUSED */
condor_exit(status)
int status;
{
	return( 0 );
}
#endif

/*
**	getppid normally returns the parents id, right?  Well in
**	the CONDOR case, this job may be started and checkpointed many
**	times.  The parent will change each time.  Instead we will
**	treat it as though the parent process died and this process
**	was inherited by init.
*/
condor_getppid()
{
	return( 1 );
}

/*
**	getpid should return the same number each time.  As indicated
**	above, this CONDOR job may be started and checkpointed several times
**	during its lifetime, we return the condor "process id".
*/
condor_getpid()
{
	extern V2_PROC *Proc;

	return( Proc->id.proc );
}

/*
**	getpgrp should return the same number each time.  As indicated
**	above, this CONDOR job may be started and checkpointed several times
**	during its lifetime, we return the condor "cluster id".
*/
#if defined(AIX31) || defined(AIX32)
condor_getpgrp()
#else
condor_getpgrp( int pid )		/* Ignore it anyway */
#endif
{
	extern V2_PROC *Proc;

	return( Proc->id.cluster );
}

#if defined(AIX31) || defined(AIX32)
/*
**	kgetpgrp should return the same number each time.  As indicated
**	above, this CONDOR job may be started and checkpointed several times
**	during its lifetime, we return the condor "cluster id".  Since we
**	don't handle multi processing, should only be asking about own pgrp.
*/
condor_kgetpgrp( pid )
int		pid;
{
	extern V2_PROC *Proc;

	if( (pid != 0) && (pid != Proc->id.proc) ) {
		errno = EINVAL;
		return -1;
	}
	return( Proc->id.cluster );
}
#endif

#if defined(AIX31) || defined(AIX32)
/*
** Ignore which uid is wanted, just give out the condor client's uid
** in every case.
*/
condor_getuidx( which )
int		which;
{
	return ClientUid;
}
#endif

#if defined(AIX31) || defined(AIX32)
/*
** Ignore which gid is wanted, just give out the condor client's gid
** in every case.
*/
condor_getgidx( which )
int		which;
{
	return ClientGid;
}
#endif
<commit_msg>added comment<commit_after>/*
** Copyright 1986, 1987, 1988, 1989, 1990, 1991 by the Condor Design Team
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the Condor Design Team not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission.  The University of Wisconsin and the Condor
** Design Team make no representations about the suitability of this
** software for any purpose.  It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE CONDOR DESIGN TEAM DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE CONDOR DESIGN TEAM BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Authors:  Allan Bricker and Michael J. Litzkow,
** 	         University of Wisconsin, Computer Sciences Dept.
**
*/

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "errno.h"
#include <sys/types.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <signal.h>
#include "condor_constants.h"

#if defined(AIX32)
#	include  <sys/statfs.h>
#	include  <sys/utsname.h>
#	include "condor_fdset.h"
#endif

#if defined(IRIX331)
#include <sys/statfs.h>
#elif !defined(ULTRIX42) && !defined(ULTRIX43) && !defined(OSF1) && !defined(IRIX53)
#include <sys/vfs.h>
#endif

#if 0
#if !defined(ultrix)
#ifdef IRIX331
#include <sys/statfs.h>
#else
#include <sys/vfs.h>
#endif
#endif !defined(ultrix)
#endif

#if defined(HPUX9)
#include <sys/ustat.h>
#endif

#include <sys/wait.h>
#include <sys/ioctl.h>

#if	defined(SUNOS40) || defined(SUNOS41) || defined(CMOS)
#include <sys/core.h>
#endif defined(SUNOS40) || defined(SUNOS41) || defined(CMOS)

#undef _POSIX_SOURCE
#include "condor_types.h"

#include "condor_sys.h"
#include "condor_rsc.h"
#include "trace.h"
#include "condor_debug.h"
#include "except.h"
#include "debug.h"
#include "fileno.h"
#include "condor_io.h"
#include "clib.h"
#include "shadow.h"

FILE	*fdopen();

static char *_FileName_ = __FILE__;		/* Used by EXCEPT (see except.h)     */

static int RSCSock;
static int LogSock;
extern int	PipeToParent;
extern int	LogPipe;
extern int	LockFd;
extern int	ImageSize;
extern int	ClientUid;
extern int	ClientGid;
extern struct rusage AccumRusage;

extern int UsePipes;

extern int free_fs_blocks();

extern V2_PROC *Proc;

/* XDR xdr_RSC, *xdr_syscall = &xdr_RSC; */
ReliSock *syscall_sock;

ReliSock *
RSC_ShadowInit( int rscsock, int errsock )
{
	RSCSock = rscsock;
	syscall_sock = new ReliSock();
	syscall_sock->attach_to_file_desc(RSCSock);

/*	xdrrec_create( xdr_syscall, XDR_BUFSIZE, XDR_BUFSIZE, (caddr_t)&RSCSock,
			(void*)XDR_ShadowRead, (void*)XDR_ShadowWrite ); */

	syscall_sock->encode();

	LogSock = errsock;
	// Now set LogSock to be posix-style non-blocking
	fcntl(LogSock,F_SETFL,O_NONBLOCK);

	return( syscall_sock );
}

#ifdef CARMI_OPS
XDR *
RSC_MyShadowInit( int *rscsock, int *errsock )
{
   XDR* xdrs;
/* AT --- have added this line here to make the streams dynamically
   allocated, rather than being a single statoc stream */
	xdrs = (XDR *) malloc(sizeof(XDR));

	xdrrec_create( xdrs, XDR_BUFSIZE, XDR_BUFSIZE, (caddr_t)rscsock,
			XDR_ShadowRead, XDR_ShadowWrite );
/*        xdrrec_skiprecord( xdrs ); */     /* flush input buffer */
	xdrs->x_op = XDR_ENCODE;
	return( xdrs );
}
#endif

#if 0
char MsgBuf[ BUFSIZ ];
HandleChildLog( log_fp )
FILE	*log_fp;
{
	register char *nlp;
	char *strchr();
	char buf[ BUFSIZ ];

	for(;;) {
		memset(buf,0, sizeof(buf));

		if( fgets(buf, sizeof(buf), log_fp) == NULL ) {
			return -1;
		}

		nlp = strchr(buf, '\n');
		if( nlp != NULL ) {
			*nlp = '\0';
		}

		dprintf(D_ALWAYS|D_NOHEADER, "%s\n", buf );
		if( strncmp("ERROR",buf,5) == 0 ) {
			(void)strcpy( MsgBuf, buf );
		}

		/*
		**	If there is more to read, read it, otherwise just return...
		*/
#if defined(LINUX)
		return 0;	/*Don't know how to handle this yet		*/
#else
		if( log_fp->_cnt == 0 ) {
			return 0;
		}
#endif
	}
}
#endif

HandleLog()
{
	char *nlp;
	char buf[ BUFSIZ ];
	int len,i,done;
	static char oldbuf[ BUFSIZ ];

	for(;;) {
		errno = 0;

		len=read(LogSock,buf,sizeof(buf)-1);
		if ( len < 0 ) {
			if ( errno == EINTR )
				continue;	// interrupted by signal; just continue
			if ( errno == EAGAIN )
				return 0;	// no more data to read

			dprintf(D_FULLDEBUG,"HandleLog() read FAILED, errno=%d\n",errno );
			return -1; 		// anything other than EINTR or EAGAIN is error
		}
		if ( len == 0 ) {
			// some platforms return 0 instead of -1/EAGAIN like POSIX says...
			return 0;
		}

		nlp = buf;
		done = 1;
		for (i=0;i<len;i++) {
			switch ( buf[i] ) {
				case '\n' :
					buf[i] = '\0';
					// NOTICE: no break here, we fall thru....
				case '\0' :
					if ( nlp[0] != '\0' ) {
						dprintf(D_ALWAYS,"Read: %s%s\n",oldbuf,nlp);
					}
					nlp = &(buf[i+1]);
					oldbuf[0] = '\0';
					done = 1;
					break;
				default :
					done = 0;
			}
		}

		if ( !done ) {
			/* we did not receive the entire line - store the first part */
			buf[ BUFSIZ - 1 ]  = '\0';  /* make certain strcpy does not SEGV */
			strcpy(oldbuf,buf);
		}

	}
}

#if 0
/*
Pseudo system call reporting virtual image size, to be used in calculating
future disk requirements.
*/
condor_image_size(d)
int d;
{
	if( d > ImageSize ) {
		ImageSize = d;
		write_to_parent( SIZE, &ImageSize, sizeof(ImageSize) );
	}
	return 0;
}
#endif

#if 0
/*
**	Make sure that they are not trying to
**	close a reserved descriptor.
*/
condor_close(d)
int d;
{
	if( d == RSC_SOCK || d == CLIENT_LOG ||
					d == PipeToParent || d == LogPipe ) {
		errno = EINVAL;
		return( -1 );
	}

	return( close(d) );
}
#endif

#if 0
/*
**	Make sure that they are not trying to
**	dup to a reserved descriptor.
*/
condor_dup2(oldd, newd)
int oldd, newd;
{
	if( newd == RSC_SOCK || newd == CLIENT_LOG ||
					newd == PipeToParent || newd == LogPipe ) {
		errno = EINVAL;
		return( -1 );
	}

	return( dup2(oldd, newd) );
}
#endif

#if 0
/*
**	We don't really want the shadow to exit here because the
**	starter may want to make a new checkpoint file.  So, just
**	respond with an error-free return code and hang out; the
**	shadow will (should) go away when (if) the starter closes
**	the LogSock.
*/
/* ARGSUSED */
condor_exit(status)
int status;
{
	return( 0 );
}
#endif

/*
**	getppid normally returns the parents id, right?  Well in
**	the CONDOR case, this job may be started and checkpointed many
**	times.  The parent will change each time.  Instead we will
**	treat it as though the parent process died and this process
**	was inherited by init.
*/
condor_getppid()
{
	return( 1 );
}

/*
**	getpid should return the same number each time.  As indicated
**	above, this CONDOR job may be started and checkpointed several times
**	during its lifetime, we return the condor "process id".
*/
condor_getpid()
{
	extern V2_PROC *Proc;

	return( Proc->id.proc );
}

/*
**	getpgrp should return the same number each time.  As indicated
**	above, this CONDOR job may be started and checkpointed several times
**	during its lifetime, we return the condor "cluster id".
*/
#if defined(AIX31) || defined(AIX32)
condor_getpgrp()
#else
condor_getpgrp( int pid )		/* Ignore it anyway */
#endif
{
	extern V2_PROC *Proc;

	return( Proc->id.cluster );
}

#if defined(AIX31) || defined(AIX32)
/*
**	kgetpgrp should return the same number each time.  As indicated
**	above, this CONDOR job may be started and checkpointed several times
**	during its lifetime, we return the condor "cluster id".  Since we
**	don't handle multi processing, should only be asking about own pgrp.
*/
condor_kgetpgrp( pid )
int		pid;
{
	extern V2_PROC *Proc;

	if( (pid != 0) && (pid != Proc->id.proc) ) {
		errno = EINVAL;
		return -1;
	}
	return( Proc->id.cluster );
}
#endif

#if defined(AIX31) || defined(AIX32)
/*
** Ignore which uid is wanted, just give out the condor client's uid
** in every case.
*/
condor_getuidx( which )
int		which;
{
	return ClientUid;
}
#endif

#if defined(AIX31) || defined(AIX32)
/*
** Ignore which gid is wanted, just give out the condor client's gid
** in every case.
*/
condor_getgidx( which )
int		which;
{
	return ClientGid;
}
#endif
<|endoftext|>


<commit_before>/** @file bts/blockchain/fork_blocks.hpp
 *  @brief Defines global block number constants for when hardforks take effect
 */

#pragma once

#include <stdint.h>
#include <vector>

#define BTS_EXPECTED_CHAIN_ID       digest_type( "6ae7455c7af731c05698dae7100345ba0e4e229b99672d025201a80909cb8092" )
#define BTS_DESIRED_CHAIN_ID        digest_type( "75c11a81b7670bbaa721cc603eadb2313756f94a3bcbb9928e9101432701ac5f" )

#define BTS_V0_4_0_FORK_BLOCK_NUM    274000
#define BTS_V0_4_9_FORK_BLOCK_NUM    316001
#define BTS_V0_4_9_FORK_2_BLOCK_NUM  340000
#define BTS_V0_4_10_FORK_BLOCK_NUM   357000
#define BTS_V0_4_12_FORK_BLOCK_NUM   408750
#define BTS_V0_4_13_FORK_BLOCK_NUM   451500
#define BTS_V0_4_15_FORK_BLOCK_NUM   494000
#define BTS_V0_4_16_FORK_BLOCK_NUM   554800
#define BTS_V0_4_17_FORK_BLOCK_NUM   578900
#define BTS_V0_4_18_FORK_BLOCK_NUM   613200
#define BTS_V0_4_19_FORK_BLOCK_NUM   640000
#define BTS_V0_4_21_FORK_BLOCK_NUM   820200
#define BTS_V0_4_23_FORK_BLOCK_NUM   871000
#define BTS_V0_4_24_FORK_BLOCK_NUM   991700
#define BTS_V0_4_26_FORK_BLOCK_NUM  1315314
#define BTS_V0_5_0_FORK_BLOCK_NUM   1575500
#define BTS_V0_6_0_FORK_BLOCK_NUM   1772200
#define BTS_V0_6_1_FORK_BLOCK_NUM   BTS_V0_6_0_FORK_BLOCK_NUM
#define BTS_V0_6_2_FORK_BLOCK_NUM   BTS_V0_6_0_FORK_BLOCK_NUM
#define BTS_V0_6_3_FORK_BLOCK_NUM   BTS_V0_6_0_FORK_BLOCK_NUM
#define BTS_V0_7_0_FORK_BLOCK_NUM   2071000
#define BTS_V0_8_0_FORK_BLOCK_NUM   2113000
#define BTS_V0_9_0_FORK_BLOCK_NUM   2400000
#define BTS_V0_9_1_FORK_BLOCK_NUM   BTS_V0_9_0_FORK_BLOCK_NUM

#define BTS_FORK_TO_UNIX_TIME_LIST  ((BTS_V0_4_0_FORK_BLOCK_NUM,   "0.4.0",     1408064036)) \
                                    ((BTS_V0_4_9_FORK_2_BLOCK_NUM, "0.4.9",     1409193626)) \
                                    ((BTS_V0_4_10_FORK_BLOCK_NUM,  "0.4.10",    1409437355)) \
                                    ((BTS_V0_4_12_FORK_BLOCK_NUM,  "0.4.12",    1409846462)) \
                                    ((BTS_V0_4_13_FORK_BLOCK_NUM,  "0.4.13",    1410294635)) \
                                    ((BTS_V0_4_15_FORK_BLOCK_NUM,  "0.4.15",    1410657316)) \
                                    ((BTS_V0_4_16_FORK_BLOCK_NUM,  "0.4.16",    1411258737)) \
                                    ((BTS_V0_4_17_FORK_BLOCK_NUM,  "0.4.17",    1411599233)) \
                                    ((BTS_V0_4_18_FORK_BLOCK_NUM,  "0.4.18",    1411765631)) \
                                    ((BTS_V0_4_19_FORK_BLOCK_NUM,  "0.4.19",    1412203442)) \
                                    ((BTS_V0_4_21_FORK_BLOCK_NUM,  "0.4.21",    1414019090)) \
                                    ((BTS_V0_4_23_FORK_BLOCK_NUM,  "0.4.23",    1414527136)) \
                                    ((BTS_V0_4_24_FORK_BLOCK_NUM,  "0.4.24",    1415731817)) \
                                    ((BTS_V0_4_26_FORK_BLOCK_NUM,  "0.4.26",    1418402446)) \
                                    ((BTS_V0_5_0_FORK_BLOCK_NUM,   "0.5.0",     1421277141)) \
                                    ((BTS_V0_6_0_FORK_BLOCK_NUM,   "0.6.0",     1423270749)) \
                                    ((BTS_V0_7_0_FORK_BLOCK_NUM,   "0.7.0",     1426625439)) \
                                    ((BTS_V0_9_0_FORK_BLOCK_NUM,   "0.9.0",     1429558848))
                                    //((BTS_V0_8_0_FORK_BLOCK_NUM,   "0.8.0",     1427147320))

namespace bts { namespace blockchain {
  uint32_t estimate_last_known_fork_from_git_revision_timestamp(uint32_t revision_time);
  std::vector<uint32_t> get_list_of_fork_block_numbers();
} }
<commit_msg>Update fork block num<commit_after>/** @file bts/blockchain/fork_blocks.hpp
 *  @brief Defines global block number constants for when hardforks take effect
 */

#pragma once

#include <stdint.h>
#include <vector>

#define BTS_EXPECTED_CHAIN_ID       digest_type( "6ae7455c7af731c05698dae7100345ba0e4e229b99672d025201a80909cb8092" )
#define BTS_DESIRED_CHAIN_ID        digest_type( "75c11a81b7670bbaa721cc603eadb2313756f94a3bcbb9928e9101432701ac5f" )

#define BTS_V0_4_0_FORK_BLOCK_NUM    274000
#define BTS_V0_4_9_FORK_BLOCK_NUM    316001
#define BTS_V0_4_9_FORK_2_BLOCK_NUM  340000
#define BTS_V0_4_10_FORK_BLOCK_NUM   357000
#define BTS_V0_4_12_FORK_BLOCK_NUM   408750
#define BTS_V0_4_13_FORK_BLOCK_NUM   451500
#define BTS_V0_4_15_FORK_BLOCK_NUM   494000
#define BTS_V0_4_16_FORK_BLOCK_NUM   554800
#define BTS_V0_4_17_FORK_BLOCK_NUM   578900
#define BTS_V0_4_18_FORK_BLOCK_NUM   613200
#define BTS_V0_4_19_FORK_BLOCK_NUM   640000
#define BTS_V0_4_21_FORK_BLOCK_NUM   820200
#define BTS_V0_4_23_FORK_BLOCK_NUM   871000
#define BTS_V0_4_24_FORK_BLOCK_NUM   991700
#define BTS_V0_4_26_FORK_BLOCK_NUM  1315314
#define BTS_V0_5_0_FORK_BLOCK_NUM   1575500
#define BTS_V0_6_0_FORK_BLOCK_NUM   1772200
#define BTS_V0_6_1_FORK_BLOCK_NUM   BTS_V0_6_0_FORK_BLOCK_NUM
#define BTS_V0_6_2_FORK_BLOCK_NUM   BTS_V0_6_0_FORK_BLOCK_NUM
#define BTS_V0_6_3_FORK_BLOCK_NUM   BTS_V0_6_0_FORK_BLOCK_NUM
#define BTS_V0_7_0_FORK_BLOCK_NUM   2071000
#define BTS_V0_8_0_FORK_BLOCK_NUM   2113000
#define BTS_V0_9_0_FORK_BLOCK_NUM   2460000
#define BTS_V0_9_1_FORK_BLOCK_NUM   BTS_V0_9_0_FORK_BLOCK_NUM

#define BTS_FORK_TO_UNIX_TIME_LIST  ((BTS_V0_4_0_FORK_BLOCK_NUM,   "0.4.0",     1408064036)) \
                                    ((BTS_V0_4_9_FORK_2_BLOCK_NUM, "0.4.9",     1409193626)) \
                                    ((BTS_V0_4_10_FORK_BLOCK_NUM,  "0.4.10",    1409437355)) \
                                    ((BTS_V0_4_12_FORK_BLOCK_NUM,  "0.4.12",    1409846462)) \
                                    ((BTS_V0_4_13_FORK_BLOCK_NUM,  "0.4.13",    1410294635)) \
                                    ((BTS_V0_4_15_FORK_BLOCK_NUM,  "0.4.15",    1410657316)) \
                                    ((BTS_V0_4_16_FORK_BLOCK_NUM,  "0.4.16",    1411258737)) \
                                    ((BTS_V0_4_17_FORK_BLOCK_NUM,  "0.4.17",    1411599233)) \
                                    ((BTS_V0_4_18_FORK_BLOCK_NUM,  "0.4.18",    1411765631)) \
                                    ((BTS_V0_4_19_FORK_BLOCK_NUM,  "0.4.19",    1412203442)) \
                                    ((BTS_V0_4_21_FORK_BLOCK_NUM,  "0.4.21",    1414019090)) \
                                    ((BTS_V0_4_23_FORK_BLOCK_NUM,  "0.4.23",    1414527136)) \
                                    ((BTS_V0_4_24_FORK_BLOCK_NUM,  "0.4.24",    1415731817)) \
                                    ((BTS_V0_4_26_FORK_BLOCK_NUM,  "0.4.26",    1418402446)) \
                                    ((BTS_V0_5_0_FORK_BLOCK_NUM,   "0.5.0",     1421277141)) \
                                    ((BTS_V0_6_0_FORK_BLOCK_NUM,   "0.6.0",     1423270749)) \
                                    ((BTS_V0_7_0_FORK_BLOCK_NUM,   "0.7.0",     1426625439)) \
                                    ((BTS_V0_9_0_FORK_BLOCK_NUM,   "0.9.0",     1429558848))
                                    //((BTS_V0_8_0_FORK_BLOCK_NUM,   "0.8.0",     1427147320))

namespace bts { namespace blockchain {
  uint32_t estimate_last_known_fork_from_git_revision_timestamp(uint32_t revision_time);
  std::vector<uint32_t> get_list_of_fork_block_numbers();
} }
<|endoftext|>