<commit_before>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber

#ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH
#define DUNE_STUFF_FUNCTIONS_CONSTANT_HH

#include <memory>

#include <dune/stuff/common/parameter/tree.hh>

#include "interfaces.hh"

namespace Dune {
namespace Stuff {
namespace Function {

template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class Constant
  : public LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >
{
  typedef LocalizableFunctionInterface
      < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >               BaseType;
  typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >  ThisType;

  class Localfunction
    : public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >
  {
    typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType;
  public:
    typedef typename BaseType::EntityType EntityType;

    typedef typename BaseType::DomainFieldType  DomainFieldType;
    static const unsigned int                   dimDomain = BaseType::dimDomain;
    typedef typename BaseType::DomainType       DomainType;

    typedef typename BaseType::RangeFieldType RangeFieldType;
    static const unsigned int                 dimRange = BaseType::dimRange;
    static const unsigned int                 dimRangeCols = BaseType::dimRangeCols;
    typedef typename BaseType::RangeType      RangeType;

    typedef typename BaseType::JacobianRangeType JacobianRangeType;

    Localfunction(const EntityType& ent, const std::shared_ptr< const RangeType > value)
      : BaseType(ent)
      , value_(value)
    {}

    Localfunction(const Localfunction& /*other*/) = delete;

    Localfunction& operator=(const Localfunction& /*other*/) = delete;

    virtual size_t order() const DS_OVERRIDE
    {
      return 0;
    }

    virtual void evaluate(const DomainType& xx, RangeType& ret) const DS_OVERRIDE
    {
      assert(this->is_a_valid_point(xx));
      ret = *value_;
    }

    virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const DS_OVERRIDE
    {
      assert(this->is_a_valid_point(xx));
      ret *= RangeFieldType(0);
    }

  private:
    const std::shared_ptr< const RangeType > value_;
  }; // class Localfunction

public:
  typedef typename BaseType::EntityType         EntityType;
  typedef typename BaseType::LocalfunctionType  LocalfunctionType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const unsigned int                   dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType       DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const unsigned int                 dimRange = BaseType::dimRange;
  static const unsigned int                 dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType      RangeType;

  static std::string static_id()
  {
    return BaseType::static_id() + ".constant";
  }

  static Dune::ParameterTree defaultSettings(const std::string subName = "")
  {
    Dune::ParameterTree description;
    description["value"] = "1.0";
    if (subName.empty())
      return description;
    else {
      Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  } // ... defaultSettings(...)

  static ThisType* create(const DSC::ExtendedParameterTree settings = defaultSettings())
  {
    return new ThisType(settings.get< RangeFieldType >("value", RangeFieldType(0)));
  } // ... create(...)

  Constant(const RangeFieldType& val, const std::string nm = static_id())
    : value_(std::make_shared< RangeType >(val))
    , name_(nm)
  {}

  Constant(const RangeType& val, const std::string nm = static_id())
    : value_(std::make_shared< RangeType >(val))
    , name_(nm)
  {}

  Constant(const ThisType& other)
    : value_(other.value_)
    , name_(other.name_)
  {}

  ThisType& operator=(const ThisType& other)
  {
    if (this != &other) {
      value_ = other.value_;
      name_ = other.name_;
    }
    return *this;
  }

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  virtual std::string name() const DS_OVERRIDE
  {
    return name_;
  }

  virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const DS_OVERRIDE
  {
    return std::unique_ptr< Localfunction >(new Localfunction(entity, value_));
  }

private:
  std::shared_ptr< const RangeType > value_;
  std::string name_;
}; // class Constant

} // namespace Function
} // namespace Stuff
} // namespace Dune

#ifdef DUNE_STUFF_FUNCTIONS_TO_LIB
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(etype, ddim) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 1) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 2) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 3)

# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, rdim) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 1) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 2) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 3)

# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim)

# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim)

# define DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \
  extern template class Dune::Stuff::Function::Constant< etype, dftype, ddim, rftype, rdim, rcdim >;

DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake3dEntityType, 3)

# if HAVE_DUNE_GRID

DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid3dEntityType, 3)

DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid3dEntityType, 3)

#   if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H

DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid3dEntityType, 3)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluCubeGrid3dEntityType, 3)

#   endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# endif // HAVE_DUNE_GRID

# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE
# endif // DUNE_STUFF_FUNCTIONS_TO_LIB

#endif // DUNE_STUFF_FUNCTIONS_CONSTANT_HH
<commit_msg>[functions.constant] updated create()<commit_after>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber

#ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH
#define DUNE_STUFF_FUNCTIONS_CONSTANT_HH

#include <memory>

#include <dune/stuff/common/parameter/tree.hh>

#include "interfaces.hh"

namespace Dune {
namespace Stuff {
namespace Function {

template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class Constant
  : public LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >
{
  typedef LocalizableFunctionInterface
      < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >               BaseType;
  typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >  ThisType;

  class Localfunction
    : public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >
  {
    typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType;
  public:
    typedef typename BaseType::EntityType EntityType;

    typedef typename BaseType::DomainFieldType  DomainFieldType;
    static const unsigned int                   dimDomain = BaseType::dimDomain;
    typedef typename BaseType::DomainType       DomainType;

    typedef typename BaseType::RangeFieldType RangeFieldType;
    static const unsigned int                 dimRange = BaseType::dimRange;
    static const unsigned int                 dimRangeCols = BaseType::dimRangeCols;
    typedef typename BaseType::RangeType      RangeType;

    typedef typename BaseType::JacobianRangeType JacobianRangeType;

    Localfunction(const EntityType& ent, const std::shared_ptr< const RangeType > value)
      : BaseType(ent)
      , value_(value)
    {}

    Localfunction(const Localfunction& /*other*/) = delete;

    Localfunction& operator=(const Localfunction& /*other*/) = delete;

    virtual size_t order() const DS_OVERRIDE
    {
      return 0;
    }

    virtual void evaluate(const DomainType& xx, RangeType& ret) const DS_OVERRIDE
    {
      assert(this->is_a_valid_point(xx));
      ret = *value_;
    }

    virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const DS_OVERRIDE
    {
      assert(this->is_a_valid_point(xx));
      ret *= RangeFieldType(0);
    }

  private:
    const std::shared_ptr< const RangeType > value_;
  }; // class Localfunction

public:
  typedef typename BaseType::EntityType         EntityType;
  typedef typename BaseType::LocalfunctionType  LocalfunctionType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const unsigned int                   dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType       DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const unsigned int                 dimRange = BaseType::dimRange;
  static const unsigned int                 dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType      RangeType;

  static std::string static_id()
  {
    return BaseType::static_id() + ".constant";
  }

  static Dune::ParameterTree defaultSettings(const std::string subName = "")
  {
    Dune::ParameterTree description;
    description["value"] = "1.0";
    if (subName.empty())
      return description;
    else {
      Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  } // ... defaultSettings(...)

  static ThisType* create(const DSC::ExtendedParameterTree settings = defaultSettings())
  {
    const DSC::ExtendedParameterTree default_settings = defaultSettings();
    return new ThisType(settings.get("value", default_settings.get< RangeFieldType >("value")),
                        settings.get("name", static_id()));
  } // ... create(...)

  Constant(const RangeFieldType& val, const std::string nm = static_id())
    : value_(std::make_shared< RangeType >(val))
    , name_(nm)
  {}

  Constant(const RangeType& val, const std::string nm = static_id())
    : value_(std::make_shared< RangeType >(val))
    , name_(nm)
  {}

  Constant(const ThisType& other)
    : value_(other.value_)
    , name_(other.name_)
  {}

  ThisType& operator=(const ThisType& other)
  {
    if (this != &other) {
      value_ = other.value_;
      name_ = other.name_;
    }
    return *this;
  }

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  virtual std::string name() const DS_OVERRIDE
  {
    return name_;
  }

  virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const DS_OVERRIDE
  {
    return std::unique_ptr< Localfunction >(new Localfunction(entity, value_));
  }

private:
  std::shared_ptr< const RangeType > value_;
  std::string name_;
}; // class Constant

} // namespace Function
} // namespace Stuff
} // namespace Dune

#ifdef DUNE_STUFF_FUNCTIONS_TO_LIB
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(etype, ddim) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 1) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 2) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 3)

# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, rdim) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 1) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 2) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 3)

# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim)

# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \
  DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim)

# define DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \
  extern template class Dune::Stuff::Function::Constant< etype, dftype, ddim, rftype, rdim, rcdim >;

DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake3dEntityType, 3)

# if HAVE_DUNE_GRID

DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid3dEntityType, 3)

DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid3dEntityType, 3)

#   if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H

DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid3dEntityType, 3)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluCubeGrid3dEntityType, 3)

#   endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# endif // HAVE_DUNE_GRID

# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE
# endif // DUNE_STUFF_FUNCTIONS_TO_LIB

#endif // DUNE_STUFF_FUNCTIONS_CONSTANT_HH
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-http/httpconnectionpool.h"
#include "fnord-mdb/MDB.h"
#include <fnord-fts/fts.h>
#include <fnord-fts/fts_common.h>
#include "CustomerNamespace.h"
#include "logjoin/LogJoin.h"
#include "logjoin/LogJoinTarget.h"
#include "logjoin/LogJoinUpload.h"
#include "logjoin/LogJoinExport.h"
#include "DocStore.h"
#include "IndexChangeRequest.h"
#include "DocIndex.h"
#include "ItemRef.h"
#include "common.h"
#include "schemas.h"

using namespace cm;
using namespace fnord;

std::atomic<bool> cm_logjoin_shutdown;
fnord::thread::EventLoop ev;

void quit(int n) {
  cm_logjoin_shutdown = true;
}

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  /* shutdown hook */
  cm_logjoin_shutdown = false;
  struct sigaction sa;
  memset(&sa, 0, sizeof(struct sigaction));
  sa.sa_handler = quit;
  sigaction(SIGTERM, &sa, NULL);
  sigaction(SIGQUIT, &sa, NULL);
  sigaction(SIGINT, &sa, NULL);

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "conf",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      "./conf",
      "conf directory",
      "<path>");

  flags.defineFlag(
      "datadir",
      cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "data dir",
      "<path>");

  flags.defineFlag(
      "index",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "index directory",
      "<path>");

  flags.defineFlag(
      "publish_to",
      fnord::cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "upload target url",
      "<addr>");

  flags.defineFlag(
      "statsd_addr",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "127.0.0.1:8192",
      "Statsd addr",
      "<addr>");

  flags.defineFlag(
      "batch_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "2048",
      "batch_size",
      "<num>");

  flags.defineFlag(
      "buffer_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8192",
      "buffer_size",
      "<num>");

  flags.defineFlag(
      "flush_interval",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "5",
      "flush_interval",
      "<num>");

  flags.defineFlag(
      "db_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "128",
      "max sessiondb size",
      "<MB>");

   flags.defineFlag(
      "no_dryrun",
      fnord::cli::FlagParser::T_SWITCH,
      false,
      NULL,
      NULL,
      "no dryrun",
      "<bool>");

  flags.defineFlag(
      "shard",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "shard",
      "<name>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* schema... */
  auto joined_sessions_schema = joinedSessionsSchema();

  /* start event loop */
  auto evloop_thread = std::thread([] {
    ev.run();
  });

  /* set up rpc client */
  HTTPRPCClient rpc_client(&ev);
  http::HTTPConnectionPool http(&ev);

  /* start stats reporting */
  fnord::stats::StatsdAgent statsd_agent(
      fnord::net::InetAddr::resolve(flags.getString("statsd_addr")),
      10 * fnord::kMicrosPerSecond);

  statsd_agent.start();

  /* get logjoin shard */
  cm::LogJoinShardMap shard_map;
  auto shard = shard_map.getShard(flags.getString("shard"));

  /* set up logjoin */
  auto dry_run = !flags.isSet("no_dryrun");
  size_t batch_size = flags.getInt("batch_size");
  size_t buffer_size = flags.getInt("buffer_size");
  size_t flush_interval = flags.getInt("flush_interval");

  fnord::logInfo(
      "cm.logjoin",
      "Starting cm-logjoin with:\n    dry_run=$0\n    batch_size=$1\n" \
      "    buffer_size=$2\n    flush_interval=$9\n"
      "    max_dbsize=$4MB\n" \
      "    shard=$5\n    shard_range=[$6, $7)\n    shard_modulo=$8",
      dry_run,
      batch_size,
      buffer_size,
      0,
      flags.getInt("db_size"),
      shard.shard_name,
      shard.begin,
      shard.end,
      cm::LogJoinShard::modulo,
      flush_interval);

  fnord::logInfo(
      "cm.logjoin",
      "Using session schema:\n$0",
      joined_sessions_schema.toString());

  /* open session db */
  auto sessdb = mdb::MDB::open(
      flags.getString("datadir"),
      false,
      1000000 * flags.getInt("db_size"),
      shard.shard_name + ".db",
      shard.shard_name + ".db.lck",
      false);

  /* set up input feed reader */
  feeds::RemoteFeedReader feed_reader(&rpc_client);
  feed_reader.setMaxSpread(10 * kMicrosPerSecond);

  HashMap<String, URI> input_feeds;
  input_feeds.emplace(
      "tracker_log.feedserver01.nue01.production.fnrd.net",
      URI("http://s01.nue01.production.fnrd.net:7001/rpc"));
  input_feeds.emplace(
      "tracker_log.feedserver02.nue01.production.fnrd.net",
      URI("http://s02.nue01.production.fnrd.net:7001/rpc"));

  input_feeds.emplace(
      "tracker_log.feedserver03.production.fnrd.net",
      URI("http://nue03.prod.fnrd.net:7001/rpc"));

  /* setup time backfill */
  feed_reader.setTimeBackfill([] (const feeds::FeedEntry& entry) -> DateTime {
    const auto& log_line = entry.data;

    auto c_end = log_line.find("|");
    if (c_end == std::string::npos) return 0;
    auto t_end = log_line.find("|", c_end + 1);
    if (t_end == std::string::npos) return 0;

    auto timestr = log_line.substr(c_end + 1, t_end - c_end - 1);
    return std::stoul(timestr) * fnord::kMicrosPerSecond;
  });

  /* open index */
  RefPtr<DocIndex> index(
      new DocIndex(
          flags.getString("index"),
          "documents-dawanda",
          true));

  /* set up logjoin target */
  fnord::fts::Analyzer analyzer(flags.getString("conf"));
  cm::LogJoinTarget logjoin_target(
      joined_sessions_schema,
      dry_run);

  auto normalize = [&analyzer] (Language lang, const String& query) -> String {
    return analyzer.normalize(lang, query);
  };
  logjoin_target.setNormalize(normalize);
  logjoin_target.setGetField(std::bind(
      &DocIndex::getField,
      index.get(),
      std::placeholders::_1,
      std::placeholders::_2));

  /* set up logjoin upload */
  cm::LogJoinUpload logjoin_upload(
      sessdb,
      flags.getString("publish_to"),
      &http);

  cm::LogJoinExport logjoin_export(&http);
  logjoin_upload.onSession(
      std::bind(
          &cm::LogJoinExport::exportSession,
          &logjoin_export,
          std::placeholders::_1));

  /* setup logjoin */
  cm::LogJoin logjoin(shard, dry_run, &logjoin_target);
  logjoin.exportStats("/cm-logjoin/global");
  logjoin.exportStats(StringUtil::format("/cm-logjoin/$0", shard.shard_name));

  fnord::stats::Counter<uint64_t> stat_stream_time_low;
  fnord::stats::Counter<uint64_t> stat_stream_time_high;
  fnord::stats::Counter<uint64_t> stat_active_sessions;
  fnord::stats::Counter<uint64_t> stat_dbsize;

  exportStat(
      StringUtil::format("/cm-logjoin/$0/stream_time_low", shard.shard_name),
      &stat_stream_time_low,
      fnord::stats::ExportMode::EXPORT_VALUE);

  exportStat(
      StringUtil::format("/cm-logjoin/$0/stream_time_high", shard.shard_name),
      &stat_stream_time_high,
      fnord::stats::ExportMode::EXPORT_VALUE);

  exportStat(
      StringUtil::format("/cm-logjoin/$0/active_sessions", shard.shard_name),
      &stat_active_sessions,
      fnord::stats::ExportMode::EXPORT_VALUE);

  exportStat(
      StringUtil::format("/cm-logjoin/$0/dbsize", shard.shard_name),
      &stat_dbsize,
      fnord::stats::ExportMode::EXPORT_VALUE);

  /* upload pending q */
  if (!dry_run) {
    logjoin_upload.upload();
  }

  /* resume from last offset */
  auto txn = sessdb->startTransaction(true);
  try {
    logjoin.importTimeoutList(txn.get());

    for (const auto& input_feed : input_feeds) {
      uint64_t offset = 0;

      auto last_offset = txn->get(
          StringUtil::format("__logjoin_offset~$0", input_feed.first));

      if (!last_offset.isEmpty()) {
        offset = std::stoul(last_offset.get().toString());
      }

      fnord::logInfo(
          "cm.logjoin",
          "Adding source feed:\n    feed=$0\n    url=$1\n    offset: $2",
          input_feed.first,
          input_feed.second.toString(),
          offset);

      feed_reader.addSourceFeed(
          input_feed.second,
          input_feed.first,
          offset,
          batch_size,
          buffer_size);
    }

    txn->abort();
  } catch (...) {
    txn->abort();
    throw;
  }

  fnord::logInfo("cm.logjoin", "Resuming logjoin...");

  DateTime last_flush;
  uint64_t rate_limit_micros = flush_interval * kMicrosPerSecond;

  for (;;) {
    auto begin = WallClock::unixMicros();

    feed_reader.fillBuffers();
    auto txn = sessdb->startTransaction();

    int i = 0;
    for (; i < batch_size; ++i) {
      auto entry = feed_reader.fetchNextEntry();

      if (entry.isEmpty()) {
        break;
      }

      try {
        logjoin.insertLogline(entry.get().data, txn.get());
      } catch (const std::exception& e) {
        fnord::logError("cm.logjoin", e, "invalid log line");
      }
    }

    auto watermarks = feed_reader.watermarks();

    auto etime = WallClock::now().unixMicros() - last_flush.unixMicros();
    if (etime > rate_limit_micros) {
      last_flush = WallClock::now();
      logjoin.flush(txn.get(), watermarks.first);
    }

    auto stream_offsets = feed_reader.streamOffsets();
    String stream_offsets_str;

    for (const auto& soff : stream_offsets) {
      txn->update(
          StringUtil::format("__logjoin_offset~$0", soff.first),
          StringUtil::toString(soff.second));

      stream_offsets_str +=
          StringUtil::format("\n    offset[$0]=$1", soff.first, soff.second);
    }

    fnord::logInfo(
        "cm.logjoin",
        "LogJoin comitting...\n    stream_time=<$0 ... $1>\n" \
        "    active_sessions=$2\n    flushed_sessions=$3$4",
        watermarks.first,
        watermarks.second,
        logjoin.numSessions(),
        logjoin_target.num_sessions,
        stream_offsets_str);

    if (dry_run) {
      txn->abort();
    } else {
      txn->commit();

      try {
        logjoin_upload.upload();
      } catch (const std::exception& e) {
        fnord::logError("cm.logjoin", e, "upload failed");
      }
    }

    sessdb->removeStaleReaders();
    index->getDBHanndle()->removeStaleReaders();

    if (cm_logjoin_shutdown.load()) {
      break;
    }

    stat_stream_time_low.set(watermarks.first.unixMicros());
    stat_stream_time_high.set(watermarks.second.unixMicros());
    stat_active_sessions.set(logjoin.numSessions());
    //stat_dbsize.set(FileUtil::du_c(flags.getString("datadir"));

    auto rtime = WallClock::unixMicros() - begin;
    auto rlimit = kMicrosPerSecond;
    if (i < 2 && rtime < rlimit) {
      usleep(rlimit - rtime);
    }
  }

  ev.shutdown();
  evloop_thread.join();

  sessdb->sync();
  fnord::logInfo("cm.logjoin", "LogJoin exiting...");
  return 0;
}

<commit_msg>remove feedserver01<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-http/httpconnectionpool.h"
#include "fnord-mdb/MDB.h"
#include <fnord-fts/fts.h>
#include <fnord-fts/fts_common.h>
#include "CustomerNamespace.h"
#include "logjoin/LogJoin.h"
#include "logjoin/LogJoinTarget.h"
#include "logjoin/LogJoinUpload.h"
#include "logjoin/LogJoinExport.h"
#include "DocStore.h"
#include "IndexChangeRequest.h"
#include "DocIndex.h"
#include "ItemRef.h"
#include "common.h"
#include "schemas.h"

using namespace cm;
using namespace fnord;

std::atomic<bool> cm_logjoin_shutdown;
fnord::thread::EventLoop ev;

void quit(int n) {
  cm_logjoin_shutdown = true;
}

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  /* shutdown hook */
  cm_logjoin_shutdown = false;
  struct sigaction sa;
  memset(&sa, 0, sizeof(struct sigaction));
  sa.sa_handler = quit;
  sigaction(SIGTERM, &sa, NULL);
  sigaction(SIGQUIT, &sa, NULL);
  sigaction(SIGINT, &sa, NULL);

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "conf",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      "./conf",
      "conf directory",
      "<path>");

  flags.defineFlag(
      "datadir",
      cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "data dir",
      "<path>");

  flags.defineFlag(
      "index",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "index directory",
      "<path>");

  flags.defineFlag(
      "publish_to",
      fnord::cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "upload target url",
      "<addr>");

  flags.defineFlag(
      "statsd_addr",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "127.0.0.1:8192",
      "Statsd addr",
      "<addr>");

  flags.defineFlag(
      "batch_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "2048",
      "batch_size",
      "<num>");

  flags.defineFlag(
      "buffer_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8192",
      "buffer_size",
      "<num>");

  flags.defineFlag(
      "flush_interval",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "5",
      "flush_interval",
      "<num>");

  flags.defineFlag(
      "db_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "128",
      "max sessiondb size",
      "<MB>");

   flags.defineFlag(
      "no_dryrun",
      fnord::cli::FlagParser::T_SWITCH,
      false,
      NULL,
      NULL,
      "no dryrun",
      "<bool>");

  flags.defineFlag(
      "shard",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "shard",
      "<name>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* schema... */
  auto joined_sessions_schema = joinedSessionsSchema();

  /* start event loop */
  auto evloop_thread = std::thread([] {
    ev.run();
  });

  /* set up rpc client */
  HTTPRPCClient rpc_client(&ev);
  http::HTTPConnectionPool http(&ev);

  /* start stats reporting */
  fnord::stats::StatsdAgent statsd_agent(
      fnord::net::InetAddr::resolve(flags.getString("statsd_addr")),
      10 * fnord::kMicrosPerSecond);

  statsd_agent.start();

  /* get logjoin shard */
  cm::LogJoinShardMap shard_map;
  auto shard = shard_map.getShard(flags.getString("shard"));

  /* set up logjoin */
  auto dry_run = !flags.isSet("no_dryrun");
  size_t batch_size = flags.getInt("batch_size");
  size_t buffer_size = flags.getInt("buffer_size");
  size_t flush_interval = flags.getInt("flush_interval");

  fnord::logInfo(
      "cm.logjoin",
      "Starting cm-logjoin with:\n    dry_run=$0\n    batch_size=$1\n" \
      "    buffer_size=$2\n    flush_interval=$9\n"
      "    max_dbsize=$4MB\n" \
      "    shard=$5\n    shard_range=[$6, $7)\n    shard_modulo=$8",
      dry_run,
      batch_size,
      buffer_size,
      0,
      flags.getInt("db_size"),
      shard.shard_name,
      shard.begin,
      shard.end,
      cm::LogJoinShard::modulo,
      flush_interval);

  fnord::logInfo(
      "cm.logjoin",
      "Using session schema:\n$0",
      joined_sessions_schema.toString());

  /* open session db */
  auto sessdb = mdb::MDB::open(
      flags.getString("datadir"),
      false,
      1000000 * flags.getInt("db_size"),
      shard.shard_name + ".db",
      shard.shard_name + ".db.lck",
      false);

  /* set up input feed reader */
  feeds::RemoteFeedReader feed_reader(&rpc_client);
  feed_reader.setMaxSpread(10 * kMicrosPerSecond);

  HashMap<String, URI> input_feeds;
  //input_feeds.emplace(
  //    "tracker_log.feedserver01.nue01.production.fnrd.net",
  //    URI("http://s01.nue01.production.fnrd.net:7001/rpc"));
  input_feeds.emplace(
      "tracker_log.feedserver02.nue01.production.fnrd.net",
      URI("http://s02.nue01.production.fnrd.net:7001/rpc"));

  input_feeds.emplace(
      "tracker_log.feedserver03.production.fnrd.net",
      URI("http://nue03.prod.fnrd.net:7001/rpc"));

  /* setup time backfill */
  feed_reader.setTimeBackfill([] (const feeds::FeedEntry& entry) -> DateTime {
    const auto& log_line = entry.data;

    auto c_end = log_line.find("|");
    if (c_end == std::string::npos) return 0;
    auto t_end = log_line.find("|", c_end + 1);
    if (t_end == std::string::npos) return 0;

    auto timestr = log_line.substr(c_end + 1, t_end - c_end - 1);
    return std::stoul(timestr) * fnord::kMicrosPerSecond;
  });

  /* open index */
  RefPtr<DocIndex> index(
      new DocIndex(
          flags.getString("index"),
          "documents-dawanda",
          true));

  /* set up logjoin target */
  fnord::fts::Analyzer analyzer(flags.getString("conf"));
  cm::LogJoinTarget logjoin_target(
      joined_sessions_schema,
      dry_run);

  auto normalize = [&analyzer] (Language lang, const String& query) -> String {
    return analyzer.normalize(lang, query);
  };
  logjoin_target.setNormalize(normalize);
  logjoin_target.setGetField(std::bind(
      &DocIndex::getField,
      index.get(),
      std::placeholders::_1,
      std::placeholders::_2));

  /* set up logjoin upload */
  cm::LogJoinUpload logjoin_upload(
      sessdb,
      flags.getString("publish_to"),
      &http);

  cm::LogJoinExport logjoin_export(&http);
  logjoin_upload.onSession(
      std::bind(
          &cm::LogJoinExport::exportSession,
          &logjoin_export,
          std::placeholders::_1));

  /* setup logjoin */
  cm::LogJoin logjoin(shard, dry_run, &logjoin_target);
  logjoin.exportStats("/cm-logjoin/global");
  logjoin.exportStats(StringUtil::format("/cm-logjoin/$0", shard.shard_name));

  fnord::stats::Counter<uint64_t> stat_stream_time_low;
  fnord::stats::Counter<uint64_t> stat_stream_time_high;
  fnord::stats::Counter<uint64_t> stat_active_sessions;
  fnord::stats::Counter<uint64_t> stat_dbsize;

  exportStat(
      StringUtil::format("/cm-logjoin/$0/stream_time_low", shard.shard_name),
      &stat_stream_time_low,
      fnord::stats::ExportMode::EXPORT_VALUE);

  exportStat(
      StringUtil::format("/cm-logjoin/$0/stream_time_high", shard.shard_name),
      &stat_stream_time_high,
      fnord::stats::ExportMode::EXPORT_VALUE);

  exportStat(
      StringUtil::format("/cm-logjoin/$0/active_sessions", shard.shard_name),
      &stat_active_sessions,
      fnord::stats::ExportMode::EXPORT_VALUE);

  exportStat(
      StringUtil::format("/cm-logjoin/$0/dbsize", shard.shard_name),
      &stat_dbsize,
      fnord::stats::ExportMode::EXPORT_VALUE);

  /* upload pending q */
  if (!dry_run) {
    logjoin_upload.upload();
  }

  /* resume from last offset */
  auto txn = sessdb->startTransaction(true);
  try {
    logjoin.importTimeoutList(txn.get());

    for (const auto& input_feed : input_feeds) {
      uint64_t offset = 0;

      auto last_offset = txn->get(
          StringUtil::format("__logjoin_offset~$0", input_feed.first));

      if (!last_offset.isEmpty()) {
        offset = std::stoul(last_offset.get().toString());
      }

      fnord::logInfo(
          "cm.logjoin",
          "Adding source feed:\n    feed=$0\n    url=$1\n    offset: $2",
          input_feed.first,
          input_feed.second.toString(),
          offset);

      feed_reader.addSourceFeed(
          input_feed.second,
          input_feed.first,
          offset,
          batch_size,
          buffer_size);
    }

    txn->abort();
  } catch (...) {
    txn->abort();
    throw;
  }

  fnord::logInfo("cm.logjoin", "Resuming logjoin...");

  DateTime last_flush;
  uint64_t rate_limit_micros = flush_interval * kMicrosPerSecond;

  for (;;) {
    auto begin = WallClock::unixMicros();

    feed_reader.fillBuffers();
    auto txn = sessdb->startTransaction();

    int i = 0;
    for (; i < batch_size; ++i) {
      auto entry = feed_reader.fetchNextEntry();

      if (entry.isEmpty()) {
        break;
      }

      try {
        logjoin.insertLogline(entry.get().data, txn.get());
      } catch (const std::exception& e) {
        fnord::logError("cm.logjoin", e, "invalid log line");
      }
    }

    auto watermarks = feed_reader.watermarks();

    auto etime = WallClock::now().unixMicros() - last_flush.unixMicros();
    if (etime > rate_limit_micros) {
      last_flush = WallClock::now();
      logjoin.flush(txn.get(), watermarks.first);
    }

    auto stream_offsets = feed_reader.streamOffsets();
    String stream_offsets_str;

    for (const auto& soff : stream_offsets) {
      txn->update(
          StringUtil::format("__logjoin_offset~$0", soff.first),
          StringUtil::toString(soff.second));

      stream_offsets_str +=
          StringUtil::format("\n    offset[$0]=$1", soff.first, soff.second);
    }

    fnord::logInfo(
        "cm.logjoin",
        "LogJoin comitting...\n    stream_time=<$0 ... $1>\n" \
        "    active_sessions=$2\n    flushed_sessions=$3$4",
        watermarks.first,
        watermarks.second,
        logjoin.numSessions(),
        logjoin_target.num_sessions,
        stream_offsets_str);

    if (dry_run) {
      txn->abort();
    } else {
      txn->commit();

      try {
        logjoin_upload.upload();
      } catch (const std::exception& e) {
        fnord::logError("cm.logjoin", e, "upload failed");
      }
    }

    sessdb->removeStaleReaders();
    index->getDBHanndle()->removeStaleReaders();

    if (cm_logjoin_shutdown.load()) {
      break;
    }

    stat_stream_time_low.set(watermarks.first.unixMicros());
    stat_stream_time_high.set(watermarks.second.unixMicros());
    stat_active_sessions.set(logjoin.numSessions());
    //stat_dbsize.set(FileUtil::du_c(flags.getString("datadir"));

    auto rtime = WallClock::unixMicros() - begin;
    auto rlimit = kMicrosPerSecond;
    if (i < 2 && rtime < rlimit) {
      usleep(rlimit - rtime);
    }
  }

  ev.shutdown();
  evloop_thread.join();

  sessdb->sync();
  fnord::logInfo("cm.logjoin", "LogJoin exiting...");
  return 0;
}

<|endoftext|>


<commit_before>/*
  Copyright 2017 Larry Gritz and the other authors and contributors.
  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 software's owners 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.

  (This is the Modified BSD License)
*/

#include <cstdio>
#include <cstdlib>

#include <OpenImageIO/dassert.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/filesystem.h>
#include "imageio_pvt.h"

OIIO_PLUGIN_NAMESPACE_BEGIN

// Null output just sits there like a lump and returns ok for everything.
class NullOutput final : public ImageOutput {
public:
    NullOutput () { }
    virtual ~NullOutput () { }
    virtual const char * format_name (void) const override { return "null"; }
    virtual int supports (string_view feature) const override { return true; }
    virtual bool open (const std::string &name, const ImageSpec &spec,
                       OpenMode mode=Create) override {
        m_spec = spec;
        return true;
    }
    virtual bool close () override { return true; }
    virtual bool write_scanline (int y, int z, TypeDesc format,
                                 const void *data, stride_t xstride) override {
        return true;
    }
    virtual bool write_tile (int x, int y, int z, TypeDesc format,
                             const void *data, stride_t xstride,
                             stride_t ystride, stride_t zstride) override {
        return true;
    }
};

// Null input emulates a file, but just returns black tiles.
// But we accept REST-like filename designations to set certain parameters,
// such as "myfile.null&RES=1920x1080&CHANNELS=3&TYPE=uint16"
class NullInput final : public ImageInput {
public:
    NullInput () { init(); }
    virtual ~NullInput () { }
    virtual const char * format_name (void) const override { return "null"; }
    virtual bool valid_file (const std::string &filename) const override;
    virtual int supports (string_view feature) const override { return true; }
    virtual bool open (const std::string &name, ImageSpec &newspec) override;
    virtual bool open (const std::string &name, ImageSpec &newspec,
                       const ImageSpec &config) override;
    virtual bool close () override { return true; }
    virtual int current_subimage (void) const override { return m_subimage; }
    virtual int current_miplevel (void) const override { return m_miplevel; }
    virtual bool seek_subimage (int subimage, int miplevel) override;
    virtual bool read_native_scanline (int subimage, int miplevel,
                                       int y, int z, void *data) override;
    virtual bool read_native_tile (int subimage, int miplevel,
                                   int x, int y, int z, void *data) override;

private:
    std::string m_filename;          ///< Stash the filename
    int m_subimage;                  ///< What subimage are we looking at?
    int m_miplevel;                  ///< What miplevel are we looking at?
    bool m_mip;                      ///< MIP-mapped?
    std::vector<uint8_t> m_value;    ///< Pixel value (if not black)
    ImageSpec m_topspec;

    // Reset everything to initial state
    void init () {
        m_subimage = -1;
        m_miplevel = -1;
        m_mip = false;
        m_value.clear ();
    }
};

// Obligatory material to make this a recognizeable imageio plugin:
OIIO_PLUGIN_EXPORTS_BEGIN

OIIO_EXPORT ImageOutput *null_output_imageio_create () {
    return new NullOutput;
}

OIIO_EXPORT int null_imageio_version = OIIO_PLUGIN_VERSION;

OIIO_EXPORT const char* null_imageio_library_version () {
    return "null 1.0";
}

OIIO_EXPORT const char * null_output_extensions[] = {
    "null", "nul", nullptr
};

OIIO_EXPORT ImageInput *null_input_imageio_create () {
    return new NullInput;
}

OIIO_EXPORT const char * null_input_extensions[] = {
    "null", "nul", nullptr
};

OIIO_PLUGIN_EXPORTS_END

bool
NullInput::valid_file (const std::string &name) const
{
    std::map<std::string,std::string> args;
    std::string filename;
    if (! Strutil::get_rest_arguments (name, filename, args))
        return false;
    return Strutil::ends_with (filename, ".null") ||
           Strutil::ends_with (filename, ".nul");
}

bool
NullInput::open (const std::string &name, ImageSpec &newspec)
{
    ImageSpec config;
    return open (name, newspec, config);
}

static void
parse_res (string_view res, int &x, int &y, int &z)
{
    if (Strutil::parse_int (res, x)) {
        if (Strutil::parse_char (res, 'x') &&
            Strutil::parse_int (res, y)) {
            if (! (Strutil::parse_char(res, 'x') &&
                   Strutil::parse_int(res, z)))
                z = 1;
        } else {
            y = x;
            z = 1;
        }
    }
}

// Add the attribute -- figure out the type
void
parse_param (string_view paramname, string_view val, ImageSpec &spec)
{
    TypeDesc type;   // start out unknown

    // If the param string starts with a type name, that's what it is
    if (size_t typeportion = type.fromstring (paramname)) {
        paramname.remove_prefix (typeportion);
        Strutil::skip_whitespace (paramname);
    }
    // If the value string starts with a type name, that's what it is
    else if (size_t typeportion = type.fromstring (val)) {
        val.remove_prefix (typeportion);
        Strutil::skip_whitespace (val);
    }

    if (type.basetype == TypeDesc::UNKNOWN) {
        // If we didn't find a type name, try to guess
        if (val.size() >= 2 && val.front() == '\"' && val.back() == '\"') {
            // Surrounded by quotes? it's a string (strip off the quotes)
            val.remove_prefix(1); val.remove_suffix(1);
            type = TypeDesc::TypeString;
        } else if (Strutil::string_is<int>(val)) {
            // Looks like an int, is an int
            type = TypeDesc::TypeInt;
        } else if (Strutil::string_is<float>(val)) {
            // Looks like a float, is a float
            type = TypeDesc::TypeFloat;
        } else {
            // Everything else is assumed a string
            type = TypeDesc::TypeString;
        }
    }

    // Read the values and set the attribute
    int n = type.numelements() * type.aggregate;
    if (type.basetype == TypeDesc::INT) {
        std::vector<int> values (n);
        for (int i = 0; i < n; ++i) {
            Strutil::parse_int (val, values[i]);
            Strutil::parse_char (val, ','); // optional
        }
        if (n > 0)
            spec.attribute (paramname, type, &values[0]);
    }
    if (type.basetype == TypeDesc::FLOAT) {
        std::vector<float> values (n);
        for (int i = 0; i < n; ++i) {
            Strutil::parse_float (val, values[i]);
            Strutil::parse_char (val, ','); // optional
        }
        if (n > 0)
            spec.attribute (paramname, type, &values[0]);
    } else if (type.basetype == TypeDesc::STRING) {
        std::vector<ustring> values (n);
        for (int i = 0; i < n; ++i) {
            string_view v;
            Strutil::parse_string (val, v);
            Strutil::parse_char (val, ','); // optional
            values[i] = v;
        }
        if (n > 0)
            spec.attribute (paramname, type, &values[0]);
    }
}

bool
NullInput::open (const std::string &name, ImageSpec &newspec,
                 const ImageSpec &config)
{
    m_filename = name;
    m_subimage = -1;
    m_miplevel = -1;
    m_mip = false;
    m_topspec = config;

    // std::vector<std::pair<string_view,string_view> > args;
    // string_view filename = deconstruct_uri (name, &args);
    std::map<std::string,std::string> args;
    std::string filename;
    if (! Strutil::get_rest_arguments (name, filename, args))
        return false;
    if (filename.empty())
        return false;

    // To keep the "null" input reader from reading from ANY name, only
    // succeed if it ends in ".null" or ".nul" --OR-- if the config has a
    // special override "null:force" set to nonzero (that lets the caller
    // guarantee a null input even if the name has no extension, say).
    if (! Strutil::ends_with (filename, ".null") &&
        ! Strutil::ends_with (filename, ".nul") &&
        config.get_int_attribute("null:force") == 0)
        return false;

    // Override the config with default resolution if it was not set
    if (m_topspec.width <= 0)
        m_topspec.width = 1024;
    if (m_topspec.height <= 0)
        m_topspec.height = 1024;
    if (m_topspec.depth <= 0)
        m_topspec.depth = 1;
    if (m_topspec.nchannels <= 0)
        m_topspec.nchannels = 4;
    if (m_topspec.format == TypeUnknown)
        m_topspec.format = TypeFloat;

    m_filename = filename;
    std::vector<float> fvalue;

    for (const auto& a : args) {
        if (a.first == "RES") {
            parse_res (a.second, m_topspec.width, m_topspec.height, m_topspec.depth);
        } else if (a.first == "TILE" || a.first == "TILES") {
            parse_res (a.second, m_topspec.tile_width, m_topspec.tile_height,
                       m_topspec.tile_depth);
        } else if (a.first == "CHANNELS") {
            m_topspec.nchannels = Strutil::from_string<int>(a.second);
        } else if (a.first == "MIP") {
            m_mip = Strutil::from_string<int>(a.second);
        } else if (a.first == "TEX") {
            if (Strutil::from_string<int>(a.second)) {
                if (!m_spec.tile_width) {
                    m_topspec.tile_width = 64;
                    m_topspec.tile_height = 64;
                    m_topspec.tile_depth = 1;
                }
                m_topspec.attribute ("wrapmodes", "black,black");
                m_topspec.attribute ("textureformat", "Plain Texture");
                m_mip = true;
            }
        } else if (a.first == "TYPE") {
            m_topspec.set_format (TypeDesc(a.second));
        } else if (a.first == "PIXEL") {
            Strutil::extract_from_list_string (fvalue, a.second);
            fvalue.resize (m_topspec.nchannels);
        } else if (a.first.size() && a.second.size()) {
            parse_param (a.first, a.second, m_topspec);
        }
    }

    m_topspec.default_channel_names ();
    m_topspec.full_x = m_topspec.x;
    m_topspec.full_y = m_topspec.y;
    m_topspec.full_z = m_topspec.z;
    m_topspec.full_width = m_topspec.width;
    m_topspec.full_height = m_topspec.height;
    m_topspec.full_depth = m_topspec.depth;

    if (fvalue.size()) {
        // Convert float to the native type
        fvalue.resize (m_topspec.nchannels, 0.0f);
        m_value.resize (m_topspec.pixel_bytes());
        convert_types (TypeFloat, fvalue.data(),
                       m_topspec.format, m_value.data(),
                       m_topspec.nchannels);
    }

    bool ok = seek_subimage (0, 0);
    newspec = spec();
    return ok;
}

bool
NullInput::seek_subimage (int subimage, int miplevel)
{
    if (subimage == current_subimage() && miplevel == current_miplevel()) {
        return true;
    }

    if (subimage != 0)
        return false;    // We only make one subimage
    m_subimage = subimage;

    if (miplevel > 0 && ! m_mip)
        return false;    // Asked for MIP levels but we aren't makign them

    m_spec = m_topspec;
    for (m_miplevel = 0; m_miplevel < miplevel; ++m_miplevel) {
        if (m_spec.width == 1 && m_spec.height == 1 && m_spec.depth == 1)
            return false;   // Asked for more MIP levels than were available
        m_spec.width = std::max (1, m_spec.width/2);
        m_spec.height = std::max (1, m_spec.height/2);
        m_spec.depth = std::max (1, m_spec.depth/2);
        m_spec.full_width = m_spec.width;
        m_spec.full_height = m_spec.height;
        m_spec.full_depth = m_spec.depth;
    }
    return true;
}

bool
NullInput::read_native_scanline (int subimage, int miplevel,
                                 int y, int z, void *data)
{
    if (m_value.size()) {
        size_t s = m_spec.pixel_bytes();
        for (int x = 0; x < m_spec.width; ++x)
            memcpy ((char *)data + s*x, m_value.data(), s);
    } else {
        memset (data, 0, m_spec.scanline_bytes());
    }
    return true;
}

bool
NullInput::read_native_tile (int subimage, int miplevel,
                             int x, int y, int z, void *data)
{
    if (m_value.size()) {
        size_t s = m_spec.pixel_bytes();
        for (size_t x = 0, e = m_spec.tile_pixels(); x < e; ++x)
            memcpy ((char *)data + s*x, m_value.data(), s);
    } else {
        memset (data, 0, m_spec.tile_bytes());
    }
    return true;
}

OIIO_PLUGIN_NAMESPACE_END

<commit_msg>null input reader: be more careful with "full" (display) size (#2042)<commit_after>/*
  Copyright 2017 Larry Gritz and the other authors and contributors.
  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 software's owners 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.

  (This is the Modified BSD License)
*/

#include <cstdio>
#include <cstdlib>

#include <OpenImageIO/dassert.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/filesystem.h>
#include "imageio_pvt.h"

OIIO_PLUGIN_NAMESPACE_BEGIN

// Null output just sits there like a lump and returns ok for everything.
class NullOutput final : public ImageOutput {
public:
    NullOutput () { }
    virtual ~NullOutput () { }
    virtual const char * format_name (void) const override { return "null"; }
    virtual int supports (string_view feature) const override { return true; }
    virtual bool open (const std::string &name, const ImageSpec &spec,
                       OpenMode mode=Create) override {
        m_spec = spec;
        return true;
    }
    virtual bool close () override { return true; }
    virtual bool write_scanline (int y, int z, TypeDesc format,
                                 const void *data, stride_t xstride) override {
        return true;
    }
    virtual bool write_tile (int x, int y, int z, TypeDesc format,
                             const void *data, stride_t xstride,
                             stride_t ystride, stride_t zstride) override {
        return true;
    }
};

// Null input emulates a file, but just returns black tiles.
// But we accept REST-like filename designations to set certain parameters,
// such as "myfile.null&RES=1920x1080&CHANNELS=3&TYPE=uint16"
class NullInput final : public ImageInput {
public:
    NullInput () { init(); }
    virtual ~NullInput () { }
    virtual const char * format_name (void) const override { return "null"; }
    virtual bool valid_file (const std::string &filename) const override;
    virtual int supports (string_view feature) const override { return true; }
    virtual bool open (const std::string &name, ImageSpec &newspec) override;
    virtual bool open (const std::string &name, ImageSpec &newspec,
                       const ImageSpec &config) override;
    virtual bool close () override { return true; }
    virtual int current_subimage (void) const override { return m_subimage; }
    virtual int current_miplevel (void) const override { return m_miplevel; }
    virtual bool seek_subimage (int subimage, int miplevel) override;
    virtual bool read_native_scanline (int subimage, int miplevel,
                                       int y, int z, void *data) override;
    virtual bool read_native_tile (int subimage, int miplevel,
                                   int x, int y, int z, void *data) override;

private:
    std::string m_filename;          ///< Stash the filename
    int m_subimage;                  ///< What subimage are we looking at?
    int m_miplevel;                  ///< What miplevel are we looking at?
    bool m_mip;                      ///< MIP-mapped?
    std::vector<uint8_t> m_value;    ///< Pixel value (if not black)
    ImageSpec m_topspec;

    // Reset everything to initial state
    void init () {
        m_subimage = -1;
        m_miplevel = -1;
        m_mip = false;
        m_value.clear ();
    }
};

// Obligatory material to make this a recognizeable imageio plugin:
OIIO_PLUGIN_EXPORTS_BEGIN

OIIO_EXPORT ImageOutput *null_output_imageio_create () {
    return new NullOutput;
}

OIIO_EXPORT int null_imageio_version = OIIO_PLUGIN_VERSION;

OIIO_EXPORT const char* null_imageio_library_version () {
    return "null 1.0";
}

OIIO_EXPORT const char * null_output_extensions[] = {
    "null", "nul", nullptr
};

OIIO_EXPORT ImageInput *null_input_imageio_create () {
    return new NullInput;
}

OIIO_EXPORT const char * null_input_extensions[] = {
    "null", "nul", nullptr
};

OIIO_PLUGIN_EXPORTS_END

bool
NullInput::valid_file (const std::string &name) const
{
    std::map<std::string,std::string> args;
    std::string filename;
    if (! Strutil::get_rest_arguments (name, filename, args))
        return false;
    return Strutil::ends_with (filename, ".null") ||
           Strutil::ends_with (filename, ".nul");
}

bool
NullInput::open (const std::string &name, ImageSpec &newspec)
{
    ImageSpec config;
    return open (name, newspec, config);
}

static void
parse_res (string_view res, int &x, int &y, int &z)
{
    if (Strutil::parse_int (res, x)) {
        if (Strutil::parse_char (res, 'x') &&
            Strutil::parse_int (res, y)) {
            if (! (Strutil::parse_char(res, 'x') &&
                   Strutil::parse_int(res, z)))
                z = 1;
        } else {
            y = x;
            z = 1;
        }
    }
}

// Add the attribute -- figure out the type
void
parse_param (string_view paramname, string_view val, ImageSpec &spec)
{
    TypeDesc type;   // start out unknown

    // If the param string starts with a type name, that's what it is
    if (size_t typeportion = type.fromstring (paramname)) {
        paramname.remove_prefix (typeportion);
        Strutil::skip_whitespace (paramname);
    }
    // If the value string starts with a type name, that's what it is
    else if (size_t typeportion = type.fromstring (val)) {
        val.remove_prefix (typeportion);
        Strutil::skip_whitespace (val);
    }

    if (type.basetype == TypeDesc::UNKNOWN) {
        // If we didn't find a type name, try to guess
        if (val.size() >= 2 && val.front() == '\"' && val.back() == '\"') {
            // Surrounded by quotes? it's a string (strip off the quotes)
            val.remove_prefix(1); val.remove_suffix(1);
            type = TypeDesc::TypeString;
        } else if (Strutil::string_is<int>(val)) {
            // Looks like an int, is an int
            type = TypeDesc::TypeInt;
        } else if (Strutil::string_is<float>(val)) {
            // Looks like a float, is a float
            type = TypeDesc::TypeFloat;
        } else {
            // Everything else is assumed a string
            type = TypeDesc::TypeString;
        }
    }

    // Read the values and set the attribute
    int n = type.numelements() * type.aggregate;
    if (type.basetype == TypeDesc::INT) {
        std::vector<int> values (n);
        for (int i = 0; i < n; ++i) {
            Strutil::parse_int (val, values[i]);
            Strutil::parse_char (val, ','); // optional
        }
        if (n > 0)
            spec.attribute (paramname, type, &values[0]);
    }
    if (type.basetype == TypeDesc::FLOAT) {
        std::vector<float> values (n);
        for (int i = 0; i < n; ++i) {
            Strutil::parse_float (val, values[i]);
            Strutil::parse_char (val, ','); // optional
        }
        if (n > 0)
            spec.attribute (paramname, type, &values[0]);
    } else if (type.basetype == TypeDesc::STRING) {
        std::vector<ustring> values (n);
        for (int i = 0; i < n; ++i) {
            string_view v;
            Strutil::parse_string (val, v);
            Strutil::parse_char (val, ','); // optional
            values[i] = v;
        }
        if (n > 0)
            spec.attribute (paramname, type, &values[0]);
    }
}

bool
NullInput::open (const std::string &name, ImageSpec &newspec,
                 const ImageSpec &config)
{
    m_filename = name;
    m_subimage = -1;
    m_miplevel = -1;
    m_mip = false;
    m_topspec = config;

    // std::vector<std::pair<string_view,string_view> > args;
    // string_view filename = deconstruct_uri (name, &args);
    std::map<std::string,std::string> args;
    std::string filename;
    if (! Strutil::get_rest_arguments (name, filename, args))
        return false;
    if (filename.empty())
        return false;

    // To keep the "null" input reader from reading from ANY name, only
    // succeed if it ends in ".null" or ".nul" --OR-- if the config has a
    // special override "null:force" set to nonzero (that lets the caller
    // guarantee a null input even if the name has no extension, say).
    if (! Strutil::ends_with (filename, ".null") &&
        ! Strutil::ends_with (filename, ".nul") &&
        config.get_int_attribute("null:force") == 0)
        return false;

    // Override the config with default resolution if it was not set
    if (m_topspec.width <= 0)
        m_topspec.width = 1024;
    if (m_topspec.height <= 0)
        m_topspec.height = 1024;
    if (m_topspec.depth <= 0)
        m_topspec.depth = 1;
    if (m_topspec.full_width <= 0)
        m_topspec.full_width = m_topspec.width;
    if (m_topspec.full_height <= 0)
        m_topspec.full_height = m_topspec.height;
    if (m_topspec.full_depth <= 0)
        m_topspec.full_depth = m_topspec.depth;
    if (m_topspec.nchannels <= 0)
        m_topspec.nchannels = 4;
    if (m_topspec.format == TypeUnknown)
        m_topspec.format = TypeFloat;

    m_filename = filename;
    std::vector<float> fvalue;

    for (const auto& a : args) {
        if (a.first == "RES") {
            parse_res (a.second, m_topspec.width, m_topspec.height, m_topspec.depth);
            m_topspec.full_x = m_topspec.x;
            m_topspec.full_y = m_topspec.y;
            m_topspec.full_z = m_topspec.z;
            m_topspec.full_width = m_topspec.width;
            m_topspec.full_height = m_topspec.height;
            m_topspec.full_depth = m_topspec.depth;
        } else if (a.first == "TILE" || a.first == "TILES") {
            parse_res (a.second, m_topspec.tile_width, m_topspec.tile_height,
                       m_topspec.tile_depth);
        } else if (a.first == "CHANNELS") {
            m_topspec.nchannels = Strutil::from_string<int>(a.second);
            m_topspec.default_channel_names ();
        } else if (a.first == "MIP") {
            m_mip = Strutil::from_string<int>(a.second);
        } else if (a.first == "TEX") {
            if (Strutil::from_string<int>(a.second)) {
                if (!m_spec.tile_width) {
                    m_topspec.tile_width = 64;
                    m_topspec.tile_height = 64;
                    m_topspec.tile_depth = 1;
                }
                m_topspec.attribute ("wrapmodes", "black,black");
                m_topspec.attribute ("textureformat", "Plain Texture");
                m_mip = true;
            }
        } else if (a.first == "TYPE") {
            m_topspec.set_format (TypeDesc(a.second));
        } else if (a.first == "PIXEL") {
            Strutil::extract_from_list_string (fvalue, a.second);
            fvalue.resize (m_topspec.nchannels);
        } else if (a.first.size() && a.second.size()) {
            parse_param (a.first, a.second, m_topspec);
        }
    }

    if (fvalue.size()) {
        // Convert float to the native type
        fvalue.resize (m_topspec.nchannels, 0.0f);
        m_value.resize (m_topspec.pixel_bytes());
        convert_types (TypeFloat, fvalue.data(),
                       m_topspec.format, m_value.data(),
                       m_topspec.nchannels);
    }

    bool ok = seek_subimage (0, 0);
    newspec = spec();
    return ok;
}

bool
NullInput::seek_subimage (int subimage, int miplevel)
{
    if (subimage == current_subimage() && miplevel == current_miplevel()) {
        return true;
    }

    if (subimage != 0)
        return false;    // We only make one subimage
    m_subimage = subimage;

    if (miplevel > 0 && ! m_mip)
        return false;    // Asked for MIP levels but we aren't makign them

    m_spec = m_topspec;
    for (m_miplevel = 0; m_miplevel < miplevel; ++m_miplevel) {
        if (m_spec.width == 1 && m_spec.height == 1 && m_spec.depth == 1)
            return false;   // Asked for more MIP levels than were available
        m_spec.width = std::max (1, m_spec.width/2);
        m_spec.height = std::max (1, m_spec.height/2);
        m_spec.depth = std::max (1, m_spec.depth/2);
        m_spec.full_width = m_spec.width;
        m_spec.full_height = m_spec.height;
        m_spec.full_depth = m_spec.depth;
    }
    return true;
}

bool
NullInput::read_native_scanline (int subimage, int miplevel,
                                 int y, int z, void *data)
{
    if (m_value.size()) {
        size_t s = m_spec.pixel_bytes();
        for (int x = 0; x < m_spec.width; ++x)
            memcpy ((char *)data + s*x, m_value.data(), s);
    } else {
        memset (data, 0, m_spec.scanline_bytes());
    }
    return true;
}

bool
NullInput::read_native_tile (int subimage, int miplevel,
                             int x, int y, int z, void *data)
{
    if (m_value.size()) {
        size_t s = m_spec.pixel_bytes();
        for (size_t x = 0, e = m_spec.tile_pixels(); x < e; ++x)
            memcpy ((char *)data + s*x, m_value.data(), s);
    } else {
        memset (data, 0, m_spec.tile_bytes());
    }
    return true;
}

OIIO_PLUGIN_NAMESPACE_END

<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <math.h>
#include "common.h"
#include "global.h"
#include "PyramidBuilding.h"
#include "Intersect.h"
#include "TriWallSceneNode.h"
#include "QuadWallSceneNode.h"
#include "BZDBCache.h"
#include "PyramidSceneNodeGenerator.h"

std::string		PyramidBuilding::typeName("PyramidBuilding");

PyramidBuilding::PyramidBuilding(const float* p, float a,
				float w, float b, float h, bool drive, bool shoot) :
				Obstacle(p, a, w, b, h,drive,shoot)
{
  // do nothing
}

PyramidBuilding::~PyramidBuilding()
{
  // do nothing
}

std::string		PyramidBuilding::getType() const
{
  return typeName;
}

std::string		PyramidBuilding::getClassName() // const
{
  return typeName;
}

float			PyramidBuilding::intersect(const Ray& r) const
{
  return timeRayHitsPyramids(r, getPosition(), getRotation(),
			     getWidth(), getBreadth(), getHeight(),
			     getZFlip());
}

void			PyramidBuilding::getNormal(const float* p,
							float* n) const
{
  // get normal in z = const plane
  const float s = shrinkFactor(p[2]);
  getNormalRect(p, getPosition(), getRotation(),
			s * getWidth(), s * getBreadth(), n);

  // make sure we are not way above or way below it
  // above is good so we can drive on it when it's fliped
  float top =  getPosition()[2]+getHeight();
  float bottom = getPosition()[2];

  if (s ==0){
	  if (this->getZFlip()){
		  if (p[2] >= top){
			  n[0] = n[1] = 0;
			  n[2] = 1;
			  return;
		  }
	  }else{
		  if (p[2] <= bottom){
			  n[0] = n[1] = 0;
			  n[2] = -1;
			  return;
		  }
	  }
  }

  // now angle it due to slope of wall
  // FIXME -- this assumes the pyramid has a square base!
  const float h = 1.0f / hypotf(getHeight(), getWidth());
  n[0] *= h * getHeight();
  n[1] *= h * getHeight();
  n[2] = h * getWidth();

  if (this->getZFlip())
	  n[2] *= -1;
}

void			PyramidBuilding::get3DNormal(const float* p,
						     float* n) const
{
  const float epsilon = ZERO_TOLERANCE;

  // get normal in z = const plane
  const float s = shrinkFactor(p[2]);
  getNormalRect(p, getPosition(), getRotation(),
		s * getWidth(), s * getBreadth(), n);

  // make sure we are not way above or way below it
  // above is good so we can drive on it when it's fliped
  float top =  getPosition()[2]+getHeight();
  float bottom = getPosition()[2];

  if (s == 0) {
    if (getZFlip()) {
      if (p[2] >= top) {
	n[0] = n[1] = 0;
	n[2] = 1;
	return;
      }
    } else {
      if (p[2] <= bottom) {
	n[0] = n[1] = 0;
	n[2] = -1;
	return;
      }
    }
  }

  if (s >= 1.0f - epsilon) {
    n[0] = n[1] = 0;
    if (getZFlip()) {
      n[2] = 1;
    } else {
      n[2] = -1;
    }
    return;
  }

  // now angle it due to slope of wall
  // FIXME -- this assumes the pyramid has a square base!
  const float h = 1.0f / hypotf(getHeight(), getWidth());
  n[0] *= h * getHeight();
  n[1] *= h * getHeight();
  n[2]  = h * getWidth();

  if (this->getZFlip())
    n[2] *= -1;
}

bool			PyramidBuilding::isInside(const float* p,
						float radius) const
{
  // really rough -- doesn't decrease size with height
  return (p[2] <= getHeight())
  &&     ((p[2]+BZDBCache::tankHeight) >= getPosition()[2])
  &&     testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius);
}

bool			PyramidBuilding::isInside(const float* p, float a,
						float dx, float dy) const
{
  // Tank is below pyramid ?
  if (p[2] + BZDBCache::tankHeight < getPosition()[2])
    return false;
  // Tank is above pyramid ?
  if (p[2] > getPosition()[2] + getHeight())
    return false;
  // Could be inside. Then check collision with the rectangle at object height
  // This is a rectangle reduced by shrinking but pass the height that we are
  // not so sure where collision can be
  const float s = shrinkFactor(p[2], BZDBCache::tankHeight);
  return testRectRect(getPosition(), getRotation(),
		      s * getWidth(), s * getBreadth(), p, a, dx, dy);
}

bool			PyramidBuilding::isCrossing(const float* p, float a,
					float dx, float dy, float* plane) const
{
  // if not inside or contained then not crossing
  if (!isInside(p, a, dx, dy) ||
	testRectInRect(getPosition(), getRotation(),
			getWidth(), getBreadth(), p, a, dx, dy))
    return false;
  if (!plane) return true;

  // it's crossing -- choose which wall is being crossed (this
  // is a guestimate, should really do a careful test).  just
  // see which wall the point is closest to.
  const float* p2 = getPosition();
  const float a2 = getRotation();
  const float c = cosf(-a2), s = sinf(-a2);
  const float x = c * (p[0] - p2[0]) - s * (p[1] - p2[1]);
  const float y = c * (p[1] - p2[1]) + s * (p[0] - p2[0]);
  float pw[2];
  if (fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) {
    plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2));
    plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2));
    pw[0] = p2[0] + getWidth() * plane[0];
    pw[1] = p2[1] + getWidth() * plane[1];
  }
  else {
    plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2));
    plane[1] = ((y < 0.0) ? -cosf(a2) : cosf(a2));
    pw[0] = p2[0] + getBreadth() * plane[0];
    pw[1] = p2[1] + getBreadth() * plane[1];
  }

  // now finish off plane equation (FIXME -- assumes a square base)
  const float h = 1.0f / hypotf(getHeight(), getWidth());
  plane[0] *= h * getHeight();
  plane[1] *= h * getHeight();
  plane[2] = h * getWidth();
  plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]);
  return true;
}

bool			PyramidBuilding::getHitNormal(
				const float* pos1, float,
				const float* pos2, float,
				float, float, float height,
				float* normal) const
{
  // pyramids height and flipping
  // normalize height sign and report that in flip
  float oHeight = getHeight();
  bool  flip    = getZFlip();
  if (oHeight < 0) {
    flip    = !flip;
    oHeight = -oHeight;
  }

  // get Bottom and Top of building
  float oBottom = getPosition()[2];
  float oTop    = oBottom + oHeight;

  // get higher and lower point of base of colliding object
  float objHigh = pos1[2];
  float objLow  = pos2[2];
  if (objHigh < objLow) {
    float temp = objHigh;
    objHigh    = objLow;
    objLow     = temp;
  }

  normal[0] = normal[1] = 0;
  if (flip && objHigh > oTop) {
    // base of higher object is over the plateau
    normal[2] = 1;
    return true;
  } else if (!flip && objLow + height < oBottom) {
    // top of lower object is below the base
    normal[2] = -1;
    return true;
  }

  // get normal in z = const plane
  const float s = shrinkFactor(pos1[2], height);

  getNormalRect(pos1, getPosition(), getRotation(),
		s * getWidth(), s * getBreadth(), normal);

  // now angle it due to slope of wall
  // FIXME -- this assumes the pyramid has a square base!
  const float h = 1.0f / hypotf(oHeight, getWidth());
  normal[0] *= h * oHeight;
  normal[1] *= h * oHeight;
  normal[2]  = h * getWidth();

  if (flip)
    normal[2] = -normal[2];
  return true;
}

ObstacleSceneNodeGenerator*	PyramidBuilding::newSceneNodeGenerator() const
{
  return new PyramidSceneNodeGenerator(this);
}

void			PyramidBuilding::getCorner(int index,
						float* pos) const
{
  const float* base = getPosition();
  const float c = cosf(getRotation());
  const float s = sinf(getRotation());
  const float w = getWidth();
  const float h = getBreadth();
  const float top  = getHeight() + base[2];
  switch (index) {
    case 0:
      pos[0] = base[0] + c * w - s * h;
      pos[1] = base[1] + s * w + c * h;
	  if (getZFlip())
		 pos[2] = top;
	  else
		 pos[2] = base[2];
      break;
    case 1:
      pos[0] = base[0] - c * w - s * h;
      pos[1] = base[1] - s * w + c * h;
	  if (getZFlip())
		 pos[2] = top;
	  else
		 pos[2] = base[2];
      break;
    case 2:
      pos[0] = base[0] - c * w + s * h;
      pos[1] = base[1] - s * w - c * h;
	  if (getZFlip())
		 pos[2] = top;
	  else
		 pos[2] = base[2];
      break;
    case 3:
      pos[0] = base[0] + c * w + s * h;
      pos[1] = base[1] + s * w - c * h;
	  if (getZFlip())
		 pos[2] = top;
	  else
		 pos[2] = base[2];
      break;
    case 4:
      pos[0] = base[0];
      pos[1] = base[1];
	  if (getZFlip())
		 pos[2] = base[2];
	  else
		 pos[2] = top;
      break;
  }
}

float			PyramidBuilding::shrinkFactor(float z,
						      float height) const
{
  float shrink;

  // Normalize Height and flip to have height > 0
  float oHeight = getHeight();
  bool  flip    = getZFlip();
  if (oHeight < 0) {
    flip    = !flip;
    oHeight = - oHeight;
  }

 // Remove heights bias
  const float *pos = getPosition();
  z -= pos[2];
  if (oHeight <= ZERO_TOLERANCE) {
    shrink = 1.0f;
  } else {
    // Normalize heights
    z /= oHeight;

    // if flipped the bigger intersection is at top of the object
    if (flip) {
      // Normalize the object height, we have not done yet
      z += height / oHeight;
    }

    // shrink is that
    if (flip) {
      shrink = z;
    } else {
      shrink = 1.0f - z;
    }
  }

  // clamp in 0 .. 1
  if (shrink < 0.0)
    shrink = 0.0;
  else if (shrink > 1.0)
    shrink = 1.0;

  return shrink;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<commit_msg>Fixing stuck on flipped pyramids<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <math.h>
#include "common.h"
#include "global.h"
#include "PyramidBuilding.h"
#include "Intersect.h"
#include "TriWallSceneNode.h"
#include "QuadWallSceneNode.h"
#include "BZDBCache.h"
#include "PyramidSceneNodeGenerator.h"

std::string		PyramidBuilding::typeName("PyramidBuilding");

PyramidBuilding::PyramidBuilding(const float* p, float a,
				float w, float b, float h, bool drive, bool shoot) :
				Obstacle(p, a, w, b, h,drive,shoot)
{
  // do nothing
}

PyramidBuilding::~PyramidBuilding()
{
  // do nothing
}

std::string		PyramidBuilding::getType() const
{
  return typeName;
}

std::string		PyramidBuilding::getClassName() // const
{
  return typeName;
}

float			PyramidBuilding::intersect(const Ray& r) const
{
  return timeRayHitsPyramids(r, getPosition(), getRotation(),
			     getWidth(), getBreadth(), getHeight(),
			     getZFlip());
}

void			PyramidBuilding::getNormal(const float* p,
							float* n) const
{
  // get normal in z = const plane
  const float s = shrinkFactor(p[2]);
  getNormalRect(p, getPosition(), getRotation(),
			s * getWidth(), s * getBreadth(), n);

  // make sure we are not way above or way below it
  // above is good so we can drive on it when it's fliped
  float top =  getPosition()[2]+getHeight();
  float bottom = getPosition()[2];

  if (s ==0){
	  if (this->getZFlip()){
		  if (p[2] >= top){
			  n[0] = n[1] = 0;
			  n[2] = 1;
			  return;
		  }
	  }else{
		  if (p[2] <= bottom){
			  n[0] = n[1] = 0;
			  n[2] = -1;
			  return;
		  }
	  }
  }

  // now angle it due to slope of wall
  // FIXME -- this assumes the pyramid has a square base!
  const float h = 1.0f / hypotf(getHeight(), getWidth());
  n[0] *= h * getHeight();
  n[1] *= h * getHeight();
  n[2] = h * getWidth();

  if (this->getZFlip())
	  n[2] *= -1;
}

void			PyramidBuilding::get3DNormal(const float* p,
						     float* n) const
{
  const float epsilon = ZERO_TOLERANCE;

  // get normal in z = const plane
  const float s = shrinkFactor(p[2]);
  getNormalRect(p, getPosition(), getRotation(),
		s * getWidth(), s * getBreadth(), n);

  // make sure we are not way above or way below it
  // above is good so we can drive on it when it's fliped
  float top =  getPosition()[2]+getHeight();
  float bottom = getPosition()[2];

  if (s == 0) {
    if (getZFlip()) {
      if (p[2] >= top) {
	n[0] = n[1] = 0;
	n[2] = 1;
	return;
      }
    } else {
      if (p[2] <= bottom) {
	n[0] = n[1] = 0;
	n[2] = -1;
	return;
      }
    }
  }

  if (s >= 1.0f - epsilon) {
    n[0] = n[1] = 0;
    if (getZFlip()) {
      n[2] = 1;
    } else {
      n[2] = -1;
    }
    return;
  }

  // now angle it due to slope of wall
  // FIXME -- this assumes the pyramid has a square base!
  const float h = 1.0f / hypotf(getHeight(), getWidth());
  n[0] *= h * getHeight();
  n[1] *= h * getHeight();
  n[2]  = h * getWidth();

  if (this->getZFlip())
    n[2] *= -1;
}

bool			PyramidBuilding::isInside(const float* p,
						float radius) const
{
  // really rough -- doesn't decrease size with height
  return (p[2] <= getHeight())
  &&     ((p[2]+BZDBCache::tankHeight) >= getPosition()[2])
  &&     testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius);
}

bool			PyramidBuilding::isInside(const float* p, float a,
						float dx, float dy) const
{
  // Tank is below pyramid ?
  if (p[2] + BZDBCache::tankHeight < getPosition()[2])
    return false;
  // Tank is above pyramid ?
  if (p[2] >= getPosition()[2] + getHeight())
    return false;
  // Could be inside. Then check collision with the rectangle at object height
  // This is a rectangle reduced by shrinking but pass the height that we are
  // not so sure where collision can be
  const float s = shrinkFactor(p[2], BZDBCache::tankHeight);
  return testRectRect(getPosition(), getRotation(),
		      s * getWidth(), s * getBreadth(), p, a, dx, dy);
}

bool			PyramidBuilding::isCrossing(const float* p, float a,
					float dx, float dy, float* plane) const
{
  // if not inside or contained then not crossing
  if (!isInside(p, a, dx, dy) ||
	testRectInRect(getPosition(), getRotation(),
			getWidth(), getBreadth(), p, a, dx, dy))
    return false;
  if (!plane) return true;

  // it's crossing -- choose which wall is being crossed (this
  // is a guestimate, should really do a careful test).  just
  // see which wall the point is closest to.
  const float* p2 = getPosition();
  const float a2 = getRotation();
  const float c = cosf(-a2), s = sinf(-a2);
  const float x = c * (p[0] - p2[0]) - s * (p[1] - p2[1]);
  const float y = c * (p[1] - p2[1]) + s * (p[0] - p2[0]);
  float pw[2];
  if (fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) {
    plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2));
    plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2));
    pw[0] = p2[0] + getWidth() * plane[0];
    pw[1] = p2[1] + getWidth() * plane[1];
  }
  else {
    plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2));
    plane[1] = ((y < 0.0) ? -cosf(a2) : cosf(a2));
    pw[0] = p2[0] + getBreadth() * plane[0];
    pw[1] = p2[1] + getBreadth() * plane[1];
  }

  // now finish off plane equation (FIXME -- assumes a square base)
  const float h = 1.0f / hypotf(getHeight(), getWidth());
  plane[0] *= h * getHeight();
  plane[1] *= h * getHeight();
  plane[2] = h * getWidth();
  plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]);
  return true;
}

bool			PyramidBuilding::getHitNormal(
				const float* pos1, float,
				const float* pos2, float,
				float, float, float height,
				float* normal) const
{
  // pyramids height and flipping
  // normalize height sign and report that in flip
  float oHeight = getHeight();
  bool  flip    = getZFlip();
  if (oHeight < 0) {
    flip    = !flip;
    oHeight = -oHeight;
  }

  // get Bottom and Top of building
  float oBottom = getPosition()[2];
  float oTop    = oBottom + oHeight;

  // get higher and lower point of base of colliding object
  float objHigh = pos1[2];
  float objLow  = pos2[2];
  if (objHigh < objLow) {
    float temp = objHigh;
    objHigh    = objLow;
    objLow     = temp;
  }

  normal[0] = normal[1] = 0;
  if (flip && objHigh >= oTop) {
    // base of higher object is over the plateau
    normal[2] = 1;
    return true;
  } else if (!flip && objLow + height < oBottom) {
    // top of lower object is below the base
    normal[2] = -1;
    return true;
  }

  // get normal in z = const plane
  const float s = shrinkFactor(pos1[2], height);

  getNormalRect(pos1, getPosition(), getRotation(),
		s * getWidth(), s * getBreadth(), normal);

  // now angle it due to slope of wall
  // FIXME -- this assumes the pyramid has a square base!
  const float h = 1.0f / hypotf(oHeight, getWidth());
  normal[0] *= h * oHeight;
  normal[1] *= h * oHeight;
  normal[2]  = h * getWidth();

  if (flip)
    normal[2] = -normal[2];
  return true;
}

ObstacleSceneNodeGenerator*	PyramidBuilding::newSceneNodeGenerator() const
{
  return new PyramidSceneNodeGenerator(this);
}

void			PyramidBuilding::getCorner(int index,
						float* pos) const
{
  const float* base = getPosition();
  const float c = cosf(getRotation());
  const float s = sinf(getRotation());
  const float w = getWidth();
  const float h = getBreadth();
  const float top  = getHeight() + base[2];
  switch (index) {
    case 0:
      pos[0] = base[0] + c * w - s * h;
      pos[1] = base[1] + s * w + c * h;
	  if (getZFlip())
		 pos[2] = top;
	  else
		 pos[2] = base[2];
      break;
    case 1:
      pos[0] = base[0] - c * w - s * h;
      pos[1] = base[1] - s * w + c * h;
	  if (getZFlip())
		 pos[2] = top;
	  else
		 pos[2] = base[2];
      break;
    case 2:
      pos[0] = base[0] - c * w + s * h;
      pos[1] = base[1] - s * w - c * h;
	  if (getZFlip())
		 pos[2] = top;
	  else
		 pos[2] = base[2];
      break;
    case 3:
      pos[0] = base[0] + c * w + s * h;
      pos[1] = base[1] + s * w - c * h;
	  if (getZFlip())
		 pos[2] = top;
	  else
		 pos[2] = base[2];
      break;
    case 4:
      pos[0] = base[0];
      pos[1] = base[1];
	  if (getZFlip())
		 pos[2] = base[2];
	  else
		 pos[2] = top;
      break;
  }
}

float			PyramidBuilding::shrinkFactor(float z,
						      float height) const
{
  float shrink;

  // Normalize Height and flip to have height > 0
  float oHeight = getHeight();
  bool  flip    = getZFlip();
  if (oHeight < 0) {
    flip    = !flip;
    oHeight = - oHeight;
  }

 // Remove heights bias
  const float *pos = getPosition();
  z -= pos[2];
  if (oHeight <= ZERO_TOLERANCE) {
    shrink = 1.0f;
  } else {
    // Normalize heights
    z /= oHeight;

    // if flipped the bigger intersection is at top of the object
    if (flip) {
      // Normalize the object height, we have not done yet
      z += height / oHeight;
    }

    // shrink is that
    if (flip) {
      shrink = z;
    } else {
      shrink = 1.0f - z;
    }
  }

  // clamp in 0 .. 1
  if (shrink < 0.0)
    shrink = 0.0;
  else if (shrink > 1.0)
    shrink = 1.0;

  return shrink;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<|endoftext|>


<commit_before>#include "animation.h"

#include <math.h>

Animation::Animation(std::string object, int duration) :
    _object(object), _duration(duration), _easing(LINEAR)
{
}

Animation::Easing Animation::strToEasing(std::string s)
{
    if (s == "LINEAR")
        return LINEAR;
    if (s == "IN_QUAD")
        return IN_QUAD;
    if (s == "OUT_QUAD")
        return OUT_QUAD;
    if (s == "IN_OUT_QUAD")
        return IN_OUT_QUAD;
    if (s == "IN_BACK")
        return IN_BACK;
    if (s == "OUT_BACK")
        return OUT_BACK;
    if (s == "IN_OUT_BACK")
        return IN_OUT_BACK;
    if (s == "IN_ELASTIC")
        return IN_ELASTIC;
    if (s == "OUT_ELASTIC")
        return OUT_ELASTIC;
    if (s == "IN_OUT_ELASTIC")
        return IN_OUT_ELASTIC;
    else
        return UNDEFINED;
}

std::string Animation::object() const
{
    return _object;
}

int Animation::duration() const
{
    return _duration;
}

void Animation::setEasing(const Easing easing)
{
    _easing = easing;
}

void Animation::addProperty(const std::string name, const float from, const float to)
{
    AnimProperty p;
    p.property = name;
    p.from = from;
    p.to = to;
    addProperty(p);
}

void Animation::addProperty(AnimProperty p)
{
    properties.push_back(p);
}

std::map<std::string, float> Animation::getStatus(int millisecond_elapsed)
{
    float progress = relativeProgress(millisecond_elapsed);
    std::map<std::string, float> res;
    std::vector<AnimProperty>::iterator i;
    for (i = properties.begin(); i != properties.end(); ++i){
        res[(*i).property] = (*i).from + (float((*i).to - (*i).from) * progress);
    }
    return res;
}

float Animation::relativeProgress(int millisecond_elapsed)
{
    float progress = float(millisecond_elapsed)/float(_duration);
    if (progress > 1.0)
        progress = 1.0;
    switch (_easing){
    case UNDEFINED:
    {
        return 1.0;
    }
    case LINEAR:
    {
        return progress;
    }
    case IN_QUAD:
    {
        return progress * progress;
    }
    case OUT_QUAD:
    {
        return -1.0 * progress * (progress - 2.0);
    }
    case IN_OUT_QUAD:
    {
        float p = progress * 2;
        if (p < 1)
            return 0.5 * p * p;
        p -= 1.0;
        return -0.5 * (p * (p - 2.0) - 1.0);
    }
    case IN_BACK:
    {
        return progress * progress * ((1.70158 + 1.0) * progress - 1.70158);
    }
    case OUT_BACK:
    {
        float p = progress - 1.0;
        return p * p * ((1.70158 + 1) * p + 1.70158) + 1.0;
    }
    case IN_OUT_BACK:
    {
        float p = progress * 2.0;
        float s = 1.70158 * 1.525;
        if (p < 1)
            return 0.5 * (p * p * ((s + 1.0) * p - s));
        p -= 2.0;
        return 0.5 * (p * p * ((s + 1.0) * p + s) + 2.0);
    }
    case IN_ELASTIC:
    {
        float p = 0.3;
        float s = p / 4.0;
        float q = progress;
        if (q == 1)
            return 1.0;
        q -= 1.0;
        return -(pow(2, 10 * q) * sin((q - s) * (2 * M_PI) / p));
    }
    case OUT_ELASTIC:
    {
        float p = 0.3;
        float s = p / 4.0;
        float q = progress;
        if (q == 1)
            return 1.0;
        return pow(2, -10 * q) * sin((q - s) * (2 * M_PI) / p) + 1.0;
    }
    case IN_OUT_ELASTIC:
    {
        float p = 0.3 * 1.5;
        float s = p / 4.0;
        float q = progress * 2;
        if (q == 2)
            return 1.0;
        float qq = q - 1.0;
        if (q < 1)
            return -0.5 * (pow(2, 10 * qq) * sin((qq - s) * (2.0 * M_PI) / p));
        return pow(2, -10 * qq) * sin((qq - s) * (2.0 * M_PI) / p) * 0.5 + 1.0;
    }
    }
    return 1.0;
}
<commit_msg>Use cmath instead of math.h<commit_after>#include "animation.h"

#include <cmath>

Animation::Animation(std::string object, int duration) :
    _object(object), _duration(duration), _easing(LINEAR)
{
}

Animation::Easing Animation::strToEasing(std::string s)
{
    if (s == "LINEAR")
        return LINEAR;
    if (s == "IN_QUAD")
        return IN_QUAD;
    if (s == "OUT_QUAD")
        return OUT_QUAD;
    if (s == "IN_OUT_QUAD")
        return IN_OUT_QUAD;
    if (s == "IN_BACK")
        return IN_BACK;
    if (s == "OUT_BACK")
        return OUT_BACK;
    if (s == "IN_OUT_BACK")
        return IN_OUT_BACK;
    if (s == "IN_ELASTIC")
        return IN_ELASTIC;
    if (s == "OUT_ELASTIC")
        return OUT_ELASTIC;
    if (s == "IN_OUT_ELASTIC")
        return IN_OUT_ELASTIC;
    else
        return UNDEFINED;
}

std::string Animation::object() const
{
    return _object;
}

int Animation::duration() const
{
    return _duration;
}

void Animation::setEasing(const Easing easing)
{
    _easing = easing;
}

void Animation::addProperty(const std::string name, const float from, const float to)
{
    AnimProperty p;
    p.property = name;
    p.from = from;
    p.to = to;
    addProperty(p);
}

void Animation::addProperty(AnimProperty p)
{
    properties.push_back(p);
}

std::map<std::string, float> Animation::getStatus(int millisecond_elapsed)
{
    float progress = relativeProgress(millisecond_elapsed);
    std::map<std::string, float> res;
    std::vector<AnimProperty>::iterator i;
    for (i = properties.begin(); i != properties.end(); ++i){
        res[(*i).property] = (*i).from + (float((*i).to - (*i).from) * progress);
    }
    return res;
}

float Animation::relativeProgress(int millisecond_elapsed)
{
    float progress = float(millisecond_elapsed)/float(_duration);
    if (progress > 1.0)
        progress = 1.0;
    switch (_easing){
    case UNDEFINED:
    {
        return 1.0;
    }
    case LINEAR:
    {
        return progress;
    }
    case IN_QUAD:
    {
        return progress * progress;
    }
    case OUT_QUAD:
    {
        return -1.0 * progress * (progress - 2.0);
    }
    case IN_OUT_QUAD:
    {
        float p = progress * 2;
        if (p < 1)
            return 0.5 * p * p;
        p -= 1.0;
        return -0.5 * (p * (p - 2.0) - 1.0);
    }
    case IN_BACK:
    {
        return progress * progress * ((1.70158 + 1.0) * progress - 1.70158);
    }
    case OUT_BACK:
    {
        float p = progress - 1.0;
        return p * p * ((1.70158 + 1) * p + 1.70158) + 1.0;
    }
    case IN_OUT_BACK:
    {
        float p = progress * 2.0;
        float s = 1.70158 * 1.525;
        if (p < 1)
            return 0.5 * (p * p * ((s + 1.0) * p - s));
        p -= 2.0;
        return 0.5 * (p * p * ((s + 1.0) * p + s) + 2.0);
    }
    case IN_ELASTIC:
    {
        float p = 0.3;
        float s = p / 4.0;
        float q = progress;
        if (q == 1)
            return 1.0;
        q -= 1.0;
        return -(pow(2, 10 * q) * sin((q - s) * (2 * M_PI) / p));
    }
    case OUT_ELASTIC:
    {
        float p = 0.3;
        float s = p / 4.0;
        float q = progress;
        if (q == 1)
            return 1.0;
        return pow(2, -10 * q) * sin((q - s) * (2 * M_PI) / p) + 1.0;
    }
    case IN_OUT_ELASTIC:
    {
        float p = 0.3 * 1.5;
        float s = p / 4.0;
        float q = progress * 2;
        if (q == 2)
            return 1.0;
        float qq = q - 1.0;
        if (q < 1)
            return -0.5 * (pow(2, 10 * qq) * sin((qq - s) * (2.0 * M_PI) / p));
        return pow(2, -10 * qq) * sin((qq - s) * (2.0 * M_PI) / p) * 0.5 + 1.0;
    }
    }
    return 1.0;
}
<|endoftext|>