<commit_before>// Open the mesh and solution file named in command line arguments,
// and plot them out to the given filename.

#include "libmesh/libmesh.h"

#include "libmesh/mesh.h"
#include "libmesh/equation_systems.h"

#include "libmesh/exodusII_io.h"
#include "libmesh/gmsh_io.h"
#include "libmesh/gmv_io.h"
#include "libmesh/gnuplot_io.h"
#include "libmesh/medit_io.h"
#include "libmesh/nemesis_io.h"
#include "libmesh/tecplot_io.h"
#include "libmesh/vtk_io.h"

int main(int argc, char** argv)
{
  using namespace libMesh;

  LibMeshInit init(argc, argv);

  Mesh mesh(init.comm());
  EquationSystems es(mesh);

  libMesh::out << "Usage: " << argv[0]
            << " inputmesh inputsolution outputplot" << std::endl;

  START_LOG("mesh.read()", "main");
  mesh.read(argv[1]);
  libMesh::out << "Loaded mesh " << argv[1] << std::endl;
  STOP_LOG("mesh.read()", "main");

  START_LOG("es.read()", "main");
  std::string solnname = argv[2];

  es.read(argv[2],
          EquationSystems::READ_HEADER |
          EquationSystems::READ_DATA |
          EquationSystems::READ_ADDITIONAL_DATA |
          EquationSystems::READ_BASIC_ONLY);
  libMesh::out << "Loaded solution " << argv[2] << std::endl;
  STOP_LOG("es.read()", "main");

  START_LOG("write_equation_systems()", "main");
  std::string outputname(argv[3]);

  if (outputname.find(".gnuplot") != std::string::npos)
    GnuPlotIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".gmv") != std::string::npos)
    GMVIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".mesh") != std::string::npos)
    MEDITIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".msh") != std::string::npos)
    GmshIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".plt") != std::string::npos)
    TecplotIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".vtu") != std::string::npos)
    VTKIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".e") != std::string::npos)
    ExodusII_IO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".n") != std::string::npos)
    Nemesis_IO(mesh).write_equation_systems (outputname, es);

  STOP_LOG("write_equation_systems()", "main");
  libMesh::out << "Wrote output " << argv[3] << std::endl;
}
<commit_msg>Make meshplot a bit more verbose<commit_after>// Open the mesh and solution file named in command line arguments,
// and plot them out to the given filename.

#include "libmesh/libmesh.h"

#include "libmesh/mesh.h"
#include "libmesh/equation_systems.h"

#include "libmesh/exodusII_io.h"
#include "libmesh/gmsh_io.h"
#include "libmesh/gmv_io.h"
#include "libmesh/gnuplot_io.h"
#include "libmesh/medit_io.h"
#include "libmesh/nemesis_io.h"
#include "libmesh/tecplot_io.h"
#include "libmesh/vtk_io.h"

int main(int argc, char** argv)
{
  using namespace libMesh;

  LibMeshInit init(argc, argv);

  Mesh mesh(init.comm());
  EquationSystems es(mesh);

  libMesh::out << "Usage: " << argv[0]
            << " inputmesh inputsolution outputplot" << std::endl;

  START_LOG("mesh.read()", "main");
  mesh.read(argv[1]);
  STOP_LOG("mesh.read()", "main");
  libMesh::out << "Loaded mesh " << argv[1] << std::endl;
  mesh.print_info();

  START_LOG("es.read()", "main");
  std::string solnname = argv[2];

  es.read(argv[2],
          EquationSystems::READ_HEADER |
          EquationSystems::READ_DATA |
          EquationSystems::READ_ADDITIONAL_DATA |
          EquationSystems::READ_BASIC_ONLY);
  STOP_LOG("es.read()", "main");
  libMesh::out << "Loaded solution " << argv[2] << std::endl;
  es.print_info();

  START_LOG("write_equation_systems()", "main");
  std::string outputname(argv[3]);

  if (outputname.find(".gnuplot") != std::string::npos)
    GnuPlotIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".gmv") != std::string::npos)
    GMVIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".mesh") != std::string::npos)
    MEDITIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".msh") != std::string::npos)
    GmshIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".plt") != std::string::npos)
    TecplotIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".vtu") != std::string::npos)
    VTKIO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".e") != std::string::npos)
    ExodusII_IO(mesh).write_equation_systems (outputname, es);
  else if (outputname.find(".n") != std::string::npos)
    Nemesis_IO(mesh).write_equation_systems (outputname, es);

  STOP_LOG("write_equation_systems()", "main");
  libMesh::out << "Wrote output " << argv[3] << std::endl;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#ifndef MFEM_COEFFICIENT
#define MFEM_COEFFICIENT

#include "../config/config.hpp"
#include "../linalg/linalg.hpp"
#include "intrules.hpp"
#include "eltrans.hpp"

namespace mfem
{

class Mesh;

#ifdef MFEM_USE_MPI
class ParMesh;
#endif

/// Base class Coefficient that may optionally depend on time.
class Coefficient
{
protected:
   double time;

public:
   Coefficient() { time = 0.; }

   void SetTime(double t) { time = t; }
   double GetTime() { return time; }

   virtual double Eval(ElementTransformation &T,
                       const IntegrationPoint &ip) = 0;

   double Eval(ElementTransformation &T,
               const IntegrationPoint &ip, double t)
   {
      SetTime(t);
      return Eval(T, ip);
   }

   virtual ~Coefficient() { }
};

/// Subclass constant coefficient.
class ConstantCoefficient : public Coefficient
{
public:
   double constant;

   /// c is value of constant function
   explicit ConstantCoefficient(double c = 1.0) { constant=c; }

   /// Evaluate the coefficient
   virtual double Eval(ElementTransformation &T,
                       const IntegrationPoint &ip)
   { return (constant); }
};

/// class for piecewise constant coefficient
class PWConstCoefficient : public Coefficient
{
private:
   Vector constants;

public:

   /// Constructs a piecewise constant coefficient in NumOfSubD subdomains
   explicit PWConstCoefficient(int NumOfSubD = 0) : constants(NumOfSubD)
   { constants = 0.0; }

   /** c should be a vector defined by attributes, so for region with
       attribute i  c[i] is the coefficient in that region */
   PWConstCoefficient(Vector &c)
   { constants.SetSize(c.Size()); constants=c; }

   /// Member function to access or modify the value of the i-th constant
   double &operator()(int i) { return constants(i-1); }

   /// Set domain constants equal to the same constant c
   void operator=(double c) { constants = c; }

   /// Returns the number of constants
   int GetNConst() { return constants.Size(); }

   /// Evaluate the coefficient function
   virtual double Eval(ElementTransformation &T,
                       const IntegrationPoint &ip);
};

/// class for C-function coefficient
class FunctionCoefficient : public Coefficient
{
protected:
   double (*Function)(const Vector &);
   double (*TDFunction)(const Vector &, double);

public:
   /// Define a time-independent coefficient from a C-function
   FunctionCoefficient(double (*f)(const Vector &))
   {
      Function = f;
      TDFunction = NULL;
   }

   /// Define a time-dependent coefficient from a C-function
   FunctionCoefficient(double (*tdf)(const Vector &, double))
   {
      Function = NULL;
      TDFunction = tdf;
   }

   /// (DEPRECATED) Define a time-independent coefficient from a C-function
   FunctionCoefficient(double (*f)(Vector &))
   {
      Function = reinterpret_cast<double(*)(const Vector&)>(f);
      TDFunction = NULL;
   }

   /// (DEPRECATED) Define a time-dependent coefficient from a C-function
   FunctionCoefficient(double (*tdf)(Vector &, double))
   {
      Function = NULL;
      TDFunction = reinterpret_cast<double(*)(const Vector&,double)>(tdf);
   }

   /// Evaluate coefficient
   virtual double Eval(ElementTransformation &T,
                       const IntegrationPoint &ip);
};

class GridFunction;

/// Coefficient defined by a GridFunction. This coefficient is mesh dependent.
class GridFunctionCoefficient : public Coefficient
{
private:
   GridFunction *GridF;
   int Component;

public:
   /** Construct GridFunctionCoefficient from a given GridFunction
       and optionally which component to use if it is a vector
       gridfunction. */
   GridFunctionCoefficient (GridFunction *gf, int comp = 1)
   { GridF = gf; Component = comp; }

   void SetGridFunction(GridFunction *gf) { GridF = gf; }
   GridFunction * GetGridFunction() const { return GridF; }

   virtual double Eval(ElementTransformation &T,
                       const IntegrationPoint &ip);
};

class TransformedCoefficient : public Coefficient
{
private:
   Coefficient * Q1;
   Coefficient * Q2;
   double (*Transform1)(double);
   double (*Transform2)(double,double);

public:
   TransformedCoefficient (Coefficient * q,double (*F)(double))
      : Q1(q), Transform1(F) { Q2 = 0; Transform2 = 0; }
   TransformedCoefficient (Coefficient * q1,Coefficient * q2,
                           double (*F)(double,double))
      : Q1(q1), Q2(q2), Transform2(F) { Transform1 = 0; }

   virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip);
};

/// Delta function coefficient
class DeltaCoefficient : public Coefficient
{
private:
   double center[3], scale, tol;
   Coefficient *weight;

public:
   DeltaCoefficient();
   DeltaCoefficient(double x, double y, double s)
   {
      center[0] = x; center[1] = y; center[2] = 0.; scale = s; tol = 1e-12;
      weight = NULL;
   }
   DeltaCoefficient(double x, double y, double z, double s)
   {
      center[0] = x; center[1] = y; center[2] = z; scale = s; tol = 1e-12;
      weight = NULL;
   }
   void SetTol(double _tol) { tol = _tol; }
   void SetWeight(Coefficient *w) { weight = w; }
   const double *Center() { return center; }
   double Scale() { return scale; }
   double Tol() { return tol; }
   Coefficient *Weight() { return weight; }
   virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)
   { mfem_error("DeltaCoefficient::Eval"); return 0.; }
   virtual ~DeltaCoefficient() { delete weight; }
};

/// Coefficient defined on a subset of domain or boundary attributes
class RestrictedCoefficient : public Coefficient
{
private:
   Coefficient *c;
   Array<int> active_attr;

public:
   RestrictedCoefficient(Coefficient &_c, Array<int> &attr)
   { c = &_c; attr.Copy(active_attr); }

   virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)
   { return active_attr[T.Attribute-1] ? c->Eval(T, ip, GetTime()) : 0.0; }
};

class VectorCoefficient
{
protected:
   int vdim;
   double time;

public:
   VectorCoefficient(int vd) { vdim = vd; time = 0.; }

   void SetTime(double t) { time = t; }
   double GetTime() { return time; }

   /// Returns dimension of the vector.
   int GetVDim() { return vdim; }

   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip) = 0;

   // General implementation using the Eval method for one IntegrationPoint.
   // Can be overloaded for more efficient implementation.
   virtual void Eval(DenseMatrix &M, ElementTransformation &T,
                     const IntegrationRule &ir);

   virtual ~VectorCoefficient() { }
};

class VectorConstantCoefficient : public VectorCoefficient
{
private:
   Vector vec;
public:
   VectorConstantCoefficient(const Vector &v)
      : VectorCoefficient(v.Size()), vec(v) { }
   using VectorCoefficient::Eval;
   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip) { V = vec; }
};

class VectorFunctionCoefficient : public VectorCoefficient
{
private:
   void (*Function)(const Vector &, Vector &);
   void (*TDFunction)(const Vector &, double, Vector &);
   Coefficient *Q;

public:
   /// Construct a time-independent vector coefficient from a C-function
   VectorFunctionCoefficient(int dim, void (*F)(const Vector &, Vector &),
                             Coefficient *q = NULL)
      : VectorCoefficient(dim), Q(q)
   {
      Function = F;
      TDFunction = NULL;
   }

   /// Construct a time-dependent vector coefficient from a C-function
   VectorFunctionCoefficient(int dim,
                             void (*TDF)(const Vector &, double, Vector &),
                             Coefficient *q = NULL)
      : VectorCoefficient(dim), Q(q)
   {
      Function = NULL;
      TDFunction = TDF;
   }

   using VectorCoefficient::Eval;
   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip);

   virtual ~VectorFunctionCoefficient() { }
};

/// Vector coefficient defined by an array of scalar coefficients.
class VectorArrayCoefficient : public VectorCoefficient
{
private:
   Array<Coefficient*> Coeff;

public:
   /// Construct vector of dim coefficients.
   explicit VectorArrayCoefficient(int dim);

   /// Returns i'th coefficient.
   Coefficient &GetCoeff(int i) { return *Coeff[i]; }

   Coefficient **GetCoeffs() { return Coeff; }

   /// Sets coefficient in the vector.
   void Set(int i, Coefficient *c) { Coeff[i] = c; }

   /// Evaluates i'th component of the vector.
   double Eval(int i, ElementTransformation &T, IntegrationPoint &ip)
   { return Coeff[i]->Eval(T, ip, GetTime()); }

   using VectorCoefficient::Eval;
   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip);

   /// Destroys vector coefficient.
   virtual ~VectorArrayCoefficient();
};

/// Vector coefficient defined by a vector GridFunction
class VectorGridFunctionCoefficient : public VectorCoefficient
{
private:
   GridFunction *GridFunc;

public:
   VectorGridFunctionCoefficient(GridFunction *gf);

   void SetGridFunction(GridFunction *gf) { GridFunc = gf; }
   GridFunction * GetGridFunction() const { return GridFunc; }

   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip);

   virtual void Eval(DenseMatrix &M, ElementTransformation &T,
                     const IntegrationRule &ir);

   virtual ~VectorGridFunctionCoefficient() { }
};

/// VectorCoefficient defined on a subset of domain or boundary attributes
class VectorRestrictedCoefficient : public VectorCoefficient
{
private:
   VectorCoefficient *c;
   Array<int> active_attr;

public:
   VectorRestrictedCoefficient(VectorCoefficient &vc, Array<int> &attr)
      : VectorCoefficient(vc.GetVDim())
   { c = &vc; attr.Copy(active_attr); }

   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip);

   virtual void Eval(DenseMatrix &M, ElementTransformation &T,
                     const IntegrationRule &ir);
};

class MatrixCoefficient
{
protected:
   int vdim;
   double time;

public:
   explicit MatrixCoefficient(int dim) { vdim = dim; time = 0.; }

   void SetTime(double t) { time = t; }
   double GetTime() { return time; }

   int GetVDim() { return vdim; }

   virtual void Eval(DenseMatrix &K, ElementTransformation &T,
                     const IntegrationPoint &ip) = 0;

   virtual ~MatrixCoefficient() { }
};

class MatrixConstantCoefficient : public MatrixCoefficient
{
private:
   DenseMatrix mat;
public:
   MatrixConstantCoefficient(const DenseMatrix &m)
      : MatrixCoefficient(m.Size()), mat(m) { }
   using MatrixCoefficient::Eval;
   virtual void Eval(DenseMatrix &M, ElementTransformation &T,
                     const IntegrationPoint &ip) { M = mat; }
};

class MatrixFunctionCoefficient : public MatrixCoefficient
{
private:
   void (*Function)(const Vector &, DenseMatrix &);
   void (*TDFunction)(const Vector &, double, DenseMatrix &);
   Coefficient *Q;
   DenseMatrix mat;

public:
   /// Construct a time-independent matrix coefficient from a C-function
   MatrixFunctionCoefficient(int dim, void (*F)(const Vector &, DenseMatrix &),
                             Coefficient *q = NULL)
      : MatrixCoefficient(dim), Q(q)
   {
      Function = F;
      TDFunction = NULL;
      mat.SetSize(0);
   }

   /// Construct a vector coefficient from a scalar coefficient
   MatrixFunctionCoefficient(const DenseMatrix &m, Coefficient &q)
      : MatrixCoefficient(m.Size()), Q(&q)
   {
      Function = NULL;
      TDFunction = NULL;
      mat = m;
   }

   /// Construct a time-dependent matrix coefficient from a C-function
   MatrixFunctionCoefficient(int dim,
                             void (*TDF)(const Vector &, double, DenseMatrix &),
                             Coefficient *q = NULL)
      : MatrixCoefficient(dim), Q(q)
   {
      Function = NULL;
      TDFunction = TDF;
      mat.SetSize(0);
   }

   virtual void Eval(DenseMatrix &K, ElementTransformation &T,
                     const IntegrationPoint &ip);

   virtual ~MatrixFunctionCoefficient() { }
};

class MatrixArrayCoefficient : public MatrixCoefficient
{
private:
   Array<Coefficient *> Coeff;

public:

   explicit MatrixArrayCoefficient (int dim);

   Coefficient &GetCoeff (int i, int j) { return *Coeff[i*vdim+j]; }

   void Set(int i, int j, Coefficient * c) { Coeff[i*vdim+j] = c; }

   double Eval(int i, int j, ElementTransformation &T, IntegrationPoint &ip)
   { return Coeff[i*vdim+j] -> Eval(T, ip, GetTime()); }

   virtual void Eval(DenseMatrix &K, ElementTransformation &T,
                     const IntegrationPoint &ip);

   virtual ~MatrixArrayCoefficient();
};

/// MatrixCoefficient defined on a subset of domain or boundary attributes
class MatrixRestrictedCoefficient : public MatrixCoefficient
{
private:
   MatrixCoefficient *c;
   Array<int> active_attr;

public:
   MatrixRestrictedCoefficient(MatrixCoefficient &mc, Array<int> &attr)
      : MatrixCoefficient(mc.GetVDim())
   { c = &mc; attr.Copy(active_attr); }

   virtual void Eval(DenseMatrix &K, ElementTransformation &T,
                     const IntegrationPoint &ip);
};

/** Compute the Lp norm of a function f.
    \f$ \| f \|_{Lp} = ( \int_\Omega | f |^p d\Omega)^{1/p} \f$ */
double ComputeLpNorm(double p, Coefficient &coeff, Mesh &mesh,
                     const IntegrationRule *irs[]);

/** Compute the Lp norm of a vector function f = {f_i}_i=1...N.
    \f$ \| f \|_{Lp} = ( \sum_i \| f_i \|_{Lp}^p )^{1/p} \f$ */
double ComputeLpNorm(double p, VectorCoefficient &coeff, Mesh &mesh,
                     const IntegrationRule *irs[]);

#ifdef MFEM_USE_MPI
/** Compute the global Lp norm of a function f.
    \f$ \| f \|_{Lp} = ( \int_\Omega | f |^p d\Omega)^{1/p} \f$ */
double ComputeGlobalLpNorm(double p, Coefficient &coeff, ParMesh &pmesh,
                           const IntegrationRule *irs[]);

/** Compute the global Lp norm of a vector function f = {f_i}_i=1...N.
    \f$ \| f \|_{Lp} = ( \sum_i \| f_i \|_{Lp}^p )^{1/p} \f$ */
double ComputeGlobalLpNorm(double p, VectorCoefficient &coeff, ParMesh &pmesh,
                           const IntegrationRule *irs[]);
#endif

}

#endif
<commit_msg>Small changes in comments<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#ifndef MFEM_COEFFICIENT
#define MFEM_COEFFICIENT

#include "../config/config.hpp"
#include "../linalg/linalg.hpp"
#include "intrules.hpp"
#include "eltrans.hpp"

namespace mfem
{

class Mesh;

#ifdef MFEM_USE_MPI
class ParMesh;
#endif

/// Base class Coefficient that may optionally depend on time.
class Coefficient
{
protected:
   double time;

public:
   Coefficient() { time = 0.; }

   void SetTime(double t) { time = t; }
   double GetTime() { return time; }

   virtual double Eval(ElementTransformation &T,
                       const IntegrationPoint &ip) = 0;

   double Eval(ElementTransformation &T,
               const IntegrationPoint &ip, double t)
   {
      SetTime(t);
      return Eval(T, ip);
   }

   virtual ~Coefficient() { }
};

/// Subclass constant coefficient.
class ConstantCoefficient : public Coefficient
{
public:
   double constant;

   /// c is value of constant function
   explicit ConstantCoefficient(double c = 1.0) { constant=c; }

   /// Evaluate the coefficient
   virtual double Eval(ElementTransformation &T,
                       const IntegrationPoint &ip)
   { return (constant); }
};

/// class for piecewise constant coefficient
class PWConstCoefficient : public Coefficient
{
private:
   Vector constants;

public:

   /// Constructs a piecewise constant coefficient in NumOfSubD subdomains
   explicit PWConstCoefficient(int NumOfSubD = 0) : constants(NumOfSubD)
   { constants = 0.0; }

   /** c should be a vector defined by attributes, so for region with
       attribute i  c[i] is the coefficient in that region */
   PWConstCoefficient(Vector &c)
   { constants.SetSize(c.Size()); constants=c; }

   /// Member function to access or modify the value of the i-th constant
   double &operator()(int i) { return constants(i-1); }

   /// Set domain constants equal to the same constant c
   void operator=(double c) { constants = c; }

   /// Returns the number of constants
   int GetNConst() { return constants.Size(); }

   /// Evaluate the coefficient function
   virtual double Eval(ElementTransformation &T,
                       const IntegrationPoint &ip);
};

/// class for C-function coefficient
class FunctionCoefficient : public Coefficient
{
protected:
   double (*Function)(const Vector &);
   double (*TDFunction)(const Vector &, double);

public:
   /// Define a time-independent coefficient from a C-function
   FunctionCoefficient(double (*f)(const Vector &))
   {
      Function = f;
      TDFunction = NULL;
   }

   /// Define a time-dependent coefficient from a C-function
   FunctionCoefficient(double (*tdf)(const Vector &, double))
   {
      Function = NULL;
      TDFunction = tdf;
   }

   /// (DEPRECATED) Define a time-independent coefficient from a C-function
   FunctionCoefficient(double (*f)(Vector &))
   {
      Function = reinterpret_cast<double(*)(const Vector&)>(f);
      TDFunction = NULL;
   }

   /// (DEPRECATED) Define a time-dependent coefficient from a C-function
   FunctionCoefficient(double (*tdf)(Vector &, double))
   {
      Function = NULL;
      TDFunction = reinterpret_cast<double(*)(const Vector&,double)>(tdf);
   }

   /// Evaluate coefficient
   virtual double Eval(ElementTransformation &T,
                       const IntegrationPoint &ip);
};

class GridFunction;

/// Coefficient defined by a GridFunction. This coefficient is mesh dependent.
class GridFunctionCoefficient : public Coefficient
{
private:
   GridFunction *GridF;
   int Component;

public:
   /** Construct GridFunctionCoefficient from a given GridFunction, and
       optionally specify a component to use if it is a vector GridFunction. */
   GridFunctionCoefficient (GridFunction *gf, int comp = 1)
   { GridF = gf; Component = comp; }

   void SetGridFunction(GridFunction *gf) { GridF = gf; }
   GridFunction * GetGridFunction() const { return GridF; }

   virtual double Eval(ElementTransformation &T,
                       const IntegrationPoint &ip);
};

class TransformedCoefficient : public Coefficient
{
private:
   Coefficient * Q1;
   Coefficient * Q2;
   double (*Transform1)(double);
   double (*Transform2)(double,double);

public:
   TransformedCoefficient (Coefficient * q,double (*F)(double))
      : Q1(q), Transform1(F) { Q2 = 0; Transform2 = 0; }
   TransformedCoefficient (Coefficient * q1,Coefficient * q2,
                           double (*F)(double,double))
      : Q1(q1), Q2(q2), Transform2(F) { Transform1 = 0; }

   virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip);
};

/// Delta function coefficient
class DeltaCoefficient : public Coefficient
{
private:
   double center[3], scale, tol;
   Coefficient *weight;

public:
   DeltaCoefficient();
   DeltaCoefficient(double x, double y, double s)
   {
      center[0] = x; center[1] = y; center[2] = 0.; scale = s; tol = 1e-12;
      weight = NULL;
   }
   DeltaCoefficient(double x, double y, double z, double s)
   {
      center[0] = x; center[1] = y; center[2] = z; scale = s; tol = 1e-12;
      weight = NULL;
   }
   void SetTol(double _tol) { tol = _tol; }
   void SetWeight(Coefficient *w) { weight = w; }
   const double *Center() { return center; }
   double Scale() { return scale; }
   double Tol() { return tol; }
   Coefficient *Weight() { return weight; }
   virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)
   { mfem_error("DeltaCoefficient::Eval"); return 0.; }
   virtual ~DeltaCoefficient() { delete weight; }
};

/// Coefficient defined on a subset of domain or boundary attributes
class RestrictedCoefficient : public Coefficient
{
private:
   Coefficient *c;
   Array<int> active_attr;

public:
   RestrictedCoefficient(Coefficient &_c, Array<int> &attr)
   { c = &_c; attr.Copy(active_attr); }

   virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)
   { return active_attr[T.Attribute-1] ? c->Eval(T, ip, GetTime()) : 0.0; }
};

class VectorCoefficient
{
protected:
   int vdim;
   double time;

public:
   VectorCoefficient(int vd) { vdim = vd; time = 0.; }

   void SetTime(double t) { time = t; }
   double GetTime() { return time; }

   /// Returns dimension of the vector.
   int GetVDim() { return vdim; }

   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip) = 0;

   // General implementation using the Eval method for one IntegrationPoint.
   // Can be overloaded for more efficient implementation.
   virtual void Eval(DenseMatrix &M, ElementTransformation &T,
                     const IntegrationRule &ir);

   virtual ~VectorCoefficient() { }
};

class VectorConstantCoefficient : public VectorCoefficient
{
private:
   Vector vec;
public:
   VectorConstantCoefficient(const Vector &v)
      : VectorCoefficient(v.Size()), vec(v) { }
   using VectorCoefficient::Eval;
   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip) { V = vec; }
};

class VectorFunctionCoefficient : public VectorCoefficient
{
private:
   void (*Function)(const Vector &, Vector &);
   void (*TDFunction)(const Vector &, double, Vector &);
   Coefficient *Q;

public:
   /// Construct a time-independent vector coefficient from a C-function
   VectorFunctionCoefficient(int dim, void (*F)(const Vector &, Vector &),
                             Coefficient *q = NULL)
      : VectorCoefficient(dim), Q(q)
   {
      Function = F;
      TDFunction = NULL;
   }

   /// Construct a time-dependent vector coefficient from a C-function
   VectorFunctionCoefficient(int dim,
                             void (*TDF)(const Vector &, double, Vector &),
                             Coefficient *q = NULL)
      : VectorCoefficient(dim), Q(q)
   {
      Function = NULL;
      TDFunction = TDF;
   }

   using VectorCoefficient::Eval;
   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip);

   virtual ~VectorFunctionCoefficient() { }
};

/// Vector coefficient defined by an array of scalar coefficients.
class VectorArrayCoefficient : public VectorCoefficient
{
private:
   Array<Coefficient*> Coeff;

public:
   /// Construct vector of dim coefficients.
   explicit VectorArrayCoefficient(int dim);

   /// Returns i'th coefficient.
   Coefficient &GetCoeff(int i) { return *Coeff[i]; }

   Coefficient **GetCoeffs() { return Coeff; }

   /// Sets coefficient in the vector.
   void Set(int i, Coefficient *c) { Coeff[i] = c; }

   /// Evaluates i'th component of the vector.
   double Eval(int i, ElementTransformation &T, IntegrationPoint &ip)
   { return Coeff[i]->Eval(T, ip, GetTime()); }

   using VectorCoefficient::Eval;
   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip);

   /// Destroys vector coefficient.
   virtual ~VectorArrayCoefficient();
};

/// Vector coefficient defined by a vector GridFunction
class VectorGridFunctionCoefficient : public VectorCoefficient
{
private:
   GridFunction *GridFunc;

public:
   VectorGridFunctionCoefficient(GridFunction *gf);

   void SetGridFunction(GridFunction *gf) { GridFunc = gf; }
   GridFunction * GetGridFunction() const { return GridFunc; }

   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip);

   virtual void Eval(DenseMatrix &M, ElementTransformation &T,
                     const IntegrationRule &ir);

   virtual ~VectorGridFunctionCoefficient() { }
};

/// VectorCoefficient defined on a subset of domain or boundary attributes
class VectorRestrictedCoefficient : public VectorCoefficient
{
private:
   VectorCoefficient *c;
   Array<int> active_attr;

public:
   VectorRestrictedCoefficient(VectorCoefficient &vc, Array<int> &attr)
      : VectorCoefficient(vc.GetVDim())
   { c = &vc; attr.Copy(active_attr); }

   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip);

   virtual void Eval(DenseMatrix &M, ElementTransformation &T,
                     const IntegrationRule &ir);
};

class MatrixCoefficient
{
protected:
   int vdim;
   double time;

public:
   explicit MatrixCoefficient(int dim) { vdim = dim; time = 0.; }

   void SetTime(double t) { time = t; }
   double GetTime() { return time; }

   int GetVDim() { return vdim; }

   virtual void Eval(DenseMatrix &K, ElementTransformation &T,
                     const IntegrationPoint &ip) = 0;

   virtual ~MatrixCoefficient() { }
};

class MatrixConstantCoefficient : public MatrixCoefficient
{
private:
   DenseMatrix mat;
public:
   MatrixConstantCoefficient(const DenseMatrix &m)
      : MatrixCoefficient(m.Size()), mat(m) { }
   using MatrixCoefficient::Eval;
   virtual void Eval(DenseMatrix &M, ElementTransformation &T,
                     const IntegrationPoint &ip) { M = mat; }
};

class MatrixFunctionCoefficient : public MatrixCoefficient
{
private:
   void (*Function)(const Vector &, DenseMatrix &);
   void (*TDFunction)(const Vector &, double, DenseMatrix &);
   Coefficient *Q;
   DenseMatrix mat;

public:
   /// Construct a time-independent matrix coefficient from a C-function
   MatrixFunctionCoefficient(int dim, void (*F)(const Vector &, DenseMatrix &),
                             Coefficient *q = NULL)
      : MatrixCoefficient(dim), Q(q)
   {
      Function = F;
      TDFunction = NULL;
      mat.SetSize(0);
   }

   /// Construct a constant matrix coefficient
   MatrixFunctionCoefficient(const DenseMatrix &m, Coefficient &q)
      : MatrixCoefficient(m.Size()), Q(&q)
   {
      Function = NULL;
      TDFunction = NULL;
      mat = m;
   }

   /// Construct a time-dependent matrix coefficient from a C-function
   MatrixFunctionCoefficient(int dim,
                             void (*TDF)(const Vector &, double, DenseMatrix &),
                             Coefficient *q = NULL)
      : MatrixCoefficient(dim), Q(q)
   {
      Function = NULL;
      TDFunction = TDF;
      mat.SetSize(0);
   }

   virtual void Eval(DenseMatrix &K, ElementTransformation &T,
                     const IntegrationPoint &ip);

   virtual ~MatrixFunctionCoefficient() { }
};

class MatrixArrayCoefficient : public MatrixCoefficient
{
private:
   Array<Coefficient *> Coeff;

public:

   explicit MatrixArrayCoefficient (int dim);

   Coefficient &GetCoeff (int i, int j) { return *Coeff[i*vdim+j]; }

   void Set(int i, int j, Coefficient * c) { Coeff[i*vdim+j] = c; }

   double Eval(int i, int j, ElementTransformation &T, IntegrationPoint &ip)
   { return Coeff[i*vdim+j] -> Eval(T, ip, GetTime()); }

   virtual void Eval(DenseMatrix &K, ElementTransformation &T,
                     const IntegrationPoint &ip);

   virtual ~MatrixArrayCoefficient();
};

/// MatrixCoefficient defined on a subset of domain or boundary attributes
class MatrixRestrictedCoefficient : public MatrixCoefficient
{
private:
   MatrixCoefficient *c;
   Array<int> active_attr;

public:
   MatrixRestrictedCoefficient(MatrixCoefficient &mc, Array<int> &attr)
      : MatrixCoefficient(mc.GetVDim())
   { c = &mc; attr.Copy(active_attr); }

   virtual void Eval(DenseMatrix &K, ElementTransformation &T,
                     const IntegrationPoint &ip);
};

/** Compute the Lp norm of a function f.
    \f$ \| f \|_{Lp} = ( \int_\Omega | f |^p d\Omega)^{1/p} \f$ */
double ComputeLpNorm(double p, Coefficient &coeff, Mesh &mesh,
                     const IntegrationRule *irs[]);

/** Compute the Lp norm of a vector function f = {f_i}_i=1...N.
    \f$ \| f \|_{Lp} = ( \sum_i \| f_i \|_{Lp}^p )^{1/p} \f$ */
double ComputeLpNorm(double p, VectorCoefficient &coeff, Mesh &mesh,
                     const IntegrationRule *irs[]);

#ifdef MFEM_USE_MPI
/** Compute the global Lp norm of a function f.
    \f$ \| f \|_{Lp} = ( \int_\Omega | f |^p d\Omega)^{1/p} \f$ */
double ComputeGlobalLpNorm(double p, Coefficient &coeff, ParMesh &pmesh,
                           const IntegrationRule *irs[]);

/** Compute the global Lp norm of a vector function f = {f_i}_i=1...N.
    \f$ \| f \|_{Lp} = ( \sum_i \| f_i \|_{Lp}^p )^{1/p} \f$ */
double ComputeGlobalLpNorm(double p, VectorCoefficient &coeff, ParMesh &pmesh,
                           const IntegrationRule *irs[]);
#endif

}

#endif
<|endoftext|>


<commit_before>/*****************************************************************************
*                                                                            *
*  OpenNI 1.x Alpha                                                          *
*  Copyright (C) 2012 PrimeSense Ltd.                                        *
*                                                                            *
*  This file is part of OpenNI.                                              *
*                                                                            *
*  Licensed under the Apache License, Version 2.0 (the "License");           *
*  you may not use this file except in compliance with the License.          *
*  You may obtain a copy of the License at                                   *
*                                                                            *
*      http://www.apache.org/licenses/LICENSE-2.0                            *
*                                                                            *
*  Unless required by applicable law or agreed to in writing, software       *
*  distributed under the License is distributed on an "AS IS" BASIS,         *
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
*  See the License for the specific language governing permissions and       *
*  limitations under the License.                                            *
*                                                                            *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <XnOpenNI.h>
#include <XnLog.h>
#include <XnCppWrapper.h>
#include <XnFPSCalculator.h>

#include <iostream>

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------

bool erroring(XnStatus nRetVal){
    if (nRetVal != XN_STATUS_OK){
      std::cout << xnGetStatusString(nRetVal) << std::endl;
      return false;
    }
    return true;
}

using namespace xn;

int main()
{
	XnStatus nRetVal = XN_STATUS_OK;

	Context context;
	ScriptNode scriptNode;
	EnumerationErrors errors;

  context.Init();

  xn::ImageGenerator imgGen;
  xn::DepthGenerator DGen;

  nRetVal = DGen.Create(context);
  erroring(nRetVal);
  nRetVal = imgGen.Create(context);
  erroring(nRetVal);

  //Recording stuff.
  Recorder recorder;
  nRetVal = recorder.Create(context);
  erroring(nRetVal);

  nRetVal = recorder.SetDestination(XN_RECORD_MEDIUM_FILE, "oni1.oni");
  erroring(nRetVal);

  nRetVal = recorder.AddNodeToRecording(DGen);
  erroring(nRetVal);

  nRetVal = recorder.AddNodeToRecording(imgGen);
  erroring(nRetVal);

  nRetVal = DGen.StartGenerating();
  erroring(nRetVal);
  nRetVal = imgGen.StartGenerating();
  erroring(nRetVal);

  //xnOSSleep(10000);

// /*
  int i=0;
  while (true){
    nRetVal = context.WaitAndUpdateAll();
    std::cout << i << std::endl;

    if(!erroring(nRetVal))
      break;
//
//    XnMapOutputMode Imode;
//    XnMapOutputMode Dmode;
//    imgGen.GetMapOutputMode(Imode);
//    DGen.GetMapOutputMode(Dmode);
//
//    int Iheight = Imode.nYRes;
//    int Dheight = Dmode.nYRes;
//    int Iwidth = Imode.nXRes;
//    int Dwidth = Dmode.nXRes;
//
//    std::cout << "Img: Height: " << Iheight << ", Width: " << Iwidth <<  std::endl;
//
//    cv::Mat img = cv::Mat( Iheight, Iwidth, CV_8UC3, (void *) imgGen.GetData()); //Color
//
//    cv::imwrite("cImg"+std::to_string(i)+".jpg", img);
//
//    std::cout << "Depth: Height: " << Dheight << ", Width: " << Dwidth <<  std::endl;
//
//    cv::Mat dimg = cv::Mat (Dheight, Dwidth,  CV_8U , (void *) DGen.GetData()); //Depth
//    cv::imwrite("dImg"+std::to_string(i)+".jpg", dimg);
    i++;
  }
 //*/
  nRetVal = recorder.RemoveNodeFromRecording(DGen);
  nRetVal = recorder.RemoveNodeFromRecording(imgGen);
	recorder.Release();

  context.Release();

	return 0;
}
<commit_msg>Attempt to make it recored .oni from converter. Almost works(?) Recorder seems to overflow.<commit_after>/*****************************************************************************
*                                                                            *
*  OpenNI 1.x Alpha                                                          *
*  Copyright (C) 2012 PrimeSense Ltd.                                        *
*                                                                            *
*  This file is part of OpenNI.                                              *
*                                                                            *
*  Licensed under the Apache License, Version 2.0 (the "License");           *
*  you may not use this file except in compliance with the License.          *
*  You may obtain a copy of the License at                                   *
*                                                                            *
*      http://www.apache.org/licenses/LICENSE-2.0                            *
*                                                                            *
*  Unless required by applicable law or agreed to in writing, software       *
*  distributed under the License is distributed on an "AS IS" BASIS,         *
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
*  See the License for the specific language governing permissions and       *
*  limitations under the License.                                            *
*                                                                            *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <XnOpenNI.h>
#include <XnLog.h>
#include <XnCppWrapper.h>
#include <XnFPSCalculator.h>

#include <iostream>

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------

bool erroring(XnStatus nRetVal){
    if (nRetVal != XN_STATUS_OK){
      std::cout << xnGetStatusString(nRetVal) << std::endl;
      return false;
    }
    return true;
}

using namespace xn;

int main()
{
	XnStatus nRetVal = XN_STATUS_OK;

	Context context;
	ScriptNode scriptNode;
	EnumerationErrors errors;

  context.Init();

  xn::ImageGenerator imgGen;
  xn::DepthGenerator DGen;

  nRetVal = DGen.Create(context);
  erroring(nRetVal);
  nRetVal = imgGen.Create(context);
  erroring(nRetVal);

  //Recording stuff.
  Recorder recorder;
  nRetVal = recorder.Create(context);
  erroring(nRetVal);

  nRetVal = recorder.SetDestination(XN_RECORD_MEDIUM_FILE, "oni1.oni");
  erroring(nRetVal);

  nRetVal = recorder.AddNodeToRecording(DGen);
  erroring(nRetVal);

  nRetVal = recorder.AddNodeToRecording(imgGen);
  erroring(nRetVal);

  std::cout << "Starting." << std::endl;

/*
  nRetVal = recorder.start();
  erroring(nRetVal);
  nRetVal = DGen.StartGenerating();
  erroring(nRetVal);
  nRetVal = imgGen.StartGenerating();
  erroring(nRetVal);
*/

  nRetVal = context.StartGeneratingAll();
  erroring(nRetVal);

  //xnOSSleep(10000);

// /*
  int i=0;
  while (true){
    nRetVal = context.WaitAnyUpdateAll();
//    nRetVal = context.WaitAndUpdateAll();
    recorder.Record();
    std::cout << "Frame: " << i << std::endl;

    if(!erroring(nRetVal)){
      std::cout << "Error, breaking." << std::endl;
      break;
    }
//
//    XnMapOutputMode Imode;
//    XnMapOutputMode Dmode;
//    imgGen.GetMapOutputMode(Imode);
//    DGen.GetMapOutputMode(Dmode);
//
//    int Iheight = Imode.nYRes;
//    int Dheight = Dmode.nYRes;
//    int Iwidth = Imode.nXRes;
//    int Dwidth = Dmode.nXRes;
//
//    std::cout << "Img: Height: " << Iheight << ", Width: " << Iwidth <<  std::endl;
//
//    cv::Mat img = cv::Mat( Iheight, Iwidth, CV_8UC3, (void *) imgGen.GetData()); //Color
//
//    cv::imwrite("cImg"+std::to_string(i)+".jpg", img);
//
//    std::cout << "Depth: Height: " << Dheight << ", Width: " << Dwidth <<  std::endl;
//
//    cv::Mat dimg = cv::Mat (Dheight, Dwidth,  CV_8U , (void *) DGen.GetData()); //Depth
//    cv::imwrite("dImg"+std::to_string(i)+".jpg", dimg);
    i++;
  }
 //*/
  nRetVal = recorder.RemoveNodeFromRecording(DGen);
  nRetVal = recorder.RemoveNodeFromRecording(imgGen);
	recorder.Release();

  context.Release();

	return 0;
}
<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*
 * Copyright (C) 2015 ScyllaDB
 */

#pragma once

#include "future.hh"

/// \addtogroup future-module
/// @{

/// \brief Like \ref future except the result can be waited for by many fibers.
///
/// Represents a value which may not yet be ready. A fiber can wait for the value using
/// the \ref future obtained by calling \ref get_future() or casting to \ref future type.
/// Multiple fibers are allowed to obtain a \ref future for the result using the same
/// instance of \ref shared_future.
///
/// All futures obtained from shared_future should end up in the same state. However,
/// if the value's copy constructor throws, some of the futures may end up in a failed state
/// with an exception thrown from the copy constructor and end up with a state
/// different than other futures.
///
/// The scope of shared_future instance doesn't have to include scopes of the futures
/// obtained from that instance. In that sense the returned futures are independent.
///
/// shared_future can be copied at any time and all copies will resolve with the same value.
///
/// shared_future can be in a disengaged state when it's default-constructed or moved-from.
/// When it's in such a state we say it's invalid and obtaining futures must not be attempted.
///
/// The types in the parameter pack T must all be copy-constructible.
template<typename... T>
class shared_future {
    /// \cond internal
    class shared_state {
        future_state<T...> _future_state;
        std::deque<promise<T...>> _peers;
    public:
        void resolve(future<T...>&& f) noexcept {
            _future_state = f.get_available_state();
            if (_future_state.failed()) {
                for (auto&& p : _peers) {
                    p.set_exception(_future_state.get_exception());
                }
            } else {
                for (auto&& p : _peers) {
                    try {
                        p.set_value(_future_state.get_value());
                    } catch (...) {
                        p.set_exception(std::current_exception());
                    }
                }
            }
            _peers.clear();
        }

        future<T...> get_future() {
            if (!_future_state.available()) {
                promise<T...> p;
                auto f = p.get_future();
                _peers.emplace_back(std::move(p));
                return f;
            } else if (_future_state.failed()) {
                return make_exception_future<T...>(_future_state.get_exception());
            } else {
                try {
                    return make_ready_future<T...>(_future_state.get_value());
                } catch (...) {
                    return make_exception_future<T...>(std::current_exception());
                }
            }
        }
    };
    /// \endcond
    lw_shared_ptr<shared_state> _state;
public:
    /// \brief Forwards the result of future \c f into this shared_future.
    shared_future(future<T...>&& f)
        : _state(make_lw_shared<shared_state>())
    {
        f.then_wrapped([s = _state] (future<T...>&& f) mutable {
            s->resolve(std::move(f));
        });
    }

    shared_future() = default;
    shared_future(const shared_future&) = default;
    shared_future& operator=(const shared_future&) = default;
    shared_future(shared_future&&) = default;
    shared_future& operator=(shared_future&&) = default;

    /// \brief Creates a new \c future which will resolve with the result of this shared_future
    ///
    /// This object must be in a valid state.
    future<T...> get_future() const {
        return _state->get_future();
    }

    /// \brief Equivalent to \ref get_future()
    operator future<T...>() const {
        return get_future();
    }

    /// \brief Returns true if the instance is in valid state
    bool valid() const {
        return bool(_state);
    }
};

/// @}
<commit_msg>shared_future: Add missing include<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*
 * Copyright (C) 2015 ScyllaDB
 */

#pragma once

#include <deque>
#include "future.hh"

/// \addtogroup future-module
/// @{

/// \brief Like \ref future except the result can be waited for by many fibers.
///
/// Represents a value which may not yet be ready. A fiber can wait for the value using
/// the \ref future obtained by calling \ref get_future() or casting to \ref future type.
/// Multiple fibers are allowed to obtain a \ref future for the result using the same
/// instance of \ref shared_future.
///
/// All futures obtained from shared_future should end up in the same state. However,
/// if the value's copy constructor throws, some of the futures may end up in a failed state
/// with an exception thrown from the copy constructor and end up with a state
/// different than other futures.
///
/// The scope of shared_future instance doesn't have to include scopes of the futures
/// obtained from that instance. In that sense the returned futures are independent.
///
/// shared_future can be copied at any time and all copies will resolve with the same value.
///
/// shared_future can be in a disengaged state when it's default-constructed or moved-from.
/// When it's in such a state we say it's invalid and obtaining futures must not be attempted.
///
/// The types in the parameter pack T must all be copy-constructible.
template<typename... T>
class shared_future {
    /// \cond internal
    class shared_state {
        future_state<T...> _future_state;
        std::deque<promise<T...>> _peers;
    public:
        void resolve(future<T...>&& f) noexcept {
            _future_state = f.get_available_state();
            if (_future_state.failed()) {
                for (auto&& p : _peers) {
                    p.set_exception(_future_state.get_exception());
                }
            } else {
                for (auto&& p : _peers) {
                    try {
                        p.set_value(_future_state.get_value());
                    } catch (...) {
                        p.set_exception(std::current_exception());
                    }
                }
            }
            _peers.clear();
        }

        future<T...> get_future() {
            if (!_future_state.available()) {
                promise<T...> p;
                auto f = p.get_future();
                _peers.emplace_back(std::move(p));
                return f;
            } else if (_future_state.failed()) {
                return make_exception_future<T...>(_future_state.get_exception());
            } else {
                try {
                    return make_ready_future<T...>(_future_state.get_value());
                } catch (...) {
                    return make_exception_future<T...>(std::current_exception());
                }
            }
        }
    };
    /// \endcond
    lw_shared_ptr<shared_state> _state;
public:
    /// \brief Forwards the result of future \c f into this shared_future.
    shared_future(future<T...>&& f)
        : _state(make_lw_shared<shared_state>())
    {
        f.then_wrapped([s = _state] (future<T...>&& f) mutable {
            s->resolve(std::move(f));
        });
    }

    shared_future() = default;
    shared_future(const shared_future&) = default;
    shared_future& operator=(const shared_future&) = default;
    shared_future(shared_future&&) = default;
    shared_future& operator=(shared_future&&) = default;

    /// \brief Creates a new \c future which will resolve with the result of this shared_future
    ///
    /// This object must be in a valid state.
    future<T...> get_future() const {
        return _state->get_future();
    }

    /// \brief Equivalent to \ref get_future()
    operator future<T...>() const {
        return get_future();
    }

    /// \brief Returns true if the instance is in valid state
    bool valid() const {
        return bool(_state);
    }
};

/// @}
<|endoftext|>


<commit_before>#include "platform.h"
#include "log.h"

#include <fstream>
#include <string>
#include <cassert>

constexpr char const* shutdown_message = "Shutting down";
constexpr char const* cancel_message = "Request canceled";

namespace Tangram {

Platform::Platform() : m_continuousRendering(false) {}

Platform::~Platform() {}

void Platform::setContinuousRendering(bool _isContinuous) {
    m_continuousRendering = _isContinuous;
}

bool Platform::isContinuousRendering() const {
    return m_continuousRendering;
}

bool Platform::bytesFromFileSystem(const char* _path, std::function<char*(size_t)> _allocator) {
    std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary);

    if(!resource.is_open()) {
        LOGW("Failed to read file at path: %s", _path);
        return false;
    }

    size_t size = resource.tellg();
    char* cdata = _allocator(size);

    resource.seekg(std::ifstream::beg);
    resource.read(cdata, size);
    resource.close();

    return true;
}

FontSourceHandle Platform::systemFont(const std::string& _name, const std::string& _weight, const std::string& _face) const {
    // No-op by default
    return FontSourceHandle();
}

std::vector<FontSourceHandle> Platform::systemFontFallbacksHandle() const {
    // No-op by default
    return {};
}

void Platform::shutdown() {
    if (m_shutdown.exchange(true)) { return; }

    {
        std::lock_guard<std::mutex> lock(m_callbackMutex);

        for (auto& entry : m_urlCallbacks) {
            auto& request = entry.second;
            if (request.callback) {
                UrlResponse response;
                response.error = shutdown_message;
                request.callback(std::move(response));
            }

            if (request.cancelable) {
                cancelUrlRequestImpl(request.id);
            }
        }
        m_urlCallbacks.clear();
    }
}

UrlRequestHandle Platform::startUrlRequest(Url _url, UrlCallback&& _callback) {

    assert(_callback);

    if (m_shutdown) {
        UrlResponse response;
        response.error = shutdown_message;
        _callback(std::move(response));
        return 0;
    }

    UrlRequestHandle handle= ++m_urlRequestCount;

    // Need to do this in advance in case startUrlRequest calls back synchronously.
    UrlRequestEntry* entry = nullptr;
    {
        std::lock_guard<std::mutex> lock(m_callbackMutex);
        auto it = m_urlCallbacks.emplace(handle, UrlRequestEntry{std::move(_callback), 0, false});
        entry = &it.first->second;
    }

    // Start Platform specific url request
    entry->cancelable = startUrlRequestImpl(_url, handle, entry->id);

    return handle;
}

void Platform::cancelUrlRequest(const UrlRequestHandle _request) {
    if (_request == 0) { return; }

    UrlRequestId id = 0;
    UrlCallback callback;
    bool cancelable = false;

    {
        std::lock_guard<std::mutex> lock(m_callbackMutex);
        auto it = m_urlCallbacks.find(_request);
        if (it != m_urlCallbacks.end()) {
            id = it->second.id;
            cancelable = it->second.cancelable;

            if (!cancelable) {
                callback = std::move(it->second.callback);
                m_urlCallbacks.erase(it);
            }
        }
    }

    if (cancelable) {
        cancelUrlRequestImpl(id);

    } else {
        // Run callback directly when platform implementation cannot cancel it.
        if (callback) {
            UrlResponse response;
            response.error = cancel_message;
            callback(std::move(response));
        }
    }
}

void Platform::onUrlResponse(const UrlRequestHandle _request, UrlResponse&& _response) {
    if (m_shutdown) {
        LOGW("onUrlResponse after shutdown");
        return;
    }
    // Find the callback associated with the request.
    UrlCallback callback;
    {
        std::lock_guard<std::mutex> lock(m_callbackMutex);
        auto it = m_urlCallbacks.find(_request);
        if (it != m_urlCallbacks.end()) {
            callback = std::move(it->second.callback);
            m_urlCallbacks.erase(it);
        }
    }
    if (callback) { callback(std::move(_response)); }
}

} // namespace Tangram
<commit_msg>Fix: entry has already been removed when request is not handled async (#2009)<commit_after>#include "platform.h"
#include "log.h"

#include <fstream>
#include <string>
#include <cassert>

constexpr char const* shutdown_message = "Shutting down";
constexpr char const* cancel_message = "Request canceled";

namespace Tangram {

Platform::Platform() : m_continuousRendering(false) {}

Platform::~Platform() {}

void Platform::setContinuousRendering(bool _isContinuous) {
    m_continuousRendering = _isContinuous;
}

bool Platform::isContinuousRendering() const {
    return m_continuousRendering;
}

bool Platform::bytesFromFileSystem(const char* _path, std::function<char*(size_t)> _allocator) {
    std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary);

    if(!resource.is_open()) {
        LOGW("Failed to read file at path: %s", _path);
        return false;
    }

    size_t size = resource.tellg();
    char* cdata = _allocator(size);

    resource.seekg(std::ifstream::beg);
    resource.read(cdata, size);
    resource.close();

    return true;
}

FontSourceHandle Platform::systemFont(const std::string& _name, const std::string& _weight, const std::string& _face) const {
    // No-op by default
    return FontSourceHandle();
}

std::vector<FontSourceHandle> Platform::systemFontFallbacksHandle() const {
    // No-op by default
    return {};
}

void Platform::shutdown() {
    if (m_shutdown.exchange(true)) { return; }

    {
        std::lock_guard<std::mutex> lock(m_callbackMutex);

        for (auto& entry : m_urlCallbacks) {
            auto& request = entry.second;
            if (request.callback) {
                UrlResponse response;
                response.error = shutdown_message;
                request.callback(std::move(response));
            }

            if (request.cancelable) {
                cancelUrlRequestImpl(request.id);
            }
        }
        m_urlCallbacks.clear();
    }
}

UrlRequestHandle Platform::startUrlRequest(Url _url, UrlCallback&& _callback) {

    assert(_callback);

    if (m_shutdown) {
        UrlResponse response;
        response.error = shutdown_message;
        _callback(std::move(response));
        return 0;
    }

    UrlRequestHandle handle= ++m_urlRequestCount;

    // Need to do this in advance in case startUrlRequest calls back synchronously.
    UrlRequestEntry* entry = nullptr;
    {
        std::lock_guard<std::mutex> lock(m_callbackMutex);
        auto it = m_urlCallbacks.emplace(handle, UrlRequestEntry{std::move(_callback), 0, false});
        entry = &it.first->second;
    }

    // Start Platform specific url request
    if (startUrlRequestImpl(_url, handle, entry->id)) {
        entry->cancelable = true;
    }

    return handle;
}

void Platform::cancelUrlRequest(const UrlRequestHandle _request) {
    if (_request == 0) { return; }

    UrlRequestId id = 0;
    UrlCallback callback;
    bool cancelable = false;

    {
        std::lock_guard<std::mutex> lock(m_callbackMutex);
        auto it = m_urlCallbacks.find(_request);
        if (it != m_urlCallbacks.end()) {
            id = it->second.id;
            cancelable = it->second.cancelable;

            if (!cancelable) {
                callback = std::move(it->second.callback);
                m_urlCallbacks.erase(it);
            }
        }
    }

    if (cancelable) {
        cancelUrlRequestImpl(id);

    } else {
        // Run callback directly when platform implementation cannot cancel it.
        if (callback) {
            UrlResponse response;
            response.error = cancel_message;
            callback(std::move(response));
        }
    }
}

void Platform::onUrlResponse(const UrlRequestHandle _request, UrlResponse&& _response) {
    if (m_shutdown) {
        LOGW("onUrlResponse after shutdown");
        return;
    }
    // Find the callback associated with the request.
    UrlCallback callback;
    {
        std::lock_guard<std::mutex> lock(m_callbackMutex);
        auto it = m_urlCallbacks.find(_request);
        if (it != m_urlCallbacks.end()) {
            callback = std::move(it->second.callback);
            m_urlCallbacks.erase(it);
        }
    }
    if (callback) { callback(std::move(_response)); }
}

} // namespace Tangram
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile: ResampleImageBySpacing.cxx,v $
  Language:  C++
  Date:      $Date: 2009/03/31 21:22:00 $
  Version:   $Revision: 1.17 $

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkIdentityTransform.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkIntensityWindowingImageFilter.h"

#include "itkDiscreteGaussianImageFilter.h"

template <class TImage>
typename TImage::Pointer
SmoothImage(typename TImage::Pointer image, float sig)
{
  typedef itk::DiscreteGaussianImageFilter<TImage, TImage> dgf;
  typename dgf::Pointer filter = dgf::New();
  filter->SetVariance(sig);
  filter->SetUseImageSpacingOn();
  filter->SetMaximumError(.01f);
  filter->SetInput(image);
  filter->Update();
  return filter->GetOutput();
}

int main( int argc, char * argv[] )
{
  if( argc < 5 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  ImageDimension inputImageFile  outputImageFile outxspc outyspc {outzspacing}  {dosmooth?}  {addvox} {interp}" << std::endl;
    std::cout <<" addvox pads each dimension by addvox " << std::endl;
    std::cerr << "  " << std::endl;
//    std::cout << " interp 0 = linear, 1 = nn " << std::endl;
    return 1;
    }

  unsigned int    Dimension = atoi(argv[1]);

  if (Dimension == 2)
    {

  typedef   float  InputPixelType;
  typedef   float           InternalPixelType;
  typedef   float   OutputPixelType;

  typedef itk::Image< InputPixelType,    2 >   InputImageType;
  typedef itk::Image< InternalPixelType, 2 >   InternalImageType;
  typedef itk::Image< OutputPixelType,   2 >   OutputImageType;

  typedef itk::ImageFileReader< InputImageType  >  ReaderType;
  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName( argv[2] );
  writer->SetFileName( argv[3] );

  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception caught!" << std::endl;
    std::cerr << excep << std::endl;
    }

  InputImageType::ConstPointer inputImage = reader->GetOutput();

  const InputImageType::SpacingType& inputSpacing = inputImage->GetSpacing();

  OutputImageType::SpacingType spacing;
  for (int i=0; i<2; i++) spacing[i]=inputSpacing[i];

  std::cout <<  " spacing " << spacing << " dim " << 2 << std::endl;

  bool dosmooth=1;
  if (argc > 4) spacing[0] = atof(argv[4]);
  if (argc > 5) spacing[1] = atof(argv[5]);
  if (argc > 6) dosmooth = atoi(argv[6]);
  int addvox=0;
  if (argc > 7) addvox = atoi(argv[7]);
  bool nn=false;
  if (argc > 8) nn = atoi(argv[7]);

  std::cout <<  " spacing2 " << spacing << std::endl;

  InternalImageType::ConstPointer smoothedImage = reader->GetOutput();
  if( dosmooth )
  {
  for (int sm=0; sm<2; sm++)
  {
  typedef itk::RecursiveGaussianImageFilter<
                                  OutputImageType,
                                  OutputImageType > GaussianFilterType;

  GaussianFilterType::Pointer smootherX = GaussianFilterType::New();
  smootherX->SetInput( smoothedImage );
  float sig = 0;
  sig = atof(argv[4+sm])/inputSpacing[sm]-1.0;
  std::cout << " smoothing by : " << sig << " dir " << sm << std::endl;
  smootherX->SetSigma( sig );
  smootherX->SetDirection( sm );
  smootherX->SetNormalizeAcrossScale( false );
  if (sig > 0 && dosmooth)
  {
  try
    {
    smootherX->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception catched !" << std::endl;
    std::cerr << excep << std::endl;
    }
    smoothedImage = smootherX->GetOutput();
  }
  }
  }

 // InternalImageType::ConstPointer smoothedImage = smootherY->GetOutput();

 // InternalImageType::ConstPointer smoothedImage = reader->GetOutput();
  //smoothedImage =SmoothImage<ImageType>(reader->GetOutput() , );

  typedef itk::ResampleImageFilter<
                  InternalImageType, OutputImageType >  ResampleFilterType;

  ResampleFilterType::Pointer resampler = ResampleFilterType::New();

  typedef itk::IdentityTransform< double, 2 >  TransformType;

  typedef itk::LinearInterpolateImageFunction<
    InternalImageType, double >  InterpolatorType;
  typedef itk::NearestNeighborInterpolateImageFunction<
    InternalImageType, double >  InterpolatorType2;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();
  InterpolatorType2::Pointer interpolator2 = InterpolatorType2::New();

  resampler->SetInterpolator( interpolator );
  if (nn == 1 ) resampler->SetInterpolator( interpolator2 );

  InternalImageType::IndexType ind;
  ind.Fill(1);
  resampler->SetDefaultPixelValue( inputImage->GetPixel(ind) ); // zero regions without source

  std::cout << " out space " << spacing << std::endl;
  resampler->SetOutputSpacing( spacing );
  // Use the same origin
  resampler->SetOutputOrigin( inputImage->GetOrigin() );
  // Use the same origin
  resampler->SetOutputDirection( inputImage->GetDirection() );

  InputImageType::SizeType   inputSize = inputImage->GetLargestPossibleRegion().GetSize();
  typedef InputImageType::SizeType::SizeValueType SizeValueType;
  InputImageType::SizeType   size;

  for (int i=0; i<2; i++)
    size[i] = static_cast<SizeValueType>(inputSize[i] * inputSpacing[i] / spacing[i]+addvox);

  std::cout << " output size " << size << " spc " << spacing << std::endl;
  resampler->SetSize( size );

  resampler->SetInput( smoothedImage );

  writer->SetInput( resampler->GetOutput() );

  TransformType::Pointer transform = TransformType::New();

  transform->SetIdentity();

  resampler->SetTransform( transform );

  try
    {
    writer->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception catched !" << std::endl;
    std::cerr << excep << std::endl;
    }

    }

  if (Dimension == 3)
    {

  typedef   float  InputPixelType;
  typedef   float           InternalPixelType;
  typedef   float   OutputPixelType;

  typedef itk::Image< InputPixelType,    3 >   InputImageType;
  typedef itk::Image< InternalPixelType, 3 >   InternalImageType;
  typedef itk::Image< OutputPixelType,   3 >   OutputImageType;

  typedef itk::ImageFileReader< InputImageType  >  ReaderType;
  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName( argv[2] );
  writer->SetFileName( argv[3] );

  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception caught!" << std::endl;
    std::cerr << excep << std::endl;
    }

  InputImageType::ConstPointer inputImage = reader->GetOutput();

  const InputImageType::SpacingType& inputSpacing = inputImage->GetSpacing();

  OutputImageType::SpacingType spacing;
  for (int i=0; i<3; i++) spacing[i]=inputSpacing[i];

  std::cout <<  " spacing " << spacing << " dim " << 3 << std::endl;

  bool dosmooth=1;
  if (argc > 4) spacing[0] = atof(argv[4]);
  if (argc > 5) spacing[1] = atof(argv[5]);
  if (argc > 6) spacing[2] = atof(argv[6]);
  if (argc > 7) dosmooth = atoi(argv[7]);
  int addvox=0;
  if (argc > 8) addvox = atoi(argv[8]);
  bool nn=false;
  if (argc > 9) nn = atoi(argv[9]);

  std::cout <<  " spacing2 " << spacing << std::endl;

  InternalImageType::ConstPointer smoothedImage = reader->GetOutput();
  if( dosmooth )
  {
  for (int sm=0; sm<3; sm++)
  {
  typedef itk::RecursiveGaussianImageFilter<
                                  OutputImageType,
                                  OutputImageType > GaussianFilterType;

  GaussianFilterType::Pointer smootherX = GaussianFilterType::New();
  smootherX->SetInput( smoothedImage );
  float sig = 0;
  sig = atof(argv[4+sm])/inputSpacing[sm]-1.0;
  std::cout << " smoothing by : " << sig << " dir " << sm << std::endl;
  smootherX->SetSigma( sig );
  smootherX->SetDirection( sm );
  smootherX->SetNormalizeAcrossScale( false );
  if (sig > 0 && dosmooth)
  {
  try
    {
    smootherX->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception catched !" << std::endl;
    std::cerr << excep << std::endl;
    }
    smoothedImage = smootherX->GetOutput();
  }
  }
  }

 // InternalImageType::ConstPointer smoothedImage = smootherY->GetOutput();

 // InternalImageType::ConstPointer smoothedImage = reader->GetOutput();
  //smoothedImage =SmoothImage<ImageType>(reader->GetOutput() , );

  typedef itk::ResampleImageFilter<
                  InternalImageType, OutputImageType >  ResampleFilterType;

  ResampleFilterType::Pointer resampler = ResampleFilterType::New();

  typedef itk::IdentityTransform< double, 3 >  TransformType;

  typedef itk::LinearInterpolateImageFunction<
    InternalImageType, double >  InterpolatorType;
  typedef itk::NearestNeighborInterpolateImageFunction<
    InternalImageType, double >  InterpolatorType2;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();
  InterpolatorType2::Pointer interpolator2 = InterpolatorType2::New();

  resampler->SetInterpolator( interpolator );
  if (nn  == 1 ) resampler->SetInterpolator( interpolator2 );

  InternalImageType::IndexType ind;
  ind.Fill(1);
  resampler->SetDefaultPixelValue( inputImage->GetPixel(ind) ); // zero regions without source

  std::cout << " out space " << spacing << std::endl;
  resampler->SetOutputSpacing( spacing );
  // Use the same origin
  resampler->SetOutputOrigin( inputImage->GetOrigin() );
  // Use the same origin
  resampler->SetOutputDirection( inputImage->GetDirection() );

  InputImageType::SizeType   inputSize = inputImage->GetLargestPossibleRegion().GetSize();
  typedef InputImageType::SizeType::SizeValueType SizeValueType;
  InputImageType::SizeType   size;

  for (int i=0; i<3; i++)
    size[i] = static_cast<SizeValueType>(inputSize[i] * inputSpacing[i] / spacing[i]+addvox);

  std::cout << " output size " << size << " spc " << spacing << std::endl;
  resampler->SetSize( size );

  resampler->SetInput( smoothedImage );

  writer->SetInput( resampler->GetOutput() );

  TransformType::Pointer transform = TransformType::New();

  transform->SetIdentity();

  resampler->SetTransform( transform );

  try
    {
    writer->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception catched !" << std::endl;
    std::cerr << excep << std::endl;
    }

    }

  return 0;
}

<commit_msg> better usage <commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile: ResampleImageBySpacing.cxx,v $
  Language:  C++
  Date:      $Date: 2009/03/31 21:22:00 $
  Version:   $Revision: 1.17 $

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkIdentityTransform.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkIntensityWindowingImageFilter.h"

#include "itkDiscreteGaussianImageFilter.h"

template <class TImage>
typename TImage::Pointer
SmoothImage(typename TImage::Pointer image, float sig)
{
  typedef itk::DiscreteGaussianImageFilter<TImage, TImage> dgf;
  typename dgf::Pointer filter = dgf::New();
  filter->SetVariance(sig);
  filter->SetUseImageSpacingOn();
  filter->SetMaximumError(.01f);
  filter->SetInput(image);
  filter->Update();
  return filter->GetOutput();
}

int main( int argc, char * argv[] )
{
  if( argc < 5 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  ImageDimension inputImageFile  outputImageFile outxspc outyspc {outzspacing}  {dosmooth?}  {addvox} {nn-interp?}" << std::endl;
    std::cout <<" addvox pads each dimension by addvox " << std::endl;
    std::cerr << "  " << std::endl;
//    std::cout << " interp 0 = linear, 1 = nn " << std::endl;
    return 1;
    }

  unsigned int    Dimension = atoi(argv[1]);

  if (Dimension == 2)
    {

  typedef   float  InputPixelType;
  typedef   float           InternalPixelType;
  typedef   float   OutputPixelType;

  typedef itk::Image< InputPixelType,    2 >   InputImageType;
  typedef itk::Image< InternalPixelType, 2 >   InternalImageType;
  typedef itk::Image< OutputPixelType,   2 >   OutputImageType;

  typedef itk::ImageFileReader< InputImageType  >  ReaderType;
  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName( argv[2] );
  writer->SetFileName( argv[3] );

  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception caught!" << std::endl;
    std::cerr << excep << std::endl;
    }

  InputImageType::ConstPointer inputImage = reader->GetOutput();

  const InputImageType::SpacingType& inputSpacing = inputImage->GetSpacing();

  OutputImageType::SpacingType spacing;
  for (int i=0; i<2; i++) spacing[i]=inputSpacing[i];

  std::cout <<  " spacing " << spacing << " dim " << 2 << std::endl;

  bool dosmooth=1;
  if (argc > 4) spacing[0] = atof(argv[4]);
  if (argc > 5) spacing[1] = atof(argv[5]);
  if (argc > 6) dosmooth = atoi(argv[6]);
  int addvox=0;
  if (argc > 7) addvox = atoi(argv[7]);
  bool nn=false;
  if (argc > 8) nn = atoi(argv[7]);

  std::cout <<  " spacing2 " << spacing << std::endl;

  InternalImageType::ConstPointer smoothedImage = reader->GetOutput();
  if( dosmooth )
  {
  for (int sm=0; sm<2; sm++)
  {
  typedef itk::RecursiveGaussianImageFilter<
                                  OutputImageType,
                                  OutputImageType > GaussianFilterType;

  GaussianFilterType::Pointer smootherX = GaussianFilterType::New();
  smootherX->SetInput( smoothedImage );
  float sig = 0;
  sig = atof(argv[4+sm])/inputSpacing[sm]-1.0;
  std::cout << " smoothing by : " << sig << " dir " << sm << std::endl;
  smootherX->SetSigma( sig );
  smootherX->SetDirection( sm );
  smootherX->SetNormalizeAcrossScale( false );
  if (sig > 0 && dosmooth)
  {
  try
    {
    smootherX->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception catched !" << std::endl;
    std::cerr << excep << std::endl;
    }
    smoothedImage = smootherX->GetOutput();
  }
  }
  }

 // InternalImageType::ConstPointer smoothedImage = smootherY->GetOutput();

 // InternalImageType::ConstPointer smoothedImage = reader->GetOutput();
  //smoothedImage =SmoothImage<ImageType>(reader->GetOutput() , );

  typedef itk::ResampleImageFilter<
                  InternalImageType, OutputImageType >  ResampleFilterType;

  ResampleFilterType::Pointer resampler = ResampleFilterType::New();

  typedef itk::IdentityTransform< double, 2 >  TransformType;

  typedef itk::LinearInterpolateImageFunction<
    InternalImageType, double >  InterpolatorType;
  typedef itk::NearestNeighborInterpolateImageFunction<
    InternalImageType, double >  InterpolatorType2;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();
  InterpolatorType2::Pointer interpolator2 = InterpolatorType2::New();

  resampler->SetInterpolator( interpolator );
  if (nn == 1 ) resampler->SetInterpolator( interpolator2 );

  InternalImageType::IndexType ind;
  ind.Fill(1);
  resampler->SetDefaultPixelValue( inputImage->GetPixel(ind) ); // zero regions without source

  std::cout << " out space " << spacing << std::endl;
  resampler->SetOutputSpacing( spacing );
  // Use the same origin
  resampler->SetOutputOrigin( inputImage->GetOrigin() );
  // Use the same origin
  resampler->SetOutputDirection( inputImage->GetDirection() );

  InputImageType::SizeType   inputSize = inputImage->GetLargestPossibleRegion().GetSize();
  typedef InputImageType::SizeType::SizeValueType SizeValueType;
  InputImageType::SizeType   size;

  for (int i=0; i<2; i++)
    size[i] = static_cast<SizeValueType>(inputSize[i] * inputSpacing[i] / spacing[i]+addvox);

  std::cout << " output size " << size << " spc " << spacing << std::endl;
  resampler->SetSize( size );

  resampler->SetInput( smoothedImage );

  writer->SetInput( resampler->GetOutput() );

  TransformType::Pointer transform = TransformType::New();

  transform->SetIdentity();

  resampler->SetTransform( transform );

  try
    {
    writer->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception catched !" << std::endl;
    std::cerr << excep << std::endl;
    }

    }

  if (Dimension == 3)
    {

  typedef   float  InputPixelType;
  typedef   float           InternalPixelType;
  typedef   float   OutputPixelType;

  typedef itk::Image< InputPixelType,    3 >   InputImageType;
  typedef itk::Image< InternalPixelType, 3 >   InternalImageType;
  typedef itk::Image< OutputPixelType,   3 >   OutputImageType;

  typedef itk::ImageFileReader< InputImageType  >  ReaderType;
  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName( argv[2] );
  writer->SetFileName( argv[3] );

  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception caught!" << std::endl;
    std::cerr << excep << std::endl;
    }

  InputImageType::ConstPointer inputImage = reader->GetOutput();

  const InputImageType::SpacingType& inputSpacing = inputImage->GetSpacing();

  OutputImageType::SpacingType spacing;
  for (int i=0; i<3; i++) spacing[i]=inputSpacing[i];

  std::cout <<  " spacing " << spacing << " dim " << 3 << std::endl;

  bool dosmooth=1;
  if (argc > 4) spacing[0] = atof(argv[4]);
  if (argc > 5) spacing[1] = atof(argv[5]);
  if (argc > 6) spacing[2] = atof(argv[6]);
  if (argc > 7) dosmooth = atoi(argv[7]);
  int addvox=0;
  if (argc > 8) addvox = atoi(argv[8]);
  bool nn=false;
  if (argc > 9) nn = atoi(argv[9]);

  std::cout <<  " spacing2 " << spacing << std::endl;

  InternalImageType::ConstPointer smoothedImage = reader->GetOutput();
  if( dosmooth )
  {
  for (int sm=0; sm<3; sm++)
  {
  typedef itk::RecursiveGaussianImageFilter<
                                  OutputImageType,
                                  OutputImageType > GaussianFilterType;

  GaussianFilterType::Pointer smootherX = GaussianFilterType::New();
  smootherX->SetInput( smoothedImage );
  float sig = 0;
  sig = atof(argv[4+sm])/inputSpacing[sm]-1.0;
  std::cout << " smoothing by : " << sig << " dir " << sm << std::endl;
  smootherX->SetSigma( sig );
  smootherX->SetDirection( sm );
  smootherX->SetNormalizeAcrossScale( false );
  if (sig > 0 && dosmooth)
  {
  try
    {
    smootherX->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception catched !" << std::endl;
    std::cerr << excep << std::endl;
    }
    smoothedImage = smootherX->GetOutput();
  }
  }
  }

 // InternalImageType::ConstPointer smoothedImage = smootherY->GetOutput();

 // InternalImageType::ConstPointer smoothedImage = reader->GetOutput();
  //smoothedImage =SmoothImage<ImageType>(reader->GetOutput() , );

  typedef itk::ResampleImageFilter<
                  InternalImageType, OutputImageType >  ResampleFilterType;

  ResampleFilterType::Pointer resampler = ResampleFilterType::New();

  typedef itk::IdentityTransform< double, 3 >  TransformType;

  typedef itk::LinearInterpolateImageFunction<
    InternalImageType, double >  InterpolatorType;
  typedef itk::NearestNeighborInterpolateImageFunction<
    InternalImageType, double >  InterpolatorType2;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();
  InterpolatorType2::Pointer interpolator2 = InterpolatorType2::New();

  resampler->SetInterpolator( interpolator );
  if (nn  == 1 ) resampler->SetInterpolator( interpolator2 );

  InternalImageType::IndexType ind;
  ind.Fill(1);
  resampler->SetDefaultPixelValue( inputImage->GetPixel(ind) ); // zero regions without source

  std::cout << " out space " << spacing << std::endl;
  resampler->SetOutputSpacing( spacing );
  // Use the same origin
  resampler->SetOutputOrigin( inputImage->GetOrigin() );
  // Use the same origin
  resampler->SetOutputDirection( inputImage->GetDirection() );

  InputImageType::SizeType   inputSize = inputImage->GetLargestPossibleRegion().GetSize();
  typedef InputImageType::SizeType::SizeValueType SizeValueType;
  InputImageType::SizeType   size;

  for (int i=0; i<3; i++)
    size[i] = static_cast<SizeValueType>(inputSize[i] * inputSpacing[i] / spacing[i]+addvox);

  std::cout << " output size " << size << " spc " << spacing << std::endl;
  resampler->SetSize( size );

  resampler->SetInput( smoothedImage );

  writer->SetInput( resampler->GetOutput() );

  TransformType::Pointer transform = TransformType::New();

  transform->SetIdentity();

  resampler->SetTransform( transform );

  try
    {
    writer->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception catched !" << std::endl;
    std::cerr << excep << std::endl;
    }

    }

  return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2015 Felix Rieseberg <feriese@microsoft.com> and
// Jason Poon <jason.poon@microsoft.com>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "brightray/browser/win/notification_presenter_win.h"

#include <string>
#include <vector>

#include "base/files/file_util.h"
#include "base/md5.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/win/windows_version.h"
#include "brightray/browser/win/notification_presenter_win7.h"
#include "brightray/browser/win/windows_toast_notification.h"
#include "content/public/browser/desktop_notification_delegate.h"
#include "content/public/common/platform_notification_data.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"

#pragma comment(lib, "runtimeobject.lib")

namespace brightray {

namespace {

bool SaveIconToPath(const SkBitmap& bitmap, const base::FilePath& path) {
  std::vector<unsigned char> png_data;
  if (!gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &png_data))
    return false;

  char* data = reinterpret_cast<char*>(&png_data[0]);
  int size = static_cast<int>(png_data.size());
  return base::WriteFile(path, data, size) == size;
}

}  // namespace

// static
NotificationPresenter* NotificationPresenter::Create() {
  auto version = base::win::GetVersion();
  if (version < base::win::VERSION_WIN8)
    return new NotificationPresenterWin7;
  if (!WindowsToastNotification::Initialize())
    return nullptr;
  std::unique_ptr<NotificationPresenterWin> presenter(
      new NotificationPresenterWin);
  if (!presenter->Init())
    return nullptr;
  return presenter.release();
}

NotificationPresenterWin::NotificationPresenterWin() {
}

NotificationPresenterWin::~NotificationPresenterWin() {
}

bool NotificationPresenterWin::Init() {
  return temp_dir_.CreateUniqueTempDir();
}

base::string16 NotificationPresenterWin::SaveIconToFilesystem(
    const SkBitmap& icon, const GURL& origin) {
  std::string filename;

  if (origin.is_valid()) {
    filename = base::MD5String(origin.spec()) + ".png";
  } else {
    base::TimeTicks now = base::TimeTicks::Now();
    filename = std::to_string(now.ToInternalValue()) + ".png";
  }

  base::FilePath path = temp_dir_.GetPath().Append(base::UTF8ToUTF16(filename));
  if (base::PathExists(path))
    return path.value();
  if (SaveIconToPath(icon, path))
    return path.value();
  return base::UTF8ToUTF16(origin.spec());
}

Notification* NotificationPresenterWin::CreateNotificationObject(
    NotificationDelegate* delegate) {
  return new WindowsToastNotification(delegate, this);
}

}  // namespace brightray
<commit_msg>Remove dead header file for notification delegate<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2015 Felix Rieseberg <feriese@microsoft.com> and
// Jason Poon <jason.poon@microsoft.com>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "brightray/browser/win/notification_presenter_win.h"

#include <string>
#include <vector>

#include "base/files/file_util.h"
#include "base/md5.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/win/windows_version.h"
#include "brightray/browser/win/notification_presenter_win7.h"
#include "brightray/browser/win/windows_toast_notification.h"
#include "content/public/common/platform_notification_data.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"

#pragma comment(lib, "runtimeobject.lib")

namespace brightray {

namespace {

bool SaveIconToPath(const SkBitmap& bitmap, const base::FilePath& path) {
  std::vector<unsigned char> png_data;
  if (!gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &png_data))
    return false;

  char* data = reinterpret_cast<char*>(&png_data[0]);
  int size = static_cast<int>(png_data.size());
  return base::WriteFile(path, data, size) == size;
}

}  // namespace

// static
NotificationPresenter* NotificationPresenter::Create() {
  auto version = base::win::GetVersion();
  if (version < base::win::VERSION_WIN8)
    return new NotificationPresenterWin7;
  if (!WindowsToastNotification::Initialize())
    return nullptr;
  std::unique_ptr<NotificationPresenterWin> presenter(
      new NotificationPresenterWin);
  if (!presenter->Init())
    return nullptr;
  return presenter.release();
}

NotificationPresenterWin::NotificationPresenterWin() {
}

NotificationPresenterWin::~NotificationPresenterWin() {
}

bool NotificationPresenterWin::Init() {
  return temp_dir_.CreateUniqueTempDir();
}

base::string16 NotificationPresenterWin::SaveIconToFilesystem(
    const SkBitmap& icon, const GURL& origin) {
  std::string filename;

  if (origin.is_valid()) {
    filename = base::MD5String(origin.spec()) + ".png";
  } else {
    base::TimeTicks now = base::TimeTicks::Now();
    filename = std::to_string(now.ToInternalValue()) + ".png";
  }

  base::FilePath path = temp_dir_.GetPath().Append(base::UTF8ToUTF16(filename));
  if (base::PathExists(path))
    return path.value();
  if (SaveIconToPath(icon, path))
    return path.value();
  return base::UTF8ToUTF16(origin.spec());
}

Notification* NotificationPresenterWin::CreateNotificationObject(
    NotificationDelegate* delegate) {
  return new WindowsToastNotification(delegate, this);
}

}  // namespace brightray
<|endoftext|>


<commit_before>#define _USE_MATH_DEFINES
#include <math.h>
#include "BLITSaw_oscillator.h"

namespace Steinberg { namespace Vst {

// constructor
BLITSaw_oscillator_note::BLITSaw_oscillator_note()
:_adsr(Off)
,t(0.0)
,saw(0.0)
,n(0)
,dt(0.0)
,srate(44100)
{
}

//
void BLITSaw_oscillator_note::setSampleRate(int srate)
{
	this->srate = srate;
}

//
void BLITSaw_oscillator_note::release()
{
	_adsr = Off;
}

//---------
//
//---------
void BLITSaw_oscillator_note::trigger(const NoteOnEvent& noteOn)
{
	_noteOn = noteOn; // copy
	_adsr = On;

	//
	double freq = 440.0*( ::pow(2.0, (_noteOn.pitch - _note_no_center)/12.0 ));
	n = static_cast<int>(srate / 2.0 / freq);
	dt = freq / srate;
}

//
int32 BLITSaw_oscillator_note::id()const
{
	return _noteOn.noteId;
}

//
double BLITSaw_oscillator_note::velocity()const
{
	return _noteOn.velocity;
}

// constructor
BLITSaw_oscillator::BLITSaw_oscillator()
{
	// sine wave table
	for(size_t ii = 0; ii< _sinTable.size()-1; ii++)
	{
		_sinTable[ii] = sin( 2.0*M_PI * ii/(_sinTable.size()-1));
	}
	_sinTable.back() = 0.0;

	_Leak = 0.995;
}

//
void BLITSaw_oscillator::setLeak(double value)
{
	_Leak = value;
}

//
double BLITSaw_oscillator::LinearInterpolatedSin( double x )
{
	//
	double pos = (_sinTable.size()-1) * x;

	//
	unsigned int idx_A = static_cast<int>(pos);

	//
	double s = pos - idx_A;

	//
	return (1.0-s) * _sinTable[idx_A] + s*_sinTable[idx_A+1];
}

//
double BLITSaw_oscillator::BLIT( double t, int N )
{
	//
	double x_denominator = LinearInterpolatedSin( 0.5*t );

	if( x_denominator < 1.0e-12 )
	{
		return 2.0*(2*N+1);
	}

	double x_numerator = LinearInterpolatedSin(::fmod((N+0.5)*t, 1.0));

	return 2.0*x_numerator/x_denominator;
}

//
void BLITSaw_oscillator::updateOscillater(BLITSaw_oscillator_note& note)
{
	note.t += note.dt;
	if ( 1.0 <= note.t )note.t -= 1.0;

	note.saw = note.saw*_Leak + (BLIT(note.t, note.n)-2.0)*note.dt;
}

}}<commit_msg>初期値設定漏れてた<commit_after>#define _USE_MATH_DEFINES
#include <math.h>
#include "BLITSaw_oscillator.h"

namespace Steinberg { namespace Vst {

// constructor
BLITSaw_oscillator_note::BLITSaw_oscillator_note()
:_adsr(Off)
,t(0.0)
,saw(0.0)
,n(0)
,dt(0.0)
,srate(44100)
{
}

//
void BLITSaw_oscillator_note::setSampleRate(int srate)
{
	this->srate = srate;
}

//
void BLITSaw_oscillator_note::release()
{
	_adsr = Off;
}

//---------
//
//---------
void BLITSaw_oscillator_note::trigger(const NoteOnEvent& noteOn)
{
	_noteOn = noteOn; // copy
	_adsr = On;

	//
	double freq = 440.0*( ::pow(2.0, (_noteOn.pitch - _note_no_center)/12.0 ));
	n = static_cast<int>(srate / 2.0 / freq);
	dt = freq / srate;
	t = 0.5;
}

//
int32 BLITSaw_oscillator_note::id()const
{
	return _noteOn.noteId;
}

//
double BLITSaw_oscillator_note::velocity()const
{
	return _noteOn.velocity;
}

// constructor
BLITSaw_oscillator::BLITSaw_oscillator()
{
	// sine wave table
	for(size_t ii = 0; ii< _sinTable.size()-1; ii++)
	{
		_sinTable[ii] = sin( 2.0*M_PI * ii/(_sinTable.size()-1));
	}
	_sinTable.back() = 0.0;

	_Leak = 0.995;
}

//
void BLITSaw_oscillator::setLeak(double value)
{
	_Leak = value;
}

//
double BLITSaw_oscillator::LinearInterpolatedSin( double x )
{
	//
	double pos = (_sinTable.size()-1) * x;

	//
	unsigned int idx_A = static_cast<int>(pos);

	//
	double s = pos - idx_A;

	//
	return (1.0-s) * _sinTable[idx_A] + s*_sinTable[idx_A+1];
}

//
double BLITSaw_oscillator::BLIT( double t, int N )
{
	//
	double x_denominator = LinearInterpolatedSin( 0.5*t );

	if( x_denominator < 1.0e-12 )
	{
		return 2.0*(2*N+1);
	}

	double x_numerator = LinearInterpolatedSin(::fmod((N+0.5)*t, 1.0));

	return 2.0*x_numerator/x_denominator;
}

//
void BLITSaw_oscillator::updateOscillater(BLITSaw_oscillator_note& note)
{
	note.t += note.dt;
	if ( 1.0 <= note.t )note.t -= 1.0;

	note.saw = note.saw*_Leak + (BLIT(note.t, note.n)-2.0)*note.dt;
}

}}<|endoftext|>