<commit_before>/// \file dtsc2flv.cpp
/// Contains the code that will transform any valid DTSC input into valid FLVs.

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <mist/flv_tag.h> //FLV support
#include <mist/dtsc.h> //DTSC support
#include <mist/amf.h> //AMF support
#include <mist/config.h>

///\brief Holds everything unique to converters.
namespace Converters {

  ///\brief Converts DTSC from stdin to FLV on stdout.
  ///\return The return code for the converter.
  int DTSC2FLV(){
    FLV::Tag FLV_out; // Temporary storage for outgoing FLV data.
    DTSC::Stream Strm;
    std::string inBuffer;
    char charBuffer[1024 * 10];
    unsigned int charCount;
    bool doneheader = false;

    while (std::cin.good()){
      if (Strm.parsePacket(inBuffer)){
        if ( !doneheader){
          doneheader = true;
          std::cout.write(FLV::Header, 13);
          FLV_out.DTSCMetaInit(Strm);
          std::cout.write(FLV_out.data, FLV_out.len);
          if (Strm.metadata.isMember("video") && Strm.metadata["video"].isMember("init")){
            FLV_out.DTSCVideoInit(Strm);
            std::cout.write(FLV_out.data, FLV_out.len);
          }
          if (Strm.metadata.isMember("audio") && Strm.metadata["audio"].isMember("init")){
            FLV_out.DTSCAudioInit(Strm);
            std::cout.write(FLV_out.data, FLV_out.len);
          }
        }
        if (FLV_out.DTSCLoader(Strm)){
          std::cout.write(FLV_out.data, FLV_out.len);
        }
      }else{
        std::cin.read(charBuffer, 1024 * 10);
        charCount = std::cin.gcount();
        inBuffer.append(charBuffer, charCount);
      }
    }

    std::cerr << "Done!" << std::endl;

    return 0;
  } //FLV2DTSC

} //Converter namespace

/// Entry point for DTSC2FLV, simply calls Converters::DTSC2FLV().
int main(int argc, char ** argv){
  Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION);
  conf.parseArgs(argc, argv);
  return Converters::DTSC2FLV();
} //main
<commit_msg>Initial DTSC2 support for DTSC2FLV converter.<commit_after>/// \file dtsc2flv.cpp
/// Contains the code that will transform any valid DTSC input into valid FLVs.

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <mist/flv_tag.h> //FLV support
#include <mist/dtsc.h> //DTSC support
#include <mist/amf.h> //AMF support
#include <mist/config.h>

///\brief Holds everything unique to converters.
namespace Converters {

  ///\brief Converts DTSC from stdin to FLV on stdout.
  ///\return The return code for the converter.
  int DTSC2FLV(){
    FLV::Tag FLV_out; // Temporary storage for outgoing FLV data.
    DTSC::Stream Strm;
    std::string inBuffer;
    char charBuffer[1024 * 10];
    unsigned int charCount;
    bool doneheader = false;
    int videoID = -1, audioID = -1;

    while (std::cin.good()){
      if (Strm.parsePacket(inBuffer)){
        if ( !doneheader){
          //find first audio and video tracks
          for (JSON::ObjIter objIt = Strm.metadata["tracks"].ObjBegin(); objIt != Strm.metadata["tracks"].ObjEnd(); objIt++){
            if (videoID == -1 && objIt->second["type"].asString() == "video"){
              videoID = objIt->second["trackid"].asInt();
            }
            if (audioID == -1 && objIt->second["type"].asString() == "audio"){
              audioID = objIt->second["trackid"].asInt();
            }
          }

          doneheader = true;
          std::cout.write(FLV::Header, 13);
          FLV_out.DTSCMetaInit(Strm, Strm.getTrackById(videoID), Strm.getTrackById(audioID));
          std::cout.write(FLV_out.data, FLV_out.len);
          if (videoID && Strm.getTrackById(videoID).isMember("init")){
            FLV_out.DTSCVideoInit(Strm.getTrackById(videoID));
            std::cout.write(FLV_out.data, FLV_out.len);
          }
          if (audioID && Strm.getTrackById(audioID).isMember("init")){
            FLV_out.DTSCAudioInit(Strm.getTrackById(audioID));
            std::cout.write(FLV_out.data, FLV_out.len);
          }
        }
        if (FLV_out.DTSCLoader(Strm)){
          std::cout.write(FLV_out.data, FLV_out.len);
        }
      }else{
        std::cin.read(charBuffer, 1024 * 10);
        charCount = std::cin.gcount();
        inBuffer.append(charBuffer, charCount);
      }
    }

    std::cerr << "Done!" << std::endl;

    return 0;
  } //FLV2DTSC

} //Converter namespace

/// Entry point for DTSC2FLV, simply calls Converters::DTSC2FLV().
int main(int argc, char ** argv){
  Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION);
  conf.parseArgs(argc, argv);
  return Converters::DTSC2FLV();
} //main
<|endoftext|>


<commit_before>#include <QDir>
#include <iostream>
#include <iterator>
#include <string>
#include "image/image.hpp"
#include "boost/program_options.hpp"
#include "dicom/dwi_header.hpp"

namespace po = boost::program_options;
QStringList search_files(QString dir,QString filter);
bool load_all_files(QStringList file_list,boost::ptr_vector<DwiHeader>& dwi_files);
int src(int ac, char *av[])
{
    po::options_description rec_desc("dicom parsing options");
    rec_desc.add_options()
    ("help", "help message")
    ("action", po::value<std::string>(), "src:dicom parsing")
    ("source", po::value<std::string>(), "assign the directory for the dicom files")
    ("recursive", po::value<std::string>(), "search subdirectories")
    ("b_table", po::value<std::string>(), "assign the b-table")
    ("output", po::value<std::string>(), "assign the output filename")
    ;
    if(!ac)
    {
        std::cout << rec_desc << std::endl;
        return 1;
    }
    po::variables_map vm;
    po::store(po::command_line_parser(ac, av).options(rec_desc).allow_unregistered().run(), vm);
    po::notify(vm);

    std::string source = vm["source"].as<std::string>();
    std::string ext;
    if(source.size() > 4)
        ext = std::string(source.end()-4,source.end());

    boost::ptr_vector<DwiHeader> dwi_files;
    QStringList file_list;
    if(ext ==".nii" || ext == ".dcm" || ext == "dseq" || ext == "i.gz")
        file_list << source.c_str();
    else
    {
        // load directory
        QDir directory = QString(source.c_str());
        if(vm.count("recursive"))
        {
            std::cout << "search recursively in the subdir" << std::endl;
            file_list = search_files(source.c_str(),"*.dcm");
        }
        else
        {
            file_list = directory.entryList(QStringList("*.dcm"),QDir::Files|QDir::NoSymLinks);
            for (unsigned int index = 0;index < file_list.size();++index)
                file_list[index] = QString(source.c_str()) + "/" + file_list[index];
        }
        std::cout << "A total of " << file_list.size() <<" files found in the directory" << std::endl;
    }

    if(file_list.empty())
    {
        std::cout << "No file found for creating src" << std::endl;
        return -1;
    }

    if(!load_all_files(file_list,dwi_files))
    {
        std::cout << "Invalid file format" << std::endl;
        return -1;
    }
    if(vm.count("b_table"))
    {
        std::string table_file_name = vm["b_table"].as<std::string>();
        std::ifstream in(table_file_name.c_str());
        if(!in)
        {
            std::cout << "Failed to open b-table" <<std::endl;
            return -1;
        }
        std::string line;
        std::vector<double> b_table;
        while(std::getline(in,line))
        {
            std::istringstream read_line(line);
            std::copy(std::istream_iterator<double>(read_line),
                      std::istream_iterator<double>(),
                      std::back_inserter(b_table));
        }
        if(b_table.size() != dwi_files.size()*4)
        {
            std::cout << "Mismatch between b-table and the loaded image" << std::endl;
            return -1;
        }
        for(unsigned int index = 0,b_index = 0;index < dwi_files.size();++index,b_index += 4)
        {
            dwi_files[index].set_bvalue(b_table[b_index]);
            dwi_files[index].set_bvec(b_table[b_index+1],b_table[b_index+2],b_table[b_index+3]);
        }
        std::cout << "B-table " << table_file_name << " loaded" << std::endl;
    }

    if(dwi_files.empty())
    {
        std::cout << "No file readed. Abort." << std::endl;
        return 1;
    }
    std::cout << "Output src" << std::endl;
    DwiHeader::output_src(vm["output"].as<std::string>().c_str(),dwi_files,false,false);
    return 0;
}
<commit_msg>more log output for cmd src<commit_after>#include <QDir>
#include <iostream>
#include <iterator>
#include <string>
#include "image/image.hpp"
#include "boost/program_options.hpp"
#include "dicom/dwi_header.hpp"

namespace po = boost::program_options;
QStringList search_files(QString dir,QString filter);
bool load_all_files(QStringList file_list,boost::ptr_vector<DwiHeader>& dwi_files);
int src(int ac, char *av[])
{
    po::options_description rec_desc("dicom parsing options");
    rec_desc.add_options()
    ("help", "help message")
    ("action", po::value<std::string>(), "src:dicom parsing")
    ("source", po::value<std::string>(), "assign the directory for the dicom files")
    ("recursive", po::value<std::string>(), "search subdirectories")
    ("b_table", po::value<std::string>(), "assign the b-table")
    ("output", po::value<std::string>(), "assign the output filename")
    ;
    if(!ac)
    {
        std::cout << rec_desc << std::endl;
        return 1;
    }
    po::variables_map vm;
    po::store(po::command_line_parser(ac, av).options(rec_desc).allow_unregistered().run(), vm);
    po::notify(vm);

    std::string source = vm["source"].as<std::string>();
    std::string ext;
    if(source.size() > 4)
        ext = std::string(source.end()-4,source.end());

    boost::ptr_vector<DwiHeader> dwi_files;
    QStringList file_list;
    if(ext ==".nii" || ext == ".dcm" || ext == "dseq" || ext == "i.gz")
    {
        std::cout << "image=" << source.c_str() << std::endl;
        file_list << source.c_str();
    }
    else
    {
        std::cout << "load files in directory " << source.c_str() << std::endl;
        QDir directory = QString(source.c_str());
        if(vm.count("recursive"))
        {
            std::cout << "search recursively in the subdir" << std::endl;
            file_list = search_files(source.c_str(),"*.dcm");
        }
        else
        {
            file_list = directory.entryList(QStringList("*.dcm"),QDir::Files|QDir::NoSymLinks);
            for (unsigned int index = 0;index < file_list.size();++index)
                file_list[index] = QString(source.c_str()) + "/" + file_list[index];
        }
        std::cout << "A total of " << file_list.size() <<" files found in the directory" << std::endl;
    }

    if(file_list.empty())
    {
        std::cout << "No file found for creating src" << std::endl;
        return -1;
    }

    if(!load_all_files(file_list,dwi_files))
    {
        std::cout << "Invalid file format" << std::endl;
        return -1;
    }
    if(vm.count("b_table"))
    {
        std::string table_file_name = vm["b_table"].as<std::string>();
        std::ifstream in(table_file_name.c_str());
        if(!in)
        {
            std::cout << "Failed to open b-table" <<std::endl;
            return -1;
        }
        std::string line;
        std::vector<double> b_table;
        while(std::getline(in,line))
        {
            std::istringstream read_line(line);
            std::copy(std::istream_iterator<double>(read_line),
                      std::istream_iterator<double>(),
                      std::back_inserter(b_table));
        }
        if(b_table.size() != dwi_files.size()*4)
        {
            std::cout << "Mismatch between b-table and the loaded image" << std::endl;
            return -1;
        }
        for(unsigned int index = 0,b_index = 0;index < dwi_files.size();++index,b_index += 4)
        {
            dwi_files[index].set_bvalue(b_table[b_index]);
            dwi_files[index].set_bvec(b_table[b_index+1],b_table[b_index+2],b_table[b_index+3]);
        }
        std::cout << "B-table " << table_file_name << " loaded" << std::endl;
    }

    if(dwi_files.empty())
    {
        std::cout << "No file readed. Abort." << std::endl;
        return 1;
    }
    std::cout << "Output src " << vm["output"].as<std::string>().c_str() << std::endl;
    DwiHeader::output_src(vm["output"].as<std::string>().c_str(),dwi_files,false,false);
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Host based encapsulated base sweeper.
 */

#ifndef _PFASST_ENCAP_ENCAP_SWEEPER_HPP_
#define _PFASST_ENCAP_ENCAP_SWEEPER_HPP_

#include <cstdlib>
#include <vector>
#include <memory>

#include "../globals.hpp"
#include "../interfaces.hpp"
#include "../quadrature.hpp"
#include "encapsulation.hpp"

namespace pfasst
{
  namespace encap
  {
    template<typename time = time_precision>
    class EncapSweeper
      : public ISweeper<time>
    {
      protected:
        //! @{
        quadrature::IQuadrature<time>* quad;
        shared_ptr<EncapFactory<time>> factory;
        shared_ptr<Encapsulation<time>> start_state;
        shared_ptr<Encapsulation<time>> end_state;
        //! @}

      public:
        //! @{
        EncapSweeper()
          : quad(nullptr)
        {}

        virtual ~EncapSweeper()
        {
          if (this->quad) delete this->quad;
        }
        //! @}

        //! @{
        virtual void spread() override
        {
          for (size_t m = 1; m < this->quad->get_num_nodes(); m++) {
            //            this->get_state(m)->copy(this->start_state);
            this->get_state(m)->copy(this->get_state(0));
          }
        }
        //! @}

        //! @{
        void set_quadrature(quadrature::IQuadrature<time>* quad)
        {
          this->quad = quad;
        }

        const quadrature::IQuadrature<time>* get_quadrature() const
        {
          return this->quad;
        }

        shared_ptr<Encapsulation<time>> get_start_state() const
        {
          return this->start_state;
        }

        const vector<time> get_nodes() const
        {
          return this->quad->get_nodes();
        }

        void set_factory(shared_ptr<EncapFactory<time>> factory)
        {
          this->factory = factory;
        }

        virtual shared_ptr<EncapFactory<time>> get_factory() const
        {
          return factory;
        }

        /**
         * retrieve solution values of current iteration at time node index `m`
         *
         * @param[in] m 0-based index of time node
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual shared_ptr<Encapsulation<time>> get_state(size_t m) const
        {
          UNUSED(m);
          throw NotImplementedYet("sweeper");
          return NULL;
        }

        /**
         * retrieves FAS correction of current iteration at time node index `m`
         *
         * @param[in] m 0-based index of time node
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual shared_ptr<Encapsulation<time>> get_tau(size_t m) const
        {
          UNUSED(m);
          throw NotImplementedYet("sweeper");
          return NULL;
        }

        /**
         * retrieves solution values of previous iteration at time node index `m`
         *
         * @param[in] m 0-based index of time node
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual shared_ptr<Encapsulation<time>> get_saved_state(size_t m) const
        {
          UNUSED(m);
          throw NotImplementedYet("sweeper");
          return NULL;
        }

        virtual shared_ptr<Encapsulation<time>> get_end_state()
        {
          return this->end_state;
        }
        //! @}

        //! @{
        /**
         * @copydoc ISweeper::advance()
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual void advance() override
        {
          throw NotImplementedYet("sweeper");
        }

        /**
         * evaluates the right hand side at given time node
         *
         * This evaluates the right hand side at the given time node with index `m` as returned by
         * pfasst::encap::EncapSweeper::get_nodes:
         *
         * @param[in] m index of the time node to evaluate at
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual void evaluate(size_t m)
        {
          UNUSED(m);
          throw NotImplementedYet("sweeper");
        }

        /**
         * integrates values of right hand side at all time nodes \\( t \\in [0,M-1] \\)
         * simultaneously
         *
         * @param[in] dt width of the time interval to integrate
         * @param[in,out] dst integrated values
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual void integrate(time dt, vector<shared_ptr<Encapsulation<time>>> dst) const
        {
          UNUSED(dt); UNUSED(dst);
          throw NotImplementedYet("sweeper");
        }
        //! @}

        //! @{
        virtual void post(ICommunicator* comm, int tag) override
        {
          this->get_state(0)->post(comm, tag);
        }

        virtual void send(ICommunicator* comm, int tag, bool blocking) override
        {
          this->get_state(this->get_nodes().size() - 1)->send(comm, tag, blocking);
        }

        virtual void recv(ICommunicator* comm, int tag, bool blocking) override
        {
          this->get_state(0)->recv(comm, tag, blocking);
        }

        virtual void broadcast(ICommunicator* comm) override
        {
          if (comm->rank() == comm->size() - 1) {
            this->get_state(0)->copy(this->get_state(this->get_nodes().size() - 1));
          }
          this->get_state(0)->broadcast(comm);
        }
        //! @}
    };

    template<typename time>
    EncapSweeper<time>& as_encap_sweeper(shared_ptr<ISweeper<time>> x)
    {
      shared_ptr<EncapSweeper<time>> y = dynamic_pointer_cast<EncapSweeper<time>>(x);
      assert(y);
      return *y.get();
    }

    template<typename time>
    const EncapSweeper<time>& as_encap_sweeper(shared_ptr<const ISweeper<time>> x)
    {
      shared_ptr<const EncapSweeper<time>> y = dynamic_pointer_cast<const EncapSweeper<time>>(x);
      assert(y);
      return *y.get();
    }

  }  // ::pfasst::encap
}  // ::pfasst

#endif
<commit_msg>encap: Provide default `converged` method.<commit_after>/*
 * Host based encapsulated base sweeper.
 */

#ifndef _PFASST_ENCAP_ENCAP_SWEEPER_HPP_
#define _PFASST_ENCAP_ENCAP_SWEEPER_HPP_

#include <algorithm>
#include <cstdlib>
#include <vector>
#include <memory>

#include "../globals.hpp"
#include "../interfaces.hpp"
#include "../quadrature.hpp"
#include "encapsulation.hpp"

namespace pfasst
{
  namespace encap
  {
    template<typename time = time_precision>
    class EncapSweeper
      : public ISweeper<time>
    {
      protected:
        //! @{
        quadrature::IQuadrature<time>* quad;
        shared_ptr<EncapFactory<time>> factory;
        shared_ptr<Encapsulation<time>> start_state;
        shared_ptr<Encapsulation<time>> end_state;
        vector<shared_ptr<Encapsulation<time>>> residuals;
        //! @}

      public:
        time abs_residual_tol, rel_residual_tol;

      public:
        //! @{
        EncapSweeper()
          : quad(nullptr), abs_residual_tol(0.0), rel_residual_tol(0.0)
        {}

        virtual ~EncapSweeper()
        {
          if (this->quad) delete this->quad;
        }
        //! @}

        //! @{
        virtual void spread() override
        {
          for (size_t m = 1; m < this->quad->get_num_nodes(); m++) {
            //            this->get_state(m)->copy(this->start_state);
            this->get_state(m)->copy(this->get_state(0));
          }
        }
        //! @}

        //! @{
        void set_quadrature(quadrature::IQuadrature<time>* quad)
        {
          this->quad = quad;
        }

        const quadrature::IQuadrature<time>* get_quadrature() const
        {
          return this->quad;
        }

        shared_ptr<Encapsulation<time>> get_start_state() const
        {
          return this->start_state;
        }

        const vector<time> get_nodes() const
        {
          return this->quad->get_nodes();
        }

        void set_factory(shared_ptr<EncapFactory<time>> factory)
        {
          this->factory = factory;
        }

        virtual shared_ptr<EncapFactory<time>> get_factory() const
        {
          return factory;
        }

        /**
         * retrieve solution values of current iteration at time node index `m`
         *
         * @param[in] m 0-based index of time node
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual shared_ptr<Encapsulation<time>> get_state(size_t m) const
        {
          UNUSED(m);
          throw NotImplementedYet("sweeper");
          return NULL;
        }

        /**
         * retrieves FAS correction of current iteration at time node index `m`
         *
         * @param[in] m 0-based index of time node
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual shared_ptr<Encapsulation<time>> get_tau(size_t m) const
        {
          UNUSED(m);
          throw NotImplementedYet("sweeper");
          return NULL;
        }

        /**
         * retrieves solution values of previous iteration at time node index `m`
         *
         * @param[in] m 0-based index of time node
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual shared_ptr<Encapsulation<time>> get_saved_state(size_t m) const
        {
          UNUSED(m);
          throw NotImplementedYet("sweeper");
          return NULL;
        }

        virtual shared_ptr<Encapsulation<time>> get_end_state()
        {
          return this->end_state;
        }
        //! @}

        //! @{
        /**
         * @copydoc ISweeper::advance()
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual void advance() override
        {
          throw NotImplementedYet("sweeper");
        }

        /**
         * Return convergence status.
         *
         * This is used by controllers to shortcircuit iterations.
         */
        virtual bool converged() override
        {
          if (this->abs_residual_tol > 0.0 || this->rel_residual_tol > 0.0) {
            if (this->residuals.size() == 0) {
              for (auto x: this->get_nodes()) {
                this->residuals.push_back(this->get_factory()->create(pfasst::encap::solution));
              }
            }
            this->residual(this->get_controller()->get_time_step(), this->residuals);
            vector<time> rnorms;
            for (auto r: this->residuals) {
              rnorms.push_back(r->norm0());
            }
            auto rmax = *std::max_element(rnorms.begin(), rnorms.end());
            if (rmax < this->abs_residual_tol) {
              return true;
            }
            // XXX: check rel norms too
          }
          return false;
        }

        /**
         * Compute residual at each SDC node (including FAS corrections).
         */
        virtual void residual(time dt, vector<shared_ptr<Encapsulation<time>>> dst) const
        {
          throw NotImplementedYet("residual");
        }

        /**
         * evaluates the right hand side at given time node
         *
         * This evaluates the right hand side at the given time node with index `m` as returned by
         * pfasst::encap::EncapSweeper::get_nodes:
         *
         * @param[in] m index of the time node to evaluate at
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual void evaluate(size_t m)
        {
          UNUSED(m);
          throw NotImplementedYet("sweeper");
        }

        /**
         * integrates values of right hand side at all time nodes \\( t \\in [0,M-1] \\)
         * simultaneously
         *
         * @param[in] dt width of the time interval to integrate
         * @param[in,out] dst integrated values
         *
         * @note This method must be implemented in derived sweepers.
         */
        virtual void integrate(time dt, vector<shared_ptr<Encapsulation<time>>> dst) const
        {
          UNUSED(dt); UNUSED(dst);
          throw NotImplementedYet("sweeper");
        }
        //! @}

        //! @{
        virtual void post(ICommunicator* comm, int tag) override
        {
          this->get_state(0)->post(comm, tag);
        }

        virtual void send(ICommunicator* comm, int tag, bool blocking) override
        {
          this->get_state(this->get_nodes().size() - 1)->send(comm, tag, blocking);
        }

        virtual void recv(ICommunicator* comm, int tag, bool blocking) override
        {
          this->get_state(0)->recv(comm, tag, blocking);
        }

        virtual void broadcast(ICommunicator* comm) override
        {
          if (comm->rank() == comm->size() - 1) {
            this->get_state(0)->copy(this->get_state(this->get_nodes().size() - 1));
          }
          this->get_state(0)->broadcast(comm);
        }
        //! @}
    };

    template<typename time>
    EncapSweeper<time>& as_encap_sweeper(shared_ptr<ISweeper<time>> x)
    {
      shared_ptr<EncapSweeper<time>> y = dynamic_pointer_cast<EncapSweeper<time>>(x);
      assert(y);
      return *y.get();
    }

    template<typename time>
    const EncapSweeper<time>& as_encap_sweeper(shared_ptr<const ISweeper<time>> x)
    {
      shared_ptr<const EncapSweeper<time>> y = dynamic_pointer_cast<const EncapSweeper<time>>(x);
      assert(y);
      return *y.get();
    }

  }  // ::pfasst::encap
}  // ::pfasst

#endif
<|endoftext|>


<commit_before>// The Art of C++ / Sequences
// Copyright (c) 2015 Daniel Frey

#ifndef TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_RANGE_HPP
#define TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_RANGE_HPP

#include "make_integer_sequence.hpp"

namespace tao
{
  namespace seq
  {
    namespace impl
    {
      template< typename T, T N, T M, bool = ( M < N ), typename = make_integer_sequence< T, ( M < N ) ? ( N - M ) : ( M - N ) > >
      struct range_t;

      template< typename T, T N, T M, T... Ns >
      struct range_t< T, N, M, false, integer_sequence< T, Ns... > >
      {
        using type = integer_sequence< T, N + Ns... >;
      };

      template< typename T, T N, T M, T... Ns >
      struct range_t< T, N, M, true, integer_sequence< T, Ns... > >
      {
        using type = integer_sequence< T, N - Ns... >;
      };
    }

    template< typename T, T N, T M >
    using make_integer_range = typename impl::range_t< T, N, M >::type;

    template< std::size_t N, std::size_t M >
    using make_index_range = make_integer_range< std::size_t, N, M >;

  }
}

#endif // TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_RANGE_HPP
<commit_msg>Simplify expression<commit_after>// The Art of C++ / Sequences
// Copyright (c) 2015 Daniel Frey

#ifndef TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_RANGE_HPP
#define TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_RANGE_HPP

#include "make_integer_sequence.hpp"

namespace tao
{
  namespace seq
  {
    namespace impl
    {
      template< typename T, T N, T M, bool B = ( M < N ), typename = make_integer_sequence< T, B ? ( N - M ) : ( M - N ) > >
      struct range_t;

      template< typename T, T N, T M, T... Ns >
      struct range_t< T, N, M, false, integer_sequence< T, Ns... > >
      {
        using type = integer_sequence< T, N + Ns... >;
      };

      template< typename T, T N, T M, T... Ns >
      struct range_t< T, N, M, true, integer_sequence< T, Ns... > >
      {
        using type = integer_sequence< T, N - Ns... >;
      };
    }

    template< typename T, T N, T M >
    using make_integer_range = typename impl::range_t< T, N, M >::type;

    template< std::size_t N, std::size_t M >
    using make_index_range = make_integer_range< std::size_t, N, M >;

  }
}

#endif // TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_RANGE_HPP
<|endoftext|>


<commit_before>#include "physics/discrete_trajectory2.hpp"

#include <vector>

#include "geometry/frame.hpp"
#include "geometry/named_quantities.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/si.hpp"
#include "testing_utilities/componentwise.hpp"
#include "testing_utilities/discrete_trajectory_factories.hpp"

namespace principia {
namespace physics {

using geometry::Displacement;
using geometry::Frame;
using geometry::Instant;
using geometry::Velocity;
using quantities::si::Metre;
using quantities::si::Second;
using testing_utilities::Componentwise;
using testing_utilities::NewLinearTrajectoryTimeline;
using ::testing::ElementsAre;
using ::testing::Eq;

class DiscreteTrajectory2Test : public ::testing::Test {
 protected:
  using World = Frame<enum class WorldTag>;

  // Constructs a trajectory with three 5-second segments.
  DiscreteTrajectory2<World> MakeTrajectory() {
    DiscreteTrajectory2<World> trajectory;
    std::optional<DegreesOfFreedom<World>> last_degrees_of_freedom;

    Velocity<World> const v1({1 * Metre / Second,
                              0 * Metre / Second,
                              0 * Metre / Second});
    for (auto const& [t, degrees_of_freedom] :
         NewLinearTrajectoryTimeline(v1,
                                     /*Δt=*/1 * Second,
                                     /*t1=*/t0_,
                                     /*t2=*/t0_ + 5 * Second)) {
      last_degrees_of_freedom = degrees_of_freedom;
      trajectory.Append(t, degrees_of_freedom);
    }

    trajectory.NewSegment();
    Velocity<World> const v2({0 * Metre / Second,
                              1 * Metre / Second,
                              0 * Metre / Second});
    for (auto const& [t, degrees_of_freedom] :
        NewLinearTrajectoryTimeline(DegreesOfFreedom<World>(
                                        last_degrees_of_freedom->position(),
                                        v2),
                                     /*Δt=*/1 * Second,
                                     /*t1=*/t0_ + 5 * Second,
                                     /*t2=*/t0_ + 10 * Second)) {
      last_degrees_of_freedom = degrees_of_freedom;
      trajectory.Append(t, degrees_of_freedom);
    }

    trajectory.NewSegment();
    Velocity<World> const v3({0 * Metre / Second,
                              0 * Metre / Second,
                              1 * Metre / Second});
    for (auto const& [t, degrees_of_freedom] :
        NewLinearTrajectoryTimeline(DegreesOfFreedom<World>(
                                        last_degrees_of_freedom->position(),
                                        v3),
                                     /*Δt=*/1 * Second,
                                     /*t1=*/t0_ + 10 * Second,
                                     /*t2=*/t0_ + 15 * Second)) {
      trajectory.Append(t, degrees_of_freedom);
    }

    return trajectory;
  }

  Instant const t0_;
};

TEST_F(DiscreteTrajectory2Test, Make) {
  auto const trajectory = MakeTrajectory();
}

TEST_F(DiscreteTrajectory2Test, IterateForward) {
  auto const trajectory = MakeTrajectory();
  std::vector<Instant> times;
  for (auto const& [t, _] : trajectory) {
    times.push_back(t);
  }
  EXPECT_THAT(times,
              ElementsAre(t0_,
                          t0_ + 1 * Second,
                          t0_+ 2 * Second,
                          t0_+ 3 * Second,
                          t0_+ 4 * Second,
                          t0_+ 5 * Second,
                          t0_+ 6 * Second,
                          t0_+ 7 * Second,
                          t0_+ 8 * Second,
                          t0_+ 9 * Second,
                          t0_+ 10 * Second,
                          t0_+ 11 * Second,
                          t0_+ 12 * Second,
                          t0_+ 13 * Second,
                          t0_+ 14 * Second));
}

TEST_F(DiscreteTrajectory2Test, IterateBackward) {
  auto const trajectory = MakeTrajectory();
  std::vector<Instant> times;
  for (auto it = trajectory.rbegin(); it != trajectory.rend(); ++it) {
    times.push_back(it->first);
  }
  EXPECT_THAT(times,
              ElementsAre(t0_ + 14 * Second,
                          t0_ + 13 * Second,
                          t0_ + 12 * Second,
                          t0_ + 11 * Second,
                          t0_ + 10 * Second,
                          t0_ + 9 * Second,
                          t0_ + 8 * Second,
                          t0_ + 7 * Second,
                          t0_ + 6 * Second,
                          t0_ + 5 * Second,
                          t0_ + 4 * Second,
                          t0_ + 3 * Second,
                          t0_ + 2 * Second,
                          t0_ + 1 * Second,
                          t0_));
}

TEST_F(DiscreteTrajectory2Test, Empty) {
  DiscreteTrajectory2<World> trajectory;
  EXPECT_TRUE(trajectory.empty());
  trajectory = MakeTrajectory();
  EXPECT_FALSE(trajectory.empty());
}

TEST_F(DiscreteTrajectory2Test, Size) {
  DiscreteTrajectory2<World> trajectory;
  EXPECT_EQ(0, trajectory.size());
  trajectory = MakeTrajectory();
  EXPECT_EQ(15, trajectory.size());
}

TEST_F(DiscreteTrajectory2Test, Find) {
  auto const trajectory = MakeTrajectory();
  {
    auto const it = trajectory.find(t0_ + 3 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 3 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({3 * Metre,
                                                   0 * Metre,
                                                   0 * Metre}));
  }
  {
    auto const it = trajectory.find(t0_ + 13 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 13 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   4 * Metre,
                                                   3 * Metre}));
  }
  {
    auto const it = trajectory.find(t0_ + 3.14 * Second);
    EXPECT_TRUE(it == trajectory.end());
  }
}

TEST_F(DiscreteTrajectory2Test, LowerBound) {
  auto const trajectory = MakeTrajectory();
  {
    auto const it = trajectory.lower_bound(t0_ + 3.1 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 4 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   0 * Metre,
                                                   0 * Metre}));
  }
  {
    auto const it = trajectory.lower_bound(t0_ + 13 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 13 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   4 * Metre,
                                                   3 * Metre}));
  }
  {
    auto const it = trajectory.lower_bound(t0_ + 14.2 * Second);
    EXPECT_TRUE(it == trajectory.end());
  }
}

}  // namespace physics
}  // namespace principia
<commit_msg>Lower and upper bound.<commit_after>#include "physics/discrete_trajectory2.hpp"

#include <vector>

#include "geometry/frame.hpp"
#include "geometry/named_quantities.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/si.hpp"
#include "testing_utilities/componentwise.hpp"
#include "testing_utilities/discrete_trajectory_factories.hpp"

namespace principia {
namespace physics {

using geometry::Displacement;
using geometry::Frame;
using geometry::Instant;
using geometry::Velocity;
using quantities::si::Metre;
using quantities::si::Second;
using testing_utilities::Componentwise;
using testing_utilities::NewLinearTrajectoryTimeline;
using ::testing::ElementsAre;
using ::testing::Eq;

class DiscreteTrajectory2Test : public ::testing::Test {
 protected:
  using World = Frame<enum class WorldTag>;

  // Constructs a trajectory with three 5-second segments.
  DiscreteTrajectory2<World> MakeTrajectory() {
    DiscreteTrajectory2<World> trajectory;
    std::optional<DegreesOfFreedom<World>> last_degrees_of_freedom;

    Velocity<World> const v1({1 * Metre / Second,
                              0 * Metre / Second,
                              0 * Metre / Second});
    for (auto const& [t, degrees_of_freedom] :
         NewLinearTrajectoryTimeline(v1,
                                     /*Δt=*/1 * Second,
                                     /*t1=*/t0_,
                                     /*t2=*/t0_ + 5 * Second)) {
      last_degrees_of_freedom = degrees_of_freedom;
      trajectory.Append(t, degrees_of_freedom);
    }

    trajectory.NewSegment();
    Velocity<World> const v2({0 * Metre / Second,
                              1 * Metre / Second,
                              0 * Metre / Second});
    for (auto const& [t, degrees_of_freedom] :
        NewLinearTrajectoryTimeline(DegreesOfFreedom<World>(
                                        last_degrees_of_freedom->position(),
                                        v2),
                                     /*Δt=*/1 * Second,
                                     /*t1=*/t0_ + 5 * Second,
                                     /*t2=*/t0_ + 10 * Second)) {
      last_degrees_of_freedom = degrees_of_freedom;
      trajectory.Append(t, degrees_of_freedom);
    }

    trajectory.NewSegment();
    Velocity<World> const v3({0 * Metre / Second,
                              0 * Metre / Second,
                              1 * Metre / Second});
    for (auto const& [t, degrees_of_freedom] :
        NewLinearTrajectoryTimeline(DegreesOfFreedom<World>(
                                        last_degrees_of_freedom->position(),
                                        v3),
                                     /*Δt=*/1 * Second,
                                     /*t1=*/t0_ + 10 * Second,
                                     /*t2=*/t0_ + 15 * Second)) {
      trajectory.Append(t, degrees_of_freedom);
    }

    return trajectory;
  }

  Instant const t0_;
};

TEST_F(DiscreteTrajectory2Test, Make) {
  auto const trajectory = MakeTrajectory();
}

TEST_F(DiscreteTrajectory2Test, IterateForward) {
  auto const trajectory = MakeTrajectory();
  std::vector<Instant> times;
  for (auto const& [t, _] : trajectory) {
    times.push_back(t);
  }
  EXPECT_THAT(times,
              ElementsAre(t0_,
                          t0_ + 1 * Second,
                          t0_+ 2 * Second,
                          t0_+ 3 * Second,
                          t0_+ 4 * Second,
                          t0_+ 5 * Second,
                          t0_+ 6 * Second,
                          t0_+ 7 * Second,
                          t0_+ 8 * Second,
                          t0_+ 9 * Second,
                          t0_+ 10 * Second,
                          t0_+ 11 * Second,
                          t0_+ 12 * Second,
                          t0_+ 13 * Second,
                          t0_+ 14 * Second));
}

TEST_F(DiscreteTrajectory2Test, IterateBackward) {
  auto const trajectory = MakeTrajectory();
  std::vector<Instant> times;
  for (auto it = trajectory.rbegin(); it != trajectory.rend(); ++it) {
    times.push_back(it->first);
  }
  EXPECT_THAT(times,
              ElementsAre(t0_ + 14 * Second,
                          t0_ + 13 * Second,
                          t0_ + 12 * Second,
                          t0_ + 11 * Second,
                          t0_ + 10 * Second,
                          t0_ + 9 * Second,
                          t0_ + 8 * Second,
                          t0_ + 7 * Second,
                          t0_ + 6 * Second,
                          t0_ + 5 * Second,
                          t0_ + 4 * Second,
                          t0_ + 3 * Second,
                          t0_ + 2 * Second,
                          t0_ + 1 * Second,
                          t0_));
}

TEST_F(DiscreteTrajectory2Test, Empty) {
  DiscreteTrajectory2<World> trajectory;
  EXPECT_TRUE(trajectory.empty());
  trajectory = MakeTrajectory();
  EXPECT_FALSE(trajectory.empty());
}

TEST_F(DiscreteTrajectory2Test, Size) {
  DiscreteTrajectory2<World> trajectory;
  EXPECT_EQ(0, trajectory.size());
  trajectory = MakeTrajectory();
  EXPECT_EQ(15, trajectory.size());
}

TEST_F(DiscreteTrajectory2Test, Find) {
  auto const trajectory = MakeTrajectory();
  {
    auto const it = trajectory.find(t0_ + 3 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 3 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({3 * Metre,
                                                   0 * Metre,
                                                   0 * Metre}));
  }
  {
    auto const it = trajectory.find(t0_ + 13 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 13 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   4 * Metre,
                                                   3 * Metre}));
  }
  {
    auto const it = trajectory.find(t0_ + 3.14 * Second);
    EXPECT_TRUE(it == trajectory.end());
  }
}

TEST_F(DiscreteTrajectory2Test, LowerBound) {
  auto const trajectory = MakeTrajectory();
  {
    auto const it = trajectory.lower_bound(t0_ + 3.9 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 4 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   0 * Metre,
                                                   0 * Metre}));
  }
  {
    auto const it = trajectory.lower_bound(t0_ + 4 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 4 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   0 * Metre,
                                                   0 * Metre}));
  }
  {
    auto const it = trajectory.lower_bound(t0_ + 4.1 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 5 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   0 * Metre,
                                                   0 * Metre}));
  }
  {
    auto const it = trajectory.lower_bound(t0_ + 13 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 13 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   4 * Metre,
                                                   3 * Metre}));
  }
  {
    auto const it = trajectory.lower_bound(t0_ + 14.2 * Second);
    EXPECT_TRUE(it == trajectory.end());
  }
}

TEST_F(DiscreteTrajectory2Test, UpperBound) {
  auto const trajectory = MakeTrajectory();
  {
    auto const it = trajectory.upper_bound(t0_ + 3.9 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 4 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   0 * Metre,
                                                   0 * Metre}));
  }
  {
    auto const it = trajectory.upper_bound(t0_ + 4 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 5 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   0 * Metre,
                                                   0 * Metre}));
  }
  {
    auto const it = trajectory.upper_bound(t0_ + 4.1 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 5 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   0 * Metre,
                                                   0 * Metre}));
  }
  {
    auto const it = trajectory.upper_bound(t0_ + 13 * Second);
    auto const& [t, degrees_of_freedom] = *it;
    EXPECT_EQ(t, t0_ + 14 * Second);
    EXPECT_EQ(degrees_of_freedom.position(),
              World::origin + Displacement<World>({4 * Metre,
                                                   4 * Metre,
                                                   4 * Metre}));
  }
  {
    auto const it = trajectory.upper_bound(t0_ + 14.2 * Second);
    EXPECT_TRUE(it == trajectory.end());
  }
}

}  // namespace physics
}  // namespace principia
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2007 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#ifndef SQLITE_TYPES_HPP
#define SQLITE_TYPES_HPP

// stdc++
#include <string.h>

// mapnik
#include <mapnik/datasource.hpp>

// boost
#include <boost/shared_ptr.hpp>

// sqlite
extern "C" {
  #include <sqlite3.h>
}

//==============================================================================

class sqlite_utils
{
public:

    static void dequote(std::string& s)
    {
        if (s[0] == '[' || s[0] == '\'' || s[0] == '"' || s[0] == '`')
        {
            s = s.substr(1, s.length() - 1);
        }
    }
};

//==============================================================================

class sqlite_resultset
{
public:

    sqlite_resultset (sqlite3_stmt* stmt)
        : stmt_(stmt)
    {
    }

    ~sqlite_resultset ()
    {
        if (stmt_)
        {
            sqlite3_finalize (stmt_);
        }
    }

    bool is_valid ()
    {
        return stmt_ != 0;
    }

    bool step_next ()
    {
        const int status = sqlite3_step (stmt_);
        if (status != SQLITE_ROW && status != SQLITE_DONE)
        {
            std::ostringstream s;
            s << "SQLite Plugin: retrieving next row failed";

            std::string msg(sqlite3_errmsg(sqlite3_db_handle(stmt_)));
            if (msg != "unknown error")
            {
                s << ": " << msg;
            }

            throw mapnik::datasource_exception(s.str());
        }
        return status == SQLITE_ROW;
    }

    int column_count ()
    {
        return sqlite3_column_count (stmt_);
    }

    int column_type (int col)
    {
        return sqlite3_column_type (stmt_, col);
    }

    const char* column_name (int col)
    {
        return sqlite3_column_name (stmt_, col);
    }

    bool column_isnull (int col)
    {
        return sqlite3_column_type (stmt_, col) == SQLITE_NULL;
    }

    int column_integer (int col)
    {
        return sqlite3_column_int (stmt_, col);
    }

    int column_integer64 (int col)
    {
        return sqlite3_column_int64 (stmt_, col);
    }

    double column_double (int col)
    {
        return sqlite3_column_double (stmt_, col);
    }

    const char* column_text (int col, int& len)
    {
        const char* text = (const char*) sqlite3_column_text (stmt_, col);
        len = sqlite3_column_bytes (stmt_, col);
        return text;
    }

    const char* column_text (int col)
    {
        return (const char*) sqlite3_column_text (stmt_, col);
    }

    const void* column_blob (int col, int& bytes)
    {
        const char* blob = (const char*) sqlite3_column_blob (stmt_, col);
        bytes = sqlite3_column_bytes (stmt_, col);
        return blob;
    }

    sqlite3_stmt* get_statement()
    {
        return stmt_;
    }

private:

    sqlite3_stmt* stmt_;
};

//==============================================================================

class sqlite_connection
{
public:

    sqlite_connection (const std::string& file)
        : db_(0)
    {
        // sqlite3_open_v2 is available earlier but
        // shared cache not available until >= 3.6.18
    #if SQLITE_VERSION_NUMBER >= 3006018
        const int rc = sqlite3_enable_shared_cache(1);
        if (rc != SQLITE_OK)
        {
            throw mapnik::datasource_exception (sqlite3_errmsg (db_));
        }

        int mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_SHAREDCACHE;
        if (sqlite3_open_v2 (file.c_str(), &db_, mode, NULL))
    #else
        #warning "Mapnik's sqlite plugin is compiling against a version of sqlite older than 3.6.18 which may make rendering slow..."
        if (sqlite3_open (file.c_str(), &db_))
    #endif
        {
            std::ostringstream s;
            s << "Sqlite Plugin: " << sqlite3_errmsg (db_);

            throw mapnik::datasource_exception (s.str());
        }
    }

    virtual ~sqlite_connection ()
    {
        if (db_)
        {
            sqlite3_close (db_);
        }
    }

    void throw_sqlite_error(const std::string& sql)
    {
        std::ostringstream s;
        s << "Sqlite Plugin: ";
        if (db_)
            s << "'" << sqlite3_errmsg(db_) << "'";
        else
            s << "unknown error, lost connection";
        s << "\nFull sql was: '" <<  sql << "'\n";

        throw mapnik::datasource_exception (s.str());
    }

    sqlite_resultset* execute_query(const std::string& sql)
    {
        sqlite3_stmt* stmt = 0;

        const int rc = sqlite3_prepare_v2 (db_, sql.c_str(), -1, &stmt, 0);
        if (rc != SQLITE_OK)
        {
            throw_sqlite_error(sql);
        }

        return new sqlite_resultset (stmt);
    }

    void execute(const std::string& sql)
    {
        const int rc = sqlite3_exec(db_, sql.c_str(), 0, 0, 0);
        if (rc != SQLITE_OK)
        {
            throw_sqlite_error(sql);
        }
    }

    int execute_with_code(const std::string& sql)
    {
        const int rc = sqlite3_exec(db_, sql.c_str(), 0, 0, 0);
        return rc;
    }

    sqlite3* operator*()
    {
        return db_;
    }

private:

    sqlite3* db_;
};

#endif //SQLITE_TYPES_HPP
<commit_msg>- avoid using temporary pointer in sqlite blob/text resultsets<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2007 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#ifndef SQLITE_TYPES_HPP
#define SQLITE_TYPES_HPP

// stdc++
#include <string.h>

// mapnik
#include <mapnik/datasource.hpp>

// boost
#include <boost/shared_ptr.hpp>

// sqlite
extern "C" {
  #include <sqlite3.h>
}

//==============================================================================

class sqlite_utils
{
public:

    static void dequote(std::string& s)
    {
        if (s[0] == '[' || s[0] == '\'' || s[0] == '"' || s[0] == '`')
        {
            s = s.substr(1, s.length() - 1);
        }
    }
};

//==============================================================================

class sqlite_resultset
{
public:

    sqlite_resultset (sqlite3_stmt* stmt)
        : stmt_(stmt)
    {
    }

    ~sqlite_resultset ()
    {
        if (stmt_)
        {
            sqlite3_finalize (stmt_);
        }
    }

    bool is_valid ()
    {
        return stmt_ != 0;
    }

    bool step_next ()
    {
        const int status = sqlite3_step (stmt_);
        if (status != SQLITE_ROW && status != SQLITE_DONE)
        {
            std::ostringstream s;
            s << "SQLite Plugin: retrieving next row failed";

            std::string msg(sqlite3_errmsg(sqlite3_db_handle(stmt_)));
            if (msg != "unknown error")
            {
                s << ": " << msg;
            }

            throw mapnik::datasource_exception(s.str());
        }
        return status == SQLITE_ROW;
    }

    int column_count ()
    {
        return sqlite3_column_count (stmt_);
    }

    int column_type (int col)
    {
        return sqlite3_column_type (stmt_, col);
    }

    const char* column_name (int col)
    {
        return sqlite3_column_name (stmt_, col);
    }

    bool column_isnull (int col)
    {
        return sqlite3_column_type (stmt_, col) == SQLITE_NULL;
    }

    int column_integer (int col)
    {
        return sqlite3_column_int (stmt_, col);
    }

    int column_integer64 (int col)
    {
        return sqlite3_column_int64 (stmt_, col);
    }

    double column_double (int col)
    {
        return sqlite3_column_double (stmt_, col);
    }

    const char* column_text (int col, int& len)
    {
        len = sqlite3_column_bytes (stmt_, col);
        return (const char*) sqlite3_column_text (stmt_, col);
    }

    const char* column_text (int col)
    {
        return (const char*) sqlite3_column_text (stmt_, col);
    }

    const void* column_blob (int col, int& bytes)
    {
        bytes = sqlite3_column_bytes (stmt_, col);
        return (const char*) sqlite3_column_blob (stmt_, col);
    }

    sqlite3_stmt* get_statement()
    {
        return stmt_;
    }

private:

    sqlite3_stmt* stmt_;
};

//==============================================================================

class sqlite_connection
{
public:

    sqlite_connection (const std::string& file)
        : db_(0)
    {
        // sqlite3_open_v2 is available earlier but
        // shared cache not available until >= 3.6.18
    #if SQLITE_VERSION_NUMBER >= 3006018
        const int rc = sqlite3_enable_shared_cache(1);
        if (rc != SQLITE_OK)
        {
            throw mapnik::datasource_exception (sqlite3_errmsg (db_));
        }

        int mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_SHAREDCACHE;
        if (sqlite3_open_v2 (file.c_str(), &db_, mode, NULL))
    #else
        #warning "Mapnik's sqlite plugin is compiling against a version of sqlite older than 3.6.18 which may make rendering slow..."
        if (sqlite3_open (file.c_str(), &db_))
    #endif
        {
            std::ostringstream s;
            s << "Sqlite Plugin: " << sqlite3_errmsg (db_);

            throw mapnik::datasource_exception (s.str());
        }
    }

    virtual ~sqlite_connection ()
    {
        if (db_)
        {
            sqlite3_close (db_);
        }
    }

    void throw_sqlite_error(const std::string& sql)
    {
        std::ostringstream s;
        s << "Sqlite Plugin: ";
        if (db_)
            s << "'" << sqlite3_errmsg(db_) << "'";
        else
            s << "unknown error, lost connection";
        s << "\nFull sql was: '" <<  sql << "'\n";

        throw mapnik::datasource_exception (s.str());
    }

    sqlite_resultset* execute_query(const std::string& sql)
    {
        sqlite3_stmt* stmt = 0;

        const int rc = sqlite3_prepare_v2 (db_, sql.c_str(), -1, &stmt, 0);
        if (rc != SQLITE_OK)
        {
            throw_sqlite_error(sql);
        }

        return new sqlite_resultset (stmt);
    }

    void execute(const std::string& sql)
    {
        const int rc = sqlite3_exec(db_, sql.c_str(), 0, 0, 0);
        if (rc != SQLITE_OK)
        {
            throw_sqlite_error(sql);
        }
    }

    int execute_with_code(const std::string& sql)
    {
        const int rc = sqlite3_exec(db_, sql.c_str(), 0, 0, 0);
        return rc;
    }

    sqlite3* operator*()
    {
        return db_;
    }

private:

    sqlite3* db_;
};

#endif //SQLITE_TYPES_HPP
<|endoftext|>


<commit_before>#include "EdGraph_GenericGraph.h"
#include "EdNode_GenericGraphNode.h"
#include "EdNode_GenericGraphEdge.h"

UEdGraph_GenericGraph::UEdGraph_GenericGraph()
{

}

UEdGraph_GenericGraph::~UEdGraph_GenericGraph()
{

}

void UEdGraph_GenericGraph::RebuildGenericGraph()
{
	LOG_WARNING(TEXT("UGenericGraphEdGraph::RebuildGenericGraph has been called"));

	UGenericGraph* G = CastChecked<UGenericGraph>(GetOuter());

	G->ClearGraph();

	for (int i = 0; i < Nodes.Num(); ++i)
	{
		if (UEdNode_GenericGraphNode* EdNode = Cast<UEdNode_GenericGraphNode>(Nodes[i]))
		{
			if (EdNode->GenericGraphNode == nullptr)
				continue;

			UGenericGraphNode* GNode = EdNode->GenericGraphNode;

			G->AllNodes.Add(GNode);

			for (int PinIdx = 0; PinIdx < EdNode->Pins.Num(); ++PinIdx)
			{
				UEdGraphPin* Pin = EdNode->Pins[PinIdx];

				if (Pin->Direction != EEdGraphPinDirection::EGPD_Output)
					continue;

				for (int LinkToIdx = 0; LinkToIdx < Pin->LinkedTo.Num(); ++LinkToIdx)
				{
					UEdNode_GenericGraphNode* ChildEdNode = Cast<UEdNode_GenericGraphNode>(Pin->LinkedTo[LinkToIdx]->GetOwningNode());

					if (ChildEdNode == nullptr)
						continue;

					UGenericGraphNode* ChildNode = ChildEdNode->GenericGraphNode;

					GNode->ChildrenNodes.Add(ChildNode);

					ChildNode->ParentNodes.Add(GNode);
				}
			}
		}
		else if (UEdNode_GenericGraphEdge* TransitionNode = Cast<UEdNode_GenericGraphEdge>(Nodes[i]))
		{
			UEdNode_GenericGraphNode* StartNode = TransitionNode->GetStartNode();
			UEdNode_GenericGraphNode* EndNode = TransitionNode->GetEndNode();
			UGenericGraphEdge* Edge = TransitionNode->GenericGraphEdge;

			if (StartNode == nullptr || EndNode == nullptr || Edge == nullptr)
				continue;

			Edge->StartNode = StartNode->GenericGraphNode;
			Edge->EndNode = EndNode->GenericGraphNode;
			Edge->StartNode->Edges.Add(Edge->EndNode, Edge);
		}
	}

	for (int i = 0; i < G->AllNodes.Num(); ++i)
	{
		UGenericGraphNode* Node = G->AllNodes[i];
		if (Node->ParentNodes.Num() == 0)
		{
			G->RootNodes.Add(Node);
		}
	}
}

#if WITH_EDITOR
void UEdGraph_GenericGraph::PostEditUndo()
{
	Super::PostEditUndo();

	NotifyGraphChanged();
}
#endif

<commit_msg>bugfix: RebuildGenericGraph support edge node<commit_after>#include "EdGraph_GenericGraph.h"
#include "EdNode_GenericGraphNode.h"
#include "EdNode_GenericGraphEdge.h"

UEdGraph_GenericGraph::UEdGraph_GenericGraph()
{

}

UEdGraph_GenericGraph::~UEdGraph_GenericGraph()
{

}

void UEdGraph_GenericGraph::RebuildGenericGraph()
{
	LOG_WARNING(TEXT("UGenericGraphEdGraph::RebuildGenericGraph has been called"));

	UGenericGraph* G = CastChecked<UGenericGraph>(GetOuter());

	G->ClearGraph();

	for (int i = 0; i < Nodes.Num(); ++i)
	{
		if (UEdNode_GenericGraphNode* EdNode = Cast<UEdNode_GenericGraphNode>(Nodes[i]))
		{
			if (EdNode->GenericGraphNode == nullptr)
				continue;

			UGenericGraphNode* GNode = EdNode->GenericGraphNode;

			G->AllNodes.Add(GNode);

			for (int PinIdx = 0; PinIdx < EdNode->Pins.Num(); ++PinIdx)
			{
				UEdGraphPin* Pin = EdNode->Pins[PinIdx];

				if (Pin->Direction != EEdGraphPinDirection::EGPD_Output)
					continue;

				for (int LinkToIdx = 0; LinkToIdx < Pin->LinkedTo.Num(); ++LinkToIdx)
				{
					UGenericGraphNode* ChildNode = nullptr;
					if (UEdNode_GenericGraphNode* EdNode_Child = Cast<UEdNode_GenericGraphNode>(Pin->LinkedTo[LinkToIdx]->GetOwningNode()))
					{
						ChildNode = EdNode_Child->GenericGraphNode;
					}
					else if (UEdNode_GenericGraphEdge* EdNode_Edge = Cast<UEdNode_GenericGraphEdge>(Pin->LinkedTo[LinkToIdx]->GetOwningNode()))
					{
						UEdNode_GenericGraphNode* EdNode_Child = EdNode_Edge->GetEndNode();;
						if (EdNode_Child != nullptr)
						{
							ChildNode = EdNode_Child->GenericGraphNode;
						}
					}

					if (ChildNode != nullptr)
					{
						GNode->ChildrenNodes.Add(ChildNode);

						ChildNode->ParentNodes.Add(GNode);
					}
					else
					{
						LOG_ERROR(TEXT("UEdGraph_GenericGraph::RebuildGenericGraph can't find child node"));
					}
				}
			}
		}
		else if (UEdNode_GenericGraphEdge* TransitionNode = Cast<UEdNode_GenericGraphEdge>(Nodes[i]))
		{
			UEdNode_GenericGraphNode* StartNode = TransitionNode->GetStartNode();
			UEdNode_GenericGraphNode* EndNode = TransitionNode->GetEndNode();
			UGenericGraphEdge* Edge = TransitionNode->GenericGraphEdge;

			if (StartNode == nullptr || EndNode == nullptr || Edge == nullptr)
				continue;

			Edge->StartNode = StartNode->GenericGraphNode;
			Edge->EndNode = EndNode->GenericGraphNode;
			Edge->StartNode->Edges.Add(Edge->EndNode, Edge);
		}
	}

	for (int i = 0; i < G->AllNodes.Num(); ++i)
	{
		UGenericGraphNode* Node = G->AllNodes[i];
		if (Node->ParentNodes.Num() == 0)
		{
			G->RootNodes.Add(Node);
		}
	}
}

#if WITH_EDITOR
void UEdGraph_GenericGraph::PostEditUndo()
{
	Super::PostEditUndo();

	NotifyGraphChanged();
}
#endif

<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetReaderTest
#include <boost/test/unit_test.hpp>

#define private public
#define protected public

#include "../../JPetReader/JPetReader.h"
#include "../../JPetWriter/JPetWriter.h"
#include "../../JPetSignal/JPetSignal.h"

#include <cstddef>
#include <iostream>
#include <vector>

#include <TError.h> /// gErrorIgnoreLevel
#include <TObjString.h>

// method list
/*
  JPetReader(void);
  explicit JPetReader(const char* p_filename);
  virtual ~JPetReader(void);
  virtual void closeFile();
  virtual long long GetEntries () const { return fTree->GetEntries(); }
  virtual int GetEntry (int entryNo);
  virtual bool OpenFile(const char* filename);
  virtual void readData(const char* objname = "");
  virtual TNamed& GetData () {return *fObject;}
  JPetTreeHeader * GetHeaderClone()const;
  void fillContainer(std::vector<T> &p_container, const std::string &p_objectName);
  virtual void closeTFile(void){};
*/

BOOST_AUTO_TEST_SUITE (FirstSuite)

BOOST_AUTO_TEST_CASE (default_constructor)
{
  JPetReader reader;
  BOOST_REQUIRE(reader.fBranch == 0);
  BOOST_REQUIRE(!reader.isOpen());
  BOOST_REQUIRE(reader.fObject == 0);
  BOOST_REQUIRE(reader.fTree == 0);
}

BOOST_AUTO_TEST_CASE (bad_file)
{
  gErrorIgnoreLevel = 6000; /// we turn off the ROOT error messages
  JPetReader reader;
  /// not a ROOT file
  BOOST_REQUIRE(!reader.openFile("bad_file.txt"));
  BOOST_REQUIRE(reader.fBranch == 0);
  BOOST_REQUIRE(!reader.isOpen());
  BOOST_REQUIRE(reader.fObject == 0);
  BOOST_REQUIRE(reader.fTree == 0);
}

BOOST_AUTO_TEST_CASE (open_file)
{
  TFile file("test.root", "RECREATE");
  TTree tree("tree", "tree");
  JPetSignal* filler = 0;
  tree.Branch("JPetSignal", "JPetSignal", &filler);

  JPetSignal signal;
  signal.setTime(101.43);
  filler = &signal;
  tree.Fill();
  file.Write();
  file.Close("R");

  JPetReader constructor_open("test.root");
  std::cout <<"open?:"<< constructor_open.fFile->IsOpen()<<std::endl;
  BOOST_REQUIRE(constructor_open.readData("tree"));
  constructor_open.closeFile();

  JPetReader reader;
  BOOST_REQUIRE(reader.openFile("test.root") );
  BOOST_REQUIRE(reader.readData("tree"));
}

BOOST_AUTO_TEST_CASE (read_and_write_objects )
{
  TFile file("test2.root", "RECREATE");
  TTree tree("tree", "tree");
  JPetSignal* filler = 0;
  tree.Branch("JPetSignal", "JPetSignal", &filler);

  JPetSignal signal;
  signal.setTime(101.43);
  filler = &signal;
  tree.Fill();
  file.Write();
  file.Close("R");

  JPetReader reader("test2.root");
  BOOST_REQUIRE_EQUAL(reader.getEntries(), 1);
  reader.getEntry(0);
  JPetSignal & signal2 = (JPetSignal&)reader.getData();
  BOOST_REQUIRE_EQUAL(signal.getTime(), signal2.getTime());
}

BOOST_AUTO_TEST_CASE (proper_file)
{
  JPetReader reader;
  bool openedPropery = reader.openFile("test2.root");
  BOOST_REQUIRE(openedPropery );
  if (openedPropery) {
    reader.readData("tree");
    BOOST_REQUIRE(reader.fBranch != 0);
    BOOST_REQUIRE(reader.isOpen());
    BOOST_REQUIRE(reader.fObject != 0);
    BOOST_REQUIRE(reader.fTree != 0);

    BOOST_REQUIRE(reader.getEntries() > 0);
    BOOST_REQUIRE(reader.getEntry(0) > 0);
  }
}

BOOST_AUTO_TEST_CASE (read_and_write_header )
{
  JPetTreeHeader input_header(43, "test", 1);
  JPetWriter writer("test3.root");
  writer.writeHeader(&input_header);
  JPetTSlot tslot;
  writer.write(tslot);
  writer.closeFile();

  JPetReader reader("test3.root");
  JPetTreeHeader* output_header = reader.getHeaderClone();
  BOOST_REQUIRE_EQUAL(input_header.GetRunNumber(), output_header->GetRunNumber());
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Repair UTs to be executable and pass.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetReaderTest
#include <boost/test/unit_test.hpp>

#define private public
#define protected public

#include "../../JPetReader/JPetReader.h"
#include "../../JPetWriter/JPetWriter.h"
#include "../../JPetSignal/JPetSignal.h"

#include <cstddef>
#include <iostream>
#include <vector>

#include <TError.h> /// gErrorIgnoreLevel
#include <TObjString.h>

// method list
/*
  JPetReader(void);
  explicit JPetReader(const char* p_filename);
  virtual ~JPetReader(void);
  virtual void closeFile();
  virtual long long GetEntries () const { return fTree->GetEntries(); }
  virtual int GetEntry (int entryNo);
  virtual bool OpenFile(const char* filename);
  virtual void readData(const char* objname = "");
  virtual TNamed& GetData () {return *fObject;}
  JPetTreeHeader * GetHeaderClone()const;
  void fillContainer(std::vector<T> &p_container, const std::string &p_objectName);
  virtual void closeTFile(void){};
*/

BOOST_AUTO_TEST_SUITE (FirstSuite)

BOOST_AUTO_TEST_CASE (default_constructor)
{
  JPetReader reader;
  BOOST_REQUIRE(reader.fBranch == 0);
  BOOST_REQUIRE(!reader.isOpen());
  BOOST_REQUIRE(reader.fObject == 0);
  BOOST_REQUIRE(reader.fTree == 0);
}

BOOST_AUTO_TEST_CASE (bad_file)
{
  gErrorIgnoreLevel = 6000; /// we turn off the ROOT error messages
  JPetReader reader;
  /// not a ROOT file
  BOOST_REQUIRE(!reader.openFile("bad_file.txt"));
  BOOST_REQUIRE(reader.fBranch == 0);
  BOOST_REQUIRE(!reader.isOpen());
  BOOST_REQUIRE(reader.fObject == 0);
  BOOST_REQUIRE(reader.fTree == 0);
}

BOOST_AUTO_TEST_CASE (open_file)
{
  TFile file("test.root", "RECREATE");
  TTree tree("tree", "tree");
  JPetSignal* filler = 0;
  tree.Branch("JPetSignal", "JPetSignal", &filler);

  JPetSignal signal;
  signal.setTime(101.43);
  filler = &signal;
  tree.Fill();
  file.Write();
  file.Close("R");

  JPetReader constructor_open("test.root");
  std::cout <<"open?:"<< constructor_open.fFile->IsOpen()<<std::endl;
  BOOST_REQUIRE(constructor_open.readData("tree"));
  constructor_open.closeFile();

  JPetReader reader;
  BOOST_REQUIRE(reader.openFile("test.root") );
  BOOST_REQUIRE(reader.readData("tree"));
}

BOOST_AUTO_TEST_CASE (read_and_write_objects )
{
  TFile file("test2.root", "RECREATE");
  TTree tree("tree", "tree");
  JPetSignal* filler = 0;
  tree.Branch("JPetSignal", "JPetSignal", &filler);

  JPetSignal signal;
  signal.setTime(101.43);
  filler = &signal;
  tree.Fill();
  file.Write();
  file.Close("R");

  JPetReader reader("test2.root");
  BOOST_REQUIRE_EQUAL(reader.getEntries(), 1);
  reader.getEntry(0);
  JPetSignal & signal2 = (JPetSignal&)reader.getData();
  BOOST_REQUIRE_EQUAL(signal.getTime(), signal2.getTime());
}

BOOST_AUTO_TEST_CASE (proper_file)
{
  JPetReader reader;
  bool openedPropery = reader.openFile("test2.root");
  BOOST_REQUIRE(openedPropery );
  if (openedPropery) {
    reader.readData("tree");
    BOOST_REQUIRE(reader.fBranch != 0);
    BOOST_REQUIRE(reader.isOpen());
    BOOST_REQUIRE(reader.fObject != 0);
    BOOST_REQUIRE(reader.fTree != 0);

    BOOST_REQUIRE(reader.getEntries() > 0);
    BOOST_REQUIRE(reader.getEntry(0) > 0);
  }
}

BOOST_AUTO_TEST_CASE (read_and_write_header )
{
  JPetTreeHeader input_header(1);
  JPetWriter writer("test3.root");
  writer.writeHeader(&input_header);
  JPetTSlot tslot;
  writer.write(tslot);
  writer.closeFile();

  JPetReader reader("test3.root");
  JPetTreeHeader* output_header = reader.getHeaderClone();
  BOOST_REQUIRE_EQUAL(input_header.getRunNumber(), output_header->getRunNumber());
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "ExampleGame/Components/GameScripts/Units/Thief.h"
#include "ExampleGame/Components/Grid/GameGrid.h"
#include "ExampleGame/Components/Grid/GridCell.h"
#include "ExampleGame/Components/Grid/GridConstants.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/GameConstants/GameConstants.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "Vajra/Engine/Components/DerivedComponents/Renderer/SpriteRenderer.h"

#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/Input/Input.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Engine/Tween/Tween.h"
#include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h"

// Tween callbacks
void thiefTweenCallback(ObjectIdType gameObjectId , std::string /* tweenClipName */) {
	GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(gameObjectId);
	ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid");
	if(go != nullptr) {
		Thief* pUnit = go->GetComponent<Thief>();
		ASSERT(pUnit != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit");
		if(pUnit != nullptr) {
			pUnit->onSpecialEnd();
		}
	}

}

void thiefNumberTweenCallback(float /* fromNumber */, float /* toNumber */, float /*currentNumber*/, std::string /*tweenClipName*/, MessageData1S1I1F* /*userParams*/) {
	/*GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(userParams->i);
	ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid");
	if(go != nullptr) {
		Thief* thief = go->GetComponent<Thief>();
		ASSERT(thief != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit");
		if(thief != nullptr) {
			if(tweenClipName == "targetsIn") {
				for(GameObject* go : thief->targetIndicators ) {

				}

			}
		}
	}*/
}

Thief::Thief() : PlayerUnit() {
	this->init();
}

Thief::Thief(Object* object_) : PlayerUnit(object_) {
	this->init();
}

Thief::~Thief() {
	this->destroy();
}

void Thief::init() {
	this->unitType = UnitType::UNIT_TYPE_THIEF;
}

void Thief::destroy() {
	this->deleteTargets();
}

bool Thief::isSpecialTouch(int touchId) {
	if(this->getTouchNearUnit()) {
		Touch touch = ENGINE->GetInput()->GetTouch(touchId);
		if(touch.timeDown >= GetFloatGameConstant(GAME_CONSTANT_long_press_length_in_seconds) && glm::distance(touch.pos, this->touchStartPos) <= GetFloatGameConstant(GAME_CONSTANT_allowed_finger_movement_in_press)) {
			this->targetedCell = nullptr;
			this->SetTouchIndicatorVisible(false);
			this->updateLegalTagets();
			return true;
		}
	}
	return false;
}

void Thief::onSpecialTouch(int touchId) {
	Touch touch = ENGINE->GetInput()->GetTouch(touchId);
	if(touch.phase == TouchPhase::Ended) {
		this->targetedCell = SINGLETONS->GetGridManager()->TouchPositionToCell(touch.pos);
		if(std::find(this->legalTargets.begin(), this->legalTargets.end(), this->GetCurrentTouchedCell()) != this->legalTargets.end()) {
			this->startSpecial();
		} else {
			this->targetedCell = this->gridNavRef->GetCurrentCell();
			this->cancelSpecial();
		}
		this->tweenOutTargets();
	}
}

void Thief::startSpecial() {
	PlayerUnit::startSpecial();
	// Remove the indicator at the selected position
	GameObject* selectedTargetIndicator = this->targetIndicators[this->targetedCell];
	this->targetIndicators.erase(this->targetedCell);
	delete selectedTargetIndicator;

	this->SetTouchIndicatorCell(this->targetedCell);
	this->startTouchIndicatorPulse();
	this->SetTouchIndicatorSprite(THIEF_SPECIAL);
	this->SetTouchIndicatorVisible(true);

	float jumpDist = glm::distance(this->targetedCell->center, this->gameObjectRef->GetTransform()->GetPosition());
	float jumpTweenTime = jumpDist / GetFloatGameConstant(GAME_CONSTANT_jump_speed_in_units_per_second);
	ENGINE->GetTween()->TweenPosition(this->gameObjectRef->GetId(),
									  this->gameObjectRef->GetTransform()->GetPosition(),
									  this->targetedCell->center,
									  jumpTweenTime,
									  false,
									  TWEEN_TRANSLATION_CURVE_TYPE_PARABOLA,
									  false,
									  thiefTweenCallback);

}

void Thief::onSpecialEnd() {
	PlayerUnit::onSpecialEnd();
	this->gridNavRef->SetGridPosition(this->targetedCell);
}

void Thief::touchedCellChanged(GridCell* prevTouchedCell) {
	if(this->inputState != InputState::INPUT_STATE_SPECIAL) {
		PlayerUnit::touchedCellChanged(prevTouchedCell);
	} else {
		if(this->targetIndicators[prevTouchedCell]) {
			ENGINE->GetTween()->TweenScale(this->targetIndicators[prevTouchedCell]->GetId(), glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale_hover)),
																							 glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)),
																							 GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
		}
		if(this->targetIndicators[this->GetCurrentTouchedCell()]) {
			ENGINE->GetTween()->TweenScale(this->targetIndicators[this->GetCurrentTouchedCell()]->GetId(),  glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)),
																											glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale_hover)),
																											GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
			this->gridNavRef->SetLookTarget(this->GetCurrentTouchedCell()->center);
		}
		if(std::find(this->legalTargets.begin(), this->legalTargets.end(), this->GetCurrentTouchedCell()) != this->legalTargets.end()) {
			this->SetTouchIndicatorSprite(GOOD_TOUCH);
		} else {
			this->SetTouchIndicatorSprite(BAD_TOUCH);
		}
	}
}

void Thief::updateLegalTagets() {
	this->legalTargets.clear();
	this->deleteTargets();
	GridCell* currentCell = this->gridNavRef->GetCurrentCell();
	int elevation = SINGLETONS->GetGridManager()->GetGrid()->GetElevationFromWorldY(currentCell->center.y);

	std::list<GridCell*> cellsInRange;
	SINGLETONS->GetGridManager()->GetGrid()->GetNeighborCells(cellsInRange, this->gridNavRef->GetCurrentCell(),
															  GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units)
															  + elevation * GetFloatGameConstant(GAME_CONSTANT_jump_elevation_multiplier));

	for ( GridCell* c : cellsInRange) {
		int cellElevation = 0;
		for(int i = 0; i < NUM_ELEVATIONS; ++i) {
			if(SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(c->x, c->z, i)) {
				cellElevation = i;
				break;
			}

		}
		if(cellElevation == 0) {
			int x = 0;
			x++;
		}
		if(cellElevation == elevation) { // is the cell on the same height
			if(this->gridNavRef->CanReachDestination(c, GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units)) && SINGLETONS->GetGridManager()->GetGrid()->HasLineOfSight(currentCell, c, elevation) ) {
				this->legalTargets.push_back(c);
			}
		}
		else if(cellElevation <= elevation + 1) { // is the cell below it
			if(SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(c->x, c->z, cellElevation)) {
				float dist = glm::distance(glm::vec2(c->x, c->z), glm::vec2(currentCell->x, currentCell->z));
				if(dist <= GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units) + cellElevation * GetFloatGameConstant(GAME_CONSTANT_jump_elevation_multiplier)) {
					this->legalTargets.push_back(c);
				}
			}
		}
	}
	this->createTargets();
	this->tweenInTargets();
}

void Thief::tweenInTargets() {
	glm::vec3 pos;
	for(auto contents : this->targetIndicators ) {
		if(contents.second != nullptr) {
			pos = contents.second->GetTransform()->GetPosition();
			ENGINE->GetTween()->TweenPosition(contents.second->GetId(), pos, pos + glm::vec3(0.0f, GetFloatGameConstant(GAME_CONSTANT_target_indicator_offset), 0.0f), GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
		}
	}
}

void Thief::tweenOutTargets() {
	glm::vec3 pos;
	for(auto contents : this->targetIndicators ) {
		if(contents.second != nullptr) {
			pos = contents.second->GetTransform()->GetPosition();
			ENGINE->GetTween()->TweenScale(contents.second->GetId(), glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)), glm::vec3(0), GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
		}
	}
}

void Thief::createTargets() {
	for( GridCell* c : this->legalTargets ) {
		GameObject* indicator = new GameObject(ENGINE->GetSceneGraph3D());
		SpriteRenderer* spriteRenderer = indicator->AddComponent<SpriteRenderer>();
		std::vector<std::string> pathsToTextures;
		pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Thief_Jump_cyan.png");
		spriteRenderer->initPlane(1.0f, 1.0f, "sptshdr", pathsToTextures, PlaneOrigin::Center);
		indicator->GetTransform()->SetPosition(c->center);
		indicator->GetTransform()->SetScale( glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)));
		indicator->GetTransform()->Translate(0.0f, YAXIS);
		indicator->GetTransform()->Rotate(90.0f inRadians, XAXIS);
		this->targetIndicators[c] = indicator;
	}
}

void Thief::deleteTargets() {
	for(auto contents : this->targetIndicators ) {
		if(contents.second != nullptr) {
			delete contents.second;
		}
	}
	this->targetIndicators.clear();
}
<commit_msg>Fix to Thief's jump ability.<commit_after>#include "ExampleGame/Components/GameScripts/Units/Thief.h"
#include "ExampleGame/Components/Grid/GameGrid.h"
#include "ExampleGame/Components/Grid/GridCell.h"
#include "ExampleGame/Components/Grid/GridConstants.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/GameConstants/GameConstants.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "Vajra/Engine/Components/DerivedComponents/Renderer/SpriteRenderer.h"

#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/Input/Input.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Engine/Tween/Tween.h"
#include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h"

// Tween callbacks
void thiefTweenCallback(ObjectIdType gameObjectId , std::string /* tweenClipName */) {
	GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(gameObjectId);
	ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid");
	if(go != nullptr) {
		Thief* pUnit = go->GetComponent<Thief>();
		ASSERT(pUnit != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit");
		if(pUnit != nullptr) {
			pUnit->onSpecialEnd();
		}
	}

}

void thiefNumberTweenCallback(float /* fromNumber */, float /* toNumber */, float /*currentNumber*/, std::string /*tweenClipName*/, MessageData1S1I1F* /*userParams*/) {
	/*GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(userParams->i);
	ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid");
	if(go != nullptr) {
		Thief* thief = go->GetComponent<Thief>();
		ASSERT(thief != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit");
		if(thief != nullptr) {
			if(tweenClipName == "targetsIn") {
				for(GameObject* go : thief->targetIndicators ) {

				}

			}
		}
	}*/
}

Thief::Thief() : PlayerUnit() {
	this->init();
}

Thief::Thief(Object* object_) : PlayerUnit(object_) {
	this->init();
}

Thief::~Thief() {
	this->destroy();
}

void Thief::init() {
	this->unitType = UnitType::UNIT_TYPE_THIEF;
}

void Thief::destroy() {
	this->deleteTargets();
}

bool Thief::isSpecialTouch(int touchId) {
	if(this->getTouchNearUnit()) {
		Touch touch = ENGINE->GetInput()->GetTouch(touchId);
		if(touch.timeDown >= GetFloatGameConstant(GAME_CONSTANT_long_press_length_in_seconds) && glm::distance(touch.pos, this->touchStartPos) <= GetFloatGameConstant(GAME_CONSTANT_allowed_finger_movement_in_press)) {
			this->targetedCell = nullptr;
			this->SetTouchIndicatorVisible(false);
			this->updateLegalTagets();
			return true;
		}
	}
	return false;
}

void Thief::onSpecialTouch(int touchId) {
	Touch touch = ENGINE->GetInput()->GetTouch(touchId);
	if(touch.phase == TouchPhase::Ended) {
		this->targetedCell = SINGLETONS->GetGridManager()->TouchPositionToCell(touch.pos);
		if(std::find(this->legalTargets.begin(), this->legalTargets.end(), this->GetCurrentTouchedCell()) != this->legalTargets.end()) {
			this->startSpecial();
		} else {
			this->targetedCell = this->gridNavRef->GetCurrentCell();
			this->cancelSpecial();
		}
		this->tweenOutTargets();
	}
}

void Thief::startSpecial() {
	PlayerUnit::startSpecial();
	// Remove the indicator at the selected position
	GameObject* selectedTargetIndicator = this->targetIndicators[this->targetedCell];
	this->targetIndicators.erase(this->targetedCell);
	delete selectedTargetIndicator;

	this->SetTouchIndicatorCell(this->targetedCell);
	this->startTouchIndicatorPulse();
	this->SetTouchIndicatorSprite(THIEF_SPECIAL);
	this->SetTouchIndicatorVisible(true);

	float jumpDist = glm::distance(this->targetedCell->center, this->gameObjectRef->GetTransform()->GetPosition());
	float jumpTweenTime = jumpDist / GetFloatGameConstant(GAME_CONSTANT_jump_speed_in_units_per_second);
	ENGINE->GetTween()->TweenPosition(this->gameObjectRef->GetId(),
									  this->gameObjectRef->GetTransform()->GetPosition(),
									  this->targetedCell->center,
									  jumpTweenTime,
									  false,
									  TWEEN_TRANSLATION_CURVE_TYPE_PARABOLA,
									  false,
									  thiefTweenCallback);

}

void Thief::onSpecialEnd() {
	PlayerUnit::onSpecialEnd();
	this->gridNavRef->SetGridPosition(this->targetedCell);
}

void Thief::touchedCellChanged(GridCell* prevTouchedCell) {
	if(this->inputState != InputState::INPUT_STATE_SPECIAL) {
		PlayerUnit::touchedCellChanged(prevTouchedCell);
	} else {
		if(this->targetIndicators[prevTouchedCell]) {
			ENGINE->GetTween()->TweenScale(this->targetIndicators[prevTouchedCell]->GetId(), glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale_hover)),
																							 glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)),
																							 GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
		}
		if(this->targetIndicators[this->GetCurrentTouchedCell()]) {
			ENGINE->GetTween()->TweenScale(this->targetIndicators[this->GetCurrentTouchedCell()]->GetId(),  glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)),
																											glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale_hover)),
																											GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
			this->gridNavRef->SetLookTarget(this->GetCurrentTouchedCell()->center);
		}
		if(std::find(this->legalTargets.begin(), this->legalTargets.end(), this->GetCurrentTouchedCell()) != this->legalTargets.end()) {
			this->SetTouchIndicatorSprite(GOOD_TOUCH);
		} else {
			this->SetTouchIndicatorSprite(BAD_TOUCH);
		}
	}
}

void Thief::updateLegalTagets() {
	this->legalTargets.clear();
	this->deleteTargets();
	GridCell* currentCell = this->gridNavRef->GetCurrentCell();
	int elevation = SINGLETONS->GetGridManager()->GetGrid()->GetElevationFromWorldY(currentCell->center.y);

	std::list<GridCell*> cellsInRange;
	SINGLETONS->GetGridManager()->GetGrid()->GetNeighborCells(cellsInRange, this->gridNavRef->GetCurrentCell(),
															  GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units)
															  + elevation * GetFloatGameConstant(GAME_CONSTANT_jump_elevation_multiplier));

	for ( GridCell* c : cellsInRange) {
		int cellElevation = 0;
		for(int i = 0; i < NUM_ELEVATIONS; ++i) {
			if(SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(c->x, c->z, i)) {
				cellElevation = i;
				break;
			}

		}

		// The thief can jump to a maximum of one elevation level above her
		if (cellElevation <= (elevation + 1)) {
			if ((cellElevation != elevation) || (SINGLETONS->GetGridManager()->GetGrid()->HasLineOfSight(currentCell, c, elevation))) {
				if (SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(c->x, c->z, cellElevation)) {
					int elevationDiff = elevation - cellElevation;
					if (elevationDiff < 0) {
						elevationDiff = 0;
					}

					float maxRange = fmax(GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units) + elevationDiff * GetFloatGameConstant(GAME_CONSTANT_jump_elevation_multiplier), 1.0f);
					float dist = SINGLETONS->GetGridManager()->GetGrid()->GetGroundDistanceBetweenCells(currentCell, c);
					if (dist <= maxRange) {
						this->legalTargets.push_back(c);
					}
				}
			}
		}
		/*
		if(cellElevation == elevation) { // is the cell on the same height
			if(this->gridNavRef->CanReachDestination(c, GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units)) && SINGLETONS->GetGridManager()->GetGrid()->HasLineOfSight(currentCell, c, elevation) ) {
				this->legalTargets.push_back(c);
			}
		}
		else if(cellElevation <= elevation + 1) { // is the cell below it
			if(SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(c->x, c->z, cellElevation)) {
				float dist = glm::distance(glm::vec2(c->x, c->z), glm::vec2(currentCell->x, currentCell->z));
				if(dist <= GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units) + cellElevation * GetFloatGameConstant(GAME_CONSTANT_jump_elevation_multiplier)) {
					this->legalTargets.push_back(c);
				}
			}
		}
		*/
	}
	this->createTargets();
	this->tweenInTargets();
}

void Thief::tweenInTargets() {
	glm::vec3 pos;
	for(auto contents : this->targetIndicators ) {
		if(contents.second != nullptr) {
			pos = contents.second->GetTransform()->GetPosition();
			ENGINE->GetTween()->TweenPosition(contents.second->GetId(), pos, pos + glm::vec3(0.0f, GetFloatGameConstant(GAME_CONSTANT_target_indicator_offset), 0.0f), GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
		}
	}
}

void Thief::tweenOutTargets() {
	glm::vec3 pos;
	for(auto contents : this->targetIndicators ) {
		if(contents.second != nullptr) {
			pos = contents.second->GetTransform()->GetPosition();
			ENGINE->GetTween()->TweenScale(contents.second->GetId(), glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)), glm::vec3(0), GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
		}
	}
}

void Thief::createTargets() {
	for( GridCell* c : this->legalTargets ) {
		GameObject* indicator = new GameObject(ENGINE->GetSceneGraph3D());
		SpriteRenderer* spriteRenderer = indicator->AddComponent<SpriteRenderer>();
		std::vector<std::string> pathsToTextures;
		pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Thief_Jump_cyan.png");
		spriteRenderer->initPlane(1.0f, 1.0f, "sptshdr", pathsToTextures, PlaneOrigin::Center);
		indicator->GetTransform()->SetPosition(c->center);
		indicator->GetTransform()->SetScale( glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)));
		indicator->GetTransform()->Translate(0.0f, YAXIS);
		indicator->GetTransform()->Rotate(90.0f inRadians, XAXIS);
		this->targetIndicators[c] = indicator;
	}
}

void Thief::deleteTargets() {
	for(auto contents : this->targetIndicators ) {
		if(contents.second != nullptr) {
			delete contents.second;
		}
	}
	this->targetIndicators.clear();
}
<|endoftext|>