<commit_before>#ifndef DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH
#define DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#include <dune/common/shared_ptr.hh>

#include <dune/grid/io/file/vtk/vtkwriter.hh>

#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/parameter.hh>
#include <dune/stuff/function/interface.hh>

namespace Dune {
namespace Detailed {
namespace Solvers {
namespace Stationary {
namespace Linear {
namespace Elliptic {
namespace Model {

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class Interface;

template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
public:
  typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;

  typedef DomainFieldImp  DomainFieldType;
  static const int        dimDomain = domainDim;

  typedef RangeFieldImp   RangeFieldType;
  static const int        dimRange = 1;

  typedef typename Stuff::Common::Parameter::FieldType  ParamFieldType;
  static const int                                      maxParamDim = Stuff::Common::Parameter::maxDim;
  typedef typename Stuff::Common::Parameter::Type       ParamType;

  typedef Dune::Stuff::Function::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > FunctionType;

  static const std::string id()
  {
    return "model.stationary.linear.elliptic";
  }

  /** \defgroup type ´´These methods determine the type of the model (and also, which of the below methods have to be implemented).'' */
  /* @{ */
  virtual bool parametric() const
  {
    if (diffusion()->parametric() || force()->parametric() || dirichlet()->parametric() || neumann()->parametric())
      return true;
    else
      return false;
  }

  virtual bool separable() const
  {
    if (parametric()) {
      if (diffusion()->parametric() && !diffusion()->separable())
        return false;
      if (force()->parametric() && !force()->separable())
        return false;
      if (dirichlet()->parametric() && !dirichlet()->separable())
        return false;
      if (neumann()->parametric() && !neumann()->separable())
        return false;
      return true;
    } else
      return false;
  }
  /* @} */

  /** \defgroup purevirtual ´´These methods have to be implemented.'' */
  /* @{ */
  virtual Dune::shared_ptr< const FunctionType > diffusion() const = 0;

  virtual Dune::shared_ptr< const FunctionType > force() const = 0;

  virtual Dune::shared_ptr< const FunctionType > dirichlet() const = 0;

  virtual Dune::shared_ptr< const FunctionType > neumann() const = 0;
  /* @} */

  /** \defgroup parametric ´´These methods have to be implemented additionally, if parametric() == true.'' */
  /* @{ */
  virtual size_t paramSize() const
  {
    if (!parametric())
      return 0;
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< ParamType >& paramRange() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< std::string >& paramExplanation() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  /**
   * \brief     Maps a global to a local parameter.
   * \param[in] ParamType _globalMu
   *            global parameter
   * \param[in] std::string _id
   *            To identify the function, wrt which the localization is carried out. Has to be one of diffusion,
   *            force, dirichlet or neumann
   * \return    ParamType
   *            local parameter
   */
  virtual ParamType mapParam(const ParamType& /*_globalMu*/, const std::string /*_id*/) const
  {
    if (!parametric())
      return ParamType();
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }
  /* @} */

//  virtual const Dune::shared_ptr< const NonparametricType > fix(const ParamType&) const = 0;

//  void report(std::ostream& out = std::cout, std::string prefix = "") const
//  {
//    out << prefix << "parameter explanation:" << std::endl;
//    assert(paramExplanation().size() == paramSize());
//    assert(paramRange().size() == 2);
//    assert(paramRange()[0].size() == paramSize());
//    assert(paramRange()[1].size() == paramSize());
//    for (size_t pp = 0; pp < paramSize(); ++pp)
//      out << prefix << "  " << paramExplanation()[pp] << ", between " << paramRange()[0](pp) << " and " << paramRange()[1](pp) << std::endl;
//  }

  template< class GridViewType >
  void visualize(const GridViewType& gridView, std::string filename) const
  {
    // prepare data
    Dune::VTKWriter< GridViewType > vtkWriter(gridView);
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > diffusionPlots
        = preparePlot(gridView, *(diffusion()), "diffusion");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > forcePlots
        = preparePlot(gridView, *(force()), "force");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > dirichletPlots
        = preparePlot(gridView, *(dirichlet()), "dirichlet");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > neumannPlots
        = preparePlot(gridView, *(neumann()), "neumann");
    // walk the grid view
    for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
         it != gridView.template end< 0 >();
         ++it) {
      const typename GridViewType::template Codim< 0 >::Entity& entity = *it;
      const typename GridViewType::IndexSet::IndexType index = gridView.indexSet().index(entity);
      const typename FunctionType::DomainType center = entity.geometry().center();
      // do a piecewise constant projection of the data functions
      //   * diffusion
      if (diffusion()->parametric() && diffusion()->separable())
        for (size_t qq = 0; qq < diffusion()->numComponents(); ++qq)
          diffusionPlots[qq].second->operator[](index) = diffusion()->components()[qq]->evaluate(center);
      else if (!diffusion()->parametric())
        diffusionPlots[0].second->operator[](index) = diffusion()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not separable data functions!");
      //   * force
      if (force()->parametric() && force()->separable())
        for (size_t qq = 0; qq < force()->numComponents(); ++qq)
          forcePlots[qq].second->operator[](index) = force()->components()[qq]->evaluate(center);
      else if (!force()->parametric())
        forcePlots[0].second->operator[](index) = force()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not separable data functions!");
      //   * dirichlet
      if (dirichlet()->parametric() && dirichlet()->separable())
        for (size_t qq = 0; qq < dirichlet()->numComponents(); ++qq)
          dirichletPlots[qq].second->operator[](index) = dirichlet()->components()[qq]->evaluate(center);
      else if (!dirichlet()->parametric())
        dirichletPlots[0].second->operator[](index) = dirichlet()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not separable data functions!");
      //   * neumann
      if (neumann()->parametric() && neumann()->separable())
        for (size_t qq = 0; qq < neumann()->numComponents(); ++qq)
          neumannPlots[qq].second->operator[](index) = neumann()->components()[qq]->evaluate(center);
      else if (!neumann()->parametric())
        neumannPlots[0].second->operator[](index) = neumann()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not separable data functions!");
    } // walk the grid view
    // write
    //   * diffusion
    for (size_t qq = 0; qq < diffusionPlots.size(); ++qq)
      vtkWriter.addCellData(*(diffusionPlots[qq].second), diffusionPlots[qq].first);
    //   * force
    for (size_t qq = 0; qq < forcePlots.size(); ++qq)
      vtkWriter.addCellData(*(forcePlots[qq].second), forcePlots[qq].first);
    //   * dirichlet
    for (size_t qq = 0; qq < dirichletPlots.size(); ++qq)
      vtkWriter.addCellData(*(dirichletPlots[qq].second), dirichletPlots[qq].first);
    //   * neumann
    for (size_t qq = 0; qq < neumannPlots.size(); ++qq)
      vtkWriter.addCellData(*(neumannPlots[qq].second), neumannPlots[qq].first);
    vtkWriter.write(filename, Dune::VTK::ascii);
  } // void visualize(const GridViewType& gridView, std::string filename) const

private:
  template< class GridViewType, class FunctionType >
  std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(const GridViewType& gridView,
                                                                                const FunctionType& function,
                                                                                const std::string name) const
  {
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > ret;
    if (function.parametric()) {
      if (function.separable()) {
        const std::vector< std::string >& paramExplanations = function.paramExplanation();
        for (size_t qq = 0; qq < function.numComponents(); ++qq)
          ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
                          name + "_component_" + Dune::Stuff::Common::toString(qq) + ": " + paramExplanations[qq],
                          new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
      } else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not separable data functions!");
    } else {
      ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
                      name,
                      new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
    }
    return ret;
  } // std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(...) const

}; // class Interface

} // namespace Model
} // namespace Elliptic
} // namespace Linear
} // namespace Stationary
} // namespace Solvers
} // namespace Detailed
} // namespace Dune

#endif // DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH
<commit_msg>[...elliptic.model.interface] added fix(mu)<commit_after>#ifndef DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH
#define DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#include <dune/common/shared_ptr.hh>

#include <dune/grid/io/file/vtk/vtkwriter.hh>

#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/parameter.hh>
#include <dune/stuff/function/interface.hh>
#include <dune/stuff/function/fixed.hh>

namespace Dune {
namespace Detailed {
namespace Solvers {
namespace Stationary {
namespace Linear {
namespace Elliptic {
namespace Model {

// forward of the nonparametric default
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class Default;

// forward to allow for specialization
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class Interface;

template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
public:
  typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;

  typedef DomainFieldImp  DomainFieldType;
  static const int        dimDomain = domainDim;

  typedef RangeFieldImp   RangeFieldType;
  static const int        dimRange = 1;

  typedef typename Stuff::Common::Parameter::FieldType  ParamFieldType;
  static const int                                      maxParamDim = Stuff::Common::Parameter::maxDim;
  typedef typename Stuff::Common::Parameter::Type       ParamType;

  typedef Dune::Stuff::Function::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > FunctionType;

  static const std::string id()
  {
    return "model.stationary.linear.elliptic";
  }

  /** \defgroup type ´´These methods determine the type of the model (and also, which of the below methods have to be implemented).'' */
  /* @{ */
  virtual bool parametric() const
  {
    if (diffusion()->parametric() || force()->parametric() || dirichlet()->parametric() || neumann()->parametric())
      return true;
    else
      return false;
  }

  virtual bool separable() const
  {
    if (parametric()) {
      if (diffusion()->parametric() && !diffusion()->separable())
        return false;
      if (force()->parametric() && !force()->separable())
        return false;
      if (dirichlet()->parametric() && !dirichlet()->separable())
        return false;
      if (neumann()->parametric() && !neumann()->separable())
        return false;
      return true;
    } else
      return false;
  }
  /* @} */

  /** \defgroup purevirtual ´´These methods have to be implemented.'' */
  /* @{ */
  virtual Dune::shared_ptr< const FunctionType > diffusion() const = 0;

  virtual Dune::shared_ptr< const FunctionType > force() const = 0;

  virtual Dune::shared_ptr< const FunctionType > dirichlet() const = 0;

  virtual Dune::shared_ptr< const FunctionType > neumann() const = 0;
  /* @} */

  /** \defgroup parametric ´´These methods have to be implemented additionally, if parametric() == true.'' */
  /* @{ */
  virtual size_t paramSize() const
  {
    if (!parametric())
      return 0;
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< ParamType >& paramRange() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< std::string >& paramExplanation() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  /**
   * \brief     Maps a global to a local parameter.
   * \param[in] ParamType _globalMu
   *            global parameter
   * \param[in] std::string _id
   *            To identify the function, wrt which the localization is carried out. Has to be one of diffusion,
   *            force, dirichlet or neumann
   * \return    ParamType
   *            local parameter
   */
  virtual ParamType mapParam(const ParamType& /*_globalMu*/, const std::string /*_id*/) const
  {
    if (!parametric())
      return ParamType();
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }
  /* @} */

  virtual Dune::shared_ptr< const ThisType > fix(const ParamType& mu) const
  {
    typedef Dune::Stuff::Function::Fixed< DomainFieldType, dimDomain, RangeFieldType, dimRange > FixedFunctionType;
    typedef Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > DefaultModelType;
    Dune::shared_ptr< DefaultModelType >
        defaultModel(Dune::make_shared< DefaultModelType >(diffusion()->parametric() ? Dune::make_shared< const FixedFunctionType >(diffusion(), mapParam(mu, "diffusion")) : diffusion(),
                                                      force()->parametric() ? Dune::make_shared< const FixedFunctionType >(force(), mapParam(mu, "force")) : force(),
                                                      dirichlet()->parametric() ? Dune::make_shared< const FixedFunctionType >(dirichlet(), mapParam(mu, "dirichlet")) : dirichlet(),
                                                      neumann()->parametric() ? Dune::make_shared< const FixedFunctionType >(neumann(), mapParam(mu, "neumann")) : neumann()));
    return defaultModel;
  }

//  void report(std::ostream& out = std::cout, std::string prefix = "") const
//  {
//    out << prefix << "parameter explanation:" << std::endl;
//    assert(paramExplanation().size() == paramSize());
//    assert(paramRange().size() == 2);
//    assert(paramRange()[0].size() == paramSize());
//    assert(paramRange()[1].size() == paramSize());
//    for (size_t pp = 0; pp < paramSize(); ++pp)
//      out << prefix << "  " << paramExplanation()[pp] << ", between " << paramRange()[0](pp) << " and " << paramRange()[1](pp) << std::endl;
//  }

  template< class GridViewType >
  void visualize(const GridViewType& gridView, std::string filename) const
  {
    // prepare data
    Dune::VTKWriter< GridViewType > vtkWriter(gridView);
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > diffusionPlots
        = preparePlot(gridView, *(diffusion()), "diffusion");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > forcePlots
        = preparePlot(gridView, *(force()), "force");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > dirichletPlots
        = preparePlot(gridView, *(dirichlet()), "dirichlet");
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > neumannPlots
        = preparePlot(gridView, *(neumann()), "neumann");
    // walk the grid view
    for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
         it != gridView.template end< 0 >();
         ++it) {
      const typename GridViewType::template Codim< 0 >::Entity& entity = *it;
      const typename GridViewType::IndexSet::IndexType index = gridView.indexSet().index(entity);
      const typename FunctionType::DomainType center = entity.geometry().center();
      // do a piecewise constant projection of the data functions
      //   * diffusion
      if (diffusion()->parametric() && diffusion()->separable())
        for (size_t qq = 0; qq < diffusion()->numComponents(); ++qq)
          diffusionPlots[qq].second->operator[](index) = diffusion()->components()[qq]->evaluate(center);
      else if (!diffusion()->parametric())
        diffusionPlots[0].second->operator[](index) = diffusion()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not separable data functions!");
      //   * force
      if (force()->parametric() && force()->separable())
        for (size_t qq = 0; qq < force()->numComponents(); ++qq)
          forcePlots[qq].second->operator[](index) = force()->components()[qq]->evaluate(center);
      else if (!force()->parametric())
        forcePlots[0].second->operator[](index) = force()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not separable data functions!");
      //   * dirichlet
      if (dirichlet()->parametric() && dirichlet()->separable())
        for (size_t qq = 0; qq < dirichlet()->numComponents(); ++qq)
          dirichletPlots[qq].second->operator[](index) = dirichlet()->components()[qq]->evaluate(center);
      else if (!dirichlet()->parametric())
        dirichletPlots[0].second->operator[](index) = dirichlet()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not separable data functions!");
      //   * neumann
      if (neumann()->parametric() && neumann()->separable())
        for (size_t qq = 0; qq < neumann()->numComponents(); ++qq)
          neumannPlots[qq].second->operator[](index) = neumann()->components()[qq]->evaluate(center);
      else if (!neumann()->parametric())
        neumannPlots[0].second->operator[](index) = neumann()->evaluate(center);
      else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not separable data functions!");
    } // walk the grid view
    // write
    //   * diffusion
    for (size_t qq = 0; qq < diffusionPlots.size(); ++qq)
      vtkWriter.addCellData(*(diffusionPlots[qq].second), diffusionPlots[qq].first);
    //   * force
    for (size_t qq = 0; qq < forcePlots.size(); ++qq)
      vtkWriter.addCellData(*(forcePlots[qq].second), forcePlots[qq].first);
    //   * dirichlet
    for (size_t qq = 0; qq < dirichletPlots.size(); ++qq)
      vtkWriter.addCellData(*(dirichletPlots[qq].second), dirichletPlots[qq].first);
    //   * neumann
    for (size_t qq = 0; qq < neumannPlots.size(); ++qq)
      vtkWriter.addCellData(*(neumannPlots[qq].second), neumannPlots[qq].first);
    vtkWriter.write(filename, Dune::VTK::ascii);
  } // void visualize(const GridViewType& gridView, std::string filename) const

private:
  template< class GridViewType, class FunctionType >
  std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(const GridViewType& gridView,
                                                                                const FunctionType& function,
                                                                                const std::string name) const
  {
    std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > ret;
    if (function.parametric()) {
      if (function.separable()) {
        const std::vector< std::string >& paramExplanations = function.paramExplanation();
        for (size_t qq = 0; qq < function.numComponents(); ++qq)
          ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
                          name + "_component_" + Dune::Stuff::Common::toString(qq) + ": " + paramExplanations[qq],
                          new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
      } else
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                   << " visualize() not yet implemented for parametric but not separable data functions!");
    } else {
      ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
                      name,
                      new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
    }
    return ret;
  } // std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(...) const

}; // class Interface

} // namespace Model
} // namespace Elliptic
} // namespace Linear
} // namespace Stationary
} // namespace Solvers
} // namespace Detailed
} // namespace Dune

#endif // DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
//	File: Date.cpp
//
//	class: Date
//	methods:
//		Date::Date(short day, short month, short year)
//		bool Date::operator==(const Comparable &other)const
//		bool Date::operator<(const Comparable &other)const
//		void Date::setCurrentDate(void)
//		void Date::setDayOfWeek(void)
//		void Date::setDayOfYear(void)
//		short Date::countLeaps(short year)const
//		void Date::setDayOfMonth(short dayOfMonth)
//		void Date::setMonth(short month)
//		void Date::setYear(short year)
//-----------------------------------------------------------------------------
#include "Date.h"

namespace NP_DATETIME
{
	//-----------------------------------------------------------------------------
	//    method:		Date(short day, short month, short year) -- constructor
	//
	//    description:	creates a new Date object
	//
	//    Calls:            setCurrentDate()
	//			daysInMonth(month, year)
	//			setDayOfYear()
	//			setDayOfWeek()
	//
	//    Called By:	ostream& operator<<(ostream& sout, const CComplex &c)
	//
	//    Parameters:	short day -- day to set
	//			short month -- month to set
	//			short year -- month to set
	//
	//    History Log:
	//			2/9/08  PB  completed version 1.0
	// ----------------------------------------------------------------------------
	Date::Date(short day, short month, short year)
	{
		setDayOfMonth(day);
		setMonth(month);
		setYear(year);
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		operator==(const Comparable& other) const
	//
	//    description:	true if the two objects are exactly the same
	//
	//    Parameters:	const Comparable &other  -- the other Date to compare
	//
	//    Called By:	main, >=, <=
	//
	//    Returns:          true if the two objects are exactly the same;
	//				false otherwise
	//    History Log:
	//			5/8/16  PB  completed version 1.1
	//-----------------------------------------------------------------------------
	bool Date::operator==(const Comparable &other) const
	{
		bool returnValue = false;
		try
		{
			const Date &otherDate =
				dynamic_cast<const Date&>(other);
			returnValue = (
				m_year == otherDate.m_year &&
				getDayOfYear() == otherDate.getDayOfYear()
				);
		}
		catch (bad_cast e)
		{
			// Should something happen here?
		}
		return returnValue;
	}
	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		operator<(const Comparable& other) const
	//
	//    description:	true if the current object is before other
	//
	//    Parameters:	const Comparable &other  -- the other Date to compare
	//
	//    Called By:	main, >, <=
	//
	//	  Calls:		getYear, getDayOfYear
	//
	//    Exceptions:	throws bad_cast if other is not a Date
	//
	//    Returns:		true if the current object is before other;
	//				false otherwise
	//    History Log:
	//			5/8/16  PB  completed version 1.1
	// ----------------------------------------------------------------------------

	bool Date::operator<(const Comparable &other) const
	{
		bool returnValue = false;

		try {
			Date otherDate = dynamic_cast<const Date&>(other);

			bool yearLT = otherDate.getYear() < getYear();
			bool yearEQ = otherDate.getYear() == getYear();
			bool dayLT = otherDate.getDayOfYear() < getDayOfYear();

			returnValue = (yearLT || yearEQ && dayLT);
		}
		catch (bad_cast e) {
			throw new invalid_argument("Date can only be compared to Date objects");
		}

		return returnValue;
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		setCurrentDate()
	//
	//    description:	sets the date from the system clock
	//
	//    Called By:	constructor
	//
	//    History Log:
	//			2/9/08  PB  completed version 1.0
	// ----------------------------------------------------------------------------
	void Date::setCurrentDate(void)
	{
		time_t rawtime;
		tm *currentTimePtr;
		time(&rawtime);
		currentTimePtr = localtime(&rawtime);

		m_year = currentTimePtr->tm_year + 1900;
		m_month = currentTimePtr->tm_mon;
		m_dayOfMonth = currentTimePtr->tm_mday;
	}

	//-----------------------------------------------------------------------------
	//    Class:			Date
	//    method:			countLeaps(short year)const
	//
	//    description:	returns the number of leap years from 1760 to year
	//
	//    Calls:            isLeapYear(short)
	//
	//    Returns:          the number of leap years from 1760 to year
	//
	//    History Log:
	//                           2/9/08  PB  completed version 1.0
	//-----------------------------------------------------------------------------
	short Date::countLeaps(short year)const
	{
		short leaps = 0;
		for (short i = LOWYEAR; i < year; i++)
			if (isLeapYear(i))
				leaps++;
		return leaps;
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		getDayOfYear() const
	//
	//    description:	python styled property for getting index of day in year
	//
	//    Calls:		getDayOfMonth(), daysInMonty(), Accessors
	//
	//    Parameters:
	//
	//	  Returns:		totalDays -- int of day index of day in year
	//
	//    History Log:
	//					02/09/08  PB  completed version 1.0
	//					04/13/17  NP  appeneded to version 1.0
	//-----------------------------------------------------------------------------
	short Date::getDayOfYear() const
	{
		short totalDays = getDayOfMonth();
		for (short month = 0; month < getMonth(); month++) {
			totalDays += daysInMonth(m_month, getYear());
		}
		return totalDays;
	}

	const string Date::monthName(int monthNum)
	{
		string month;
		switch (monthNum) {
		case 0:
			month = "January";
			break;
		case 1:
			month = "February";
			break;
		case 2:
			month = "March";
			break;
		case 3:
			month = "April";
			break;
		case 4:
			month = "May";
			break;
		case 5:
			month = "June";
			break;
		case 6:
			month = "July";
			break;
		case 7:
			month = "August";
			break;
		case 8:
			month = "September";
			break;
		case 9:
			month = "October";
			break;
		case 10:
			month = "November";
			break;
		case 11:
			month = "December";
			break;
		}
		return month;
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		setDayOfMonth(short dayOfMonth)
	//
	//    description:	mutator for m_dayOfMonth
	//
	//    Calls:            daysInMonth(short, short)
	//
	//    Parameters:	dayOfMonth --  day of month to set
	//
	//    History Log:
	//			2/9/08  PB  completed version 1.0
	//-----------------------------------------------------------------------------
	void Date::setDayOfMonth(short dayOfMonth)
	{
		if (dayOfMonth > 0
			&& dayOfMonth <= daysInMonth(m_month, m_year))
		{
			m_dayOfMonth = dayOfMonth;
		}
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		setMonth(short dmonth)
	//
	//    description:	mutator for m_month
	//
	//    Calls:        daysInMonth(short, short)
	//
	//    Parameters:	month --  month to set
	//
	//    History Log:
	//			2/9/08  PB  completed version 1.0
	//-----------------------------------------------------------------------------
	void Date::setMonth(short month)
	{
		if (month > 0 && month < MONTHSINYEAR)
			m_month = month;
		else
			m_month = 0;
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		setYear(short year)
	//
	//    description:	mutator for m_year
	//
	//    Calls:        isLeapYear(short)
	//
	//    Parameters:	year --  year to set
	//
	//    History Log:
	//			 2/9/08  PB  completed version 1.0
	//-----------------------------------------------------------------------------
	void Date::setYear(short year)
	{
		if (year > LOWYEAR)
			m_year = year;
		else
			m_year = LOWYEAR;
	}
	//-----------------------------------------------------------------------------
	void Date::input(istream& sin)
	{

	}
	//-----------------------------------------------------------------------------
	void Date::print(ostream& sout)const
	{
		sout << m_dayOfMonth << '/' << m_month << '/' << m_year;
	}

}
<commit_msg>add weekdayName method<commit_after>//-----------------------------------------------------------------------------
//	File: Date.cpp
//
//	class: Date
//	methods:
//		Date::Date(short day, short month, short year)
//		bool Date::operator==(const Comparable &other)const
//		bool Date::operator<(const Comparable &other)const
//		void Date::setCurrentDate(void)
//		void Date::setDayOfWeek(void)
//		void Date::setDayOfYear(void)
//		short Date::countLeaps(short year)const
//		void Date::setDayOfMonth(short dayOfMonth)
//		void Date::setMonth(short month)
//		void Date::setYear(short year)
//-----------------------------------------------------------------------------
#include "Date.h"

namespace NP_DATETIME
{
	//-----------------------------------------------------------------------------
	//    method:		Date(short day, short month, short year) -- constructor
	//
	//    description:	creates a new Date object
	//
	//    Calls:            setCurrentDate()
	//			daysInMonth(month, year)
	//			setDayOfYear()
	//			setDayOfWeek()
	//
	//    Called By:	ostream& operator<<(ostream& sout, const CComplex &c)
	//
	//    Parameters:	short day -- day to set
	//			short month -- month to set
	//			short year -- month to set
	//
	//    History Log:
	//			2/9/08  PB  completed version 1.0
	// ----------------------------------------------------------------------------
	Date::Date(short day, short month, short year)
	{
		setDayOfMonth(day);
		setMonth(month);
		setYear(year);
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		operator==(const Comparable& other) const
	//
	//    description:	true if the two objects are exactly the same
	//
	//    Parameters:	const Comparable &other  -- the other Date to compare
	//
	//    Called By:	main, >=, <=
	//
	//    Returns:          true if the two objects are exactly the same;
	//				false otherwise
	//    History Log:
	//			5/8/16  PB  completed version 1.1
	//-----------------------------------------------------------------------------
	bool Date::operator==(const Comparable &other) const
	{
		bool returnValue = false;
		try
		{
			const Date &otherDate =
				dynamic_cast<const Date&>(other);
			returnValue = (
				m_year == otherDate.m_year &&
				getDayOfYear() == otherDate.getDayOfYear()
				);
		}
		catch (bad_cast e)
		{
			// Should something happen here?
		}
		return returnValue;
	}
	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		operator<(const Comparable& other) const
	//
	//    description:	true if the current object is before other
	//
	//    Parameters:	const Comparable &other  -- the other Date to compare
	//
	//    Called By:	main, >, <=
	//
	//	  Calls:		getYear, getDayOfYear
	//
	//    Exceptions:	throws bad_cast if other is not a Date
	//
	//    Returns:		true if the current object is before other;
	//				false otherwise
	//    History Log:
	//			5/8/16  PB  completed version 1.1
	// ----------------------------------------------------------------------------

	bool Date::operator<(const Comparable &other) const
	{
		bool returnValue = false;

		try {
			Date otherDate = dynamic_cast<const Date&>(other);

			bool yearLT = otherDate.getYear() < getYear();
			bool yearEQ = otherDate.getYear() == getYear();
			bool dayLT = otherDate.getDayOfYear() < getDayOfYear();

			returnValue = (yearLT || yearEQ && dayLT);
		}
		catch (bad_cast e) {
			throw new invalid_argument("Date can only be compared to Date objects");
		}

		return returnValue;
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		setCurrentDate()
	//
	//    description:	sets the date from the system clock
	//
	//    Called By:	constructor
	//
	//    History Log:
	//			2/9/08  PB  completed version 1.0
	// ----------------------------------------------------------------------------
	void Date::setCurrentDate(void)
	{
		time_t rawtime;
		tm *currentTimePtr;
		time(&rawtime);
		currentTimePtr = localtime(&rawtime);

		m_year = currentTimePtr->tm_year + 1900;
		m_month = currentTimePtr->tm_mon;
		m_dayOfMonth = currentTimePtr->tm_mday;
	}

	//-----------------------------------------------------------------------------
	//    Class:			Date
	//    method:			countLeaps(short year)const
	//
	//    description:	returns the number of leap years from 1760 to year
	//
	//    Calls:            isLeapYear(short)
	//
	//    Returns:          the number of leap years from 1760 to year
	//
	//    History Log:
	//                           2/9/08  PB  completed version 1.0
	//-----------------------------------------------------------------------------
	short Date::countLeaps(short year)const
	{
		short leaps = 0;
		for (short i = LOWYEAR; i < year; i++)
			if (isLeapYear(i))
				leaps++;
		return leaps;
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		getDayOfYear() const
	//
	//    description:	python styled property for getting index of day in year
	//
	//    Calls:		getDayOfMonth(), daysInMonty(), Accessors
	//
	//    Parameters:
	//
	//	  Returns:		totalDays -- int of day index of day in year
	//
	//    History Log:
	//					02/09/08  PB  completed version 1.0
	//					04/13/17  NP  appeneded to version 1.0
	//-----------------------------------------------------------------------------
	short Date::getDayOfYear() const
	{
		short totalDays = getDayOfMonth();
		for (short month = 0; month < getMonth(); month++) {
			totalDays += daysInMonth(m_month, getYear());
		}
		return totalDays;
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		monthName() const
	//
	//    description:	returns string of month name
	//
	//    Calls:
	//
	//    Parameters:
	//
	//	  Returns:		string -- month name
	//
	//    History Log:
	//					02/09/08  PB  completed version 1.0
	//					04/13/17  NP  appeneded to version 1.0
	//-----------------------------------------------------------------------------
	const string Date::monthName(int monthNum)
	{
		string month;
		switch (monthNum) {
		case 0:
			month = "January";
			break;
		case 1:
			month = "February";
			break;
		case 2:
			month = "March";
			break;
		case 3:
			month = "April";
			break;
		case 4:
			month = "May";
			break;
		case 5:
			month = "June";
			break;
		case 6:
			month = "July";
			break;
		case 7:
			month = "August";
			break;
		case 8:
			month = "September";
			break;
		case 9:
			month = "October";
			break;
		case 10:
			month = "November";
			break;
		case 11:
			month = "December";
			break;
		}
		return month;
	}

	const string Date::weekdayName(int weekdayNum)
	{
		string dayOfWeek;
		switch (getDayOfWeek()) {
		case 0:
			dayOfWeek = "Sunday";
			break;
		case 1:
			dayOfWeek = "Monday";
			break;
		case 2:
			dayOfWeek = "Tuesday";
			break;
		case 3:
			dayOfWeek = "Wednesday";
			break;
		case 4:
			dayOfWeek = "Thursday";
			break;
		case 5:
			dayOfWeek = "Friday";
			break;
		case 6:
			dayOfWeek = "Saturday";
			break;
		}
		return dayOfWeek;
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		setDayOfMonth(short dayOfMonth)
	//
	//    description:	mutator for m_dayOfMonth
	//
	//    Calls:            daysInMonth(short, short)
	//
	//    Parameters:	dayOfMonth --  day of month to set
	//
	//    History Log:
	//			2/9/08  PB  completed version 1.0
	//-----------------------------------------------------------------------------
	void Date::setDayOfMonth(short dayOfMonth)
	{
		if (dayOfMonth > 0
			&& dayOfMonth <= daysInMonth(m_month, m_year))
		{
			m_dayOfMonth = dayOfMonth;
		}
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		setMonth(short dmonth)
	//
	//    description:	mutator for m_month
	//
	//    Calls:        daysInMonth(short, short)
	//
	//    Parameters:	month --  month to set
	//
	//    History Log:
	//			2/9/08  PB  completed version 1.0
	//-----------------------------------------------------------------------------
	void Date::setMonth(short month)
	{
		if (month > 0 && month < MONTHSINYEAR)
			m_month = month;
		else
			m_month = 0;
	}

	//-----------------------------------------------------------------------------
	//    Class:		Date
	//    method:		setYear(short year)
	//
	//    description:	mutator for m_year
	//
	//    Calls:        isLeapYear(short)
	//
	//    Parameters:	year --  year to set
	//
	//    History Log:
	//			 2/9/08  PB  completed version 1.0
	//-----------------------------------------------------------------------------
	void Date::setYear(short year)
	{
		if (year > LOWYEAR)
			m_year = year;
		else
			m_year = LOWYEAR;
	}

	//-----------------------------------------------------------------------------
	void Date::input(istream& sin)
	{

	}

	//-----------------------------------------------------------------------------
	void Date::print(ostream& sout)const
	{
		sout << m_dayOfMonth << '/' << m_month << '/' << m_year;
	}

}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2019 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "Builder.h"
#include "ospray_testing.h"
// stl
#include <random>
#include <vector>
// ospcommon
#include "ospcommon/tasking/parallel_for.h"
// raw_to_amr
#include "rawToAMR.h"

using namespace ospcommon;
using namespace ospcommon::math;

namespace ospray {
  namespace testing {

    using VoxelArray = std::vector<float>;

    struct GravitySpheres : public detail::Builder
    {
      GravitySpheres(bool addVolume     = true,
                     bool asAMR         = false,
                     bool addIsosurface = false);
      ~GravitySpheres() override = default;

      void commit() override;

      cpp::Group buildGroup() const override;

     private:
      VoxelArray generateVoxels() const;

      cpp::Volume createStructuredVolume(const VoxelArray &voxels) const;
      cpp::Volume createAMRVolume(const VoxelArray &voxels) const;

      // Data //

      vec3i volumeDimensions{128};
      int numPoints{10};
      bool withVolume{true};
      bool createAsAMR{false};
      bool withIsosurface{false};
      float isovalue{2.5f};
    };

    // Inlined definitions ////////////////////////////////////////////////////

    GravitySpheres::GravitySpheres(bool addVolume,
                                   bool asAMR,
                                   bool addIsosurface)
        : withVolume(addVolume),
          createAsAMR(asAMR),
          withIsosurface(addIsosurface)
    {
    }

    void GravitySpheres::commit()
    {
      Builder::commit();

      volumeDimensions = getParam<vec3i>("volumeDimensions", vec3i(128));
      numPoints        = getParam<int>("numPoints", 10);
      withVolume       = getParam<bool>("withVolume", withVolume);
      createAsAMR      = getParam<bool>("asAMR", createAsAMR);
      withIsosurface   = getParam<bool>("withIsosurface", withIsosurface);
      isovalue         = getParam<float>("isovalue", 2.5f);

      addPlane = false;
    }

    cpp::Group GravitySpheres::buildGroup() const
    {
      auto voxels     = generateVoxels();
      auto voxelRange = vec2f(0.f, 10.f);

      cpp::Volume volume = createAsAMR ? createAMRVolume(voxels)
                                       : createStructuredVolume(voxels);

      cpp::VolumetricModel model(volume);
      model.setParam("transferFunction", makeTransferFunction(voxelRange));
      model.commit();

      cpp::Group group;

      if (withVolume)
        group.setParam("volume", cpp::Data(model));

      if (withIsosurface) {
        cpp::Geometry isoGeom("isosurfaces");
        isoGeom.setParam("isovalue", cpp::Data(isovalue));
        isoGeom.setParam("volume", model);
        isoGeom.commit();

        cpp::Material mat(rendererType, "OBJMaterial");
        mat.setParam("Ks", vec3f(0.2f));
        mat.commit();

        cpp::GeometricModel isoModel(isoGeom);
        isoModel.setParam("material", cpp::Data(mat));
        isoModel.commit();

        group.setParam("geometry", cpp::Data(isoModel));
      }

      group.commit();

      return group;
    }

    std::vector<float> GravitySpheres::generateVoxels() const
    {
      struct Point
      {
        vec3f center;
        float weight;
      };

      // create random number distributions for point center and weight
      std::mt19937 gen(randomSeed);

      std::uniform_real_distribution<float> centerDistribution(-1.f, 1.f);
      std::uniform_real_distribution<float> weightDistribution(0.1f, 0.3f);

      // populate the points
      std::vector<Point> points(numPoints);

      for (auto &p : points) {
        p.center.x = centerDistribution(gen);
        p.center.y = centerDistribution(gen);
        p.center.z = centerDistribution(gen);

        p.weight = weightDistribution(gen);
      }

      // get world coordinate in [-1.f, 1.f] from logical coordinates in [0,
      // volumeDimension)
      auto logicalToWorldCoordinates = [&](int i, int j, int k) {
        return vec3f(-1.f + float(i) / float(volumeDimensions.x - 1) * 2.f,
                     -1.f + float(j) / float(volumeDimensions.y - 1) * 2.f,
                     -1.f + float(k) / float(volumeDimensions.z - 1) * 2.f);
      };

      // generate voxels
      std::vector<float> voxels(volumeDimensions.long_product());

      tasking::parallel_for(volumeDimensions.z, [&](int k) {
        for (int j = 0; j < volumeDimensions.y; j++) {
          for (int i = 0; i < volumeDimensions.x; i++) {
            // index in array
            size_t index = k * volumeDimensions.z * volumeDimensions.y +
                           j * volumeDimensions.x + i;

            // compute volume value
            float value = 0.f;

            for (auto &p : points) {
              vec3f pointCoordinate = logicalToWorldCoordinates(i, j, k);
              const float distance  = length(pointCoordinate - p.center);

              // contribution proportional to weighted inverse-square distance
              // (i.e. gravity)
              value += p.weight / (distance * distance);
            }

            voxels[index] = value;
          }
        }
      });

      return voxels;
    }

    cpp::Volume GravitySpheres::createStructuredVolume(
        const VoxelArray &voxels) const
    {
      cpp::Volume volume("structured_volume");

      volume.setParam("dimensions", volumeDimensions);
      volume.setParam("voxelType", int(OSP_FLOAT));
      volume.setParam("gridOrigin", vec3f(-1.f, -1.f, -1.f));
      volume.setParam("gridSpacing", vec3f(2.f / reduce_max(volumeDimensions)));
      volume.setParam("voxelData", cpp::Data(voxels));

      volume.commit();
      return volume;
    }

    cpp::Volume GravitySpheres::createAMRVolume(const VoxelArray &voxels) const
    {
      const int numLevels       = 2;
      const int blockSize       = 16;
      const int refinementLevel = 4;
      const float threshold     = 1.0;

      std::vector<box3i> blockBounds;
      std::vector<int> refinementLevels;
      std::vector<float> cellWidths;
      std::vector<std::vector<float>> blockDataVectors;
      std::vector<cpp::Data> blockData;

      // convert the structured volume to AMR
      ospray::amr::makeAMR(voxels,
                           volumeDimensions,
                           numLevels,
                           blockSize,
                           refinementLevel,
                           threshold,
                           blockBounds,
                           refinementLevels,
                           cellWidths,
                           blockDataVectors);

      for (const std::vector<float> &bd : blockDataVectors)
        blockData.emplace_back(bd.size(), OSP_FLOAT, bd.data());

      // create an AMR volume and assign attributes
      cpp::Volume volume("amr_volume");

      volume.setParam("voxelType", int(OSP_FLOAT));
      volume.setParam("block.data", cpp::Data(blockData));
      volume.setParam("block.bounds", cpp::Data(blockBounds));
      volume.setParam("block.level", cpp::Data(refinementLevels));
      volume.setParam("block.cellWidth", cpp::Data(cellWidths));

      volume.commit();

      return volume;
    }

    OSP_REGISTER_TESTING_BUILDER(GravitySpheres, gravity_spheres_volume);

    OSP_REGISTER_TESTING_BUILDER(GravitySpheres(true, true, false),
                                 gravity_spheres_amr);

    OSP_REGISTER_TESTING_BUILDER(GravitySpheres(false, false, true),
                                 gravity_spheres_isosurface);

  }  // namespace testing
}  // namespace ospray
<commit_msg>fix for 64-bit addresses + use 3D dimensions in GravitySpheresVolume<commit_after>// ======================================================================== //
// Copyright 2009-2019 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "Builder.h"
#include "ospray_testing.h"
// stl
#include <random>
#include <vector>
// ospcommon
#include "ospcommon/tasking/parallel_for.h"
// raw_to_amr
#include "rawToAMR.h"

using namespace ospcommon;
using namespace ospcommon::math;

namespace ospray {
  namespace testing {

    using VoxelArray = std::vector<float>;

    struct GravitySpheres : public detail::Builder
    {
      GravitySpheres(bool addVolume     = true,
                     bool asAMR         = false,
                     bool addIsosurface = false);
      ~GravitySpheres() override = default;

      void commit() override;

      cpp::Group buildGroup() const override;

     private:
      VoxelArray generateVoxels() const;

      cpp::Volume createStructuredVolume(const VoxelArray &voxels) const;
      cpp::Volume createAMRVolume(const VoxelArray &voxels) const;

      // Data //

      vec3i volumeDimensions{128};
      int numPoints{10};
      bool withVolume{true};
      bool createAsAMR{false};
      bool withIsosurface{false};
      float isovalue{2.5f};
    };

    // Inlined definitions ////////////////////////////////////////////////////

    GravitySpheres::GravitySpheres(bool addVolume,
                                   bool asAMR,
                                   bool addIsosurface)
        : withVolume(addVolume),
          createAsAMR(asAMR),
          withIsosurface(addIsosurface)
    {
    }

    void GravitySpheres::commit()
    {
      Builder::commit();

      volumeDimensions = getParam<vec3i>("volumeDimensions", vec3i(128));
      numPoints        = getParam<int>("numPoints", 10);
      withVolume       = getParam<bool>("withVolume", withVolume);
      createAsAMR      = getParam<bool>("asAMR", createAsAMR);
      withIsosurface   = getParam<bool>("withIsosurface", withIsosurface);
      isovalue         = getParam<float>("isovalue", 2.5f);

      addPlane = false;
    }

    cpp::Group GravitySpheres::buildGroup() const
    {
      auto voxels     = generateVoxels();
      auto voxelRange = vec2f(0.f, 10.f);

      cpp::Volume volume = createAsAMR ? createAMRVolume(voxels)
                                       : createStructuredVolume(voxels);

      cpp::VolumetricModel model(volume);
      model.setParam("transferFunction", makeTransferFunction(voxelRange));
      model.commit();

      cpp::Group group;

      if (withVolume)
        group.setParam("volume", cpp::Data(model));

      if (withIsosurface) {
        cpp::Geometry isoGeom("isosurfaces");
        isoGeom.setParam("isovalue", cpp::Data(isovalue));
        isoGeom.setParam("volume", model);
        isoGeom.commit();

        cpp::Material mat(rendererType, "OBJMaterial");
        mat.setParam("Ks", vec3f(0.2f));
        mat.commit();

        cpp::GeometricModel isoModel(isoGeom);
        isoModel.setParam("material", cpp::Data(mat));
        isoModel.commit();

        group.setParam("geometry", cpp::Data(isoModel));
      }

      group.commit();

      return group;
    }

    std::vector<float> GravitySpheres::generateVoxels() const
    {
      struct Point
      {
        vec3f center;
        float weight;
      };

      // create random number distributions for point center and weight
      std::mt19937 gen(randomSeed);

      std::uniform_real_distribution<float> centerDistribution(-1.f, 1.f);
      std::uniform_real_distribution<float> weightDistribution(0.1f, 0.3f);

      // populate the points
      std::vector<Point> points(numPoints);

      for (auto &p : points) {
        p.center.x = centerDistribution(gen);
        p.center.y = centerDistribution(gen);
        p.center.z = centerDistribution(gen);

        p.weight = weightDistribution(gen);
      }

      // get world coordinate in [-1.f, 1.f] from logical coordinates in [0,
      // volumeDimension)
      auto logicalToWorldCoordinates = [&](int i, int j, int k) {
        return vec3f(-1.f + float(i) / float(volumeDimensions.x - 1) * 2.f,
                     -1.f + float(j) / float(volumeDimensions.y - 1) * 2.f,
                     -1.f + float(k) / float(volumeDimensions.z - 1) * 2.f);
      };

      // generate voxels
      std::vector<float> voxels(volumeDimensions.long_product());

      tasking::parallel_for(volumeDimensions.z, [&](int k) {
        for (int j = 0; j < volumeDimensions.y; j++) {
          for (int i = 0; i < volumeDimensions.x; i++) {
            // index in array
            size_t index = size_t(k) * volumeDimensions.z * volumeDimensions.y +
                           size_t(j) * volumeDimensions.x + size_t(i);

            // compute volume value
            float value = 0.f;

            for (auto &p : points) {
              vec3f pointCoordinate = logicalToWorldCoordinates(i, j, k);
              const float distance  = length(pointCoordinate - p.center);

              // contribution proportional to weighted inverse-square distance
              // (i.e. gravity)
              value += p.weight / (distance * distance);
            }

            voxels[index] = value;
          }
        }
      });

      return voxels;
    }

    cpp::Volume GravitySpheres::createStructuredVolume(
        const VoxelArray &voxels) const
    {
      cpp::Volume volume("structured_volume");

      volume.setParam("dimensions", volumeDimensions);
      volume.setParam("voxelType", int(OSP_FLOAT));
      volume.setParam("gridOrigin", vec3f(-1.f, -1.f, -1.f));
      volume.setParam("gridSpacing", vec3f(2.f / reduce_max(volumeDimensions)));
      volume.setParam("voxelData",
                      cpp::Data(volumeDimensions, {0}, voxels.data()));

      volume.commit();
      return volume;
    }

    cpp::Volume GravitySpheres::createAMRVolume(const VoxelArray &voxels) const
    {
      const int numLevels       = 2;
      const int blockSize       = 16;
      const int refinementLevel = 4;
      const float threshold     = 1.0;

      std::vector<box3i> blockBounds;
      std::vector<int> refinementLevels;
      std::vector<float> cellWidths;
      std::vector<std::vector<float>> blockDataVectors;
      std::vector<cpp::Data> blockData;

      // convert the structured volume to AMR
      ospray::amr::makeAMR(voxels,
                           volumeDimensions,
                           numLevels,
                           blockSize,
                           refinementLevel,
                           threshold,
                           blockBounds,
                           refinementLevels,
                           cellWidths,
                           blockDataVectors);

      for (const std::vector<float> &bd : blockDataVectors)
        blockData.emplace_back(bd.size(), OSP_FLOAT, bd.data());

      // create an AMR volume and assign attributes
      cpp::Volume volume("amr_volume");

      volume.setParam("voxelType", int(OSP_FLOAT));
      volume.setParam("block.data", cpp::Data(blockData));
      volume.setParam("block.bounds", cpp::Data(blockBounds));
      volume.setParam("block.level", cpp::Data(refinementLevels));
      volume.setParam("block.cellWidth", cpp::Data(cellWidths));

      volume.commit();

      return volume;
    }

    OSP_REGISTER_TESTING_BUILDER(GravitySpheres, gravity_spheres_volume);

    OSP_REGISTER_TESTING_BUILDER(GravitySpheres(true, true, false),
                                 gravity_spheres_amr);

    OSP_REGISTER_TESTING_BUILDER(GravitySpheres(false, false, true),
                                 gravity_spheres_isosurface);

  }  // namespace testing
}  // namespace ospray
<|endoftext|>


<commit_before>/*
 * ArcEmu MMORPG Server
 * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
 * Copyright (C) 2008 <http://www.ArcEmu.org/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

//
// MapCell.cpp
//
#include "StdAfx.h"

MapCell::~MapCell()
{
	RemoveObjects();
}

void MapCell::Init(uint32 x, uint32 y, uint32 mapid, MapMgr *mapmgr)
{
	_mapmgr = mapmgr;
	_active = false;
	_loaded = false;
	_playerCount = 0;
	_x=x;
	_y=y;
	_unloadpending=false;
	_objects.clear();
}

void MapCell::AddObject(Object *obj)
{
	if(obj->IsPlayer())
		++_playerCount;

	_objects.insert(obj);
}

void MapCell::RemoveObject(Object *obj)
{
	if(obj->IsPlayer())
		--_playerCount;

	_objects.erase(obj);
}

void MapCell::SetActivity(bool state)
{
	if(!_active && state)
	{
		// Move all objects to active set.
		for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
		{
			if(!(*itr)->Active && (*itr)->CanActivate())
				(*itr)->Activate(_mapmgr);
		}

		if(_unloadpending)
			CancelPendingUnload();

		if (sWorld.Collision) {
			CollideInterface.ActivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
		}
	} else if(_active && !state)
	{
		// Move all objects from active set.
		for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
		{
			if((*itr)->Active)
				(*itr)->Deactivate(_mapmgr);
		}

		if(sWorld.map_unload_time && !_unloadpending)
			QueueUnloadPending();

		if (sWorld.Collision) {
			CollideInterface.DeactivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
		}
	}

	_active = state;

}
void MapCell::RemoveObjects()
{
	ObjectSet::iterator itr;
	uint32 count = 0;
	//uint32 ltime = getMSTime();

	/* delete objects in pending respawn state */
	for(itr = _respawnObjects.begin(); itr != _respawnObjects.end(); ++itr)
	{
		switch((*itr)->GetTypeId())
		{
		case TYPEID_UNIT: {
				if( !(*itr)->IsPet() )
				{
					_mapmgr->_reusable_guids_creature.push_back( (*itr)->GetUIdFromGUID() );
					static_cast< Creature* >( *itr )->m_respawnCell=NULL;
					delete static_cast< Creature* >( *itr );
				}
			}break;

		case TYPEID_GAMEOBJECT: {
			_mapmgr->_reusable_guids_gameobject.push_back( (*itr)->GetUIdFromGUID() );
			static_cast< GameObject* >( *itr )->m_respawnCell=NULL;
			delete static_cast< GameObject* >( *itr );
			}break;
		}
	}
	_respawnObjects.clear();

	//This time it's simpler! We just remove everything :)
	for(itr = _objects.begin(); itr != _objects.end(); )
	{
		count++;

		Object *obj = (*itr);

		itr++;

		if(!obj || _unloadpending)
			continue;

		if( obj->Active )
			obj->Deactivate( _mapmgr );

		if( obj->IsInWorld() )
			obj->RemoveFromWorld( true );

		delete obj;
	}
	_objects.clear();

	_playerCount = 0;
	_loaded = false;
}

void MapCell::LoadObjects(CellSpawns * sp)
{
	_loaded = true;
	Instance * pInstance = _mapmgr->pInstance;
	InstanceBossInfoMap *bossInfoMap = objmgr.m_InstanceBossInfoMap[_mapmgr->GetMapId()];

	if(sp->CreatureSpawns.size())//got creatures
	{
		for(CreatureSpawnList::iterator i=sp->CreatureSpawns.begin();i!=sp->CreatureSpawns.end();i++)
		{
			uint32 respawnTimeOverride = 0;
			if(pInstance)
			{
				if(bossInfoMap != NULL && IS_PERSISTENT_INSTANCE(pInstance))
				{
					bool skip = false;
					for(std::set<uint32>::iterator killedNpc = pInstance->m_killedNpcs.begin(); killedNpc != pInstance->m_killedNpcs.end(); ++killedNpc)
					{
						// Do not spawn the killed boss.
						if((*killedNpc) == (*i)->entry)
						{
							skip = true;
							break;
						}
						// Do not spawn the killed boss' trash.
						InstanceBossInfoMap::const_iterator bossInfo = bossInfoMap->find((*killedNpc));
						if (bossInfo != bossInfoMap->end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
						{
							skip = true;
							break;
						}
					}
					if(skip)
						continue;

					for(InstanceBossInfoMap::iterator bossInfo = bossInfoMap->begin(); bossInfo != bossInfoMap->end(); ++bossInfo)
					{
						if(pInstance->m_killedNpcs.find(bossInfo->second->creatureid) == pInstance->m_killedNpcs.end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
						{
							respawnTimeOverride = bossInfo->second->trashRespawnOverride;
						}
					}
				}
				else
				{
					// No boss information available ... fallback ...
					if(pInstance->m_killedNpcs.find((*i)->id) != pInstance->m_killedNpcs.end())
						continue;
				}
			}

			Creature * c=_mapmgr->CreateCreature((*i)->entry);

			c->SetMapId(_mapmgr->GetMapId());
			c->SetInstanceID(_mapmgr->GetInstanceID());
			c->m_loadedFromDB = true;
			if(respawnTimeOverride > 0)
				c->m_respawnTimeOverride = respawnTimeOverride;

            if(c->Load(*i, _mapmgr->iInstanceMode, _mapmgr->GetMapInfo()))
			{
				if(!c->CanAddToWorld())
					delete c;

				c->PushToWorld(_mapmgr);
			}
			else
				delete c;//missing proto or smth of that kind
		}
	}

	if(sp->GOSpawns.size())//got GOs
	{
		for(GOSpawnList::iterator i=sp->GOSpawns.begin();i!=sp->GOSpawns.end();i++)
		{
			GameObject * go=_mapmgr->CreateGameObject((*i)->entry);
			go->SetInstanceID(_mapmgr->GetInstanceID());
			if(go->Load(*i))
			{
				//uint32 state = go->GetUInt32Value(GAMEOBJECT_STATE);

				// FIXME - burlex
				/*
				if(pInstance && pInstance->FindObject((*i)->stateNpcLink))
				{
					go->SetUInt32Value(GAMEOBJECT_STATE, (state ? 0 : 1));
				}*/

				go->m_loadedFromDB = true;
				go->PushToWorld(_mapmgr);
			}
			else
				delete go;//missing proto or smth of that kind
		}
	}
}

void MapCell::QueueUnloadPending()
{
	if(_unloadpending)
		return;

	_unloadpending = true;
	//Log.Debug("MapCell", "Queueing pending unload of cell %u %u", _x, _y);
	sEventMgr.AddEvent(_mapmgr, &MapMgr::UnloadCell,(uint32)_x,(uint32)_y,MAKE_CELL_EVENT(_x,_y),sWorld.map_unload_time * 1000,1,0);
}

void MapCell::CancelPendingUnload()
{
	//Log.Debug("MapCell", "Cancelling pending unload of cell %u %u", _x, _y);
	if(!_unloadpending)
		return;

	sEventMgr.RemoveEvents(_mapmgr,MAKE_CELL_EVENT(_x,_y));
}

void MapCell::Unload()
{
	//Log.Debug("MapCell", "Unloading cell %u %u", _x, _y);
	ASSERT(_unloadpending);
	if(_active)
		return;

	RemoveObjects();
	_unloadpending=false;
}
<commit_msg>extending rev 1235 crashfix by 0x0f7afc68. I think there was a logic problem there. The pointout seemed to be good but the fix not. Not sure that was actually a crash issue though. Problem was with cells that entered pending state and meanwhile they got active. This made them get stuck in pending state and not unload anymore and stay loaded forever. NTY.<commit_after>/*
 * ArcEmu MMORPG Server
 * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
 * Copyright (C) 2008 <http://www.ArcEmu.org/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

//
// MapCell.cpp
//
#include "StdAfx.h"

MapCell::~MapCell()
{
	RemoveObjects();
}

void MapCell::Init(uint32 x, uint32 y, uint32 mapid, MapMgr *mapmgr)
{
	_mapmgr = mapmgr;
	_active = false;
	_loaded = false;
	_playerCount = 0;
	_x=x;
	_y=y;
	_unloadpending=false;
	_objects.clear();
}

void MapCell::AddObject(Object *obj)
{
	if(obj->IsPlayer())
		++_playerCount;

	_objects.insert(obj);
}

void MapCell::RemoveObject(Object *obj)
{
	if(obj->IsPlayer())
		--_playerCount;

	_objects.erase(obj);
}

void MapCell::SetActivity(bool state)
{
	if(!_active && state)
	{
		// Move all objects to active set.
		for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
		{
			if(!(*itr)->Active && (*itr)->CanActivate())
				(*itr)->Activate(_mapmgr);
		}

		if(_unloadpending)
			CancelPendingUnload();

		if (sWorld.Collision) {
			CollideInterface.ActivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
		}
	} else if(_active && !state)
	{
		// Move all objects from active set.
		for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
		{
			if((*itr)->Active)
				(*itr)->Deactivate(_mapmgr);
		}

		if(sWorld.map_unload_time && !_unloadpending)
			QueueUnloadPending();

		if (sWorld.Collision) {
			CollideInterface.DeactivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
		}
	}

	_active = state;

}
void MapCell::RemoveObjects()
{
	ObjectSet::iterator itr;
	uint32 count = 0;
	//uint32 ltime = getMSTime();

	//Zack : we are delaying cell removal so transports can see objects far away. We are waiting for the event to remove us
	if( _unloadpending == true )
		return;

	/* delete objects in pending respawn state */
	for(itr = _respawnObjects.begin(); itr != _respawnObjects.end(); ++itr)
	{
		switch((*itr)->GetTypeId())
		{
		case TYPEID_UNIT: {
				if( !(*itr)->IsPet() )
				{
					_mapmgr->_reusable_guids_creature.push_back( (*itr)->GetUIdFromGUID() );
					static_cast< Creature* >( *itr )->m_respawnCell=NULL;
					delete static_cast< Creature* >( *itr );
				}
			}break;

		case TYPEID_GAMEOBJECT: {
			_mapmgr->_reusable_guids_gameobject.push_back( (*itr)->GetUIdFromGUID() );
			static_cast< GameObject* >( *itr )->m_respawnCell=NULL;
			delete static_cast< GameObject* >( *itr );
			}break;
		}
	}
	_respawnObjects.clear();

	//This time it's simpler! We just remove everything :)
	for(itr = _objects.begin(); itr != _objects.end(); )
	{
		count++;

		Object *obj = (*itr);

		itr++;

		//zack : we actually never set this to null. Useless check for lucky memory corruption hit.
		if(!obj)
			continue;

		if( obj->Active )
			obj->Deactivate( _mapmgr );

		if( obj->IsInWorld() )
			obj->RemoveFromWorld( true );

		delete obj;
	}
	_objects.clear();

	_playerCount = 0;
	_loaded = false;
}

void MapCell::LoadObjects(CellSpawns * sp)
{
	//we still have mobs loaded on cell. There is no point of loading them again
	if( _loaded == true )
		return;

	_loaded = true;
	Instance * pInstance = _mapmgr->pInstance;
	InstanceBossInfoMap *bossInfoMap = objmgr.m_InstanceBossInfoMap[_mapmgr->GetMapId()];

	if(sp->CreatureSpawns.size())//got creatures
	{
		for(CreatureSpawnList::iterator i=sp->CreatureSpawns.begin();i!=sp->CreatureSpawns.end();i++)
		{
			uint32 respawnTimeOverride = 0;
			if(pInstance)
			{
				if(bossInfoMap != NULL && IS_PERSISTENT_INSTANCE(pInstance))
				{
					bool skip = false;
					for(std::set<uint32>::iterator killedNpc = pInstance->m_killedNpcs.begin(); killedNpc != pInstance->m_killedNpcs.end(); ++killedNpc)
					{
						// Do not spawn the killed boss.
						if((*killedNpc) == (*i)->entry)
						{
							skip = true;
							break;
						}
						// Do not spawn the killed boss' trash.
						InstanceBossInfoMap::const_iterator bossInfo = bossInfoMap->find((*killedNpc));
						if (bossInfo != bossInfoMap->end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
						{
							skip = true;
							break;
						}
					}
					if(skip)
						continue;

					for(InstanceBossInfoMap::iterator bossInfo = bossInfoMap->begin(); bossInfo != bossInfoMap->end(); ++bossInfo)
					{
						if(pInstance->m_killedNpcs.find(bossInfo->second->creatureid) == pInstance->m_killedNpcs.end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
						{
							respawnTimeOverride = bossInfo->second->trashRespawnOverride;
						}
					}
				}
				else
				{
					// No boss information available ... fallback ...
					if(pInstance->m_killedNpcs.find((*i)->id) != pInstance->m_killedNpcs.end())
						continue;
				}
			}

			Creature * c=_mapmgr->CreateCreature((*i)->entry);

			c->SetMapId(_mapmgr->GetMapId());
			c->SetInstanceID(_mapmgr->GetInstanceID());
			c->m_loadedFromDB = true;
			if(respawnTimeOverride > 0)
				c->m_respawnTimeOverride = respawnTimeOverride;

            if(c->Load(*i, _mapmgr->iInstanceMode, _mapmgr->GetMapInfo()))
			{
				if(!c->CanAddToWorld())
					delete c;

				c->PushToWorld(_mapmgr);
			}
			else
				delete c;//missing proto or smth of that kind
		}
	}

	if(sp->GOSpawns.size())//got GOs
	{
		for(GOSpawnList::iterator i=sp->GOSpawns.begin();i!=sp->GOSpawns.end();i++)
		{
			GameObject * go=_mapmgr->CreateGameObject((*i)->entry);
			go->SetInstanceID(_mapmgr->GetInstanceID());
			if(go->Load(*i))
			{
				//uint32 state = go->GetUInt32Value(GAMEOBJECT_STATE);

				// FIXME - burlex
				/*
				if(pInstance && pInstance->FindObject((*i)->stateNpcLink))
				{
					go->SetUInt32Value(GAMEOBJECT_STATE, (state ? 0 : 1));
				}*/

				go->m_loadedFromDB = true;
				go->PushToWorld(_mapmgr);
			}
			else
				delete go;//missing proto or smth of that kind
		}
	}
}

void MapCell::QueueUnloadPending()
{
	if(_unloadpending)
		return;

	_unloadpending = true;
	//Log.Debug("MapCell", "Queueing pending unload of cell %u %u", _x, _y);
	sEventMgr.AddEvent(_mapmgr, &MapMgr::UnloadCell,(uint32)_x,(uint32)_y,MAKE_CELL_EVENT(_x,_y),sWorld.map_unload_time * 1000,1,0);
}

void MapCell::CancelPendingUnload()
{
	//Log.Debug("MapCell", "Cancelling pending unload of cell %u %u", _x, _y);
	if(!_unloadpending)
		return;

	sEventMgr.RemoveEvents(_mapmgr,MAKE_CELL_EVENT(_x,_y));
}

void MapCell::Unload()
{
	//Log.Debug("MapCell", "Unloading cell %u %u", _x, _y);
	ASSERT(_unloadpending);
	if(_active)
	{
		_unloadpending=false;
		return;
	}

	_unloadpending=false;
	RemoveObjects();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003-2007 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#include "arch/x86/floatregfile.hh"
#include "sim/serialize.hh"

#include <string.h>

using namespace X86ISA;
using namespace std;

class Checkpoint;

string X86ISA::getFloatRegName(RegIndex index)
{
    static std::string floatRegName[NumFloatRegs] =
        {"mmx0", "mmx1", "mmx2", "mmx3", "mmx4", "mmx5", "mmx6", "mmx7",
         "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
         "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"};
    return floatRegName[index];
}

void FloatRegFile::clear()
{
    memset(q, 0, sizeof(FloatReg) * NumFloatRegs);
}

FloatReg FloatRegFile::readReg(int floatReg, int width)
{
    return d[floatReg];
}

FloatRegBits FloatRegFile::readRegBits(int floatReg, int width)
{
    return q[floatReg];
}

Fault FloatRegFile::setReg(int floatReg, const FloatReg &val, int width)
{
    d[floatReg] = val;
    return NoFault;
}

Fault FloatRegFile::setRegBits(int floatReg, const FloatRegBits &val, int width)
{
    q[floatReg] = val;
    return NoFault;
}

void FloatRegFile::serialize(std::ostream &os)
{
    SERIALIZE_ARRAY(q, NumFloatRegs);
}

void FloatRegFile::unserialize(Checkpoint *cp, const std::string &section)
{
    UNSERIALIZE_ARRAY(q, NumFloatRegs);
}

<commit_msg>X86: Add tracing to the floating point register file.<commit_after>/*
 * Copyright (c) 2003-2007 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#include "arch/x86/floatregfile.hh"
#include "base/trace.hh"
#include "sim/serialize.hh"

#include <string.h>

using namespace X86ISA;
using namespace std;

class Checkpoint;

string X86ISA::getFloatRegName(RegIndex index)
{
    static std::string floatRegName[NumFloatRegs] =
        {"mmx0", "mmx1", "mmx2", "mmx3", "mmx4", "mmx5", "mmx6", "mmx7",
         "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
         "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"};
    return floatRegName[index];
}

void FloatRegFile::clear()
{
    memset(q, 0, sizeof(FloatReg) * NumFloatRegs);
}

FloatReg FloatRegFile::readReg(int floatReg, int width)
{
    FloatReg reg = d[floatReg];
    DPRINTF(X86, "Reading %f from register %d.\n", reg, floatReg);
    return reg;
}

FloatRegBits FloatRegFile::readRegBits(int floatReg, int width)
{
    FloatRegBits reg = q[floatReg];
    DPRINTF(X86, "Reading %#x from register %d.\n", reg, floatReg);
    return reg;
}

Fault FloatRegFile::setReg(int floatReg, const FloatReg &val, int width)
{
    DPRINTF(X86, "Writing %f to register %d.\n", val, floatReg);
    d[floatReg] = val;
    return NoFault;
}

Fault FloatRegFile::setRegBits(int floatReg, const FloatRegBits &val, int width)
{
    DPRINTF(X86, "Writing bits %#x to register %d.\n", val, floatReg);
    q[floatReg] = val;
    return NoFault;
}

void FloatRegFile::serialize(std::ostream &os)
{
    SERIALIZE_ARRAY(q, NumFloatRegs);
}

void FloatRegFile::unserialize(Checkpoint *cp, const std::string &section)
{
    UNSERIALIZE_ARRAY(q, NumFloatRegs);
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009 Toni Gundogdu.
 *
 * This file is part of cclive.
 *
 * cclive is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * cclive is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HOST_W32
// A peculiar thing this one. If commented out or included *after* "config.h",
// mingw32-g++ returns: error: '::malloc' has not been declared
#include <cstdlib>
#endif

#include "config.h"

#include <iterator>
#include <sstream>
#include <climits>
#include <iomanip>
#include <string>
#include <vector>

#include "except.h"
#include "util.h"
#include "opts.h"
#include "curl.h"
#include "video.h"

VideoProperties::VideoProperties()
    : id(""),          link(""),      host(""),    domain(""),
      formats("flv"),  title(""),     length(0),   initial(0),
      contentType(""), suffix("flv"), filename(""),pageLink("")
{
}

void
VideoProperties::setId(const std::string& id) {
    this->id = id;
}

void
VideoProperties::setLink(std::string link) {
    this->link = curlmgr.unescape(link);
}

void
VideoProperties::setHost(const std::string& host) {
    this->host = host;
}

void
VideoProperties::setDomain(const std::string& domain) {
    this->domain = domain;
}

void
VideoProperties::setFormats(const std::string& formats) {
    this->formats = formats;
}

void
VideoProperties::setLength(const double length) {
    this->length = length;
}

void
VideoProperties::setPageLink(const std::string& link) {
    this->pageLink = link;
}

void
VideoProperties::setContentType(const std::string& contentType) {
    this->contentType = contentType;

    std::string::size_type pos = contentType.find("/");

    if (pos != std::string::npos) {
        suffix = contentType.substr(pos+1);
        // set to "flv" for these:
        if (suffix.find("octet") != std::string::npos
            || suffix.find("plain") != std::string::npos)
        {
            suffix = "flv";
        }
        Util::subStrReplace(suffix, "x-", "");
    }
}

void
VideoProperties::setInitial(const double initial) {
    this->initial = initial;
}

#include <iostream>
void
VideoProperties::setTitle(const std::string& title) {
    this->title = title;
    std::cout << __func__ << ": " << title << std::endl;
}

const std::string&
VideoProperties::getId() const {
    return id;
}

const std::string&
VideoProperties::getLink() const {
    return link;
}

const std::string&
VideoProperties::getHost() const {
    return host;
}

const std::string&
VideoProperties::getDomain() const {
    return domain;
}

const std::string&
VideoProperties::getFormats() const {
    return formats;
}

const std::string&
VideoProperties::getTitle() const {
    return title;
}

const double
VideoProperties::getLength() const {
    return length;
}

const std::string&
VideoProperties::getPageLink() const {
    return pageLink;
}

const double
VideoProperties::getInitial() const {
    return initial;
}

const std::string&
VideoProperties::getContentType() const {
    return contentType;
}

const std::string&
VideoProperties::getFilename() const {
    return filename;
}

static int video_num;

void
VideoProperties::formatOutputFilename() {

    std::cout << __func__ << ": " << title << std::endl;

    Options opts = optsmgr.getOptions();

    if (!opts.output_video_given) {
        std::stringstream b;

        if (opts.number_videos_given) {
            b << std::setw(4)
              << std::setfill('0')
              << ++video_num
              << "_";
        }

        if (!opts.filename_format_given)
            defaultOutputFilenameFormatter(b);
        else
            customOutputFilenameFormatter(b);

        filename = b.str();

        for (register int i=1; i<INT_MAX; ++i) {
            initial = Util::fileExists(filename);

            if (initial == 0)
                break;
            else if (initial == length)
                throw NothingToDoException();
            else {
                if (opts.continue_given)
                    break;
            }
            std::stringstream tmp;
            tmp << b.str() << "." << i;
            filename = tmp.str();
        }
    }
    else {
        initial = Util::fileExists(opts.output_video_arg);
        if (initial == length)
            throw NothingToDoException();
        filename = opts.output_video_arg;
    }

    if (!opts.continue_given)
        initial = 0;
}

void
VideoProperties::defaultOutputFilenameFormatter(
    std::stringstream& b)
{
    Options opts = optsmgr.getOptions();
    if (opts.title_given && title.length() > 0)
        b << title;
    else {
        Util::subStrReplace(id, "-", "_");
        b << host << "_" << id;
    }

    b << "." << suffix;
}

void
VideoProperties::customOutputFilenameFormatter(
    std::stringstream& b)
{
    Options opts = optsmgr.getOptions();
    std::string fmt = opts.filename_format_arg;
    std::string _title = id;
#ifdef WITH_PERL
    if (opts.title_given && title.length() > 0)
        _title = title;
#endif
    Util::subStrReplace(fmt, "%t", _title);
    Util::subStrReplace(fmt, "%i", id);
    Util::subStrReplace(fmt, "%h", host);
    Util::subStrReplace(fmt, "%s", suffix);

    b << fmt;
}

VideoProperties::
    NothingToDoException::NothingToDoException()
    : RuntimeException(CCLIVE_NOTHINGTODO)
{
}
<commit_msg>video.cpp: remove std::cout from earlier debugging.<commit_after>/*
 * Copyright (C) 2009 Toni Gundogdu.
 *
 * This file is part of cclive.
 *
 * cclive is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * cclive is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HOST_W32
// A peculiar thing this one. If commented out or included *after* "config.h",
// mingw32-g++ returns: error: '::malloc' has not been declared
#include <cstdlib>
#endif

#include "config.h"

#include <iterator>
#include <sstream>
#include <climits>
#include <iomanip>
#include <string>
#include <vector>

#include "except.h"
#include "util.h"
#include "opts.h"
#include "curl.h"
#include "video.h"

VideoProperties::VideoProperties()
    : id(""),          link(""),      host(""),    domain(""),
      formats("flv"),  title(""),     length(0),   initial(0),
      contentType(""), suffix("flv"), filename(""),pageLink("")
{
}

void
VideoProperties::setId(const std::string& id) {
    this->id = id;
}

void
VideoProperties::setLink(std::string link) {
    this->link = curlmgr.unescape(link);
}

void
VideoProperties::setHost(const std::string& host) {
    this->host = host;
}

void
VideoProperties::setDomain(const std::string& domain) {
    this->domain = domain;
}

void
VideoProperties::setFormats(const std::string& formats) {
    this->formats = formats;
}

void
VideoProperties::setLength(const double length) {
    this->length = length;
}

void
VideoProperties::setPageLink(const std::string& link) {
    this->pageLink = link;
}

void
VideoProperties::setContentType(const std::string& contentType) {
    this->contentType = contentType;

    std::string::size_type pos = contentType.find("/");

    if (pos != std::string::npos) {
        suffix = contentType.substr(pos+1);
        // set to "flv" for these:
        if (suffix.find("octet") != std::string::npos
            || suffix.find("plain") != std::string::npos)
        {
            suffix = "flv";
        }
        Util::subStrReplace(suffix, "x-", "");
    }
}

void
VideoProperties::setInitial(const double initial) {
    this->initial = initial;
}

void
VideoProperties::setTitle(const std::string& title) {
    this->title = title;
}

const std::string&
VideoProperties::getId() const {
    return id;
}

const std::string&
VideoProperties::getLink() const {
    return link;
}

const std::string&
VideoProperties::getHost() const {
    return host;
}

const std::string&
VideoProperties::getDomain() const {
    return domain;
}

const std::string&
VideoProperties::getFormats() const {
    return formats;
}

const std::string&
VideoProperties::getTitle() const {
    return title;
}

const double
VideoProperties::getLength() const {
    return length;
}

const std::string&
VideoProperties::getPageLink() const {
    return pageLink;
}

const double
VideoProperties::getInitial() const {
    return initial;
}

const std::string&
VideoProperties::getContentType() const {
    return contentType;
}

const std::string&
VideoProperties::getFilename() const {
    return filename;
}

static int video_num;

void
VideoProperties::formatOutputFilename() {

    Options opts = optsmgr.getOptions();

    if (!opts.output_video_given) {
        std::stringstream b;

        if (opts.number_videos_given) {
            b << std::setw(4)
              << std::setfill('0')
              << ++video_num
              << "_";
        }

        if (!opts.filename_format_given)
            defaultOutputFilenameFormatter(b);
        else
            customOutputFilenameFormatter(b);

        filename = b.str();

        for (register int i=1; i<INT_MAX; ++i) {
            initial = Util::fileExists(filename);

            if (initial == 0)
                break;
            else if (initial == length)
                throw NothingToDoException();
            else {
                if (opts.continue_given)
                    break;
            }
            std::stringstream tmp;
            tmp << b.str() << "." << i;
            filename = tmp.str();
        }
    }
    else {
        initial = Util::fileExists(opts.output_video_arg);
        if (initial == length)
            throw NothingToDoException();
        filename = opts.output_video_arg;
    }

    if (!opts.continue_given)
        initial = 0;
}

void
VideoProperties::defaultOutputFilenameFormatter(
    std::stringstream& b)
{
    Options opts = optsmgr.getOptions();
    if (opts.title_given && title.length() > 0)
        b << title;
    else {
        Util::subStrReplace(id, "-", "_");
        b << host << "_" << id;
    }

    b << "." << suffix;
}

void
VideoProperties::customOutputFilenameFormatter(
    std::stringstream& b)
{
    Options opts = optsmgr.getOptions();
    std::string fmt = opts.filename_format_arg;
    std::string _title = id;
#ifdef WITH_PERL
    if (opts.title_given && title.length() > 0)
        _title = title;
#endif
    Util::subStrReplace(fmt, "%t", _title);
    Util::subStrReplace(fmt, "%i", id);
    Util::subStrReplace(fmt, "%h", host);
    Util::subStrReplace(fmt, "%s", suffix);

    b << fmt;
}

VideoProperties::
    NothingToDoException::NothingToDoException()
    : RuntimeException(CCLIVE_NOTHINGTODO)
{
}
<|endoftext|>