<commit_before>#pragma once
#include <bts/blockchain/chain_database.hpp>
#include <bts/wallet/wallet.hpp>
#include <bts/net/node.hpp>
#include <bts/rpc/rpc_client_api.hpp>
#include <bts/api/common_api.hpp>
#include <bts/rpc_stubs/common_api_client.hpp>
#include <fc/thread/thread.hpp>
#include <fc/log/logger_config.hpp>
#include <memory>
#include <boost/program_options.hpp>

namespace bts { namespace rpc {
  class rpc_server;
  typedef std::shared_ptr<rpc_server> rpc_server_ptr;
} }
namespace bts { namespace cli {
    class cli;
}};

namespace bts { namespace client {

    using namespace bts::blockchain;
    using namespace bts::wallet;

    boost::program_options::variables_map parse_option_variables(int argc, char** argv);
    fc::path get_data_dir(const boost::program_options::variables_map& option_variables);

    namespace detail { class client_impl; }

    using namespace bts::rpc;

    struct rpc_server_config
    {
      rpc_server_config()
      : enable(false),
        rpc_endpoint(fc::ip::endpoint::from_string("127.0.0.1:0")),
        httpd_endpoint(fc::ip::endpoint::from_string("127.0.0.1:0")),
        htdocs("./htdocs")
      {}

      bool             enable;
      std::string      rpc_user;
      std::string      rpc_password;
      fc::ip::endpoint rpc_endpoint;
      fc::ip::endpoint httpd_endpoint;
      fc::path         htdocs;

      bool is_valid() const; /* Currently just checks if rpc port is set */
    };

    struct chain_server_config
    {
        chain_server_config()
         : enabled(false),
           listen_port(0)
        {}

        bool enabled;
        uint16_t listen_port;
    };

    struct config
    {
       config( ) :
          default_peers(vector<string>{
                  "178.62.50.61:1776",
                  "80.240.133.79:1776",
                  "5.101.106.138:1777",
                  "128.199.137.122:1776",
                  "95.85.33.16:8764",
                  "180.153.142.120:1777",
                  "84.238.140.192:42577",
                  "104.131.35.149:1776",
                  "178.62.50.61:1777",
                  "80.240.133.79:1777",
                  "5.101.106.138:1778",
                  "128.199.137.122:1777",
                  "178.62.50.61:1778",
                  "80.240.133.79:1778",
                  "178.62.50.61:1779"
                  }),
          ignore_console(false),
          use_upnp(true),
          maximum_number_of_connections(BTS_NET_DEFAULT_MAX_CONNECTIONS) ,
          delegate_server( fc::ip::endpoint::from_string("0.0.0.0:0") ),
          default_delegate_peers( vector<string>({"178.62.50.61:9988"}) )
          {
              logging = fc::logging_config::default_config();
          }

          rpc_server_config   rpc;
          vector<string>      default_peers;
          vector<string>      chain_servers;
          chain_server_config chain_server;
          bool                ignore_console;
          bool                use_upnp;
          optional<fc::path>  genesis_config;
          uint16_t            maximum_number_of_connections;
          fc::logging_config  logging;
          fc::ip::endpoint    delegate_server;
          vector<string>      default_delegate_peers;
    };

    /**
     * @class client
     * @brief integrates the network, wallet, and blockchain
     *
     */
    class client : public bts::rpc_stubs::common_api_client,
                   public std::enable_shared_from_this<client>
    {
       public:
         client();
         client(bts::net::simulated_network_ptr network_to_connect_to);

         void simulate_disconnect( bool state );

         virtual ~client();

         void start_networking(std::function<void()> network_started_callback = std::function<void()>());
         void configure_from_command_line(int argc, char** argv);
         fc::future<void> start();
         void open(const path& data_dir,
                   optional<fc::path> genesis_file_path = optional<fc::path>(),
                   std::function<void(uint32_t)> reindex_status_callback = std::function<void(uint32_t)>());

         void init_cli();
         void set_daemon_mode(bool daemon_mode);

         void add_node( const string& ep );

         chain_database_ptr         get_chain()const;
         wallet_ptr                 get_wallet()const;
         bts::rpc::rpc_server_ptr   get_rpc_server()const;
         bts::net::node_ptr         get_node()const;
         fc::path                   get_data_dir()const;

         // returns true if the client is connected to the network
         bool                is_connected() const;
         bts::net::node_id_t get_node_id() const;

         const config& configure(const fc::path& configuration_directory);

         // functions for taking command-line parameters and passing them on to the p2p node
         void listen_on_port( uint16_t port_to_listen, bool wait_if_not_available);
         void accept_incoming_p2p_connections(bool accept);
         void listen_to_p2p_network();
         void connect_to_peer( const string& remote_endpoint );
         void connect_to_p2p_network();

         fc::ip::endpoint get_p2p_listening_endpoint() const;
         bool handle_message(const bts::net::message&, bool sync_mode);
         void sync_status(uint32_t item_type, uint32_t item_count);

       protected:
         virtual bts::api::common_api* get_impl() const override;

       private:
         unique_ptr<detail::client_impl> my;
    };

    typedef shared_ptr<client> client_ptr;

    /* Message broadcast on the network to notify all clients of some important information
      (security vulnerability, new version, that sort of thing) */
    class client_notification
    {
       public:
         fc::time_point_sec         timestamp;
         string                message;
         fc::ecc::compact_signature signature;

         //client_notification();
         fc::sha256 digest() const;
         void sign(const fc::ecc::private_key& key);
         fc::ecc::public_key signee() const;
    };
    typedef shared_ptr<client_notification> client_notification_ptr;

} } // bts::client

extern const std::string BTS_MESSAGE_MAGIC;

FC_REFLECT(bts::client::client_notification, (timestamp)(message)(signature) )
FC_REFLECT( bts::client::rpc_server_config, (enable)(rpc_user)(rpc_password)(rpc_endpoint)(httpd_endpoint)(htdocs) )
FC_REFLECT( bts::client::chain_server_config, (enabled)(listen_port) )
FC_REFLECT( bts::client::config,
            (rpc)(default_peers)(chain_servers)(chain_server)(ignore_console)(logging)
            (delegate_server)
            (default_delegate_peers) )

<commit_msg>Update seed nodes<commit_after>#pragma once
#include <bts/blockchain/chain_database.hpp>
#include <bts/wallet/wallet.hpp>
#include <bts/net/node.hpp>
#include <bts/rpc/rpc_client_api.hpp>
#include <bts/api/common_api.hpp>
#include <bts/rpc_stubs/common_api_client.hpp>
#include <fc/thread/thread.hpp>
#include <fc/log/logger_config.hpp>
#include <memory>
#include <boost/program_options.hpp>

namespace bts { namespace rpc {
  class rpc_server;
  typedef std::shared_ptr<rpc_server> rpc_server_ptr;
} }
namespace bts { namespace cli {
    class cli;
}};

namespace bts { namespace client {

    using namespace bts::blockchain;
    using namespace bts::wallet;

    boost::program_options::variables_map parse_option_variables(int argc, char** argv);
    fc::path get_data_dir(const boost::program_options::variables_map& option_variables);

    namespace detail { class client_impl; }

    using namespace bts::rpc;

    struct rpc_server_config
    {
      rpc_server_config()
      : enable(false),
        rpc_endpoint(fc::ip::endpoint::from_string("127.0.0.1:0")),
        httpd_endpoint(fc::ip::endpoint::from_string("127.0.0.1:0")),
        htdocs("./htdocs")
      {}

      bool             enable;
      std::string      rpc_user;
      std::string      rpc_password;
      fc::ip::endpoint rpc_endpoint;
      fc::ip::endpoint httpd_endpoint;
      fc::path         htdocs;

      bool is_valid() const; /* Currently just checks if rpc port is set */
    };

    struct chain_server_config
    {
        chain_server_config()
         : enabled(false),
           listen_port(0)
        {}

        bool enabled;
        uint16_t listen_port;
    };

    struct config
    {
       config( ) :
          default_peers(vector<string>{
                  "5.101.106.138:1777",
                  "5.101.106.138:1778",
                  "61.129.33.213:1776",
                  "80.240.133.79:1776",
                  "80.240.133.79:1777",
                  "80.240.133.79:1778",
                  "84.238.140.192:42577",
                  "89.187.144.203:8764",
                  "95.85.33.16:8764",
                  "104.131.35.149:1776",
                  "178.62.50.61:1776",
                  "178.62.50.61:1777",
                  "178.62.50.61:1778",
                  "178.62.50.61:1779",
                  "178.62.157.161:1776",
                  "180.153.142.120:1777",
                  "188.226.195.137:60696",
                  "auseednode.minebitshares.com:1776",
                  "euseednode.minebitshares.com:1776"
                  }),
          ignore_console(false),
          use_upnp(true),
          maximum_number_of_connections(BTS_NET_DEFAULT_MAX_CONNECTIONS) ,
          delegate_server( fc::ip::endpoint::from_string("0.0.0.0:0") ),
          default_delegate_peers( vector<string>({"178.62.50.61:9988"}) )
          {
              logging = fc::logging_config::default_config();
          }

          rpc_server_config   rpc;
          vector<string>      default_peers;
          vector<string>      chain_servers;
          chain_server_config chain_server;
          bool                ignore_console;
          bool                use_upnp;
          optional<fc::path>  genesis_config;
          uint16_t            maximum_number_of_connections;
          fc::logging_config  logging;
          fc::ip::endpoint    delegate_server;
          vector<string>      default_delegate_peers;
    };

    /**
     * @class client
     * @brief integrates the network, wallet, and blockchain
     *
     */
    class client : public bts::rpc_stubs::common_api_client,
                   public std::enable_shared_from_this<client>
    {
       public:
         client();
         client(bts::net::simulated_network_ptr network_to_connect_to);

         void simulate_disconnect( bool state );

         virtual ~client();

         void start_networking(std::function<void()> network_started_callback = std::function<void()>());
         void configure_from_command_line(int argc, char** argv);
         fc::future<void> start();
         void open(const path& data_dir,
                   optional<fc::path> genesis_file_path = optional<fc::path>(),
                   std::function<void(uint32_t)> reindex_status_callback = std::function<void(uint32_t)>());

         void init_cli();
         void set_daemon_mode(bool daemon_mode);

         void add_node( const string& ep );

         chain_database_ptr         get_chain()const;
         wallet_ptr                 get_wallet()const;
         bts::rpc::rpc_server_ptr   get_rpc_server()const;
         bts::net::node_ptr         get_node()const;
         fc::path                   get_data_dir()const;

         // returns true if the client is connected to the network
         bool                is_connected() const;
         bts::net::node_id_t get_node_id() const;

         const config& configure(const fc::path& configuration_directory);

         // functions for taking command-line parameters and passing them on to the p2p node
         void listen_on_port( uint16_t port_to_listen, bool wait_if_not_available);
         void accept_incoming_p2p_connections(bool accept);
         void listen_to_p2p_network();
         void connect_to_peer( const string& remote_endpoint );
         void connect_to_p2p_network();

         fc::ip::endpoint get_p2p_listening_endpoint() const;
         bool handle_message(const bts::net::message&, bool sync_mode);
         void sync_status(uint32_t item_type, uint32_t item_count);

       protected:
         virtual bts::api::common_api* get_impl() const override;

       private:
         unique_ptr<detail::client_impl> my;
    };

    typedef shared_ptr<client> client_ptr;

    /* Message broadcast on the network to notify all clients of some important information
      (security vulnerability, new version, that sort of thing) */
    class client_notification
    {
       public:
         fc::time_point_sec         timestamp;
         string                message;
         fc::ecc::compact_signature signature;

         //client_notification();
         fc::sha256 digest() const;
         void sign(const fc::ecc::private_key& key);
         fc::ecc::public_key signee() const;
    };
    typedef shared_ptr<client_notification> client_notification_ptr;

} } // bts::client

extern const std::string BTS_MESSAGE_MAGIC;

FC_REFLECT(bts::client::client_notification, (timestamp)(message)(signature) )
FC_REFLECT( bts::client::rpc_server_config, (enable)(rpc_user)(rpc_password)(rpc_endpoint)(httpd_endpoint)(htdocs) )
FC_REFLECT( bts::client::chain_server_config, (enabled)(listen_port) )
FC_REFLECT( bts::client::config,
            (rpc)(default_peers)(chain_servers)(chain_server)(ignore_console)(logging)
            (delegate_server)
            (default_delegate_peers) )

<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2010 Hauke Heibel <hauke.heibel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"

#include <Eigen/StdDeque>
#include <Eigen/Geometry>

EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Vector4f)

EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Matrix2f)
EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Matrix4f)
EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Matrix4d)

EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Affine3f)
EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Affine3d)

EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Quaternionf)
EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Quaterniond)

template<typename MatrixType>
void check_stddeque_matrix(const MatrixType& m)
{
  typename MatrixType::Index rows = m.rows();
  typename MatrixType::Index cols = m.cols();
  MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);
  std::deque<MatrixType> v(10, MatrixType(rows,cols)), w(20, y);
  v[5] = x;
  w[6] = v[5];
  VERIFY_IS_APPROX(w[6], v[5]);
  v = w;
  for(int i = 0; i < 20; i++)
  {
    VERIFY_IS_APPROX(w[i], v[i]);
  }

  v.resize(21);
  v[20] = x;
  VERIFY_IS_APPROX(v[20], x);
  v.resize(22,y);
  VERIFY_IS_APPROX(v[21], y);
  v.push_back(x);
  VERIFY_IS_APPROX(v[22], x);
  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType));

  // do a lot of push_back such that the deque gets internally resized
  // (with memory reallocation)
  MatrixType* ref = &w[0];
  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)
    v.push_back(w[i%w.size()]);
  for(unsigned int i=23; i<v.size(); ++i)
  {
    VERIFY(v[i]==w[(i-23)%w.size()]);
  }
}

template<typename TransformType>
void check_stddeque_transform(const TransformType&)
{
  typedef typename TransformType::MatrixType MatrixType;
  TransformType x(MatrixType::Random()), y(MatrixType::Random());
  std::deque<TransformType> v(10), w(20, y);
  v[5] = x;
  w[6] = v[5];
  VERIFY_IS_APPROX(w[6], v[5]);
  v = w;
  for(int i = 0; i < 20; i++)
  {
    VERIFY_IS_APPROX(w[i], v[i]);
  }

  v.resize(21);
  v[20] = x;
  VERIFY_IS_APPROX(v[20], x);
  v.resize(22,y);
  VERIFY_IS_APPROX(v[21], y);
  v.push_back(x);
  VERIFY_IS_APPROX(v[22], x);

  // do a lot of push_back such that the deque gets internally resized
  // (with memory reallocation)
  TransformType* ref = &w[0];
  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)
    v.push_back(w[i%w.size()]);
  for(unsigned int i=23; i<v.size(); ++i)
  {
    VERIFY(v[i].matrix()==w[(i-23)%w.size()].matrix());
  }
}

template<typename QuaternionType>
void check_stddeque_quaternion(const QuaternionType&)
{
  typedef typename QuaternionType::Coefficients Coefficients;
  QuaternionType x(Coefficients::Random()), y(Coefficients::Random());
  std::deque<QuaternionType> v(10), w(20, y);
  v[5] = x;
  w[6] = v[5];
  VERIFY_IS_APPROX(w[6], v[5]);
  v = w;
  for(int i = 0; i < 20; i++)
  {
    VERIFY_IS_APPROX(w[i], v[i]);
  }

  v.resize(21);
  v[20] = x;
  VERIFY_IS_APPROX(v[20], x);
  v.resize(22,y);
  VERIFY_IS_APPROX(v[21], y);
  v.push_back(x);
  VERIFY_IS_APPROX(v[22], x);

  // do a lot of push_back such that the deque gets internally resized
  // (with memory reallocation)
  QuaternionType* ref = &w[0];
  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)
    v.push_back(w[i%w.size()]);
  for(unsigned int i=23; i<v.size(); ++i)
  {
    VERIFY(v[i].coeffs()==w[(i-23)%w.size()].coeffs());
  }
}

void test_stddeque_overload()
{
  // some non vectorizable fixed sizes
  CALL_SUBTEST_1(check_stddeque_matrix(Vector2f()));
  CALL_SUBTEST_1(check_stddeque_matrix(Matrix3f()));
  CALL_SUBTEST_2(check_stddeque_matrix(Matrix3d()));

  // some vectorizable fixed sizes
  CALL_SUBTEST_1(check_stddeque_matrix(Matrix2f()));
  CALL_SUBTEST_1(check_stddeque_matrix(Vector4f()));
  CALL_SUBTEST_1(check_stddeque_matrix(Matrix4f()));
  CALL_SUBTEST_2(check_stddeque_matrix(Matrix4d()));

  // some dynamic sizes
  CALL_SUBTEST_3(check_stddeque_matrix(MatrixXd(1,1)));
  CALL_SUBTEST_3(check_stddeque_matrix(VectorXd(20)));
  CALL_SUBTEST_3(check_stddeque_matrix(RowVectorXf(20)));
  CALL_SUBTEST_3(check_stddeque_matrix(MatrixXcf(10,10)));

  // some Transform
  CALL_SUBTEST_4(check_stddeque_transform(Affine2f())); // does not need the specialization (2+1)^2 = 9
  CALL_SUBTEST_4(check_stddeque_transform(Affine3f()));
  CALL_SUBTEST_4(check_stddeque_transform(Affine3d()));

  // some Quaternion
  CALL_SUBTEST_5(check_stddeque_quaternion(Quaternionf()));
  CALL_SUBTEST_5(check_stddeque_quaternion(Quaterniond()));
}
<commit_msg>Fix unit test: accessing elements in a deque by offsetting a pointer to another element causes undefined behavior.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2010 Hauke Heibel <hauke.heibel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"

#include <Eigen/StdDeque>
#include <Eigen/Geometry>

EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Vector4f)

EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Matrix2f)
EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Matrix4f)
EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Matrix4d)

EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Affine3f)
EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Affine3d)

EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Quaternionf)
EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(Quaterniond)

template<typename MatrixType>
void check_stddeque_matrix(const MatrixType& m)
{
  typename MatrixType::Index rows = m.rows();
  typename MatrixType::Index cols = m.cols();
  MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);
  std::deque<MatrixType> v(10, MatrixType(rows,cols)), w(20, y);
  v[5] = x;
  w[6] = v[5];
  VERIFY_IS_APPROX(w[6], v[5]);
  v = w;
  for(int i = 0; i < 20; i++)
  {
    VERIFY_IS_APPROX(w[i], v[i]);
  }

  v.resize(21);
  v[20] = x;
  VERIFY_IS_APPROX(v[20], x);
  v.resize(22,y);
  VERIFY_IS_APPROX(v[21], y);
  v.push_back(x);
  VERIFY_IS_APPROX(v[22], x);

  // do a lot of push_back such that the deque gets internally resized
  // (with memory reallocation)
  MatrixType* ref = &w[0];
  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)
    v.push_back(w[i%w.size()]);
  for(unsigned int i=23; i<v.size(); ++i)
  {
    VERIFY(v[i]==w[(i-23)%w.size()]);
  }
}

template<typename TransformType>
void check_stddeque_transform(const TransformType&)
{
  typedef typename TransformType::MatrixType MatrixType;
  TransformType x(MatrixType::Random()), y(MatrixType::Random());
  std::deque<TransformType> v(10), w(20, y);
  v[5] = x;
  w[6] = v[5];
  VERIFY_IS_APPROX(w[6], v[5]);
  v = w;
  for(int i = 0; i < 20; i++)
  {
    VERIFY_IS_APPROX(w[i], v[i]);
  }

  v.resize(21);
  v[20] = x;
  VERIFY_IS_APPROX(v[20], x);
  v.resize(22,y);
  VERIFY_IS_APPROX(v[21], y);
  v.push_back(x);
  VERIFY_IS_APPROX(v[22], x);

  // do a lot of push_back such that the deque gets internally resized
  // (with memory reallocation)
  TransformType* ref = &w[0];
  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)
    v.push_back(w[i%w.size()]);
  for(unsigned int i=23; i<v.size(); ++i)
  {
    VERIFY(v[i].matrix()==w[(i-23)%w.size()].matrix());
  }
}

template<typename QuaternionType>
void check_stddeque_quaternion(const QuaternionType&)
{
  typedef typename QuaternionType::Coefficients Coefficients;
  QuaternionType x(Coefficients::Random()), y(Coefficients::Random());
  std::deque<QuaternionType> v(10), w(20, y);
  v[5] = x;
  w[6] = v[5];
  VERIFY_IS_APPROX(w[6], v[5]);
  v = w;
  for(int i = 0; i < 20; i++)
  {
    VERIFY_IS_APPROX(w[i], v[i]);
  }

  v.resize(21);
  v[20] = x;
  VERIFY_IS_APPROX(v[20], x);
  v.resize(22,y);
  VERIFY_IS_APPROX(v[21], y);
  v.push_back(x);
  VERIFY_IS_APPROX(v[22], x);

  // do a lot of push_back such that the deque gets internally resized
  // (with memory reallocation)
  QuaternionType* ref = &w[0];
  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)
    v.push_back(w[i%w.size()]);
  for(unsigned int i=23; i<v.size(); ++i)
  {
    VERIFY(v[i].coeffs()==w[(i-23)%w.size()].coeffs());
  }
}

void test_stddeque_overload()
{
  // some non vectorizable fixed sizes
  CALL_SUBTEST_1(check_stddeque_matrix(Vector2f()));
  CALL_SUBTEST_1(check_stddeque_matrix(Matrix3f()));
  CALL_SUBTEST_2(check_stddeque_matrix(Matrix3d()));

  // some vectorizable fixed sizes
  CALL_SUBTEST_1(check_stddeque_matrix(Matrix2f()));
  CALL_SUBTEST_1(check_stddeque_matrix(Vector4f()));
  CALL_SUBTEST_1(check_stddeque_matrix(Matrix4f()));
  CALL_SUBTEST_2(check_stddeque_matrix(Matrix4d()));

  // some dynamic sizes
  CALL_SUBTEST_3(check_stddeque_matrix(MatrixXd(1,1)));
  CALL_SUBTEST_3(check_stddeque_matrix(VectorXd(20)));
  CALL_SUBTEST_3(check_stddeque_matrix(RowVectorXf(20)));
  CALL_SUBTEST_3(check_stddeque_matrix(MatrixXcf(10,10)));

  // some Transform
  CALL_SUBTEST_4(check_stddeque_transform(Affine2f())); // does not need the specialization (2+1)^2 = 9
  CALL_SUBTEST_4(check_stddeque_transform(Affine3f()));
  CALL_SUBTEST_4(check_stddeque_transform(Affine3d()));

  // some Quaternion
  CALL_SUBTEST_5(check_stddeque_quaternion(Quaternionf()));
  CALL_SUBTEST_5(check_stddeque_quaternion(Quaterniond()));
}
<|endoftext|>


<commit_before>//
// Created by monty on 30/07/16.
//

#include "glm/glm.hpp"

#include <memory>
#include <functional>
#include <iostream>
#include <array>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#include <map>
#include <vector>
#include "NativeBitmap.h"
#include "Material.h"
#include "Trig.h"
#include "TrigBatch.h"
#include "MeshObject.h"
#include "MaterialList.h"
#include "Scene.h"
#include "VBORenderingJob.h"

#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"

#include "NoudarDungeonSnapshot.h"

#include "VisibilityStrategy.h"

namespace odb {

    const bool kNarrowByDistance =
#ifdef OSMESA
    true;
#else
    false;
#endif

	bool VisibilityStrategy::isValid(Knights::Vec2i pos) {
		return 0 <= pos.x && pos.x < Knights::kMapSize && 0 <= pos.y && pos.y < Knights::kMapSize;
	}

	void VisibilityStrategy::mergeInto(const VisMap &map1, const VisMap &map2, VisMap &result) {
		for ( int y = 0; y < Knights::kMapSize; ++y ) {
			for ( int x = 0; x < Knights::kMapSize; ++x ) {
				if ( map1[ y ][ x ] == EVisibility::kVisible || map2[ y ][ x ] == EVisibility::kVisible ) {
					result[ y ][ x ] = EVisibility::kVisible;
				} else {
					result[ y ][ x ] = EVisibility::kInvisible;
				}
			}
		}
	}

	bool VisibilityStrategy::isBlock(const IntMap& occluders, Knights::EDirection direction, Knights::Vec2i currentPos) {

        auto transformed = transform( direction, currentPos );

		auto tile = occluders[ transformed.y][transformed.x];

		for (auto candidate : {'1', 'Y', 'X', '\\', '/', 'S', 'Z', '|', '%', '<', '>'}) {
			if (candidate == tile) {
				return true;
			}
		}

		return false;
	}

	void VisibilityStrategy::castVisibility(VisMap &visMap, const IntMap &occluders, Knights::Vec2i pos, Knights::EDirection direction, bool cleanPrevious) {
		if ( cleanPrevious ) {
			for (auto &line : visMap) {
				std::fill(std::begin(line), std::end(line), EVisibility::kInvisible);
			}
		}

		castVisibility(direction, visMap, occluders, transform( direction, pos ), {0, 0});
	}

	bool VisibilityStrategy::isVisibleAt(const VisMap& visMap, Knights::EDirection from, Knights::Vec2i currentPos ) {
		auto converted = transform( from, currentPos );
		return visMap[ converted.y ][ converted.x ] == EVisibility::kVisible;
	}

	void VisibilityStrategy::setIsVisible(VisMap& visMap, Knights::EDirection from, Knights::Vec2i currentPos ) {
		auto converted = transform( from, currentPos );
		visMap[ converted.y ][ converted.x ] = EVisibility::kVisible;
	}

	Knights::Vec2i VisibilityStrategy::transform( Knights::EDirection from, Knights::Vec2i currentPos ) {

		switch( from ) {
			case Knights::EDirection::kNorth:
				return currentPos;
			case Knights::EDirection::kSouth:
				return { Knights::kMapSize - currentPos.x - 1, Knights::kMapSize - currentPos.y - 1};
			case Knights::EDirection::kEast:
				return { Knights::kMapSize - currentPos.y - 1, Knights::kMapSize - currentPos.x - 1};
			case Knights::EDirection::kWest:
				return { currentPos.y, currentPos.x};
		}
	}

	void VisibilityStrategy::castVisibility(Knights::EDirection from, VisMap &visMap, const IntMap &occluders,
	                                        Knights::Vec2i originalPos, Knights::Vec2i offset) {

		std::array<Knights::Vec2i, Knights::kMapSize + Knights::kMapSize> positions;
		int stackPos = 0;
		Knights::Vec2i currentPos;

		positions[stackPos] = originalPos;
		++stackPos;

		while (stackPos > 0) {
			--stackPos;

			currentPos = positions[ stackPos ];

			if (!isValid(transform( from, currentPos))) {
				continue;
			}

			if ( isVisibleAt( visMap, from, currentPos ) ) {
				continue;
			}

			setIsVisible( visMap, from, currentPos );

			if (isBlock(occluders, from, currentPos )) {
				continue;
			}

			auto leftDirection = Knights::EDirection::kWest;
			auto rightDirection = Knights::EDirection::kEast;
			auto rightOffset = Knights::mapOffsetForDirection(rightDirection);
			auto leftOffset = Knights::mapOffsetForDirection(leftDirection);

            //The -1 is due to the fact I will add a new element.

            int distance = ( currentPos.y - originalPos.y );
            int narrowing = 1;
#ifdef OSMESA
            if ( std::abs( distance ) >= 9 ) {
                continue;
            }
            narrowing = (distance / 2);
#endif

			if ( ( !kNarrowByDistance || ( currentPos.x - originalPos.x ) >= -std::abs(narrowing) )&& ( currentPos.x - originalPos.x ) <= 0 && stackPos < positions.size() - 1) {
				positions[stackPos] =  Knights::Vec2i{currentPos.x + leftOffset.x, currentPos.y + leftOffset.y};
				++stackPos;
			}

			if ( ( !kNarrowByDistance || ( currentPos.x - originalPos.x ) <= std::abs(narrowing) ) && ( currentPos.x - originalPos.x ) >= 0 && stackPos < positions.size() - 1) {
				positions[stackPos] =  Knights::Vec2i{currentPos.x + rightOffset.x, currentPos.y + rightOffset.y};
				++stackPos;
			}

            if (  distance <= 0 && stackPos < positions.size() - 1) {
                auto mapOffset = Knights::mapOffsetForDirection(Knights::EDirection::kNorth);
                positions[stackPos] =  Knights::Vec2i{currentPos.x + mapOffset.x, currentPos.y + mapOffset.y};
                ++stackPos;
            }

		}
	}

    void VisibilityStrategy::makeAllVisible(VisMap& map) {
		for ( int y = 0; y < Knights::kMapSize; ++y ) {
			for ( int x = 0; x < Knights::kMapSize; ++x ) {
				map[ y ][ x ] = EVisibility::kVisible;
			}
		}
    }
}
<commit_msg>Close the gaps on the narrow view for limited visibility<commit_after>//
// Created by monty on 30/07/16.
//

#include "glm/glm.hpp"

#include <memory>
#include <functional>
#include <iostream>
#include <array>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#include <map>
#include <vector>
#include "NativeBitmap.h"
#include "Material.h"
#include "Trig.h"
#include "TrigBatch.h"
#include "MeshObject.h"
#include "MaterialList.h"
#include "Scene.h"
#include "VBORenderingJob.h"

#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"

#include "NoudarDungeonSnapshot.h"

#include "VisibilityStrategy.h"

namespace odb {

    const bool kNarrowByDistance =
#ifdef OSMESA
    true;
#else
    false;
#endif

	bool VisibilityStrategy::isValid(Knights::Vec2i pos) {
		return 0 <= pos.x && pos.x < Knights::kMapSize && 0 <= pos.y && pos.y < Knights::kMapSize;
	}

	void VisibilityStrategy::mergeInto(const VisMap &map1, const VisMap &map2, VisMap &result) {
		for ( int y = 0; y < Knights::kMapSize; ++y ) {
			for ( int x = 0; x < Knights::kMapSize; ++x ) {
				if ( map1[ y ][ x ] == EVisibility::kVisible || map2[ y ][ x ] == EVisibility::kVisible ) {
					result[ y ][ x ] = EVisibility::kVisible;
				} else {
					result[ y ][ x ] = EVisibility::kInvisible;
				}
			}
		}
	}

	bool VisibilityStrategy::isBlock(const IntMap& occluders, Knights::EDirection direction, Knights::Vec2i currentPos) {

        auto transformed = transform( direction, currentPos );

		auto tile = occluders[ transformed.y][transformed.x];

		for (auto candidate : {'1', 'Y', 'X', '\\', '/', 'S', 'Z', '|', '%', '<', '>'}) {
			if (candidate == tile) {
				return true;
			}
		}

		return false;
	}

	void VisibilityStrategy::castVisibility(VisMap &visMap, const IntMap &occluders, Knights::Vec2i pos, Knights::EDirection direction, bool cleanPrevious) {
		if ( cleanPrevious ) {
			for (auto &line : visMap) {
				std::fill(std::begin(line), std::end(line), EVisibility::kInvisible);
			}
		}

		castVisibility(direction, visMap, occluders, transform( direction, pos ), {0, 0});
	}

	bool VisibilityStrategy::isVisibleAt(const VisMap& visMap, Knights::EDirection from, Knights::Vec2i currentPos ) {
		auto converted = transform( from, currentPos );
		return visMap[ converted.y ][ converted.x ] == EVisibility::kVisible;
	}

	void VisibilityStrategy::setIsVisible(VisMap& visMap, Knights::EDirection from, Knights::Vec2i currentPos ) {
		auto converted = transform( from, currentPos );
		visMap[ converted.y ][ converted.x ] = EVisibility::kVisible;
	}

	Knights::Vec2i VisibilityStrategy::transform( Knights::EDirection from, Knights::Vec2i currentPos ) {

		switch( from ) {
			case Knights::EDirection::kNorth:
				return currentPos;
			case Knights::EDirection::kSouth:
				return { Knights::kMapSize - currentPos.x - 1, Knights::kMapSize - currentPos.y - 1};
			case Knights::EDirection::kEast:
				return { Knights::kMapSize - currentPos.y - 1, Knights::kMapSize - currentPos.x - 1};
			case Knights::EDirection::kWest:
				return { currentPos.y, currentPos.x};
		}
	}

	void VisibilityStrategy::castVisibility(Knights::EDirection from, VisMap &visMap, const IntMap &occluders,
	                                        Knights::Vec2i originalPos, Knights::Vec2i offset) {

		std::array<Knights::Vec2i, Knights::kMapSize + Knights::kMapSize> positions;
		int stackPos = 0;
		Knights::Vec2i currentPos;

		positions[stackPos] = originalPos;
		++stackPos;

		while (stackPos > 0) {
			--stackPos;

			currentPos = positions[ stackPos ];

			if (!isValid(transform( from, currentPos))) {
				continue;
			}

			if ( isVisibleAt( visMap, from, currentPos ) ) {
				continue;
			}

			setIsVisible( visMap, from, currentPos );

			if (isBlock(occluders, from, currentPos )) {
				continue;
			}

			auto leftDirection = Knights::EDirection::kWest;
			auto rightDirection = Knights::EDirection::kEast;
			auto rightOffset = Knights::mapOffsetForDirection(rightDirection);
			auto leftOffset = Knights::mapOffsetForDirection(leftDirection);

            //The -1 is due to the fact I will add a new element.

            int distance = ( currentPos.y - originalPos.y );
            int narrowing = 1;
#ifdef OSMESA
            if ( std::abs( distance ) >= 9 ) {
                continue;
            }
            narrowing = (distance / 2) + 1;
#endif

			if ( ( !kNarrowByDistance || ( currentPos.x - originalPos.x ) >= -std::abs(narrowing) )&& ( currentPos.x - originalPos.x ) <= 0 && stackPos < positions.size() - 1) {
				positions[stackPos] =  Knights::Vec2i{currentPos.x + leftOffset.x, currentPos.y + leftOffset.y};
				++stackPos;
			}

			if ( ( !kNarrowByDistance || ( currentPos.x - originalPos.x ) <= std::abs(narrowing) ) && ( currentPos.x - originalPos.x ) >= 0 && stackPos < positions.size() - 1) {
				positions[stackPos] =  Knights::Vec2i{currentPos.x + rightOffset.x, currentPos.y + rightOffset.y};
				++stackPos;
			}

            if (  distance <= 0 && stackPos < positions.size() - 1) {
                auto mapOffset = Knights::mapOffsetForDirection(Knights::EDirection::kNorth);
                positions[stackPos] =  Knights::Vec2i{currentPos.x + mapOffset.x, currentPos.y + mapOffset.y};
                ++stackPos;
            }

		}
	}

    void VisibilityStrategy::makeAllVisible(VisMap& map) {
		for ( int y = 0; y < Knights::kMapSize; ++y ) {
			for ( int x = 0; x < Knights::kMapSize; ++x ) {
				map[ y ][ x ] = EVisibility::kVisible;
			}
		}
    }
}
<|endoftext|>


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

// Methods for keeping track of quadtree bounds and writing them to a JSON file.

#include "fusion/portableglobe/shared/bounds_tracker.h"
#include <fstream>  // NOLINT(readability/streams)
#include <iostream>  // NOLINT(readability/streams)
#include <string>
#include "common/khFileUtils.h"
#include "common/khSimpleException.h"
#include "fusion/portableglobe/quadtree/qtutils.h"
#include "fusion/portableglobe/shared/packetbundle.h"

namespace fusion_portableglobe {

BoundsTracker::BoundsTracker() {}

void BoundsTracker::update(uint16_t channel_id, PacketType type, const std::string& qtpath) {
  std::string real_path = "0" + qtpath;

  uint32_t column, row, zoom;
  ConvertFromQtNode(real_path, &column, &row, &zoom);

  uint32_t level = qtpath.size();

  if (channels.count(channel_id) == 0) {
    channels[channel_id] = {channel_id, type, row, column, level};

  } else {
    channel_info& channel = channels[channel_id];

    // BoundsTracker only tracks bounds at the maximum zoom level (max_level)
    if (level < channel.min_level) {
      channel.min_level = level;

      // If this node is at a new max_level then set max_level and also update the bounds
      // to be the current row and column.
    } else if (level > channel.max_level) {
      channel.max_level = level;
      channel.left = channel.right = column;
      channel.top = channel.bottom = row;

      // A new node at max_level, so expand the bounding box if necessary.
    } else if (level == channel.max_level) {
      channel.left = std::min(column, channel.left);
      channel.right = std::max(column, channel.right);
      channel.top = std::min(row, channel.top);
      channel.bottom = std::max(row, channel.bottom);
    }
  }
}

void BoundsTracker::write_json_file(const std::string& filename) const {
  khEnsureParentDir(filename);

  static std::map<PacketType, std::string> channel_type_strings =
    {{ kDbRootPacket,  "DbRoot"},
     { kDbRoot2Packet, "DbRoot2"},
     { kQtpPacket,     "Qtp"},
     { kQtp2Packet,    "Qtp2"},
     { kImagePacket,   "Image"},
     { kTerrainPacket, "Terrain"},
     { kVectorPacket,  "Vector"}};

  std::ofstream fout(filename.c_str());

  // Find the last entry so the last comma can be skipped
  auto last_entry = channels.end();
  --last_entry;

  fout << "[\n";
  for (auto iter =  channels.begin(); iter != channels.end(); ++iter) {

    const std::pair<uint16_t, channel_info> channel_pair = *iter;
    const auto &channel = channel_pair.second;

    fout << "  {\n"
         << "    \"channel_id\": "      << channel.channel_id << ",\n"
         << "    \"type\": \""          << channel_type_strings[channel.type] << "\"\n"
         << "    \"top\": "             << channel.top << ",\n"
         << "    \"bottom\": "          << channel.bottom << ",\n"
         << "    \"left\": "            << channel.left << ",\n"
         << "    \"right\": "           << channel.right << ",\n"
         << "    \"min_image_level\": " << channel.min_level << ",\n"
         << "    \"max_image_level\": " << channel.max_level << ",\n"
         << "  }";

    if (iter != last_entry) {
      fout << ",";
    }
    fout << "\n";
  }
  fout << "]\n";
  fout.close();
}

const channel_info& BoundsTracker::channel(uint16_t channel_id) const {
  if (channels.count(channel_id) == 0) {
    throw khSimpleException("Channel not found in BoundsTracker: ") << channel_id;
  }
  return channels.at(channel_id);
}

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

// Methods for keeping track of quadtree bounds and writing them to a JSON file.

#include "fusion/portableglobe/shared/bounds_tracker.h"
#include <fstream>  // NOLINT(readability/streams)
#include <iostream>  // NOLINT(readability/streams)
#include <string>
#include "common/khFileUtils.h"
#include "common/khSimpleException.h"
#include "fusion/portableglobe/quadtree/qtutils.h"
#include "fusion/portableglobe/shared/packetbundle.h"

namespace fusion_portableglobe {

BoundsTracker::BoundsTracker() {}

void BoundsTracker::update(uint16_t channel_id, PacketType type, const std::string& qtpath) {
  std::string real_path = "0" + qtpath;

  uint32_t column, row, zoom;
  ConvertFromQtNode(real_path, &column, &row, &zoom);

  uint32_t level = qtpath.size();

  if (channels.count(channel_id) == 0) {
    channels[channel_id] = {channel_id, type, row, column, level};

  } else {
    channel_info& channel = channels[channel_id];

    // BoundsTracker only tracks bounds at the maximum zoom level (max_level)
    if (level < channel.min_level) {
      channel.min_level = level;

      // If this node is at a new max_level then set max_level and also update the bounds
      // to be the current row and column.
    } else if (level > channel.max_level) {
      channel.max_level = level;
      channel.left = channel.right = column;
      channel.top = channel.bottom = row;

      // A new node at max_level, so expand the bounding box if necessary.
    } else if (level == channel.max_level) {
      channel.left = std::min(column, channel.left);
      channel.right = std::max(column, channel.right);
      channel.top = std::min(row, channel.top);
      channel.bottom = std::max(row, channel.bottom);
    }
  }
}

void BoundsTracker::write_json_file(const std::string& filename) const {
  khEnsureParentDir(filename);

  static std::map<PacketType, std::string> channel_type_strings =
    {{ kDbRootPacket,  "DbRoot"},
     { kDbRoot2Packet, "DbRoot2"},
     { kQtpPacket,     "Qtp"},
     { kQtp2Packet,    "Qtp2"},
     { kImagePacket,   "Image"},
     { kTerrainPacket, "Terrain"},
     { kVectorPacket,  "Vector"}};

  std::ofstream fout(filename.c_str());

  // Find the last entry so the last comma can be skipped
  auto last_entry = channels.end();
  --last_entry;

  fout << "[\n";
  for (auto iter =  channels.begin(); iter != channels.end(); ++iter) {

    const std::pair<uint16_t, channel_info> channel_pair = *iter;
    const auto &channel = channel_pair.second;

    fout << "  {\n"
         << "    \"channel_id\": "      << channel.channel_id << ",\n"
         << "    \"type\": \""          << channel_type_strings[channel.type] << "\",\n"
         << "    \"top\": "             << channel.top << ",\n"
         << "    \"bottom\": "          << channel.bottom << ",\n"
         << "    \"left\": "            << channel.left << ",\n"
         << "    \"right\": "           << channel.right << ",\n"
         << "    \"min_level\": "       << channel.min_level << ",\n"
         << "    \"max_level\": "       << channel.max_level << "\n"
         << "  }";

    if (iter != last_entry) {
      fout << ",";
    }
    fout << "\n";
  }
  fout << "]\n";
  fout.close();
}

const channel_info& BoundsTracker::channel(uint16_t channel_id) const {
  if (channels.count(channel_id) == 0) {
    throw khSimpleException("Channel not found in BoundsTracker: ") << channel_id;
  }
  return channels.at(channel_id);
}

}  // namespace fusion_portableglobe
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <chrono>
#include <arm_neon.h>
#include <stdlib.h>
#include <inttypes.h>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <signal.h>

std::mutex m ;
std::condition_variable cv ;
std::chrono::high_resolution_clock::time_point mid ;
std::chrono::high_resolution_clock::time_point reset ;

int32x4_t va;
int32_t a ;
int32_t * ptr;
int32_t n = 2500;
int64_t size = sizeof(a)*n;
static int sig{1};
//int32_t mm = n-4;

void sig_handler(int sign) {
    free(ptr);
    exit(-1);
}

void inline boost_song() {
    using namespace std::chrono ;

    //int i{0} ;
    while( true ) {
        std::unique_lock<std::mutex> lk{m} ;
        cv.wait( lk ) ;

        while( high_resolution_clock::now() < mid ) {
            int32_t var[4] = { *(ptr), *(ptr + 2), *(ptr + 3), *(ptr + 4) };
            va = vld1q_s32(var);
            //i++;
        }
        //if(i==mm) i=0;
        std::this_thread::sleep_until( reset ) ;
    }
}

int init_memory(void) {
    ptr = (int32_t *)malloc(size);
    if( ptr == NULL ){
        std::cout << "Malloc Error\n";
        return -1;
    }
    for(int i=0; i<=n; i++){
        ptr[i] = i;
    }
    return 0;
}

void square_am_signal(float time, float frequency) {
    using namespace std::chrono ;

    std::cout << "Playing / " << time << " seconds / " << frequency << " Hz\n" ;

    seconds const sec{1} ;
    nanoseconds const nsec{ sec } ;
    using rep = nanoseconds::rep ;
    auto nsec_per_sec = nsec.count() ;

    nanoseconds const period( static_cast<rep>( nsec_per_sec / frequency) ) ;

    auto start = high_resolution_clock::now() ;
    auto const end = start + nanoseconds( static_cast<rep>(time * nsec_per_sec) ) ;

    while (high_resolution_clock::now() < end) {
        mid = start + period / 2 ;
        reset = start + period ;
        cv.notify_all() ;
        std::this_thread::sleep_until( reset ) ;
        start = reset;
    }
}

int main(){
    signal(SIGINT, sig_handler);

    init_memory();
    for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) {
        std::thread t( boost_song ) ;
        t.detach() ;
    }
    while (1) {
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2093);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.790, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2349);
        square_am_signal(0.790, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 3136);
        square_am_signal(0.790, 3136);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2093);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.790, 2093);
    }
    free(ptr);
    return 0;
}
<commit_msg>change method<commit_after>#include <iostream>
#include <iomanip>
#include <chrono>
#include <arm_neon.h>
#include <stdlib.h>
#include <inttypes.h>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <signal.h>

std::mutex m ;
std::condition_variable cv ;
std::chrono::high_resolution_clock::time_point mid ;
std::chrono::high_resolution_clock::time_point reset ;

int32x4_t va;
int32_t a ;
int32_t * ptr;
int32_t n = 2500;
int64_t size = sizeof(a)*n;
int32_t mm = n-4;

void inline sig_handler(int sign) {
    free(ptr);
    std::cout << "Received signal. aborting.\n" ;
    exit(-1);
}

void inline boost_song() {
    using namespace std::chrono ;

    int i{0} ;
    while( true ) {
        std::unique_lock<std::mutex> lk{m} ;
        cv.wait( lk ) ;

        while( high_resolution_clock::now() < mid ) {
            int32_t var[4] = { *(ptr + i), *(ptr + i + 2), *(ptr + i + 3), *(ptr + i + 4) };
            va = vld1q_s32(var);
            i++;
        }
        if(i==mm) i=0;
        std::this_thread::sleep_until( reset ) ;
    }
}

int init_memory(void) {
    ptr = (int32_t *)malloc(size);
    if( ptr == NULL ){
        std::cout << "Malloc Error\n";
        return -1;
    }
    for(int i=0; i<=n; i++){
        ptr[i] = i;
    }
    return 0;
}

void square_am_signal(float time, float frequency) {
    using namespace std::chrono ;

    std::cout << "Playing / " << time << " seconds / " << frequency << " Hz\n" ;

    seconds const sec{1} ;
    nanoseconds const nsec{ sec } ;
    using rep = nanoseconds::rep ;
    auto nsec_per_sec = nsec.count() ;

    nanoseconds const period( static_cast<rep>( nsec_per_sec / frequency) ) ;

    auto start = high_resolution_clock::now() ;
    auto const end = start + nanoseconds( static_cast<rep>(time * nsec_per_sec) ) ;

    while (high_resolution_clock::now() < end) {
        mid = start + period / 2 ;
        reset = start + period ;
        cv.notify_all() ;
        std::this_thread::sleep_until( reset ) ;
        start = reset;
    }
}

int main(){
    signal(SIGINT, sig_handler);

    init_memory();
    for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) {
        std::thread t( boost_song ) ;
        t.detach() ;
    }
    while (1) {
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2093);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.790, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2349);
        square_am_signal(0.790, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 3136);
        square_am_signal(0.790, 3136);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2093);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.790, 2093);
    }
    free(ptr);
    return 0;
}
<|endoftext|>


<commit_before>#include "SINParserTester.h"

#include "Common.h"
#include "SINTest.h"
#include "SINLogger.h"
#include "SINASTNode.h"
#include "SINConstants.h"
#include "SINBufferedOutputStream.h"
#include "SINFileOutputStream.h"
#include "SINParserAPI.h"
#include "SINTestingCommon.h"
#include "SINLoggerManager.h"
#include "SINASTTreeVisualisationVisitor.h"
#include "SINASTMITTreeVisualizerXMLProducerVisitor.h"

#define SIN_TESTS_PARSER_RUN(NAME)               SINTESTS_RUNTEST(NAME)
#define SIN_TESTS_PARSER_TESTDEF(NAME,TESTCODE)  SINTESTS_TESTDEF(NAME,TESTCODE)
#define SIN_TESTS_PARSER_TESTRUN(NAME)           SINTESTS_CALLTEST(NAME)

#ifdef _MSC_VER
	#define FILE_PATH	".\\..\\..\\..\\Tests\\SINParser_Test\\Resource\\sin_grammar_test.sin"
#else
	#define FILE_PATH	"./../../../Tests/SINParser_Test/Resource/sin_grammar_test.sin"
#endif

namespace SIN {
	namespace Tests {
		namespace Parser {
			static InstanceProxy<SIN::Logger> logger;
			static InstanceProxy<TestFactory> test_factory;

			namespace { static void __list_parsing_errors(ParserAPI const& _papi) {
				for (
					LexAndBisonParseArguments::Errors::const_iterator ite = _papi.GetErrors().begin(),
						end = _papi.GetErrors().end();
					ite != end;
					++ite
				)
					logger->Error(string_cast("Parsing error: line ") << ite->second <<
						": " << ite->first);
			}}

			SIN_TESTS_PARSER_TESTDEF(ParserFileTest,
				ParserAPI test;
				TRY(test.ParseFile(FILE_PATH) == 0);
				if (test.HasError()) {
					__list_parsing_errors(test);
					ASSERT(!test.HasError()); // certain failure here, to stop the test
				}
				ASTNode* root = test.GetAST();
				ASSERT(root != 0x00);

				FileOutputStream _fout("treeVisualisation.txt", FileOutputStream::Mode::Truncate());
				FileOutputStream _foutxml("treeVisualisation.xml", FileOutputStream::Mode::Truncate());
				BufferedOutputStream fout(_fout);
				BufferedOutputStream foutxml(_foutxml);
				ASTTreeVisualisationVisitor visitor(fout);
				ASTMITTreeVisualizerXMLProducerVisitor mitvis(foutxml);
				root->Accept(&visitor);
				root->Accept(&mitvis);
			)

			void test(InstanceProxy<TestFactory> const &tf) {
				logger = LoggerManager::SingletonGetInstance()->GetLogger("SIN::Tests::Parser");
				test_factory = tf;
				SIN_TESTS_PARSER_TESTRUN(ParserFileTest);
			}
		}	//namespace Parser
	}		//namespace Tests
}			//namspace SIN<commit_msg>Now you can do debug in SINPaserTester.<commit_after>#include "SINParserTester.h"

#include "Common.h"
#include "SINTest.h"
#include "SINLogger.h"
#include "SINASTNode.h"
#include "SINConstants.h"
#include "SINBufferedOutputStream.h"
#include "SINFileOutputStream.h"
#include "SINParserAPI.h"
#include "SINTestingCommon.h"
#include "SINLoggerManager.h"
#include "SINASTTreeVisualisationVisitor.h"
#include "SINASTMITTreeVisualizerXMLProducerVisitor.h"

#define SIN_TESTS_PARSER_RUN(NAME)               SINTESTS_RUNTEST(NAME)
#define SIN_TESTS_PARSER_TESTDEF(NAME,TESTCODE)  SINTESTS_TESTDEF(NAME,TESTCODE)
#define SIN_TESTS_PARSER_TESTRUN(NAME)           SINTESTS_CALLTEST(NAME)

#ifdef _MSC_VER
	#define FILE_PATH	".\\..\\..\\..\\Tests\\SINParser_Test\\Resource\\sin_grammar_test.sin"
#else
	#define FILE_PATH	"./../../../Tests/SINParser_Test/Resource/sin_grammar_test.sin"
#endif

namespace SIN {
	namespace Tests {
		namespace Parser {
			static InstanceProxy<SIN::Logger> logger;
			static InstanceProxy<TestFactory> test_factory;

			namespace { static void __list_parsing_errors(ParserAPI const& _papi) {
				for (
					LexAndBisonParseArguments::Errors::const_iterator ite = _papi.GetErrors().begin(),
						end = _papi.GetErrors().end();
					ite != end;
					++ite
				)
					logger->Error(string_cast("Parsing error: line ") << ite->second <<
						": " << ite->first);
			}}

			//------------------------------------------------------------------
			class ParserFileTestTest : public Test {
			public:
				ParserFileTestTest(void): Test("ParserFileTest" "Test") { }
			protected:
				virtual void TestLogic(void);
			};

			//------------------------------------------------------------------

			void ParserFileTestTest::TestLogic(void) {
				ParserAPI test;
				TRY(test.ParseFile(FILE_PATH) == 0);
				if (test.HasError()) {
					__list_parsing_errors(test);
					ASSERT(!test.HasError()); // certain failure here, to stop the test
				}
				ASTNode* root = test.GetAST();
				ASSERT(root != 0x00);

				FileOutputStream _fout("treeVisualisation.txt", FileOutputStream::Mode::Truncate());
				FileOutputStream _foutxml("treeVisualisation.xml", FileOutputStream::Mode::Truncate());
				BufferedOutputStream fout(_fout);
				BufferedOutputStream foutxml(_foutxml);
				ASTTreeVisualisationVisitor visitor(fout);
				ASTMITTreeVisualizerXMLProducerVisitor mitvis(foutxml);
				root->Accept(&visitor);
				root->Accept(&mitvis);
			}

			//------------------------------------------------------------------
			static void test_ParserFileTest(void){
				SINTESTS_RUNTEST(ParserFileTest);
			}

			//------------------------------------------------------------------

			void test(InstanceProxy<TestFactory> const &tf) {
				logger = LoggerManager::SingletonGetInstance()->GetLogger("SIN::Tests::Parser");
				test_factory = tf;
				SIN_TESTS_PARSER_TESTRUN(ParserFileTest);
			}
		}	//namespace Parser
	}		//namespace Tests
}			//namspace SIN<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    TiffVolumeConverter.h
  \author  Tom Fogal
           SCI Institute
           University of Utah
*/
#include "../3rdParty/tiff/tiffio.h"
#include "TiffVolumeConverter.h"
#include "../StdTuvokDefines.h"
#include "../Controller/MasterController.h"
#include "../Basics/SysTools.h"

#ifdef __GNUC__
# define _malloc __attribute__((malloc))
#else
# define _malloc /* nothing */
#endif

static void tv_dimensions(TIFF *, size_t dims[3]);
_malloc static BYTE* tv_read_slice(TIFF *, AbstrDebugOut &);
#if 0
// currently disabled -- mistakenly thought I was reading 4-component data for
// a while.  left in because we'll probably want to be able to convert
// 4-component data to 1-component data at some point.
_malloc static UINT32* tv_vector_to_scalar_magnitude(UINT32 *, size_t, size_t);
#endif

TiffVolumeConverter::TiffVolumeConverter()
{
  m_vConverterDesc = "TIFF Volume (Image stack)";
  m_vSupportedExt.push_back("OME.TIF");
  m_vSupportedExt.push_back("OME.TIFF");
  m_vSupportedExt.push_back("TIF");
  m_vSupportedExt.push_back("TIFF");
}

bool
TiffVolumeConverter::ConvertToRAW(const std::string& strSourceFilename,
                                  const std::string& strTempDir,
                                  MasterController* pMasterController,
                                  bool, UINT64& iHeaderSkip,
                                  UINT64& iComponentSize,
                                  UINT64& iComponentCount,
                                  bool& bConvertEndianess, bool& bSigned,
                                  bool& bIsFloat, UINTVECTOR3& vVolumeSize,
                                  FLOATVECTOR3& vVolumeAspect,
                                  std::string& strTitle,
                                  std::string& strSource,
                                  UVFTables::ElementSemanticTable& eType,
                                  std::string& strIntermediateFile,
                                  bool& bDeleteIntermediateFile)
{
  AbstrDebugOut& dbg = *(pMasterController->DebugOut());
  dbg.Message(_func_, "Attempting to convert TiffVolume: %s",
              strSourceFilename.c_str());

  TIFF *tif = TIFFOpen(strSourceFilename.c_str(), "r");
  if(tif == NULL) {
    dbg.Error(_func_, "Could not open %s", strSourceFilename.c_str());
    return false;
  }

  // Get the dimensions of the volume.
  {
    size_t dims[3];
    tv_dimensions(tif, dims);
    vVolumeSize[0] = dims[0];
    vVolumeSize[1] = dims[1];
    vVolumeSize[2] = dims[2];
    dbg.Message(_func_, "TiffVolume dimensions: %zux%zux%zu",
                dims[0], dims[1], dims[2]);
    if(dims[2] <= 1) {
      dbg.Error(_func_, "TIFF is not a volume; use "
                        "`Load Dataset from Directory' instead!");
      TIFFClose(tif);
      return false;
    }
  }
  iHeaderSkip = 0;
  /// @todo FIXME read the component size && n_components from the tag.
  // For now, assuming monochrome, 8-bit data.
  iComponentSize = 8;
  iComponentCount = 1;
  bConvertEndianess = false;
  bSigned = false;
  bIsFloat = false;
  vVolumeAspect[0] = 1;
  vVolumeAspect[1] = 1;
  vVolumeAspect[2] = 1;
  strTitle = "TIFF Volume";
  strSource = SysTools::GetFilename(strSourceFilename); // fixme, move up.
  eType = UVFTables::ES_UNDEFINED;

  strIntermediateFile = strTempDir +
                        SysTools::GetFilename(strSourceFilename) + ".binary";
  LargeRAWFile binary(strIntermediateFile);
  binary.Create(iComponentSize/8 * iComponentCount * vVolumeSize.volume());
  if(!binary.IsOpen()) {
    dbg.Error(_func_, "Could not create binary file %s",
              strIntermediateFile.c_str());
    TIFFClose(tif);
    return false;
  }
  bDeleteIntermediateFile = true;
  do {
    BYTE* slice = tv_read_slice(tif, dbg);
    if(slice) {
      binary.WriteRAW(static_cast<unsigned char*>(slice),
                      vVolumeSize[0]*vVolumeSize[1]*sizeof(BYTE));
      _TIFFfree(slice);
    } else {
      binary.Close();
      binary.Delete();
      TIFFClose(tif);
      return false;
    }
  } while(TIFFReadDirectory(tif));
  binary.Close();

  TIFFClose(tif);
  return true;
}

// unimplemented!
bool
TiffVolumeConverter::ConvertToNative(const std::string&,
                                     const std::string&,
                                     UINT64, UINT64,
                                     UINT64, bool,
                                     bool,
                                     UINTVECTOR3,
                                     FLOATVECTOR3,
                                     MasterController*,
                                     bool)
{
  return false;
}

// Reads the dimensions of the TIFF volume.  X and Y come from the dimensions
// of the first image in the stack: we assume that this stays constant
// throughout the volume.  Z comes from the number of images in the stack.
static void
tv_dimensions(TIFF *tif, size_t dims[3])
{
  UINT32 x,y;
  size_t z=0;

  TIFFSetDirectory(tif, 0);
  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &x);
  // tiff calls the height "length" for some reason.
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &y);
  do {
    ++z;
  } while(TIFFReadDirectory(tif));
  TIFFSetDirectory(tif, 0);

  dims[0] = x;
  dims[1] = y;
  dims[2] = z;
}

_malloc static BYTE*
tv_read_slice(TIFF *tif, AbstrDebugOut& dbg)
{
  BYTE *slice;
  UINT32 width;
  UINT32 height;
  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);

  dbg.Message(_func_, "Reading %ux%u TIFF slice.", width, height);
  slice = static_cast<BYTE*>(_TIFFmalloc((width*height) * sizeof(BYTE)));
  if(slice == NULL) {
    dbg.Error(_func_, "TIFFmalloc failed.");
    return NULL;
  }
  const tstrip_t n_strips = TIFFNumberOfStrips(tif);
  {
    BYTE *data = slice;
    tdata_t buf = static_cast<tdata_t>(_TIFFmalloc(TIFFStripSize(tif)));
    for(tstrip_t s=0; s < n_strips; ++s) {
      /// @todo FIXME: don't assume the strip is raw; could be encoded.
      /// There's a `compression scheme' tag which probably details this.
      tsize_t n_bytes = TIFFReadRawStrip(tif, s, buf,
                                         static_cast<tsize_t>(-1));
      memcpy(data, buf, n_bytes);
      data += TIFFStripSize(tif);
    }
    _TIFFfree(buf);
  }

  return slice;
}

#if 0
// Converts an RGBA vector `field' to a scalar field of the "vector"'s
// magnitude.  Ignores the alpha component.
_malloc static UINT32*
tv_vector_to_scalar_magnitude(UINT32 *field, size_t w, size_t h)
{
  UINT32* ret = new UINT32[w*h];
  for(size_t i=0; i < w*h; ++i) {
    unsigned char r = field[i] & 0xFF000000;
    unsigned char g = field[i] & 0x00FF0000;
    unsigned char b = field[i] & 0x0000FF00;
    ret[i] = (static_cast<UINT32>(r) +
              static_cast<UINT32>(g) +
              static_cast<UINT32>(b)) / 3;
  }
  return ret;
}
#endif
<commit_msg>Cleanup the TiffVolume code a bit.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    TiffVolumeConverter.h
  \author  Tom Fogal
           SCI Institute
           University of Utah
*/
#include "TiffVolumeConverter.h"
#include "../3rdParty/boost/cstdint.hpp"
#include "../3rdParty/tiff/tiffio.h"
#include "../StdTuvokDefines.h"
#include "../Controller/MasterController.h"
#include "../Basics/SysTools.h"

#ifdef __GNUC__
# define _malloc __attribute__((malloc))
#else
# define _malloc /* nothing */
#endif

static void tv_dimensions(TIFF *, size_t dims[3]);
_malloc static BYTE* tv_read_slice(TIFF *, AbstrDebugOut &);
#if 0
// currently disabled -- mistakenly thought I was reading 4-component data for
// a while.  left in because we'll probably want to be able to convert
// 4-component data to 1-component data at some point.
_malloc static UINT32* tv_vector_to_scalar_magnitude(UINT32 *, size_t, size_t);
#endif

TiffVolumeConverter::TiffVolumeConverter()
{
  m_vConverterDesc = "TIFF Volume (Image stack)";
  m_vSupportedExt.push_back("OME.TIF");
  m_vSupportedExt.push_back("OME.TIFF");
  m_vSupportedExt.push_back("TIF");
  m_vSupportedExt.push_back("TIFF");
}

// converts a TiffVolume to a `raw' file.  We'll read through the TIFF
// slice-by-slice, copying each slice to the raw file.
bool
TiffVolumeConverter::ConvertToRAW(const std::string& strSourceFilename,
                                  const std::string& strTempDir,
                                  MasterController* pMasterController,
                                  bool, UINT64& iHeaderSkip,
                                  UINT64& iComponentSize,
                                  UINT64& iComponentCount,
                                  bool& bConvertEndianess, bool& bSigned,
                                  bool& bIsFloat, UINTVECTOR3& vVolumeSize,
                                  FLOATVECTOR3& vVolumeAspect,
                                  std::string& strTitle,
                                  std::string& strSource,
                                  UVFTables::ElementSemanticTable& eType,
                                  std::string& strIntermediateFile,
                                  bool& bDeleteIntermediateFile)
{
  AbstrDebugOut& dbg = *(pMasterController->DebugOut());
  dbg.Message(_func_, "Attempting to convert TiffVolume: %s",
              strSourceFilename.c_str());

  TIFF *tif = TIFFOpen(strSourceFilename.c_str(), "r");
  if(tif == NULL) {
    dbg.Error(_func_, "Could not open %s", strSourceFilename.c_str());
    return false;
  }

  // Get the dimensions of the volume.
  {
    size_t dims[3];
    tv_dimensions(tif, dims);
    vVolumeSize[0] = dims[0];
    vVolumeSize[1] = dims[1];
    vVolumeSize[2] = dims[2];
    dbg.Message(_func_, "TiffVolume dimensions: %zux%zux%zu",
                dims[0], dims[1], dims[2]);
    if(dims[2] <= 1) {
      dbg.Error(_func_, "TIFF is not a volume; use "
                        "`Load Dataset from Directory' instead!");
      TIFFClose(tif);
      return false;
    }
  }
  iHeaderSkip = 0;

  // read the number of bits per component from the tiff tag.
  {
    boost::uint16_t bits_per_sample;
    TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);
    iComponentSize = bits_per_sample;
    dbg.Message(_func_, "%ld bits per component.", iComponentSize);
  }
  // likewise for the number of components / pixel.
  {
    boost::uint16_t components;
    TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &components);
    iComponentCount = components;
    dbg.Message(_func_, "%ld component%s.", iComponentCount,
                (components == 1) ? "" : "s");
  }
  // IIRC libtiff handles all the endian issues for us.
  bConvertEndianess = false;

  // This group might be bugs; not quite sure where to read these from.  In any
  // case, we don't have any data which does not have these properties.
  bSigned = false;
  bIsFloat = false;
  vVolumeAspect[0] = 1;
  vVolumeAspect[1] = 1;
  vVolumeAspect[2] = 1;

  strTitle = "TIFF Volume";
  // @todo FIXME: this assignment to be the same in every reader, should be
  // moved to the caller or parent:
  strSource = SysTools::GetFilename(strSourceFilename);
  eType = UVFTables::ES_UNDEFINED;

  // Create an intermediate file to hold the data.
  strIntermediateFile = strTempDir +
                        SysTools::GetFilename(strSourceFilename) + ".binary";
  LargeRAWFile binary(strIntermediateFile);
  binary.Create(iComponentSize/8 * iComponentCount * vVolumeSize.volume());
  if(!binary.IsOpen()) {
    dbg.Error(_func_, "Could not create binary file %s",
              strIntermediateFile.c_str());
    TIFFClose(tif);
    return false;
  }
  bDeleteIntermediateFile = true;
  // Populate the intermediate file.  We'll do this slice-by-slice, which isn't
  // kosher for Tuvok semantics -- a slice could technically be larger than
  // INCORESIZE.  But it won't be.
  do {
    BYTE* slice = tv_read_slice(tif, dbg);
    if(slice) {
      // assuming 8-bit monochrome data here, which might not always be valid.
      binary.WriteRAW(static_cast<unsigned char*>(slice),
                      vVolumeSize[0]*vVolumeSize[1]*sizeof(BYTE));
      _TIFFfree(slice);
    } else {
      binary.Close();
      binary.Delete();
      TIFFClose(tif);
      return false;
    }
  } while(TIFFReadDirectory(tif));
  binary.Close();

  TIFFClose(tif);
  return true;
}

// unimplemented!
bool
TiffVolumeConverter::ConvertToNative(const std::string&,
                                     const std::string&,
                                     UINT64, UINT64,
                                     UINT64, bool,
                                     bool,
                                     UINTVECTOR3,
                                     FLOATVECTOR3,
                                     MasterController*,
                                     bool)
{
  return false;
}

// Reads the dimensions of the TIFF volume.  X and Y come from the dimensions
// of the first image in the stack: we assume that this stays constant
// throughout the volume.  Z comes from the number of images in the stack.
static void
tv_dimensions(TIFF *tif, size_t dims[3])
{
  UINT32 x,y;
  size_t z=0;

  TIFFSetDirectory(tif, 0);
  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &x);
  // tiff calls the height "length" for some reason.
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &y);
  do {
    ++z;
  } while(TIFFReadDirectory(tif));
  TIFFSetDirectory(tif, 0);

  dims[0] = x;
  dims[1] = y;
  dims[2] = z;
}

_malloc static BYTE*
tv_read_slice(TIFF *tif, AbstrDebugOut& dbg)
{
  BYTE *slice;
  UINT32 width;
  UINT32 height;
  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);

  dbg.Message(_func_, "Reading %ux%u TIFF slice.", width, height);
  slice = static_cast<BYTE*>(_TIFFmalloc((width*height) * sizeof(BYTE)));
  if(slice == NULL) {
    dbg.Error(_func_, "TIFFmalloc failed.");
    return NULL;
  }
  const tstrip_t n_strips = TIFFNumberOfStrips(tif);
  {
    BYTE *data = slice;
    tdata_t buf = static_cast<tdata_t>(_TIFFmalloc(TIFFStripSize(tif)));
    for(tstrip_t s=0; s < n_strips; ++s) {
      /// @todo FIXME: don't assume the strip is raw; could be encoded.
      /// There's a `compression scheme' tag which probably details this.
      tsize_t n_bytes = TIFFReadRawStrip(tif, s, buf,
                                         static_cast<tsize_t>(-1));
      memcpy(data, buf, n_bytes);
      data += TIFFStripSize(tif);
    }
    _TIFFfree(buf);
  }

  return slice;
}

#if 0
// Converts an RGBA vector `field' to a scalar field of the "vector"'s
// magnitude.  Ignores the alpha component.
_malloc static UINT32*
tv_vector_to_scalar_magnitude(UINT32 *field, size_t w, size_t h)
{
  UINT32* ret = new UINT32[w*h];
  for(size_t i=0; i < w*h; ++i) {
    unsigned char r = field[i] & 0xFF000000;
    unsigned char g = field[i] & 0x00FF0000;
    unsigned char b = field[i] & 0x0000FF00;
    ret[i] = (static_cast<UINT32>(r) +
              static_cast<UINT32>(g) +
              static_cast<UINT32>(b)) / 3;
  }
  return ret;
}
#endif
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002-2012, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////

//---------------------------------------------------------------------
//
//	Constructors and destructors for our exception base class.
//
//---------------------------------------------------------------------

#include "IexExport.h"
#include "IexBaseExc.h"
#include "IexMacros.h"

#ifdef PLATFORM_WINDOWS
#include <windows.h>
#endif

IEX_INTERNAL_NAMESPACE_SOURCE_ENTER

namespace {

StackTracer currentStackTracer = 0;

} // namespace

void
setStackTracer (StackTracer stackTracer)
{
    currentStackTracer = stackTracer;
}

StackTracer
stackTracer ()
{
    return currentStackTracer;
}

BaseExc::BaseExc (const char* s) throw () :
    std::string (s? s: ""),
    _stackTrace (currentStackTracer? currentStackTracer(): "")
{
    // empty
}

BaseExc::BaseExc (const std::string &s) throw () :
    std::string (s),
    _stackTrace (currentStackTracer? currentStackTracer(): "")
{
    // empty
}

BaseExc::BaseExc (std::stringstream &s) throw () :
    std::string (s.str()),
    _stackTrace (currentStackTracer? currentStackTracer(): "")
{
    // empty
}

BaseExc::BaseExc (const BaseExc &be) throw () :
    std::string (be),
    _stackTrace (be._stackTrace)
{
    // empty
}

BaseExc::~BaseExc () throw ()
{
    // empty
}

const char *
BaseExc::what () const throw ()
{
    return c_str();
}

BaseExc &
BaseExc::assign (std::stringstream &s)
{
    std::string::assign (s.str());
    return *this;
}

BaseExc &
BaseExc::append (std::stringstream &s)
{
    std::string::append (s.str());
    return *this;
}

IEX_INTERNAL_NAMESPACE_SOURCE_EXIT

#ifdef PLATFORM_WINDOWS

#pragma optimize("", off)
void
iex_debugTrap()
{
    if (0 != getenv("IEXDEBUGTHROW"))
        DebugBreak();
}
#else
void
iex_debugTrap()
{
    // how to in Linux?
}
#endif
<commit_msg>Adding linux debug trap code.<commit_after>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002-2012, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////

//---------------------------------------------------------------------
//
//	Constructors and destructors for our exception base class.
//
//---------------------------------------------------------------------

#include "IexExport.h"
#include "IexBaseExc.h"
#include "IexMacros.h"

#ifdef PLATFORM_WINDOWS
#include <windows.h>
#endif

IEX_INTERNAL_NAMESPACE_SOURCE_ENTER

namespace {

StackTracer currentStackTracer = 0;

} // namespace

void
setStackTracer (StackTracer stackTracer)
{
    currentStackTracer = stackTracer;
}

StackTracer
stackTracer ()
{
    return currentStackTracer;
}

BaseExc::BaseExc (const char* s) throw () :
    std::string (s? s: ""),
    _stackTrace (currentStackTracer? currentStackTracer(): "")
{
    // empty
}

BaseExc::BaseExc (const std::string &s) throw () :
    std::string (s),
    _stackTrace (currentStackTracer? currentStackTracer(): "")
{
    // empty
}

BaseExc::BaseExc (std::stringstream &s) throw () :
    std::string (s.str()),
    _stackTrace (currentStackTracer? currentStackTracer(): "")
{
    // empty
}

BaseExc::BaseExc (const BaseExc &be) throw () :
    std::string (be),
    _stackTrace (be._stackTrace)
{
    // empty
}

BaseExc::~BaseExc () throw ()
{
    // empty
}

const char *
BaseExc::what () const throw ()
{
    return c_str();
}

BaseExc &
BaseExc::assign (std::stringstream &s)
{
    std::string::assign (s.str());
    return *this;
}

BaseExc &
BaseExc::append (std::stringstream &s)
{
    std::string::append (s.str());
    return *this;
}

IEX_INTERNAL_NAMESPACE_SOURCE_EXIT

#ifdef PLATFORM_WINDOWS

#pragma optimize("", off)
void
iex_debugTrap()
{
    if (0 != getenv("IEXDEBUGTHROW"))
        ::DebugBreak();
}
#else
void
iex_debugTrap()
{
    // how to in Linux?
    if (0 != ::getenv("IEXDEBUGTHROW"))
        __builtin_trap();
}
#endif
<|endoftext|>


<commit_before>#include "test_env.h"

int called = 0;

extern "C" void mbed_main() {
    printf("This should be called before main.\n");
    called = 1;
}

int main() {
    printf("main() starts now.\n");
    notify_completion(called == 1);
}
<commit_msg>Minor modifications to mbed_main call testcase<commit_after>#include "test_env.h"

namespace {
    bool mbed_main_called = false;
}

extern "C" void mbed_main() {
    printf("MBED: mbed_main() call before main()\r\n");
    mbed_main_called = true;
}

int main() {
    printf("MBED: main() starts now!\r\n");
    notify_completion(mbed_main_called);
}
<|endoftext|>