<commit_before>//
//  GLGlobalState.hpp
//  G3MiOSSDK
//
//  Created by Agustín Trujillo Pino on 27/10/12.
//  Copyright (c) 2012 Universidad de Las Palmas. All rights reserved.
//

#ifndef G3MiOSSDK_GLGlobalState_hpp
#define G3MiOSSDK_GLGlobalState_hpp

class IFloatBuffer;

#include "Color.hpp"
#include "GLConstants.hpp"
#include "IFloatBuffer.hpp"
#include "MutableVector2D.hpp"
#include "MutableMatrix44D.hpp"
#include "Vector2D.hpp"

#include <list>

class GL;
struct AttributesStruct;
class UniformsStruct;
class GPUProgram;

class GLGlobalState {
private:
  bool _depthTest;
  bool _blend;
  bool _cullFace;
  int  _culledFace;

#ifdef C_CODE
  const IGLTextureId* _boundTextureId;
#endif
#ifdef JAVA_CODE
  private IGLTextureId _boundTextureId;
#endif

  float _lineWidth;

  //Polygon Offset
  bool  _polygonOffsetFill;
  float _polygonOffsetFactor;
  float _polygonOffsetUnits;

  //Blending Factors
  int _blendSFactor;
  int _blendDFactor;

  //Texture Parameters
  int _pixelStoreIAlignmentUnpack;

  //Clear color
  float _clearColorR;
  float _clearColorG;
  float _clearColorB;
  float _clearColorA;

  //Marks of state changed
  bool _depthTestChanged;
  bool _blendChanged;
  bool _cullFaceChanged;
  bool _lineWidthChanged;
  bool _polygonOffsetChanged;
  bool _blendFactorsChanged;
  bool _boundTextureChanged;
  bool _pixelStoreIChanged;
  bool _clearColorChanged;
/*
  GLGlobalState(const GLGlobalState& parentState) :
  _depthTest(parentState._depthTest),
  _blend(parentState._blend),
  _cullFace(parentState._cullFace),
  _culledFace(parentState._culledFace),
  _lineWidth(parentState._lineWidth),
  _polygonOffsetFactor(parentState._polygonOffsetFactor),
  _polygonOffsetUnits(parentState._polygonOffsetUnits),
  _polygonOffsetFill(parentState._polygonOffsetFill),
  _blendDFactor(parentState._blendDFactor),
  _blendSFactor(parentState._blendSFactor),
  _boundTextureId(parentState._boundTextureId),
  _pixelStoreIAlignmentUnpack(parentState._pixelStoreIAlignmentUnpack),
  _clearColorR(parentState._clearColorR),
  _clearColorG(parentState._clearColorG),
  _clearColorB(parentState._clearColorB),
  _clearColorA(parentState._clearColorA)
  {
  }
  */
public:

  GLGlobalState() :
  _depthTest(false),
  _blend(false),
  _cullFace(true),
  _culledFace(GLCullFace::back()),
  _lineWidth(1),
  _polygonOffsetFactor(0),
  _polygonOffsetUnits(0),
  _polygonOffsetFill(false),
  _blendDFactor(GLBlendFactor::zero()),
  _blendSFactor(GLBlendFactor::one()),
  _boundTextureId(NULL),
  _pixelStoreIAlignmentUnpack(-1),
  _clearColorR(0.0),
  _clearColorG(0.0),
  _clearColorB(0.0),
  _clearColorA(0.0),
  _depthTestChanged(false),
  _blendChanged(false),
  _cullFaceChanged(false),
  _lineWidthChanged(false),
  _polygonOffsetChanged(false),
  _blendFactorsChanged(false),
  _boundTextureChanged(false),
  _pixelStoreIChanged(false),
  _clearColorChanged(false)
  {
  }

  static GLGlobalState* newDefault() {
    return new GLGlobalState();
  }

  GLGlobalState* createCopy(){
    return new GLGlobalState(*this);
  }

  //  explicit GLGlobalState(const GLGlobalState& parentState) :
  //  _depthTest(parentState._depthTest),
  //  _blend(parentState._blend),
  //  _cullFace(parentState._cullFace),
  //  _culledFace(parentState._culledFace),
  //  _lineWidth(parentState._lineWidth),
  //  _polygonOffsetFactor(parentState._polygonOffsetFactor),
  //  _polygonOffsetUnits(parentState._polygonOffsetUnits),
  //  _polygonOffsetFill(parentState._polygonOffsetFill),
  //  _blendDFactor(parentState._blendDFactor),
  //  _blendSFactor(parentState._blendSFactor),
  //  _boundTextureId(parentState._boundTextureId),
  //  _pixelStoreIAlignmentUnpack(parentState._pixelStoreIAlignmentUnpack),
  //  _clearColorR(parentState._clearColorR),
  //  _clearColorG(parentState._clearColorG),
  //  _clearColorB(parentState._clearColorB),
  //  _clearColorA(parentState._clearColorA)
  //  {
  //  }

  ~GLGlobalState() {}

  void enableDepthTest() {
      _depthTest = true;
    _depthTestChanged = true;
  }
  void disableDepthTest() {
      _depthTest = false;
    _depthTestChanged = true;
  }
  bool isEnabledDepthTest() const { return _depthTest; }

  void enableBlend() {
      _blend = true;
    _blendChanged = true;
  }
  void disableBlend() {
      _blend = false;
    _blendChanged = true;
  }
  bool isEnabledBlend() const { return _blend; }

  void enableCullFace(int face) {
    _cullFace   = true;
    _culledFace = face;
    _cullFaceChanged = true;
  }
  void disableCullFace() {
    _cullFace = false;
    _cullFaceChanged = true;
  }
  bool isEnabledCullFace() const { return _cullFace; }
  int getCulledFace() const { return _culledFace; }

  void setLineWidth(float lineWidth) {
    _lineWidth = lineWidth;
    _lineWidthChanged = true;
  }
  float lineWidth() const { return _lineWidth; }

  void enablePolygonOffsetFill(float factor, float units){
    _polygonOffsetFill = true;
    _polygonOffsetFactor = factor;
    _polygonOffsetUnits = units;

    _polygonOffsetChanged = true;
  }
  void disPolygonOffsetFill(){
    _polygonOffsetFill = false;

    _polygonOffsetChanged = true;
  }

  bool getPolygonOffsetFill() const { return _polygonOffsetFill;}
  float getPolygonOffsetUnits() const { return _polygonOffsetUnits;}
  float getPolygonOffsetFactor() const { return _polygonOffsetFactor;}

  void setBlendFactors(int sFactor, int dFactor) {
    _blendSFactor = sFactor;
    _blendDFactor = dFactor;

    _blendFactorsChanged = true;
  }

  void bindTexture(const IGLTextureId* textureId){
    _boundTextureId = textureId;

    _boundTextureChanged = true;
  }

  const IGLTextureId* getBoundTexture() const{
    return _boundTextureId;
  }

  void setPixelStoreIAlignmentUnpack(int p){
    _pixelStoreIAlignmentUnpack = p;

    _pixelStoreIChanged = true;
  }

  void setClearColor(const Color& color){
    _clearColorR = color.getRed();
    _clearColorG = color.getGreen();
    _clearColorB = color.getBlue();
    _clearColorA = color.getAlpha();

    _clearColorChanged = true;
  }

  void applyChanges(GL* gl, GLGlobalState& currentState) const;
};

#endif
<commit_msg>Fixing conversion<commit_after>//
//  GLGlobalState.hpp
//  G3MiOSSDK
//
//  Created by Agustín Trujillo Pino on 27/10/12.
//  Copyright (c) 2012 Universidad de Las Palmas. All rights reserved.
//

#ifndef G3MiOSSDK_GLGlobalState_hpp
#define G3MiOSSDK_GLGlobalState_hpp

class IFloatBuffer;

#include "Color.hpp"
#include "GLConstants.hpp"
#include "IFloatBuffer.hpp"
#include "MutableVector2D.hpp"
#include "MutableMatrix44D.hpp"
#include "Vector2D.hpp"

#include <list>

class GL;
struct AttributesStruct;
class UniformsStruct;
class GPUProgram;

class GLGlobalState {
private:
  bool _depthTest;
  bool _blend;
  bool _cullFace;
  int  _culledFace;

#ifdef C_CODE
  const IGLTextureId* _boundTextureId;
#endif
#ifdef JAVA_CODE
  private IGLTextureId _boundTextureId;
#endif

  float _lineWidth;

  //Polygon Offset
  bool  _polygonOffsetFill;
  float _polygonOffsetFactor;
  float _polygonOffsetUnits;

  //Blending Factors
  int _blendSFactor;
  int _blendDFactor;

  //Texture Parameters
  int _pixelStoreIAlignmentUnpack;

  //Clear color
  float _clearColorR;
  float _clearColorG;
  float _clearColorB;
  float _clearColorA;

  //Marks of state changed
  bool _depthTestChanged;
  bool _blendChanged;
  bool _cullFaceChanged;
  bool _lineWidthChanged;
  bool _polygonOffsetChanged;
  bool _blendFactorsChanged;
  bool _boundTextureChanged;
  bool _pixelStoreIChanged;
  bool _clearColorChanged;

  GLGlobalState(const GLGlobalState& parentState) :
  _depthTest(parentState._depthTest),
  _blend(parentState._blend),
  _cullFace(parentState._cullFace),
  _culledFace(parentState._culledFace),
  _lineWidth(parentState._lineWidth),
  _polygonOffsetFactor(parentState._polygonOffsetFactor),
  _polygonOffsetUnits(parentState._polygonOffsetUnits),
  _polygonOffsetFill(parentState._polygonOffsetFill),
  _blendDFactor(parentState._blendDFactor),
  _blendSFactor(parentState._blendSFactor),
  _boundTextureId(parentState._boundTextureId),
  _pixelStoreIAlignmentUnpack(parentState._pixelStoreIAlignmentUnpack),
  _clearColorR(parentState._clearColorR),
  _clearColorG(parentState._clearColorG),
  _clearColorB(parentState._clearColorB),
  _clearColorA(parentState._clearColorA),
  _depthTestChanged(parentState._depthTestChanged),
  _blendChanged(parentState._blendChanged),
  _cullFaceChanged(parentState._cullFaceChanged),
  _lineWidthChanged(parentState._lineWidthChanged),
  _polygonOffsetChanged(parentState._polygonOffsetChanged),
  _blendFactorsChanged(parentState._blendFactorsChanged),
  _boundTextureChanged(parentState._boundTextureChanged),
  _pixelStoreIChanged(parentState._pixelStoreIChanged),
  _clearColorChanged(parentState._clearColorChanged)
  {
  }

public:

  GLGlobalState() :
  _depthTest(false),
  _blend(false),
  _cullFace(true),
  _culledFace(GLCullFace::back()),
  _lineWidth(1),
  _polygonOffsetFactor(0),
  _polygonOffsetUnits(0),
  _polygonOffsetFill(false),
  _blendDFactor(GLBlendFactor::zero()),
  _blendSFactor(GLBlendFactor::one()),
  _boundTextureId(NULL),
  _pixelStoreIAlignmentUnpack(-1),
  _clearColorR(0.0),
  _clearColorG(0.0),
  _clearColorB(0.0),
  _clearColorA(0.0),
  _depthTestChanged(false),
  _blendChanged(false),
  _cullFaceChanged(false),
  _lineWidthChanged(false),
  _polygonOffsetChanged(false),
  _blendFactorsChanged(false),
  _boundTextureChanged(false),
  _pixelStoreIChanged(false),
  _clearColorChanged(false)
  {
  }

  static GLGlobalState* newDefault() {
    return new GLGlobalState();
  }

  GLGlobalState* createCopy(){
    return new GLGlobalState(*this);
  }

  //  explicit GLGlobalState(const GLGlobalState& parentState) :
  //  _depthTest(parentState._depthTest),
  //  _blend(parentState._blend),
  //  _cullFace(parentState._cullFace),
  //  _culledFace(parentState._culledFace),
  //  _lineWidth(parentState._lineWidth),
  //  _polygonOffsetFactor(parentState._polygonOffsetFactor),
  //  _polygonOffsetUnits(parentState._polygonOffsetUnits),
  //  _polygonOffsetFill(parentState._polygonOffsetFill),
  //  _blendDFactor(parentState._blendDFactor),
  //  _blendSFactor(parentState._blendSFactor),
  //  _boundTextureId(parentState._boundTextureId),
  //  _pixelStoreIAlignmentUnpack(parentState._pixelStoreIAlignmentUnpack),
  //  _clearColorR(parentState._clearColorR),
  //  _clearColorG(parentState._clearColorG),
  //  _clearColorB(parentState._clearColorB),
  //  _clearColorA(parentState._clearColorA)
  //  {
  //  }

  ~GLGlobalState() {}

  void enableDepthTest() {
      _depthTest = true;
    _depthTestChanged = true;
  }
  void disableDepthTest() {
      _depthTest = false;
    _depthTestChanged = true;
  }
  bool isEnabledDepthTest() const { return _depthTest; }

  void enableBlend() {
      _blend = true;
    _blendChanged = true;
  }
  void disableBlend() {
      _blend = false;
    _blendChanged = true;
  }
  bool isEnabledBlend() const { return _blend; }

  void enableCullFace(int face) {
    _cullFace   = true;
    _culledFace = face;
    _cullFaceChanged = true;
  }
  void disableCullFace() {
    _cullFace = false;
    _cullFaceChanged = true;
  }
  bool isEnabledCullFace() const { return _cullFace; }
  int getCulledFace() const { return _culledFace; }

  void setLineWidth(float lineWidth) {
    _lineWidth = lineWidth;
    _lineWidthChanged = true;
  }
  float lineWidth() const { return _lineWidth; }

  void enablePolygonOffsetFill(float factor, float units){
    _polygonOffsetFill = true;
    _polygonOffsetFactor = factor;
    _polygonOffsetUnits = units;

    _polygonOffsetChanged = true;
  }
  void disPolygonOffsetFill(){
    _polygonOffsetFill = false;

    _polygonOffsetChanged = true;
  }

  bool getPolygonOffsetFill() const { return _polygonOffsetFill;}
  float getPolygonOffsetUnits() const { return _polygonOffsetUnits;}
  float getPolygonOffsetFactor() const { return _polygonOffsetFactor;}

  void setBlendFactors(int sFactor, int dFactor) {
    _blendSFactor = sFactor;
    _blendDFactor = dFactor;

    _blendFactorsChanged = true;
  }

  void bindTexture(const IGLTextureId* textureId){
    _boundTextureId = textureId;

    _boundTextureChanged = true;
  }

  const IGLTextureId* getBoundTexture() const{
    return _boundTextureId;
  }

  void setPixelStoreIAlignmentUnpack(int p){
    _pixelStoreIAlignmentUnpack = p;

    _pixelStoreIChanged = true;
  }

  void setClearColor(const Color& color){
    _clearColorR = color.getRed();
    _clearColorG = color.getGreen();
    _clearColorB = color.getBlue();
    _clearColorA = color.getAlpha();

    _clearColorChanged = true;
  }

  void applyChanges(GL* gl, GLGlobalState& currentState) const;
};

#endif
<|endoftext|>


<commit_before>#include <cctag/CCTag.hpp>
#include <cctag/global.hpp>
#include <cctag/dataSerialization.hpp>
#include <cctag/algebra/invert.hpp>
#include <cctag/geometry/Ellipse.hpp>
#include <cctag/statistic/statistic.hpp>
#include <cctag/algebra/matrix/operation.hpp>
#include <cctag/geometry/distance.hpp>
#include <cctag/optimization/conditioner.hpp>
#include <cctag/viewGeometry/homography.hpp>
#include <cctag/viewGeometry/2DTransform.hpp>

#ifdef WITH_CMINPACK
#include <cminpack.h>
#endif

#include <opencv2/core/core_c.h>

#include <boost/foreach.hpp>
#include <boost/timer.hpp>
#include <boost/array.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/functional.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>

#include <cstddef>
#include <cmath>
#include <iomanip>

namespace cctag
{

namespace ublas = boost::numeric::ublas;
namespace optimization = cctag::numerical::optimization;

// todo@Lilian : used in the initRadiusRatio called in the CCTag constructor. Need to be changed while reading the CCTagBank build from the textFile.
const boost::array<double, 5> CCTag::_radiusRatiosInit =
{
  (29.0 / 9.0),
  (29.0 / 13.0),
  (29.0 / 17.0),
  (29.0 / 21.0),
  (29.0 / 25.0)
};

void CCTag::condition(const cctag::numerical::BoundedMatrix3x3d & mT, const cctag::numerical::BoundedMatrix3x3d & mInvT)
{
  using namespace cctag::numerical::geometry;

  // Condition outer ellipse
  _outerEllipse = _outerEllipse.transform(mInvT);
  cctag::numerical::normalizeDet1(_outerEllipse.matrix());

  // Condition all ellipses
  BOOST_FOREACH(cctag::numerical::geometry::Ellipse & ellipse, _ellipses)
  {
    ellipse = ellipse.transform(mInvT);
    cctag::numerical::normalizeDet1(ellipse.matrix());
  }

  BOOST_FOREACH(std::vector<cctag::Point2dN<double> > & pts, _points)
  {
    cctag::numerical::optimization::condition(pts, mT);
  }

  cctag::numerical::optimization::condition(_centerImg, mT);
}

void CCTag::scale(const double s)
{

  BOOST_FOREACH(std::vector< Point2dN<double> > &vp, _points)
  {

    BOOST_FOREACH(Point2dN<double> &p, vp)
    {
      p.setX(p.x() * s);
      p.setY(p.y() * s);
    }
  }

  _centerImg.setX(_centerImg.x() * s);
  _centerImg.setY(_centerImg.y() * s);

  _outerEllipse.setCenter(Point2dN<double>(_outerEllipse.center().x() * s,
                          _outerEllipse.center().y() * s));
  _outerEllipse.setA(_outerEllipse.a() * s);
  _outerEllipse.setB(_outerEllipse.b() * s);
}

void CCTag::serialize(boost::archive::text_oarchive & ar, const unsigned int version)
{
  ar & BOOST_SERIALIZATION_NVP(_nCircles);
  ar & BOOST_SERIALIZATION_NVP(_id);
  ar & BOOST_SERIALIZATION_NVP(_pyramidLevel);
  ar & BOOST_SERIALIZATION_NVP(_scale);
  ar & BOOST_SERIALIZATION_NVP(_status);
  serializeEllipse(ar, _outerEllipse);
  serializeEllipse(ar, _rescaledOuterEllipse);
  serializeIdSet(ar, _idSet);
  serializeRadiusRatios(ar, _radiusRatios);
  ar & BOOST_SERIALIZATION_NVP(_quality);
  serializePoints(ar, _points);
  serializeEllipses(ar, _ellipses);
  serializeBoundedMatrix3x3d(ar, _mHomography);
  serializePoint(ar, _centerImg);
#ifdef CCTAG_SERIALIZE
  serializeFlowComponents(ar, _flowComponents);
#endif
}

} // namespace cctag
<commit_msg>Fix header<commit_after>#include <cctag/CCTag.hpp>
#include <cctag/global.hpp>
#include <cctag/dataSerialization.hpp>
#include <cctag/algebra/invert.hpp>
#include <cctag/geometry/Ellipse.hpp>
#include <cctag/statistic/statistic.hpp>
#include <cctag/algebra/matrix/operation.hpp>
#include <cctag/geometry/distance.hpp>
#include <cctag/optimization/conditioner.hpp>
#include <cctag/viewGeometry/2DTransform.hpp>

#ifdef WITH_CMINPACK
#include <cminpack.h>
#endif

#include <opencv2/core/core_c.h>

#include <boost/foreach.hpp>
#include <boost/timer.hpp>
#include <boost/array.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/functional.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>

#include <cstddef>
#include <cmath>
#include <iomanip>

namespace cctag
{

namespace ublas = boost::numeric::ublas;
namespace optimization = cctag::numerical::optimization;

// todo@Lilian : used in the initRadiusRatio called in the CCTag constructor. Need to be changed while reading the CCTagBank build from the textFile.
const boost::array<double, 5> CCTag::_radiusRatiosInit =
{
  (29.0 / 9.0),
  (29.0 / 13.0),
  (29.0 / 17.0),
  (29.0 / 21.0),
  (29.0 / 25.0)
};

void CCTag::condition(const cctag::numerical::BoundedMatrix3x3d & mT, const cctag::numerical::BoundedMatrix3x3d & mInvT)
{
  using namespace cctag::numerical::geometry;

  // Condition outer ellipse
  _outerEllipse = _outerEllipse.transform(mInvT);
  cctag::numerical::normalizeDet1(_outerEllipse.matrix());

  // Condition all ellipses
  BOOST_FOREACH(cctag::numerical::geometry::Ellipse & ellipse, _ellipses)
  {
    ellipse = ellipse.transform(mInvT);
    cctag::numerical::normalizeDet1(ellipse.matrix());
  }

  BOOST_FOREACH(std::vector<cctag::Point2dN<double> > & pts, _points)
  {
    cctag::numerical::optimization::condition(pts, mT);
  }

  cctag::numerical::optimization::condition(_centerImg, mT);
}

void CCTag::scale(const double s)
{

  BOOST_FOREACH(std::vector< Point2dN<double> > &vp, _points)
  {

    BOOST_FOREACH(Point2dN<double> &p, vp)
    {
      p.setX(p.x() * s);
      p.setY(p.y() * s);
    }
  }

  _centerImg.setX(_centerImg.x() * s);
  _centerImg.setY(_centerImg.y() * s);

  _outerEllipse.setCenter(Point2dN<double>(_outerEllipse.center().x() * s,
                          _outerEllipse.center().y() * s));
  _outerEllipse.setA(_outerEllipse.a() * s);
  _outerEllipse.setB(_outerEllipse.b() * s);
}

void CCTag::serialize(boost::archive::text_oarchive & ar, const unsigned int version)
{
  ar & BOOST_SERIALIZATION_NVP(_nCircles);
  ar & BOOST_SERIALIZATION_NVP(_id);
  ar & BOOST_SERIALIZATION_NVP(_pyramidLevel);
  ar & BOOST_SERIALIZATION_NVP(_scale);
  ar & BOOST_SERIALIZATION_NVP(_status);
  serializeEllipse(ar, _outerEllipse);
  serializeEllipse(ar, _rescaledOuterEllipse);
  serializeIdSet(ar, _idSet);
  serializeRadiusRatios(ar, _radiusRatios);
  ar & BOOST_SERIALIZATION_NVP(_quality);
  serializePoints(ar, _points);
  serializeEllipses(ar, _ellipses);
  serializeBoundedMatrix3x3d(ar, _mHomography);
  serializePoint(ar, _centerImg);
#ifdef CCTAG_SERIALIZE
  serializeFlowComponents(ar, _flowComponents);
#endif
}

} // namespace cctag
<|endoftext|>


<commit_before>#include "ajokki_console.hpp"
#include "code/ylikuutio/config/setting.hpp"
#include "code/ylikuutio/config/setting_master.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/common/globals.hpp"

// Include standard headers
#include <memory> // std::make_shared, std::shared_ptr

namespace config
{
    class SettingMaster;
}

namespace ajokki
{
    void set_console(config::SettingMaster* const setting_master)
    {
        // Variables related to console.
        uint32_t console_top_y = 15.0f;
        std::shared_ptr<datatypes::AnyValue> any_value_console_top_y = std::make_shared<datatypes::AnyValue>(console_top_y);
        SettingStruct console_top_y_setting_struct(any_value_console_top_y);
        console_top_y_setting_struct.name = "console_top_y";
        console_top_y_setting_struct.setting_master_pointer = setting_master;
        console_top_y_setting_struct.activate_callback = nullptr;
        console_top_y_setting_struct.should_ylikuutio_call_activate_callback_now = false;
        new config::Setting(console_top_y_setting_struct);

        uint32_t console_bottom_y = 0.0f;
        std::shared_ptr<datatypes::AnyValue> any_value_console_bottom_y = std::make_shared<datatypes::AnyValue>(console_bottom_y);
        SettingStruct console_bottom_y_setting_struct(any_value_console_bottom_y);
        console_bottom_y_setting_struct.name = "console_bottom_y";
        console_bottom_y_setting_struct.setting_master_pointer = setting_master;
        console_bottom_y_setting_struct.activate_callback = nullptr;
        console_bottom_y_setting_struct.should_ylikuutio_call_activate_callback_now = false;
        new config::Setting(console_bottom_y_setting_struct);
    }
}
<commit_msg>Bugfix: `console_top_y` & `console_bottom_y` are not floating point.<commit_after>#include "ajokki_console.hpp"
#include "code/ylikuutio/config/setting.hpp"
#include "code/ylikuutio/config/setting_master.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/common/globals.hpp"

// Include standard headers
#include <memory> // std::make_shared, std::shared_ptr

namespace config
{
    class SettingMaster;
}

namespace ajokki
{
    void set_console(config::SettingMaster* const setting_master)
    {
        // Variables related to console.
        uint32_t console_top_y = 15;
        std::shared_ptr<datatypes::AnyValue> any_value_console_top_y = std::make_shared<datatypes::AnyValue>(console_top_y);
        SettingStruct console_top_y_setting_struct(any_value_console_top_y);
        console_top_y_setting_struct.name = "console_top_y";
        console_top_y_setting_struct.setting_master_pointer = setting_master;
        console_top_y_setting_struct.activate_callback = nullptr;
        console_top_y_setting_struct.should_ylikuutio_call_activate_callback_now = false;
        new config::Setting(console_top_y_setting_struct);

        uint32_t console_bottom_y = 0;
        std::shared_ptr<datatypes::AnyValue> any_value_console_bottom_y = std::make_shared<datatypes::AnyValue>(console_bottom_y);
        SettingStruct console_bottom_y_setting_struct(any_value_console_bottom_y);
        console_bottom_y_setting_struct.name = "console_bottom_y";
        console_bottom_y_setting_struct.setting_master_pointer = setting_master;
        console_bottom_y_setting_struct.activate_callback = nullptr;
        console_bottom_y_setting_struct.should_ylikuutio_call_activate_callback_now = false;
        new config::Setting(console_bottom_y_setting_struct);
    }
}
<|endoftext|>


<commit_before>/*****************************************************************************************
*                                                                                *
* OpenSpace                                                                             *
*                                                                                *
* Copyright (c) 2014-2015                                                               *
*                                                                                *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify,    *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
* permit persons to whom the Software is furnished to do so, subject to the following   *
* conditions:                                                                           *
*                                                                                *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software.                                              *
*                                                                                *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
****************************************************************************************/
#include <modules/iswa/rendering/iswadatagroup.h>

#include <fstream>
#include <modules/iswa/ext/json/json.hpp>

#include <modules/iswa/util/dataprocessortext.h>
#include <modules/iswa/util/dataprocessorjson.h>
#include <modules/iswa/util/dataprocessorkameleon.h>

#include <modules/iswa/rendering/dataplane.h>
#include <modules/iswa/rendering/datasphere.h>
#include <modules/iswa/rendering/kameleonplane.h>

namespace {
    const std::string _loggerCat = "IswaDataGroup";
    using json = nlohmann::json;
}

namespace openspace{
IswaDataGroup::IswaDataGroup(std::string name, std::string type)
    :IswaBaseGroup(name, type)
    ,_useLog("useLog","Use Logarithm", false)
    ,_useHistogram("useHistogram", "Use Histogram", false)
    ,_autoFilter("autoFilter", "Auto Filter", true)
    ,_normValues("normValues", "Normalize Values", glm::vec2(1.0,1.0), glm::vec2(0), glm::vec2(5.0))
    ,_backgroundValues("backgroundValues", "Background Values", glm::vec2(0.0), glm::vec2(0), glm::vec2(1.0))
    ,_transferFunctionsFile("transferfunctions", "Transfer Functions", "${SCENE}/iswa/tfs/default.tf")
    ,_dataOptions("dataOptions", "Data Options")
{
    addProperty(_useLog);
    addProperty(_useHistogram);
    addProperty(_autoFilter);
    addProperty(_normValues);
    addProperty(_backgroundValues);
    addProperty(_transferFunctionsFile);
    addProperty(_dataOptions);

    createDataProcessor();
    registerProperties();
}

IswaDataGroup::~IswaDataGroup(){}

void IswaDataGroup::registerProperties(){
    OsEng.gui()._iswa.registerProperty(&_useLog);
    OsEng.gui()._iswa.registerProperty(&_useHistogram);
    OsEng.gui()._iswa.registerProperty(&_autoFilter);
    OsEng.gui()._iswa.registerProperty(&_backgroundValues);
    OsEng.gui()._iswa.registerProperty(&_normValues);
    OsEng.gui()._iswa.registerProperty(&_transferFunctionsFile);
    OsEng.gui()._iswa.registerProperty(&_dataOptions);

    _useLog.onChange([this]{
        LDEBUG("Group " + name() + " published useLogChanged");
        _groupEvent->publish("useLogChanged", ghoul::Dictionary({{"useLog", _useLog.value()}}));
    });

    _useHistogram.onChange([this]{
        LDEBUG("Group " + name() + " published useHistogramChanged");
        _groupEvent->publish("useHistogramChanged", ghoul::Dictionary({{"useHistogram", _useHistogram.value()}}));
    });

    //If autofiler is on, background values property should be hidden
    _autoFilter.onChange([this](){
        LDEBUG("Group " + name() + " published autoFilterChanged");
        // If autofiler is selected, use _dataProcessor to set backgroundValues
        // and unregister backgroundvalues property.
        if(_autoFilter.value()){
            _backgroundValues.setValue(_dataProcessor->filterValues());
            OsEng.gui()._iswa.unregisterProperty(&_backgroundValues);
        // else if autofilter is turned off, register backgroundValues
        } else {
            OsEng.gui()._iswa.registerProperty(&_backgroundValues, &_autoFilter);
        }
        _groupEvent->publish("autoFilterChanged", ghoul::Dictionary({{"autoFilter", _autoFilter.value()}}));
    });

    _normValues.onChange([this]{
        LDEBUG("Group " + name() + " published normValuesChanged");
        _groupEvent->publish("normValuesChanged", ghoul::Dictionary({{"normValues", std::make_shared<glm::vec2>(_normValues.value())}}));
    });

    _backgroundValues.onChange([this]{
        LDEBUG("Group " + name() + " published backgroundValuesChanged");
        _groupEvent->publish("backgroundValuesChanged", ghoul::Dictionary({{"backgroundValues", std::make_shared<glm::vec2>(_backgroundValues.value())}}));
    });

    _transferFunctionsFile.onChange([this]{
        LDEBUG("Group " + name() + " published transferFunctionsChanged");
        _groupEvent->publish("transferFunctionsChanged", ghoul::Dictionary({{"transferFunctions", _transferFunctionsFile.value()}}));
    });

    _dataOptions.onChange([this]{
        LDEBUG("Group " + name() + " published dataOptionsChanged");
        _groupEvent->publish("dataOptionsChanged", ghoul::Dictionary({{"dataOptions", std::make_shared<std::vector<int> >(_dataOptions.value())}}));
    });
}

void IswaDataGroup::registerOptions(const std::vector<properties::SelectionProperty::Option>& options){
    if(!_registered)
        registerProperties();

    if(_dataOptions.options().empty()){
        for(auto option : options){
            _dataOptions.addOption({option.value, option.description});
        }
        _dataOptions.setValue(std::vector<int>(1,0));
    }
}

void IswaDataGroup::createDataProcessor(){
    if(_type == typeid(DataPlane).name()){
        _dataProcessor = std::make_shared<DataProcessorText>();
    }else if(_type == typeid(DataSphere).name()){
        _dataProcessor = std::make_shared<DataProcessorJson>();
    }else if(_type == typeid(KameleonPlane).name()){
        _dataProcessor = std::make_shared<DataProcessorKameleon>();
    }
}

std::vector<int> IswaDataGroup::dataOptionsValue(){
    return _dataOptions.value();
}

} //namespace openspace
<commit_msg>Do not register backgroundValues when autoFilter is true<commit_after>/*****************************************************************************************
*                                                                                *
* OpenSpace                                                                             *
*                                                                                *
* Copyright (c) 2014-2015                                                               *
*                                                                                *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify,    *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
* permit persons to whom the Software is furnished to do so, subject to the following   *
* conditions:                                                                           *
*                                                                                *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software.                                              *
*                                                                                *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
****************************************************************************************/
#include <modules/iswa/rendering/iswadatagroup.h>

#include <fstream>
#include <modules/iswa/ext/json/json.hpp>

#include <modules/iswa/util/dataprocessortext.h>
#include <modules/iswa/util/dataprocessorjson.h>
#include <modules/iswa/util/dataprocessorkameleon.h>

#include <modules/iswa/rendering/dataplane.h>
#include <modules/iswa/rendering/datasphere.h>
#include <modules/iswa/rendering/kameleonplane.h>

namespace {
    const std::string _loggerCat = "IswaDataGroup";
    using json = nlohmann::json;
}

namespace openspace{
IswaDataGroup::IswaDataGroup(std::string name, std::string type)
    :IswaBaseGroup(name, type)
    ,_useLog("useLog","Use Logarithm", false)
    ,_useHistogram("useHistogram", "Use Histogram", false)
    ,_autoFilter("autoFilter", "Auto Filter", true)
    ,_normValues("normValues", "Normalize Values", glm::vec2(1.0,1.0), glm::vec2(0), glm::vec2(5.0))
    ,_backgroundValues("backgroundValues", "Background Values", glm::vec2(0.0), glm::vec2(0), glm::vec2(1.0))
    ,_transferFunctionsFile("transferfunctions", "Transfer Functions", "${SCENE}/iswa/tfs/default.tf")
    ,_dataOptions("dataOptions", "Data Options")
{
    addProperty(_useLog);
    addProperty(_useHistogram);
    addProperty(_autoFilter);
    addProperty(_normValues);
    addProperty(_backgroundValues);
    addProperty(_transferFunctionsFile);
    addProperty(_dataOptions);

    createDataProcessor();
    registerProperties();
}

IswaDataGroup::~IswaDataGroup(){}

void IswaDataGroup::registerProperties(){
    OsEng.gui()._iswa.registerProperty(&_useLog);
    OsEng.gui()._iswa.registerProperty(&_useHistogram);
    OsEng.gui()._iswa.registerProperty(&_autoFilter);
    if(!_autoFilter.value())
        OsEng.gui()._iswa.registerProperty(&_backgroundValues);
    // OsEng.gui()._iswa.registerProperty(&_autoFilter);
    OsEng.gui()._iswa.registerProperty(&_normValues);
    OsEng.gui()._iswa.registerProperty(&_transferFunctionsFile);
    OsEng.gui()._iswa.registerProperty(&_dataOptions);

    _useLog.onChange([this]{
        LDEBUG("Group " + name() + " published useLogChanged");
        _groupEvent->publish("useLogChanged", ghoul::Dictionary({{"useLog", _useLog.value()}}));
    });

    _useHistogram.onChange([this]{
        LDEBUG("Group " + name() + " published useHistogramChanged");
        _groupEvent->publish("useHistogramChanged", ghoul::Dictionary({{"useHistogram", _useHistogram.value()}}));
    });

    //If autofiler is on, background values property should be hidden
    _autoFilter.onChange([this](){
        LDEBUG("Group " + name() + " published autoFilterChanged");
        // If autofiler is selected, use _dataProcessor to set backgroundValues
        // and unregister backgroundvalues property.
        if(_autoFilter.value()){
            _backgroundValues.setValue(_dataProcessor->filterValues());
            OsEng.gui()._iswa.unregisterProperty(&_backgroundValues);
        // else if autofilter is turned off, register backgroundValues
        } else {
            OsEng.gui()._iswa.registerProperty(&_backgroundValues, &_autoFilter);
        }
        _groupEvent->publish("autoFilterChanged", ghoul::Dictionary({{"autoFilter", _autoFilter.value()}}));
    });

    _normValues.onChange([this]{
        LDEBUG("Group " + name() + " published normValuesChanged");
        _groupEvent->publish("normValuesChanged", ghoul::Dictionary({{"normValues", std::make_shared<glm::vec2>(_normValues.value())}}));
    });

    _backgroundValues.onChange([this]{
        LDEBUG("Group " + name() + " published backgroundValuesChanged");
        _groupEvent->publish("backgroundValuesChanged", ghoul::Dictionary({{"backgroundValues", std::make_shared<glm::vec2>(_backgroundValues.value())}}));
    });

    _transferFunctionsFile.onChange([this]{
        LDEBUG("Group " + name() + " published transferFunctionsChanged");
        _groupEvent->publish("transferFunctionsChanged", ghoul::Dictionary({{"transferFunctions", _transferFunctionsFile.value()}}));
    });

    _dataOptions.onChange([this]{
        LDEBUG("Group " + name() + " published dataOptionsChanged");
        _groupEvent->publish("dataOptionsChanged", ghoul::Dictionary({{"dataOptions", std::make_shared<std::vector<int> >(_dataOptions.value())}}));
    });
}

void IswaDataGroup::registerOptions(const std::vector<properties::SelectionProperty::Option>& options){
    if(!_registered)
        registerProperties();

    if(_dataOptions.options().empty()){
        for(auto option : options){
            _dataOptions.addOption({option.value, option.description});
        }
        _dataOptions.setValue(std::vector<int>(1,0));
    }
}

void IswaDataGroup::createDataProcessor(){
    if(_type == typeid(DataPlane).name()){
        _dataProcessor = std::make_shared<DataProcessorText>();
    }else if(_type == typeid(DataSphere).name()){
        _dataProcessor = std::make_shared<DataProcessorJson>();
    }else if(_type == typeid(KameleonPlane).name()){
        _dataProcessor = std::make_shared<DataProcessorKameleon>();
    }
}

std::vector<int> IswaDataGroup::dataOptionsValue(){
    return _dataOptions.value();
}

} //namespace openspace
<|endoftext|>


<commit_before>#define INIT(module) (compile (preprocessFileLineNumbers (\
        format ["modules\%1\init.sqf", module])))

#define FUNC(name) (compile (preprocessFileLineNumbers (\
        format ["modules\%1\functions\fnc_%2.sqf", MODULE, name])))
#define FUNC_FILE(name) (format ["modules\%1\functions\fnc_%2.sqf", MODULE,\
        name]);

#define MCFG (missionConfigFile >> format ["Cfg%1", MODULE])
#define EMCFG(name) (missionConfigFile >> format ["Cfg%1", name])

#define INCREASE(var) var = var + 1

#define ARR_ADD(array, element) array = array + [element]

<commit_msg>updated main/script_macros documentation<commit_after>/*
 * Author: r4vn
 *
 * Description:
 * Defines common macros used across modules.
 */

// Macro to get code of a module init function
#define INIT(module) (compile (preprocessFileLineNumbers (\
        format ["modules\%1\init.sqf", module])))

// Macro to get code of a private module function
#define FUNC(name) (compile (preprocessFileLineNumbers (\
        format ["modules\%1\functions\fnc_%2.sqf", MODULE, name])))
// Macro to get file name of private module function
#define FUNC_FILE(name) (format ["modules\%1\functions\fnc_%2.sqf", MODULE,\
        name]);

// Macro to get module configuration
#define MCFG (missionConfigFile >> format ["Cfg%1", MODULE])
// Macro to get an external mission configuration by its name
#define EMCFG(name) (missionConfigFile >> format ["Cfg%1", name])

// Macro to increase a number variable by one
#define INCREASE(var) var = var + 1

// Macro to add a element to an array
#define ARR_ADD(array, element) array = array + [element]

<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "assert.h"

#include <iostream>

#include "chainparams.h"
#include "main.h"
#include "util.h"

#include <boost/assign/list_of.hpp>

using namespace boost::assign;

struct SeedSpec6 {
    uint8_t addr[16];
    uint16_t port;
};

#include "chainparamsseeds.h"

//
// Main network
//

// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
    // It'll only connect to one or two seed nodes because once it connects,
    // it'll get a pile of addresses with newer timestamps.
    // Seed nodes are given a random 'last seen time' of between one and two
    // weeks ago.
    const int64_t nOneWeek = 7*24*60*60;
    for (unsigned int i = 0; i < count; i++)
    {
        struct in6_addr ip;
        memcpy(&ip, data[i].addr, sizeof(ip));
        CAddress addr(CService(ip, data[i].port));
        addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
        vSeedsOut.push_back(addr);
    }
}

class CMainParams : public CChainParams {
public:
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
        // a large 4-byte int at any alignment.
        pchMessageStart[0] = 0x70;
        pchMessageStart[1] = 0x35;
        pchMessageStart[2] = 0x42;
        pchMessageStart[3] = 0x05;
        vAlertPubKey = ParseHex("0486bce1bac0d543f104cbff2bd23680056a3b9ea05e1137d2ff90eeb5e08472eb500322593a2cb06fbf8297d7beb6cd30cb90f98153b5b7cce1493749e41e0284");
        nDefaultPort = 18114;
        nRPCPort = 19114;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
        /*
        nNonce is: 61618576
        Hash is: 000001768b08da66b92dede0ea8e7dcb97424f93d7ac2ac59e7a6cf98f20615a
        Block is: CBlock(hash=000001768b08da66b92dede0ea8e7dcb97424f93d7ac2ac59e7a6cf98f20615a, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=2da7a0080141ea1b6e32f670af4461801b638ba867241d319c3d590d03d75614, nTime=1445353519, nBits=1e0fffff, nNonce=61618576, vtx=1, vchBlockSig=)
          Coinbase(hash=2da7a0080141ea1b6e32f670af4461801b638ba867241d319c3d590d03d75614, nTime=1445353519, ver=1, vin.size=1, vout.size=1, nLockTime=0)
            CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a2e3230204f63742032303135204120426c6f6f6d626572672052756e3f204472756d73204172652042656174696e67)
            CTxOut(empty)
          vMerkleTree:  2da7a0080141ea1b6e32f670af4461801b638ba867241d319c3d590d03d75614
        */
        const char* pszTimestamp = "20 Oct 2015 A Bloomberg Run? Drums Are Beating";
        const uint32_t genesisTimestamp = 1445353519;
        std::vector<CTxIn> vin;
        vin.resize(1);
        vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        std::vector<CTxOut> vout;
        vout.resize(1);
        vout[0].SetEmpty();
        CTransaction txNew(1, genesisTimestamp, vin, vout, 0);
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = genesisTimestamp;
        genesis.nBits    = bnProofOfWorkLimit.GetCompact();

/*
        // "mine" the nonce
        for (genesis.nNonce = 0; genesis.nNonce < 0xffffffff; genesis.nNonce++) {
            if (genesis.nNonce % 1000000 == 0)
                std::cout << "tried " << genesis.nNonce << " nonces" << std::endl;
            hashGenesisBlock = genesis.GetHash();
            unsigned char *b = hashGenesisBlock.end() - 3;
            if (memcmp(b, "\x01\x00\x00", 3) == 0) {
                std::cout << "nNonce is: " << genesis.nNonce << std::endl;
                std::cout << "Hash is: " << genesis.GetHash().ToString() << std::endl;
                std::cout << "Block is: " << genesis.ToString() << std::endl;
                abort();
                break;
            }
        }
*/

        genesis.nNonce = 61618576;
        hashGenesisBlock = genesis.GetHash();

        assert(hashGenesisBlock == uint256("0x000001768b08da66b92dede0ea8e7dcb97424f93d7ac2ac59e7a6cf98f20615a"));
        assert(genesis.hashMerkleRoot == uint256("0x2da7a0080141ea1b6e32f670af4461801b638ba867241d319c3d590d03d75614"));

        vSeeds.push_back(CDNSSeedData("seed1.clubcoin.io", "seed1.clubcoin.io"));
        vSeeds.push_back(CDNSSeedData("seed2.clubcoin.io", "seed2.clubcoin.io"));
        vSeeds.push_back(CDNSSeedData("seed3.clubcoin.io", "seed3.clubcoin.io"));
        vSeeds.push_back(CDNSSeedData("seed4.clubcoin.io", "seed4.clubcoin.io"));
        vSeeds.push_back(CDNSSeedData("seed5.clubcoin.io", "seed5.clubcoin.io"));

        base58Prefixes[PUBKEY_ADDRESS] = list_of(28); // appears as "C" in base58
        base58Prefixes[SCRIPT_ADDRESS] = list_of(85);
        base58Prefixes[SECRET_KEY] =     list_of(153);
        base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
        base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);

        convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));

        nLastPOWBlock = LAST_POW_BLOCK;
    }

    virtual const CBlock& GenesisBlock() const { return genesis; }
    virtual Network NetworkID() const { return CChainParams::MAIN; }

    virtual const vector<CAddress>& FixedSeeds() const {
        return vFixedSeeds;
    }
protected:
    CBlock genesis;
    vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;

//
// Testnet
//

class CTestNetParams : public CMainParams {
public:
    CTestNetParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
        // a large 4-byte int at any alignment.
        pchMessageStart[0] = 0xcd;
        pchMessageStart[1] = 0xf2;
        pchMessageStart[2] = 0x42;
        pchMessageStart[3] = 0xef;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
        vAlertPubKey = ParseHex("0471dc165db490094d35cde15b1f5d755fa6ad6f2b5ed0f340e3f17f57389c3c2af113a8cbcc885bde73305a553b5640c83021128008ddf882e856336269080496");
        nDefaultPort = 28114;
        nRPCPort = 29114;
        strDataDir = "testnet";

        // Modify the testnet genesis block so the timestamp is valid for a later start.
        genesis.nBits  = bnProofOfWorkLimit.GetCompact();

/*
        // "mine" the nonce
        for (genesis.nNonce = 0; genesis.nNonce < 0xffffffff; genesis.nNonce++) {
            if (genesis.nNonce % 1000000 == 0)
                std::cout << "tried " << genesis.nNonce << " nonces" << std::endl;
            hashGenesisBlock = genesis.GetHash();
            unsigned char *b = hashGenesisBlock.end() - 2;
            if (memcmp(b, "\x00\x00", 2) == 0) {
                std::cout << "testnet nNonce is: " << genesis.nNonce << std::endl;
                std::cout << "Hash is: " << genesis.GetHash().ToString() << std::endl;
                std::cout << "Block is: " << genesis.ToString() << std::endl;
                abort();
                break;
            }
        }
*/

        genesis.nNonce = 96540;
        hashGenesisBlock = genesis.GetHash();

        assert(hashGenesisBlock == uint256("0x0000fb7faf0608bb189df6bfde6c17b7d9bb337056bb8c97f7973f929b493a4e"));

        vFixedSeeds.clear();
        vSeeds.clear();

        base58Prefixes[PUBKEY_ADDRESS] = list_of(111);
        base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
        base58Prefixes[SECRET_KEY]     = list_of(239);
        base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
        base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);

        convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));

        nLastPOWBlock = 0x7fffffff;
    }
    virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;

//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
    CRegTestParams() {
        pchMessageStart[0] = 0xfa;
        pchMessageStart[1] = 0xbf;
        pchMessageStart[2] = 0xb5;
        pchMessageStart[3] = 0xda;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
        genesis.nTime = 1411111111;
        genesis.nBits  = bnProofOfWorkLimit.GetCompact();
        genesis.nNonce = 2;
        hashGenesisBlock = genesis.GetHash();
        nDefaultPort = 18444;
        strDataDir = "regtest";

        /*
        std::cout << "Block is: " << genesis.ToString() << std::endl;
        */
        assert(hashGenesisBlock == uint256("0xb0dd3b9300bac6ebca952b64d8f8e70698c5b94a8bef14e94d564ee6a0d4e00c"));

        vSeeds.clear();  // Regtest mode doesn't have any DNS seeds.
    }

    virtual bool RequireRPCPassword() const { return false; }
    virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;

static CChainParams *pCurrentParams = &mainParams;

const CChainParams &Params() {
    return *pCurrentParams;
}

void SelectParams(CChainParams::Network network) {
    switch (network) {
        case CChainParams::MAIN:
            pCurrentParams = &mainParams;
            break;
        case CChainParams::TESTNET:
            pCurrentParams = &testNetParams;
            break;
        case CChainParams::REGTEST:
            pCurrentParams = &regTestParams;
            break;
        default:
            assert(false && "Unimplemented network");
            return;
    }
}

bool SelectParamsFromCommandLine() {
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest) {
        return false;
    }

    if (fRegTest) {
        SelectParams(CChainParams::REGTEST);
    } else if (fTestNet) {
        SelectParams(CChainParams::TESTNET);
    } else {
        SelectParams(CChainParams::MAIN);
    }
    return true;
}
<commit_msg>vector<> changes to get C++11 support.<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "assert.h"

#include <iostream>

#include "chainparams.h"
#include "main.h"
#include "util.h"

#include <boost/assign/list_of.hpp>

using namespace boost::assign;

struct SeedSpec6 {
    uint8_t addr[16];
    uint16_t port;
};

#include "chainparamsseeds.h"

//
// Main network
//

// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
    // It'll only connect to one or two seed nodes because once it connects,
    // it'll get a pile of addresses with newer timestamps.
    // Seed nodes are given a random 'last seen time' of between one and two
    // weeks ago.
    const int64_t nOneWeek = 7*24*60*60;
    for (unsigned int i = 0; i < count; i++)
    {
        struct in6_addr ip;
        memcpy(&ip, data[i].addr, sizeof(ip));
        CAddress addr(CService(ip, data[i].port));
        addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
        vSeedsOut.push_back(addr);
    }
}

class CMainParams : public CChainParams {
public:
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
        // a large 4-byte int at any alignment.
        pchMessageStart[0] = 0x70;
        pchMessageStart[1] = 0x35;
        pchMessageStart[2] = 0x42;
        pchMessageStart[3] = 0x05;
        vAlertPubKey = ParseHex("0486bce1bac0d543f104cbff2bd23680056a3b9ea05e1137d2ff90eeb5e08472eb500322593a2cb06fbf8297d7beb6cd30cb90f98153b5b7cce1493749e41e0284");
        nDefaultPort = 18114;
        nRPCPort = 19114;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
        /*
        nNonce is: 61618576
        Hash is: 000001768b08da66b92dede0ea8e7dcb97424f93d7ac2ac59e7a6cf98f20615a
        Block is: CBlock(hash=000001768b08da66b92dede0ea8e7dcb97424f93d7ac2ac59e7a6cf98f20615a, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=2da7a0080141ea1b6e32f670af4461801b638ba867241d319c3d590d03d75614, nTime=1445353519, nBits=1e0fffff, nNonce=61618576, vtx=1, vchBlockSig=)
          Coinbase(hash=2da7a0080141ea1b6e32f670af4461801b638ba867241d319c3d590d03d75614, nTime=1445353519, ver=1, vin.size=1, vout.size=1, nLockTime=0)
            CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a2e3230204f63742032303135204120426c6f6f6d626572672052756e3f204472756d73204172652042656174696e67)
            CTxOut(empty)
          vMerkleTree:  2da7a0080141ea1b6e32f670af4461801b638ba867241d319c3d590d03d75614
        */
        const char* pszTimestamp = "20 Oct 2015 A Bloomberg Run? Drums Are Beating";
        const uint32_t genesisTimestamp = 1445353519;
        std::vector<CTxIn> vin;
        vin.resize(1);
        vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        std::vector<CTxOut> vout;
        vout.resize(1);
        vout[0].SetEmpty();
        CTransaction txNew(1, genesisTimestamp, vin, vout, 0);
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = genesisTimestamp;
        genesis.nBits    = bnProofOfWorkLimit.GetCompact();

/*
        // "mine" the nonce
        for (genesis.nNonce = 0; genesis.nNonce < 0xffffffff; genesis.nNonce++) {
            if (genesis.nNonce % 1000000 == 0)
                std::cout << "tried " << genesis.nNonce << " nonces" << std::endl;
            hashGenesisBlock = genesis.GetHash();
            unsigned char *b = hashGenesisBlock.end() - 3;
            if (memcmp(b, "\x01\x00\x00", 3) == 0) {
                std::cout << "nNonce is: " << genesis.nNonce << std::endl;
                std::cout << "Hash is: " << genesis.GetHash().ToString() << std::endl;
                std::cout << "Block is: " << genesis.ToString() << std::endl;
                abort();
                break;
            }
        }
*/

        genesis.nNonce = 61618576;
        hashGenesisBlock = genesis.GetHash();

        assert(hashGenesisBlock == uint256("0x000001768b08da66b92dede0ea8e7dcb97424f93d7ac2ac59e7a6cf98f20615a"));
        assert(genesis.hashMerkleRoot == uint256("0x2da7a0080141ea1b6e32f670af4461801b638ba867241d319c3d590d03d75614"));

        vSeeds.push_back(CDNSSeedData("seed1.clubcoin.io", "seed1.clubcoin.io"));
        vSeeds.push_back(CDNSSeedData("seed2.clubcoin.io", "seed2.clubcoin.io"));
        vSeeds.push_back(CDNSSeedData("seed3.clubcoin.io", "seed3.clubcoin.io"));
        vSeeds.push_back(CDNSSeedData("seed4.clubcoin.io", "seed4.clubcoin.io"));
        vSeeds.push_back(CDNSSeedData("seed5.clubcoin.io", "seed5.clubcoin.io"));

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,28); // appears as "C" in base58
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,85);
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,153);
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();

        convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));

        nLastPOWBlock = LAST_POW_BLOCK;
    }

    virtual const CBlock& GenesisBlock() const { return genesis; }
    virtual Network NetworkID() const { return CChainParams::MAIN; }

    virtual const vector<CAddress>& FixedSeeds() const {
        return vFixedSeeds;
    }
protected:
    CBlock genesis;
    vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;

//
// Testnet
//

class CTestNetParams : public CMainParams {
public:
    CTestNetParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
        // a large 4-byte int at any alignment.
        pchMessageStart[0] = 0xcd;
        pchMessageStart[1] = 0xf2;
        pchMessageStart[2] = 0x42;
        pchMessageStart[3] = 0xef;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
        vAlertPubKey = ParseHex("0471dc165db490094d35cde15b1f5d755fa6ad6f2b5ed0f340e3f17f57389c3c2af113a8cbcc885bde73305a553b5640c83021128008ddf882e856336269080496");
        nDefaultPort = 28114;
        nRPCPort = 29114;
        strDataDir = "testnet";

        // Modify the testnet genesis block so the timestamp is valid for a later start.
        genesis.nBits  = bnProofOfWorkLimit.GetCompact();

/*
        // "mine" the nonce
        for (genesis.nNonce = 0; genesis.nNonce < 0xffffffff; genesis.nNonce++) {
            if (genesis.nNonce % 1000000 == 0)
                std::cout << "tried " << genesis.nNonce << " nonces" << std::endl;
            hashGenesisBlock = genesis.GetHash();
            unsigned char *b = hashGenesisBlock.end() - 2;
            if (memcmp(b, "\x00\x00", 2) == 0) {
                std::cout << "testnet nNonce is: " << genesis.nNonce << std::endl;
                std::cout << "Hash is: " << genesis.GetHash().ToString() << std::endl;
                std::cout << "Block is: " << genesis.ToString() << std::endl;
                abort();
                break;
            }
        }
*/

        genesis.nNonce = 96540;
        hashGenesisBlock = genesis.GetHash();

        assert(hashGenesisBlock == uint256("0x0000fb7faf0608bb189df6bfde6c17b7d9bb337056bb8c97f7973f929b493a4e"));

        vFixedSeeds.clear();
        vSeeds.clear();

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
        base58Prefixes[SECRET_KEY]     = std::vector<unsigned char>(1,239);
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();;
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();;

        convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));

        nLastPOWBlock = 0x7fffffff;
    }
    virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;

//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
    CRegTestParams() {
        pchMessageStart[0] = 0xfa;
        pchMessageStart[1] = 0xbf;
        pchMessageStart[2] = 0xb5;
        pchMessageStart[3] = 0xda;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
        genesis.nTime = 1411111111;
        genesis.nBits  = bnProofOfWorkLimit.GetCompact();
        genesis.nNonce = 2;
        hashGenesisBlock = genesis.GetHash();
        nDefaultPort = 18444;
        strDataDir = "regtest";

        /*
        std::cout << "Block is: " << genesis.ToString() << std::endl;
        */
        assert(hashGenesisBlock == uint256("0xb0dd3b9300bac6ebca952b64d8f8e70698c5b94a8bef14e94d564ee6a0d4e00c"));

        vSeeds.clear();  // Regtest mode doesn't have any DNS seeds.
    }

    virtual bool RequireRPCPassword() const { return false; }
    virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;

static CChainParams *pCurrentParams = &mainParams;

const CChainParams &Params() {
    return *pCurrentParams;
}

void SelectParams(CChainParams::Network network) {
    switch (network) {
        case CChainParams::MAIN:
            pCurrentParams = &mainParams;
            break;
        case CChainParams::TESTNET:
            pCurrentParams = &testNetParams;
            break;
        case CChainParams::REGTEST:
            pCurrentParams = &regTestParams;
            break;
        default:
            assert(false && "Unimplemented network");
            return;
    }
}

bool SelectParamsFromCommandLine() {
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest) {
        return false;
    }

    if (fRegTest) {
        SelectParams(CChainParams::REGTEST);
    } else if (fTestNet) {
        SelectParams(CChainParams::TESTNET);
    } else {
        SelectParams(CChainParams::MAIN);
    }
    return true;
}
<|endoftext|>


<commit_before>#include "OldJunction.h"
#include "SinglePhaseFluidProperties.h"
#include "FlowModelSinglePhase.h"

registerMooseObject("THMApp", OldJunction);

template <>
InputParameters
validParams<OldJunction>()
{
  InputParameters params = validParams<JunctionWithLossesBase>();
  params.addParam<Real>("initial_p", 1e5, "Initial pressure of this junction");
  params.addParam<Real>("initial_T", 300, "Initial temperature of this junction");
  params.addParam<Real>(
      "initial_alpha_vapor", 1., "Initial vapor volume fraction in the OldJunction");
  std::vector<Real> sf(2, 1.e0);
  params.addParam<std::vector<Real>>(
      "scaling_factors", sf, "Scaling factors for variables: pressure, energy");
  return params;
}

OldJunction::OldJunction(const InputParameters & params)
  : JunctionWithLossesBase(params),
    _pressure_var_name(genName(name(), "p")),
    _energy_var_name(genName(name(), "energy")),
    _initial_P(getParam<Real>("initial_p")),
    _initial_void_fraction(getParam<Real>("initial_alpha_vapor")),
    _total_mfr_in_var_name(genName(name(), "tmfri")),
    _total_int_energy_rate_in_var_name(genName(name(), "ntei")),
    _scaling_factors(getParam<std::vector<Real>>("scaling_factors"))
{
}

void
OldJunction::check() const
{
  JunctionWithLossesBase::check();

  if (_flow_model_id != THM::FM_SINGLE_PHASE)
    logModelNotImplementedError(_flow_model_id);

  checkSizeEqualsValue<Real>("scaling_factors", 2);
}

void
OldJunction::addVariables()
{
  auto connected_subdomains = getConnectedSubdomainIDs();

  _sim.addVariable(
      true, _pressure_var_name, FEType(FIRST, SCALAR), connected_subdomains, _scaling_factors[0]);
  _sim.addConstantScalarIC(_pressure_var_name, _initial_P);

  const SinglePhaseFluidProperties & spfp =
      _sim.getUserObject<SinglePhaseFluidProperties>(_fp_name);
  Real initial_T = getParam<Real>("initial_T");
  Real initial_rho = spfp.rho_from_p_T(_initial_P, initial_T);
  Real initial_e = spfp.e_from_p_rho(_initial_P, initial_rho);

  _sim.addVariable(
      true, _energy_var_name, FEType(FIRST, SCALAR), connected_subdomains, _scaling_factors[1]);
  _sim.addConstantScalarIC(_energy_var_name, initial_e);

  _sim.addVariable(false, _total_mfr_in_var_name, FEType(FIRST, SCALAR), 0);
  _sim.addConstantScalarIC(_total_mfr_in_var_name, 0);

  _sim.addVariable(false, _total_int_energy_rate_in_var_name, FEType(FIRST, SCALAR), 0);
  _sim.addConstantScalarIC(_total_int_energy_rate_in_var_name, 0);
}

void
OldJunction::addMooseObjects()
{
  std::vector<VariableName> cv_vel(1, FlowModelSinglePhase::VELOCITY);
  std::vector<VariableName> cv_pressure(1, FlowModelSinglePhase::PRESSURE);
  std::vector<VariableName> cv_rho(1, FlowModelSinglePhase::DENSITY);
  std::vector<VariableName> cv_rhoA(1, FlowModelSinglePhase::RHOA);
  std::vector<VariableName> cv_rhou(1, FlowModelSinglePhase::MOMENTUM_DENSITY);
  std::vector<VariableName> cv_rhouA(1, FlowModelSinglePhase::RHOUA);
  std::vector<VariableName> cv_rhoE(1, FlowModelSinglePhase::TOTAL_ENERGY_DENSITY);
  std::vector<VariableName> cv_rhoEA(1, FlowModelSinglePhase::RHOEA);
  std::vector<VariableName> cv_enthalpy(1, FlowModelSinglePhase::SPECIFIC_TOTAL_ENTHALPY);
  std::vector<VariableName> cv_area(1, FlowModelSinglePhase::AREA);
  std::vector<VariableName> cv_junction_pressure(1, _pressure_var_name);
  std::vector<VariableName> cv_junction_energy(1, _energy_var_name);

  std::vector<OutputName> outputs = _sim.getOutputsVector("none");

  const SinglePhaseFluidProperties & spfp =
      _sim.getUserObject<SinglePhaseFluidProperties>(_fp_name);
  Real initial_T = getParam<Real>("initial_T");
  Real initial_rho = spfp.rho_from_p_T(_initial_P, initial_T);

  {
    std::string class_name = "TotalMassFlowRateIntoJunctionAux";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<AuxVariableName>("variable") = _total_mfr_in_var_name;
    params.set<std::vector<dof_id_type>>("nodes") = _nodes;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    _sim.addAuxScalarKernel(class_name, genName(name(), "total_mfr_in"), params);
  }

  {
    std::string class_name = "TotalInternalEnergyRateIntoJunctionAux";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<AuxVariableName>("variable") = _total_int_energy_rate_in_var_name;
    params.set<std::vector<dof_id_type>>("nodes") = _nodes;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<VariableName>>("rhoA") = cv_rhoA;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA;
    _sim.addAuxScalarKernel(class_name, genName(name(), "total_int_energy_rate_in"), params);
  }

  {
    std::string class_name = "MassFreeConstraint";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOA;
    params.set<std::vector<dof_id_type>>("nodes") = _nodes;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    _sim.addConstraint(class_name, genName(name(), "ced_rho"), params);
  }
  {
    std::string class_name = "OldJunctionMomentumConstraint";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA;
    params.set<std::vector<dof_id_type>>("nodes") = _nodes;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<Real>>("K") = _k_coeffs;
    params.set<std::vector<Real>>("K_reverse") = _kr_coeffs;
    params.set<Real>("ref_area") = _ref_area;
    params.set<Real>("initial_rho") = initial_rho;
    params.set<UserObjectName>("fp") = _fp_name;
    params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name};
    params.set<std::vector<VariableName>>("total_int_energy_rate_in") = {
        _total_int_energy_rate_in_var_name};
    params.set<std::vector<VariableName>>("rhoA") = cv_rhoA;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA;
    params.set<std::vector<VariableName>>("rho") = cv_rho;
    params.set<std::vector<VariableName>>("vel") = cv_vel;
    params.set<std::vector<VariableName>>("A") = cv_area;
    params.set<std::vector<VariableName>>("p_junction") = cv_junction_pressure;
    _sim.addConstraint(class_name, genName(name(), "ced_rhou"), params);
  }

  {
    std::string class_name = "OldJunctionEnergyConstraint";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOEA;
    params.set<std::vector<dof_id_type>>("nodes") = _nodes;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<Real>>("K") = _k_coeffs;
    params.set<std::vector<Real>>("K_reverse") = _kr_coeffs;
    params.set<Real>("ref_area") = _ref_area;
    params.set<Real>("initial_rho") = initial_rho;
    params.set<UserObjectName>("fp") = _fp_name;
    params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name};
    params.set<std::vector<VariableName>>("total_int_energy_rate_in") = {
        _total_int_energy_rate_in_var_name};
    params.set<std::vector<VariableName>>("rhoA") = cv_rhoA;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA;
    params.set<std::vector<VariableName>>("rho") = cv_rho;
    params.set<std::vector<VariableName>>("vel") = cv_vel;
    params.set<std::vector<VariableName>>("A") = cv_area;
    params.set<std::vector<VariableName>>("p_junction") = cv_junction_pressure;
    params.set<std::vector<VariableName>>("energy_junction") = cv_junction_energy;
    _sim.addConstraint(class_name, genName(name(), "ced_rhoE"), params);
  }

  // add constraints
  {
    std::string class_name = "OldJunctionMassBalanceScalarKernel";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<NonlinearVariableName>("variable") = _pressure_var_name;

    params.set<std::vector<BoundaryName>>("boundary") = _boundary_names;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<VariableName>>("rhoA") = cv_rhoA;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;

    _sim.addScalarKernel(class_name, genName(name(), "mass_balance"), params);
  }
  {
    std::string class_name = "EnergyScalarKernel";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<NonlinearVariableName>("variable") = _energy_var_name;
    params.set<std::vector<BoundaryName>>("boundary") = _boundary_names;

    params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name};
    params.set<std::vector<VariableName>>("total_int_energy_rate_in") = {
        _total_int_energy_rate_in_var_name};
    params.set<std::vector<Real>>("normals") = _normals;

    params.set<std::vector<VariableName>>("rhoA") = cv_rhoA;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA;
    params.set<std::vector<VariableName>>("vel") = cv_vel;
    params.set<std::vector<VariableName>>("A") = cv_area;

    _sim.addScalarKernel(class_name, genName(name(), "energy_ced"), params);
  }
}
<commit_msg>Cleanup in OldJunction<commit_after>#include "OldJunction.h"
#include "SinglePhaseFluidProperties.h"
#include "FlowModelSinglePhase.h"

registerMooseObject("THMApp", OldJunction);

template <>
InputParameters
validParams<OldJunction>()
{
  InputParameters params = validParams<JunctionWithLossesBase>();
  params.addParam<Real>("initial_p", 1e5, "Initial pressure of this junction");
  params.addParam<Real>("initial_T", 300, "Initial temperature of this junction");
  params.addParam<Real>(
      "initial_alpha_vapor", 1., "Initial vapor volume fraction in the OldJunction");
  std::vector<Real> sf(2, 1.e0);
  params.addParam<std::vector<Real>>(
      "scaling_factors", sf, "Scaling factors for variables: pressure, energy");
  return params;
}

OldJunction::OldJunction(const InputParameters & params)
  : JunctionWithLossesBase(params),
    _pressure_var_name(genName(name(), "p")),
    _energy_var_name(genName(name(), "energy")),
    _initial_P(getParam<Real>("initial_p")),
    _initial_void_fraction(getParam<Real>("initial_alpha_vapor")),
    _total_mfr_in_var_name(genName(name(), "tmfri")),
    _total_int_energy_rate_in_var_name(genName(name(), "ntei")),
    _scaling_factors(getParam<std::vector<Real>>("scaling_factors"))
{
}

void
OldJunction::check() const
{
  JunctionWithLossesBase::check();

  if (_flow_model_id != THM::FM_SINGLE_PHASE)
    logModelNotImplementedError(_flow_model_id);

  checkSizeEqualsValue<Real>("scaling_factors", 2);
}

void
OldJunction::addVariables()
{
  auto connected_subdomains = getConnectedSubdomainIDs();

  _sim.addVariable(
      true, _pressure_var_name, FEType(FIRST, SCALAR), connected_subdomains, _scaling_factors[0]);
  _sim.addConstantScalarIC(_pressure_var_name, _initial_P);

  const SinglePhaseFluidProperties & spfp =
      _sim.getUserObject<SinglePhaseFluidProperties>(_fp_name);
  Real initial_T = getParam<Real>("initial_T");
  Real initial_rho = spfp.rho_from_p_T(_initial_P, initial_T);
  Real initial_e = spfp.e_from_p_rho(_initial_P, initial_rho);

  _sim.addVariable(
      true, _energy_var_name, FEType(FIRST, SCALAR), connected_subdomains, _scaling_factors[1]);
  _sim.addConstantScalarIC(_energy_var_name, initial_e);

  _sim.addVariable(false, _total_mfr_in_var_name, FEType(FIRST, SCALAR), 0);
  _sim.addConstantScalarIC(_total_mfr_in_var_name, 0);

  _sim.addVariable(false, _total_int_energy_rate_in_var_name, FEType(FIRST, SCALAR), 0);
  _sim.addConstantScalarIC(_total_int_energy_rate_in_var_name, 0);
}

void
OldJunction::addMooseObjects()
{
  std::vector<VariableName> cv_vel(1, FlowModelSinglePhase::VELOCITY);
  std::vector<VariableName> cv_pressure(1, FlowModelSinglePhase::PRESSURE);
  std::vector<VariableName> cv_rho(1, FlowModelSinglePhase::DENSITY);
  std::vector<VariableName> cv_rhoA(1, FlowModelSinglePhase::RHOA);
  std::vector<VariableName> cv_rhouA(1, FlowModelSinglePhase::RHOUA);
  std::vector<VariableName> cv_rhoEA(1, FlowModelSinglePhase::RHOEA);
  std::vector<VariableName> cv_enthalpy(1, FlowModelSinglePhase::SPECIFIC_TOTAL_ENTHALPY);
  std::vector<VariableName> cv_area(1, FlowModelSinglePhase::AREA);
  std::vector<VariableName> cv_junction_pressure(1, _pressure_var_name);
  std::vector<VariableName> cv_junction_energy(1, _energy_var_name);

  std::vector<OutputName> outputs = _sim.getOutputsVector("none");

  const SinglePhaseFluidProperties & spfp =
      _sim.getUserObject<SinglePhaseFluidProperties>(_fp_name);
  Real initial_T = getParam<Real>("initial_T");
  Real initial_rho = spfp.rho_from_p_T(_initial_P, initial_T);

  {
    std::string class_name = "TotalMassFlowRateIntoJunctionAux";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<AuxVariableName>("variable") = _total_mfr_in_var_name;
    params.set<std::vector<dof_id_type>>("nodes") = _nodes;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    _sim.addAuxScalarKernel(class_name, genName(name(), "total_mfr_in"), params);
  }

  {
    std::string class_name = "TotalInternalEnergyRateIntoJunctionAux";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<AuxVariableName>("variable") = _total_int_energy_rate_in_var_name;
    params.set<std::vector<dof_id_type>>("nodes") = _nodes;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<VariableName>>("rhoA") = cv_rhoA;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA;
    _sim.addAuxScalarKernel(class_name, genName(name(), "total_int_energy_rate_in"), params);
  }

  {
    std::string class_name = "MassFreeConstraint";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOA;
    params.set<std::vector<dof_id_type>>("nodes") = _nodes;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    _sim.addConstraint(class_name, genName(name(), "ced_rho"), params);
  }
  {
    std::string class_name = "OldJunctionMomentumConstraint";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA;
    params.set<std::vector<dof_id_type>>("nodes") = _nodes;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<Real>>("K") = _k_coeffs;
    params.set<std::vector<Real>>("K_reverse") = _kr_coeffs;
    params.set<Real>("ref_area") = _ref_area;
    params.set<Real>("initial_rho") = initial_rho;
    params.set<UserObjectName>("fp") = _fp_name;
    params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name};
    params.set<std::vector<VariableName>>("total_int_energy_rate_in") = {
        _total_int_energy_rate_in_var_name};
    params.set<std::vector<VariableName>>("rhoA") = cv_rhoA;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA;
    params.set<std::vector<VariableName>>("rho") = cv_rho;
    params.set<std::vector<VariableName>>("vel") = cv_vel;
    params.set<std::vector<VariableName>>("A") = cv_area;
    params.set<std::vector<VariableName>>("p_junction") = cv_junction_pressure;
    _sim.addConstraint(class_name, genName(name(), "ced_rhou"), params);
  }

  {
    std::string class_name = "OldJunctionEnergyConstraint";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOEA;
    params.set<std::vector<dof_id_type>>("nodes") = _nodes;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<Real>>("K") = _k_coeffs;
    params.set<std::vector<Real>>("K_reverse") = _kr_coeffs;
    params.set<Real>("ref_area") = _ref_area;
    params.set<Real>("initial_rho") = initial_rho;
    params.set<UserObjectName>("fp") = _fp_name;
    params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name};
    params.set<std::vector<VariableName>>("total_int_energy_rate_in") = {
        _total_int_energy_rate_in_var_name};
    params.set<std::vector<VariableName>>("rhoA") = cv_rhoA;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA;
    params.set<std::vector<VariableName>>("rho") = cv_rho;
    params.set<std::vector<VariableName>>("vel") = cv_vel;
    params.set<std::vector<VariableName>>("A") = cv_area;
    params.set<std::vector<VariableName>>("p_junction") = cv_junction_pressure;
    params.set<std::vector<VariableName>>("energy_junction") = cv_junction_energy;
    _sim.addConstraint(class_name, genName(name(), "ced_rhoE"), params);
  }

  // add constraints
  {
    std::string class_name = "OldJunctionMassBalanceScalarKernel";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<NonlinearVariableName>("variable") = _pressure_var_name;

    params.set<std::vector<BoundaryName>>("boundary") = _boundary_names;
    params.set<std::vector<Real>>("normals") = _normals;
    params.set<std::vector<VariableName>>("rhoA") = cv_rhoA;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;

    _sim.addScalarKernel(class_name, genName(name(), "mass_balance"), params);
  }
  {
    std::string class_name = "EnergyScalarKernel";
    InputParameters params = _factory.getValidParams(class_name);
    params.set<NonlinearVariableName>("variable") = _energy_var_name;
    params.set<std::vector<BoundaryName>>("boundary") = _boundary_names;

    params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name};
    params.set<std::vector<VariableName>>("total_int_energy_rate_in") = {
        _total_int_energy_rate_in_var_name};
    params.set<std::vector<Real>>("normals") = _normals;

    params.set<std::vector<VariableName>>("rhoA") = cv_rhoA;
    params.set<std::vector<VariableName>>("rhouA") = cv_rhouA;
    params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA;
    params.set<std::vector<VariableName>>("vel") = cv_vel;
    params.set<std::vector<VariableName>>("A") = cv_area;

    _sim.addScalarKernel(class_name, genName(name(), "energy_ced"), params);
  }
}
<|endoftext|>


<commit_before>/*************************************************
* Pooling Allocator Source File                  *
* (C) 1999-2007 The Botan Project                *
*************************************************/

#include <botan/mem_pool.h>
#include <botan/libstate.h>
#include <botan/config.h>
#include <botan/bit_ops.h>
#include <botan/util.h>
#include <algorithm>

namespace Botan {

namespace {

/*************************************************
* Decide how much memory to allocate at once     *
*************************************************/
u32bit choose_pref_size(u32bit provided)
   {
   if(provided)
      return provided;

   u32bit result = global_config().option_as_u32bit("base/memory_chunk");
   if(result)
      return result;

   return 16*1024;
   }

}

/*************************************************
* Memory_Block Constructor                       *
*************************************************/
Pooling_Allocator::Memory_Block::Memory_Block(void* buf)
   {
   buffer = static_cast<byte*>(buf);
   bitmap = 0;
   buffer_end = buffer + (BLOCK_SIZE * BITMAP_SIZE);
   }

/*************************************************
* Compare a Memory_Block with a void pointer     *
*************************************************/
inline bool Pooling_Allocator::Memory_Block::operator<(const void* other) const
   {
   if(buffer <= other && other < buffer_end)
      return false;
   return (buffer < other);
   }

/*************************************************
* See if ptr is contained by this block          *
*************************************************/
bool Pooling_Allocator::Memory_Block::contains(void* ptr,
                                               u32bit length) const throw()
   {
   return ((buffer <= ptr) &&
           (buffer_end >= (byte*)ptr + length * BLOCK_SIZE));
   }

/*************************************************
* Allocate some memory, if possible              *
*************************************************/
byte* Pooling_Allocator::Memory_Block::alloc(u32bit n) throw()
   {
   if(n == 0 || n > BITMAP_SIZE)
      return 0;

   if(n == BITMAP_SIZE)
      {
      if(bitmap)
         return 0;
      else
         {
         bitmap = ~bitmap;
         return buffer;
         }
      }

   bitmap_type mask = ((bitmap_type)1 << n) - 1;
   u32bit offset = 0;

   while(bitmap & mask)
      {
      mask <<= 1;
      ++offset;

      if((bitmap & mask) == 0)
         break;
      if(mask >> 63)
         break;
      }

   if(bitmap & mask)
      return 0;

   bitmap |= mask;
   return buffer + offset * BLOCK_SIZE;
   }

/*************************************************
* Mark this memory as free, if we own it         *
*************************************************/
void Pooling_Allocator::Memory_Block::free(void* ptr, u32bit blocks) throw()
   {
   clear_mem((byte*)ptr, blocks * BLOCK_SIZE);

   const u32bit offset = ((byte*)ptr - buffer) / BLOCK_SIZE;

   if(offset == 0 && blocks == BITMAP_SIZE)
      bitmap = ~bitmap;
   else
      {
      for(u32bit j = 0; j != blocks; ++j)
         bitmap &= ~((bitmap_type)1 << (j+offset));
      }
   }

/*************************************************
* Pooling_Allocator Constructor                  *
*************************************************/
Pooling_Allocator::Pooling_Allocator(u32bit p_size, bool) :
   PREF_SIZE(choose_pref_size(p_size))
   {
   mutex = global_state().get_mutex();
   last_used = blocks.begin();
   }

/*************************************************
* Pooling_Allocator Destructor                   *
*************************************************/
Pooling_Allocator::~Pooling_Allocator()
   {
   delete mutex;
   if(blocks.size())
      throw Invalid_State("Pooling_Allocator: Never released memory");
   }

/*************************************************
* Free all remaining memory                      *
*************************************************/
void Pooling_Allocator::destroy()
   {
   Mutex_Holder lock(mutex);

   blocks.clear();

   for(u32bit j = 0; j != allocated.size(); ++j)
      dealloc_block(allocated[j].first, allocated[j].second);
   allocated.clear();
   }

/*************************************************
* Allocation                                     *
*************************************************/
void* Pooling_Allocator::allocate(u32bit n)
   {
   const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
   const u32bit BLOCK_SIZE = Memory_Block::block_size();

   Mutex_Holder lock(mutex);

   if(n <= BITMAP_SIZE * BLOCK_SIZE)
      {
      const u32bit block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE;

      byte* mem = allocate_blocks(block_no);
      if(mem)
         return mem;

      get_more_core(PREF_SIZE);

      mem = allocate_blocks(block_no);
      if(mem)
         return mem;

      throw Memory_Exhaustion();
      }

   void* new_buf = alloc_block(n);
   if(new_buf)
      return new_buf;

   throw Memory_Exhaustion();
   }

/*************************************************
* Deallocation                                   *
*************************************************/
void Pooling_Allocator::deallocate(void* ptr, u32bit n)
   {
   const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
   const u32bit BLOCK_SIZE = Memory_Block::block_size();

   if(ptr == 0 && n == 0)
      return;

   Mutex_Holder lock(mutex);

   if(n > BITMAP_SIZE * BLOCK_SIZE)
      dealloc_block(ptr, n);
   else
      {
      const u32bit block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE;

      std::vector<Memory_Block>::iterator i =
         std::lower_bound(blocks.begin(), blocks.end(), ptr);

      if(i == blocks.end() || !i->contains(ptr, block_no))
         throw Invalid_State("Pointer released to the wrong allocator");

      i->free(ptr, block_no);
      }
   }

/*************************************************
* Try to get some memory from an existing block  *
*************************************************/
byte* Pooling_Allocator::allocate_blocks(u32bit n)
   {
   if(blocks.empty())
      return 0;

   std::vector<Memory_Block>::iterator i = last_used;

   do
      {
      byte* mem = i->alloc(n);
      if(mem)
         {
         last_used = i;
         return mem;
         }

      ++i;
      if(i == blocks.end())
         i = blocks.begin();
      }
   while(i != last_used);

   return 0;
   }

/*************************************************
* Allocate more memory for the pool              *
*************************************************/
void Pooling_Allocator::get_more_core(u32bit in_bytes)
   {
   const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
   const u32bit BLOCK_SIZE = Memory_Block::block_size();

   const u32bit TOTAL_BLOCK_SIZE = BLOCK_SIZE * BITMAP_SIZE;

   const u32bit in_blocks = round_up(in_bytes, BLOCK_SIZE) / TOTAL_BLOCK_SIZE;
   const u32bit to_allocate = in_blocks * TOTAL_BLOCK_SIZE;

   void* ptr = alloc_block(to_allocate);
   if(ptr == 0)
      throw Memory_Exhaustion();

   allocated.push_back(std::make_pair(ptr, to_allocate));

   for(u32bit j = 0; j != in_blocks; ++j)
      {
      byte* byte_ptr = static_cast<byte*>(ptr);
      blocks.push_back(Memory_Block(byte_ptr + j * TOTAL_BLOCK_SIZE));
      }

   std::sort(blocks.begin(), blocks.end());
   last_used = std::lower_bound(blocks.begin(), blocks.end(), ptr);
   }

}
<commit_msg>Fixes for Visual C++ 2005; it wasn't picking up the needed conversion from a void* to a Memory_Block, so call the constructor explicitly.<commit_after>/*************************************************
* Pooling Allocator Source File                  *
* (C) 1999-2007 The Botan Project                *
*************************************************/

#include <botan/mem_pool.h>
#include <botan/libstate.h>
#include <botan/config.h>
#include <botan/bit_ops.h>
#include <botan/util.h>
#include <algorithm>

namespace Botan {

namespace {

/*************************************************
* Decide how much memory to allocate at once     *
*************************************************/
u32bit choose_pref_size(u32bit provided)
   {
   if(provided)
      return provided;

   u32bit result = global_config().option_as_u32bit("base/memory_chunk");
   if(result)
      return result;

   return 16*1024;
   }

}

/*************************************************
* Memory_Block Constructor                       *
*************************************************/
Pooling_Allocator::Memory_Block::Memory_Block(void* buf)
   {
   buffer = static_cast<byte*>(buf);
   bitmap = 0;
   buffer_end = buffer + (BLOCK_SIZE * BITMAP_SIZE);
   }

/*************************************************
* Compare a Memory_Block with a void pointer     *
*************************************************/
inline bool Pooling_Allocator::Memory_Block::operator<(const void* other) const
   {
   if(buffer <= other && other < buffer_end)
      return false;
   return (buffer < other);
   }

/*************************************************
* See if ptr is contained by this block          *
*************************************************/
bool Pooling_Allocator::Memory_Block::contains(void* ptr,
                                               u32bit length) const throw()
   {
   return ((buffer <= ptr) &&
           (buffer_end >= (byte*)ptr + length * BLOCK_SIZE));
   }

/*************************************************
* Allocate some memory, if possible              *
*************************************************/
byte* Pooling_Allocator::Memory_Block::alloc(u32bit n) throw()
   {
   if(n == 0 || n > BITMAP_SIZE)
      return 0;

   if(n == BITMAP_SIZE)
      {
      if(bitmap)
         return 0;
      else
         {
         bitmap = ~bitmap;
         return buffer;
         }
      }

   bitmap_type mask = ((bitmap_type)1 << n) - 1;
   u32bit offset = 0;

   while(bitmap & mask)
      {
      mask <<= 1;
      ++offset;

      if((bitmap & mask) == 0)
         break;
      if(mask >> 63)
         break;
      }

   if(bitmap & mask)
      return 0;

   bitmap |= mask;
   return buffer + offset * BLOCK_SIZE;
   }

/*************************************************
* Mark this memory as free, if we own it         *
*************************************************/
void Pooling_Allocator::Memory_Block::free(void* ptr, u32bit blocks) throw()
   {
   clear_mem((byte*)ptr, blocks * BLOCK_SIZE);

   const u32bit offset = ((byte*)ptr - buffer) / BLOCK_SIZE;

   if(offset == 0 && blocks == BITMAP_SIZE)
      bitmap = ~bitmap;
   else
      {
      for(u32bit j = 0; j != blocks; ++j)
         bitmap &= ~((bitmap_type)1 << (j+offset));
      }
   }

/*************************************************
* Pooling_Allocator Constructor                  *
*************************************************/
Pooling_Allocator::Pooling_Allocator(u32bit p_size, bool) :
   PREF_SIZE(choose_pref_size(p_size))
   {
   mutex = global_state().get_mutex();
   last_used = blocks.begin();
   }

/*************************************************
* Pooling_Allocator Destructor                   *
*************************************************/
Pooling_Allocator::~Pooling_Allocator()
   {
   delete mutex;
   if(blocks.size())
      throw Invalid_State("Pooling_Allocator: Never released memory");
   }

/*************************************************
* Free all remaining memory                      *
*************************************************/
void Pooling_Allocator::destroy()
   {
   Mutex_Holder lock(mutex);

   blocks.clear();

   for(u32bit j = 0; j != allocated.size(); ++j)
      dealloc_block(allocated[j].first, allocated[j].second);
   allocated.clear();
   }

/*************************************************
* Allocation                                     *
*************************************************/
void* Pooling_Allocator::allocate(u32bit n)
   {
   const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
   const u32bit BLOCK_SIZE = Memory_Block::block_size();

   Mutex_Holder lock(mutex);

   if(n <= BITMAP_SIZE * BLOCK_SIZE)
      {
      const u32bit block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE;

      byte* mem = allocate_blocks(block_no);
      if(mem)
         return mem;

      get_more_core(PREF_SIZE);

      mem = allocate_blocks(block_no);
      if(mem)
         return mem;

      throw Memory_Exhaustion();
      }

   void* new_buf = alloc_block(n);
   if(new_buf)
      return new_buf;

   throw Memory_Exhaustion();
   }

/*************************************************
* Deallocation                                   *
*************************************************/
void Pooling_Allocator::deallocate(void* ptr, u32bit n)
   {
   const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
   const u32bit BLOCK_SIZE = Memory_Block::block_size();

   if(ptr == 0 && n == 0)
      return;

   Mutex_Holder lock(mutex);

   if(n > BITMAP_SIZE * BLOCK_SIZE)
      dealloc_block(ptr, n);
   else
      {
      const u32bit block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE;

      std::vector<Memory_Block>::iterator i =
         std::lower_bound(blocks.begin(), blocks.end(), Memory_Block(ptr));

      if(i == blocks.end() || !i->contains(ptr, block_no))
         throw Invalid_State("Pointer released to the wrong allocator");

      i->free(ptr, block_no);
      }
   }

/*************************************************
* Try to get some memory from an existing block  *
*************************************************/
byte* Pooling_Allocator::allocate_blocks(u32bit n)
   {
   if(blocks.empty())
      return 0;

   std::vector<Memory_Block>::iterator i = last_used;

   do
      {
      byte* mem = i->alloc(n);
      if(mem)
         {
         last_used = i;
         return mem;
         }

      ++i;
      if(i == blocks.end())
         i = blocks.begin();
      }
   while(i != last_used);

   return 0;
   }

/*************************************************
* Allocate more memory for the pool              *
*************************************************/
void Pooling_Allocator::get_more_core(u32bit in_bytes)
   {
   const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
   const u32bit BLOCK_SIZE = Memory_Block::block_size();

   const u32bit TOTAL_BLOCK_SIZE = BLOCK_SIZE * BITMAP_SIZE;

   const u32bit in_blocks = round_up(in_bytes, BLOCK_SIZE) / TOTAL_BLOCK_SIZE;
   const u32bit to_allocate = in_blocks * TOTAL_BLOCK_SIZE;

   void* ptr = alloc_block(to_allocate);
   if(ptr == 0)
      throw Memory_Exhaustion();

   allocated.push_back(std::make_pair(ptr, to_allocate));

   for(u32bit j = 0; j != in_blocks; ++j)
      {
      byte* byte_ptr = static_cast<byte*>(ptr);
      blocks.push_back(Memory_Block(byte_ptr + j * TOTAL_BLOCK_SIZE));
      }

   std::sort(blocks.begin(), blocks.end());
   last_used = std::lower_bound(blocks.begin(), blocks.end(),
                                Memory_Block(ptr));
   }

}
<|endoftext|>