<commit_before>#include <ros/ros.h>
#include <chrono>
#include <cstdlib>
#include <string>
#include <thread>

#include "ur_modern_driver/log.h"
#include "ur_modern_driver/pipeline.h"
#include "ur_modern_driver/ros/action_server.h"
#include "ur_modern_driver/ros/controller.h"
#include "ur_modern_driver/ros/io_service.h"
#include "ur_modern_driver/ros/mb_publisher.h"
#include "ur_modern_driver/ros/rt_publisher.h"
#include "ur_modern_driver/ros/service_stopper.h"
#include "ur_modern_driver/ros/trajectory_follower.h"
#include "ur_modern_driver/ur/commander.h"
#include "ur_modern_driver/ur/factory.h"
#include "ur_modern_driver/ur/messages.h"
#include "ur_modern_driver/ur/parser.h"
#include "ur_modern_driver/ur/producer.h"
#include "ur_modern_driver/ur/rt_state.h"
#include "ur_modern_driver/ur/state.h"

static const std::string IP_ADDR_ARG("~robot_ip_address");
static const std::string REVERSE_PORT_ARG("~reverse_port");
static const std::string ROS_CONTROL_ARG("~use_ros_control");
static const std::string MAX_VEL_CHANGE_ARG("~max_vel_change");
static const std::string PREFIX_ARG("~prefix");
static const std::string BASE_FRAME_ARG("~base_frame");
static const std::string TOOL_FRAME_ARG("~tool_frame");
static const std::string TCP_LINK_ARG("~tcp_link");
static const std::string JOINT_NAMES_PARAM("hardware_interface/joints");

static const std::vector<std::string> DEFAULT_JOINTS = { "shoulder_pan_joint", "shoulder_lift_joint", "elbow_joint",
                                                         "wrist_1_joint",      "wrist_2_joint",       "wrist_3_joint" };

static const int UR_SECONDARY_PORT = 30002;
static const int UR_RT_PORT = 30003;

struct ProgArgs
{
public:
  std::string host;
  std::string prefix;
  std::string base_frame;
  std::string tool_frame;
  std::string tcp_link;
  std::vector<std::string> joint_names;
  double max_acceleration;
  double max_velocity;
  double max_vel_change;
  int32_t reverse_port;
  bool use_ros_control;
};

bool parse_args(ProgArgs &args)
{
  if (!ros::param::get(IP_ADDR_ARG, args.host))
  {
    LOG_ERROR("robot_ip_address parameter must be set!");
    return false;
  }
  ros::param::param(REVERSE_PORT_ARG, args.reverse_port, int32_t(50001));
  ros::param::param(MAX_VEL_CHANGE_ARG, args.max_vel_change, 15.0);  // rad/s
  ros::param::param(MAX_VEL_CHANGE_ARG, args.max_velocity, 10.0);
  ros::param::param(ROS_CONTROL_ARG, args.use_ros_control, false);
  ros::param::param(PREFIX_ARG, args.prefix, std::string());
  ros::param::param(BASE_FRAME_ARG, args.base_frame, args.prefix + "base_link");
  ros::param::param(TOOL_FRAME_ARG, args.tool_frame, args.prefix + "tool0_controller");
  ros::param::param(TCP_LINK_ARG, args.tcp_link, args.prefix + "ee_link");
  ros::param::param(JOINT_NAMES_PARAM, args.joint_names, DEFAULT_JOINTS);
  return true;
}

std::string getLocalIPAccessibleFromHost(std::string &host)
{
  URStream stream(host, UR_RT_PORT);
  return stream.connect() ? stream.getIP() : std::string();
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "ur_driver");

  ProgArgs args;
  if (!parse_args(args))
  {
    return EXIT_FAILURE;
  }

  //Add prefix to joint names
  std::transform (args.joint_names.begin(), args.joint_names.end(), args.joint_names.begin(),
        [&args](std::string name){return args.prefix + name;});

  std::string local_ip(getLocalIPAccessibleFromHost(args.host));

  URFactory factory(args.host);
  vector<Service *> services;

  // RT packets
  auto rt_parser = factory.getRTParser();
  URStream rt_stream(args.host, UR_RT_PORT);
  URProducer<RTPacket> rt_prod(rt_stream, *rt_parser);
  RTPublisher rt_pub(args.prefix, args.base_frame, args.tool_frame, args.use_ros_control);
  auto rt_commander = factory.getCommander(rt_stream);
  vector<IConsumer<RTPacket> *> rt_vec{ &rt_pub };

  TrajectoryFollower traj_follower(*rt_commander, local_ip, args.reverse_port, factory.isVersion3());

  ROSController *controller(nullptr);
  ActionServer *action_server(nullptr);
  if (args.use_ros_control)
  {
    LOG_INFO("ROS control enabled");
    controller = new ROSController(*rt_commander, traj_follower, args.joint_names, args.max_vel_change, args.tcp_link);
    rt_vec.push_back(controller);
    services.push_back(controller);
  }
  else
  {
    LOG_INFO("ActionServer enabled");
    action_server = new ActionServer(traj_follower, args.joint_names, args.max_velocity);
    rt_vec.push_back(action_server);
    services.push_back(action_server);
  }

  MultiConsumer<RTPacket> rt_cons(rt_vec);
  Pipeline<RTPacket> rt_pl(rt_prod, rt_cons);

  // Message packets
  auto state_parser = factory.getStateParser();
  URStream state_stream(args.host, UR_SECONDARY_PORT);
  URProducer<StatePacket> state_prod(state_stream, *state_parser);
  MBPublisher state_pub;

  ServiceStopper service_stopper(services);

  vector<IConsumer<StatePacket> *> state_vec{ &state_pub, &service_stopper };
  MultiConsumer<StatePacket> state_cons(state_vec);
  Pipeline<StatePacket> state_pl(state_prod, state_cons);

  LOG_INFO("Starting main loop");

  rt_pl.run();
  state_pl.run();

  auto state_commander = factory.getCommander(state_stream);
  IOService io_service(*state_commander);

  if (action_server)
    action_server->start();

  ros::spin();

  LOG_INFO("ROS stopping, shutting down pipelines");

  rt_pl.stop();
  state_pl.stop();

  if (controller)
    delete controller;

  LOG_INFO("Pipelines shutdown complete");

  return EXIT_SUCCESS;
}
<commit_msg>Fixed default tcp_link value<commit_after>#include <ros/ros.h>
#include <chrono>
#include <cstdlib>
#include <string>
#include <thread>

#include "ur_modern_driver/log.h"
#include "ur_modern_driver/pipeline.h"
#include "ur_modern_driver/ros/action_server.h"
#include "ur_modern_driver/ros/controller.h"
#include "ur_modern_driver/ros/io_service.h"
#include "ur_modern_driver/ros/mb_publisher.h"
#include "ur_modern_driver/ros/rt_publisher.h"
#include "ur_modern_driver/ros/service_stopper.h"
#include "ur_modern_driver/ros/trajectory_follower.h"
#include "ur_modern_driver/ur/commander.h"
#include "ur_modern_driver/ur/factory.h"
#include "ur_modern_driver/ur/messages.h"
#include "ur_modern_driver/ur/parser.h"
#include "ur_modern_driver/ur/producer.h"
#include "ur_modern_driver/ur/rt_state.h"
#include "ur_modern_driver/ur/state.h"

static const std::string IP_ADDR_ARG("~robot_ip_address");
static const std::string REVERSE_PORT_ARG("~reverse_port");
static const std::string ROS_CONTROL_ARG("~use_ros_control");
static const std::string MAX_VEL_CHANGE_ARG("~max_vel_change");
static const std::string PREFIX_ARG("~prefix");
static const std::string BASE_FRAME_ARG("~base_frame");
static const std::string TOOL_FRAME_ARG("~tool_frame");
static const std::string TCP_LINK_ARG("~tcp_link");
static const std::string JOINT_NAMES_PARAM("hardware_interface/joints");

static const std::vector<std::string> DEFAULT_JOINTS = { "shoulder_pan_joint", "shoulder_lift_joint", "elbow_joint",
                                                         "wrist_1_joint",      "wrist_2_joint",       "wrist_3_joint" };

static const int UR_SECONDARY_PORT = 30002;
static const int UR_RT_PORT = 30003;

struct ProgArgs
{
public:
  std::string host;
  std::string prefix;
  std::string base_frame;
  std::string tool_frame;
  std::string tcp_link;
  std::vector<std::string> joint_names;
  double max_acceleration;
  double max_velocity;
  double max_vel_change;
  int32_t reverse_port;
  bool use_ros_control;
};

bool parse_args(ProgArgs &args)
{
  if (!ros::param::get(IP_ADDR_ARG, args.host))
  {
    LOG_ERROR("robot_ip_address parameter must be set!");
    return false;
  }
  ros::param::param(REVERSE_PORT_ARG, args.reverse_port, int32_t(50001));
  ros::param::param(MAX_VEL_CHANGE_ARG, args.max_vel_change, 15.0);  // rad/s
  ros::param::param(MAX_VEL_CHANGE_ARG, args.max_velocity, 10.0);
  ros::param::param(ROS_CONTROL_ARG, args.use_ros_control, false);
  ros::param::param(PREFIX_ARG, args.prefix, std::string());
  ros::param::param(BASE_FRAME_ARG, args.base_frame, args.prefix + "base_link");
  ros::param::param(TOOL_FRAME_ARG, args.tool_frame, args.prefix + "tool0_controller");
  ros::param::param(TCP_LINK_ARG, args.tcp_link, args.prefix + "tool0");
  ros::param::param(JOINT_NAMES_PARAM, args.joint_names, DEFAULT_JOINTS);
  return true;
}

std::string getLocalIPAccessibleFromHost(std::string &host)
{
  URStream stream(host, UR_RT_PORT);
  return stream.connect() ? stream.getIP() : std::string();
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "ur_driver");

  ProgArgs args;
  if (!parse_args(args))
  {
    return EXIT_FAILURE;
  }

  //Add prefix to joint names
  std::transform (args.joint_names.begin(), args.joint_names.end(), args.joint_names.begin(),
        [&args](std::string name){return args.prefix + name;});

  std::string local_ip(getLocalIPAccessibleFromHost(args.host));

  URFactory factory(args.host);
  vector<Service *> services;

  // RT packets
  auto rt_parser = factory.getRTParser();
  URStream rt_stream(args.host, UR_RT_PORT);
  URProducer<RTPacket> rt_prod(rt_stream, *rt_parser);
  RTPublisher rt_pub(args.prefix, args.base_frame, args.tool_frame, args.use_ros_control);
  auto rt_commander = factory.getCommander(rt_stream);
  vector<IConsumer<RTPacket> *> rt_vec{ &rt_pub };

  TrajectoryFollower traj_follower(*rt_commander, local_ip, args.reverse_port, factory.isVersion3());

  ROSController *controller(nullptr);
  ActionServer *action_server(nullptr);
  if (args.use_ros_control)
  {
    LOG_INFO("ROS control enabled");
    controller = new ROSController(*rt_commander, traj_follower, args.joint_names, args.max_vel_change, args.tcp_link);
    rt_vec.push_back(controller);
    services.push_back(controller);
  }
  else
  {
    LOG_INFO("ActionServer enabled");
    action_server = new ActionServer(traj_follower, args.joint_names, args.max_velocity);
    rt_vec.push_back(action_server);
    services.push_back(action_server);
  }

  MultiConsumer<RTPacket> rt_cons(rt_vec);
  Pipeline<RTPacket> rt_pl(rt_prod, rt_cons);

  // Message packets
  auto state_parser = factory.getStateParser();
  URStream state_stream(args.host, UR_SECONDARY_PORT);
  URProducer<StatePacket> state_prod(state_stream, *state_parser);
  MBPublisher state_pub;

  ServiceStopper service_stopper(services);

  vector<IConsumer<StatePacket> *> state_vec{ &state_pub, &service_stopper };
  MultiConsumer<StatePacket> state_cons(state_vec);
  Pipeline<StatePacket> state_pl(state_prod, state_cons);

  LOG_INFO("Starting main loop");

  rt_pl.run();
  state_pl.run();

  auto state_commander = factory.getCommander(state_stream);
  IOService io_service(*state_commander);

  if (action_server)
    action_server->start();

  ros::spin();

  LOG_INFO("ROS stopping, shutting down pipelines");

  rt_pl.stop();
  state_pl.stop();

  if (controller)
    delete controller;

  LOG_INFO("Pipelines shutdown complete");

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "cons_util.hh"
#include "env.hh"
#include "s_closure.hh"
#include "zs_error.hh"

SyntacticClosure::SyntacticClosure(Env* e, Lisp_ptr f, Lisp_ptr ex)
  : env_(e), free_names_(f), expr_(ex){
  for(auto i : f){
    if(!identifierp(i)){
      throw_zs_error(i, "syntactic closure: free-list has a non-identifier value");
    }
  }
}

SyntacticClosure::~SyntacticClosure() = default;

// checks recursively
bool identifierp(Lisp_ptr p){
  if(p.tag() == Ptr_tag::symbol){
    return true;
  }else if(p.tag() == Ptr_tag::syntactic_closure){
    return identifierp(p.get<SyntacticClosure*>()->expr());
  }else{
    return false;
  }
}

bool identifier_eq(Env* ident1_env, Lisp_ptr ident1,
                   Env* ident2_env, Lisp_ptr ident2){
  return eq_internal(ident1_env->find(ident1).first,
                     ident2_env->find(ident2).first);
}
<commit_msg>cleanup s_closure<commit_after>#include "cons_util.hh"
#include "env.hh"
#include "s_closure.hh"
#include "zs_error.hh"

SyntacticClosure::SyntacticClosure(Env* e, Lisp_ptr f, Lisp_ptr ex)
  : env_(e), free_names_(f), expr_(ex){
  for(auto i : f){
    check_identifier_type(i);
  }
}

SyntacticClosure::~SyntacticClosure() = default;

// checks recursively
bool identifierp(Lisp_ptr p){
  if(p.tag() == Ptr_tag::symbol){
    return true;
  }else if(p.tag() == Ptr_tag::syntactic_closure){
    return identifierp(p.get<SyntacticClosure*>()->expr());
  }else{
    return false;
  }
}

bool identifier_eq(Env* ident1_env, Lisp_ptr ident1,
                   Env* ident2_env, Lisp_ptr ident2){
  return eq_internal(ident1_env->find(ident1).first,
                     ident2_env->find(ident2).first);
}
<|endoftext|>


<commit_before>#pragma once
/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _SRC_SIGNAL_P_HPP_
#define _SRC_SIGNAL_P_HPP_

#include <qitype/signal.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/recursive_mutex.hpp>

namespace qi {

  typedef std::map<SignalBase::Link, SignalSubscriberPtr> SignalSubscriberMap;

  class SignalBasePrivate
  {
  public:
    bool disconnect(const SignalBase::Link& l);
    bool reset();

  public:
    SignalBase::OnSubscribers      onSubscribers;
    SignalSubscriberMap            subscriberMap;
    std::string                    signature;
    boost::recursive_mutex         mutex;
    MetaCallType                   defaultCallType;
  };

}

#endif  // _SRC_SIGNAL_P_HPP_
<commit_msg>Signal: Fix uninitialized variable.<commit_after>#pragma once
/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _SRC_SIGNAL_P_HPP_
#define _SRC_SIGNAL_P_HPP_

#include <qitype/signal.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/recursive_mutex.hpp>

namespace qi {

  typedef std::map<SignalBase::Link, SignalSubscriberPtr> SignalSubscriberMap;

  class SignalBasePrivate
  {
  public:
    SignalBasePrivate(): defaultCallType(MetaCallType_Auto) {}
    bool disconnect(const SignalBase::Link& l);
    bool reset();

  public:
    SignalBase::OnSubscribers      onSubscribers;
    SignalSubscriberMap            subscriberMap;
    std::string                    signature;
    boost::recursive_mutex         mutex;
    MetaCallType                   defaultCallType;
  };

}

#endif  // _SRC_SIGNAL_P_HPP_
<|endoftext|>


<commit_before>#include <mapbox/geojsonvt/simplify.hpp>

#include <deque>

namespace mapbox {
namespace geojsonvt {

// calculate simplification data using optimized Douglas-Peucker algorithm

void Simplify::simplify(ProjectedPoints& points, double tolerance) {
    const double sqTolerance = tolerance * tolerance;
    const size_t len = points.size();
    size_t first = 0;
    size_t last = len - 1;
    std::deque<std::pair<size_t,size_t>> stack;
    double maxSqDist = 0;
    double sqDist = 0;
    size_t index = 0;

    // always retain the endpoints (1 is the max value)
    points[first].z = 1;
    points[last].z = 1;

    // avoid recursion by using a stack
    while (last != 0u) {

        maxSqDist = 0;

        for (size_t i = (first + 1); i < last; ++i) {
            sqDist = getSqSegDist(points[i], points[first], points[last]);

            if (sqDist > maxSqDist) {
                index = i;
                maxSqDist = sqDist;
            }
        }

        if (maxSqDist > sqTolerance) {
            // save the point importance in squared pixels as a z coordinate
            points[index].z = maxSqDist;
            stack.emplace_back(first, index);
            first = index;

        } else {
            if (!stack.empty()) {
                auto const& p = stack.back();
                first = p.first;
                last = p.second;
                stack.pop_back();
            } else {
                last = 0;
                first = 0;
            }
        }
    }
}

// square distance from a point to a segment
double
Simplify::getSqSegDist(const ProjectedPoint& p, const ProjectedPoint& a, const ProjectedPoint& b) {
    double x = a.x;
    double y = a.y;
    double dx = b.x - a.x;
    double dy = b.y - a.y;

    if ((dx != 0.0) || (dy != 0.0)) {

        const double t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy);

        if (t > 1) {
            x = b.x;
            y = b.y;

        } else if (t > 0) {
            x += dx * t;
            y += dy * t;
        }
    }

    dx = p.x - x;
    dy = p.y - y;

    return dx * dx + dy * dy;
}

} // namespace geojsonvt
} // namespace mapbox
<commit_msg>sprinkle syntactic sugar<commit_after>#include <mapbox/geojsonvt/simplify.hpp>

#include <deque>

namespace mapbox {
namespace geojsonvt {

// calculate simplification data using optimized Douglas-Peucker algorithm

void Simplify::simplify(ProjectedPoints& points, double tolerance) {
    const double sqTolerance = tolerance * tolerance;
    const size_t len = points.size();
    size_t first = 0;
    size_t last = len - 1;
    std::deque<std::pair<size_t,size_t>> stack;
    double maxSqDist = 0;
    double sqDist = 0;
    size_t index = 0;

    // always retain the endpoints (1 is the max value)
    points[first].z = 1;
    points[last].z = 1;

    // avoid recursion by using a stack
    while (last != 0u) {

        maxSqDist = 0;

        for (size_t i = (first + 1); i < last; ++i) {
            sqDist = getSqSegDist(points[i], points[first], points[last]);

            if (sqDist > maxSqDist) {
                index = i;
                maxSqDist = sqDist;
            }
        }

        if (maxSqDist > sqTolerance) {
            // save the point importance in squared pixels as a z coordinate
            points[index].z = maxSqDist;
            stack.emplace_back(first, index);
            first = index;

        } else {
            if (!stack.empty()) {
                std::tie(first, last) = stack.back();
                stack.pop_back();
            } else {
                last = 0;
                first = 0;
            }
        }
    }
}

// square distance from a point to a segment
double
Simplify::getSqSegDist(const ProjectedPoint& p, const ProjectedPoint& a, const ProjectedPoint& b) {
    double x = a.x;
    double y = a.y;
    double dx = b.x - a.x;
    double dy = b.y - a.y;

    if ((dx != 0.0) || (dy != 0.0)) {

        const double t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy);

        if (t > 1) {
            x = b.x;
            y = b.y;

        } else if (t > 0) {
            x += dx * t;
            y += dy * t;
        }
    }

    dx = p.x - x;
    dy = p.y - y;

    return dx * dx + dy * dy;
}

} // namespace geojsonvt
} // namespace mapbox
<|endoftext|>


<commit_before>/* Luwra
 * Minimal-overhead Lua wrapper for C++
 *
 * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
 */

#ifndef LUWRA_COMMON_H_
#define LUWRA_COMMON_H_

extern "C" {
	#include <lua.h>
	#include <lualib.h>
	#include <lauxlib.h>
}

// Check for proper Lua version
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 501 || LUA_VERSION_NUM >= 600
	#error Luwra has not been tested against your installed version of Lua
#endif

// Namespaces
#define LUWRA_NS_BEGIN namespace luwra {
#define LUWRA_NS_END }

// Version MAJOR.MINOR.PATCH
#define LUWRA_VERSION_MAJOR 0
#define LUWRA_VERSION_MINOR 2
#define LUWRA_VERSION_PATCH 0

#endif
<commit_msg>Bump version<commit_after>/* Luwra
 * Minimal-overhead Lua wrapper for C++
 *
 * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
 */

#ifndef LUWRA_COMMON_H_
#define LUWRA_COMMON_H_

extern "C" {
	#include <lua.h>
	#include <lualib.h>
	#include <lauxlib.h>
}

// Check for proper Lua version
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 501 || LUA_VERSION_NUM >= 600
	#error Luwra has not been tested against your installed version of Lua
#endif

// Namespaces
#define LUWRA_NS_BEGIN namespace luwra {
#define LUWRA_NS_END }

// Version MAJOR.MINOR.PATCH
#define LUWRA_VERSION_MAJOR 0
#define LUWRA_VERSION_MINOR 3
#define LUWRA_VERSION_PATCH 0

#endif
<|endoftext|>


<commit_before>#include "momentum.h"
#include <boost/unordered_map.hpp>
#include <iostream>
#include <semiOrderedMap.cpp>

namespace bts
{
	#define MAX_MOMENTUM_NONCE  (1<<26)
	#define SEARCH_SPACE_BITS 50
	#define BIRTHDAYS_PER_HASH 8

	std::vector< std::pair<uint32_t,uint32_t> > momentum_search( uint256 midHash )
  {
			semiOrderedMap somap;
			somap.allocate(4);
      std::vector< std::pair<uint32_t,uint32_t> > results;

      char  hash_tmp[sizeof(midHash)+4];
      memcpy((char*)&hash_tmp[4], (char*)&midHash, sizeof(midHash) );
      uint32_t* index = (uint32_t*)hash_tmp;

      for( uint32_t i = 0; i < MAX_MOMENTUM_NONCE;  )
      {
	      if(i%1048576==0){
		boost::this_thread::interruption_point();
	      }
          *index = i;
          uint64_t  result_hash[8];
          SHA512((unsigned char*)hash_tmp, sizeof(hash_tmp), (unsigned char*)result_hash);

          for( uint32_t x = 0; x < 8; ++x )
          {
              uint64_t birthday = result_hash[x] >> (64-SEARCH_SPACE_BITS);
              uint32_t nonce = i+x;
              //boost::unordered_map<uint64_t,uint32_t>::const_iterator itr = found.find( birthday );

              uint64_t foundMatch=somap.checkAdd( birthday, nonce );
              if( foundMatch != 0 ){
                  results.push_back( std::make_pair( foundMatch, nonce ) );
              }
          }
          i += BIRTHDAYS_PER_HASH;
      }
      //for( auto itr = results.begin(); itr != results.end(); ++itr )
      //{
      //   assert( momentum_verify( midHash, itr->first, itr->second ) );
     // }
      //somap.destroy();
      return results;
   }

	uint64_t getBirthdayHash(const uint256& midHash, uint32_t a)
  {
    uint32_t index = a - (a%8);
    char  hash_tmp[sizeof(midHash)+4];
  //  std::cerr<<"midHash size:" <<sizeof(midHash)<<"\n";
    memcpy(&hash_tmp[4], (char*)&midHash, sizeof(midHash) );
    memcpy(&hash_tmp[0], (char*)&index, sizeof(index) );

    uint64_t  result_hash[8];
//      for( uint32_t i = 0; i < sizeof(hash_tmp); ++i )
 //     {
  //       std::cerr<<" "<<uint16_t((((unsigned char*)hash_tmp)[i]));
   //   }
//      std::cerr<<"\n";
		SHA512((unsigned char*)hash_tmp, sizeof(hash_tmp), (unsigned char*)&result_hash);
//    std::cerr<<"result_hash "<<a<<"  "<<a%8<<"  --- ";
 //   for( uint32_t i = 0; i < 8; ++i ) std::cerr<<result_hash[i]<<" ";
  //  std::cerr<<"\n";

    uint64_t r = result_hash[a%BIRTHDAYS_PER_HASH]>>(64-SEARCH_SPACE_BITS);
  //  std::cerr<<"bdayresult: "<<r<<"\n";
    return r;
	}

	bool momentum_verify( uint256 head, uint32_t a, uint32_t b ){
 //   std::cerr<<"verify  "<<a<<"  and "<<b<<"  mid: "<<head.ToString()<<"\n";
 //   std::cerr<<"    "<<getBirthdayHash(head,a)<<"   "<<getBirthdayHash(head,b)<<"\n";
		if( a == b ) return false;
		if( a > MAX_MOMENTUM_NONCE ) return false;
		if( b > MAX_MOMENTUM_NONCE ) return false;

     bool r = (getBirthdayHash(head,a) == getBirthdayHash(head,b));
  //   std::cerr<< "####### Verified "<<int(r)<<"\n";
     return r;
	}

}
<commit_msg>Initial Commit<commit_after>#include "momentum.h"
#include <boost/unordered_map.hpp>
#include <iostream>

namespace bts
{
#define MAX_MOMENTUM_NONCE  (1<<26)
#define SEARCH_SPACE_BITS 50
#define BIRTHDAYS_PER_HASH 8

std::vector< std::pair<uint32_t, uint32_t> > momentum_search(uint256 midHash)
{
    std::vector< std::pair<uint32_t, uint32_t> > results;

    char  hash_tmp[sizeof(midHash) + 4];
    memcpy((char *)&hash_tmp[4], (char *)&midHash, sizeof(midHash));
    uint32_t *index = (uint32_t *)hash_tmp;
    bool found_hit = false;

    // X
    uint32_t turtle_nonce = 0;
    uint32_t turtle_offset = 0;
    uint64_t turtle[8];

    // X'
    uint32_t hare_nonce = 0;
    uint32_t hare_offset = 0;
    uint64_t hare[8];

    // Defining X_0
    *index = 0;
    uint64_t result_hash[8];
    SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)result_hash);
    turtle = result_hash;
    hare = result_hash;

    // Dig for a hit.
    // We can optimize out the backtrack step
    //    because we're keeping track of our nonces.
    for(uint32_t i = 0; i < (1<<(SEARCH_SPACE_BITS/2) + 1); ++i) {

        // TURTLE
        // X = H(X)
        ++turtle_offset;
        if (turtle_offset >= BIRTHDAYS_PER_HASH) {
            turtle_offset = turtle_offset % BIRTHDAYS_PER_HASH;
            turtle_nonce = (turtle_nonce + BIRTHDAYS_PER_HASH) % MAX_MOMENTUM_NONCE;

            *index = turtle_nonce;
            SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)result_hash);
            turtle = result_hash;
        }

        // HARE
        // X' = H( H(X) )
        hare_offset += 2;
        if (hare_offset >= BIRTHDAYS_PER_HASH) {
            hare_offset = hare_offset % BIRTHDAYS_PER_HASH;
            hare_nonce = (hare_nonce + BIRTHDAYS_PER_HASH) % MAX_MOMENTUM_NONCE;

            *index = hare_nonce;
            SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)result_hash);
            hare = result_hash;
        }

        // Found a collision!
        if (turtle[turtle_offset] >> (64 - SEARCH_SPACE_BITS) == hare[hare_offset] >> (64 - SEARCH_SPACE_BITS) {
            fount_hit = true;
            break;
        }
    }

    // If we stopped due to running out of entries, return the empty list
    if (!found_hit) {
        std::cerr << "No collision found.\n";
        return results;
    }

    std::cerr << "Collision found!\n";
    results.push_back( std::make_pair(turtle_nonce + turtle_offset, hare_nonce + hare_offset) );
    return results;
}

uint64_t getBirthdayHash(const uint256 &midHash, uint32_t a)
{
    uint32_t index = a - (a % 8);
    char  hash_tmp[sizeof(midHash) + 4];

    memcpy(&hash_tmp[4], (char *)&midHash, sizeof(midHash));
    memcpy(&hash_tmp[0], (char *)&index, sizeof(index));

    uint64_t  result_hash[8];

    SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)&result_hash);

    uint64_t r = result_hash[a % BIRTHDAYS_PER_HASH] >> (64 - SEARCH_SPACE_BITS);

    return r;
}

bool momentum_verify(uint256 head, uint32_t a, uint32_t b)
{

    if(a == b) {
        return false;
    }

    if(a > MAX_MOMENTUM_NONCE) {
        return false;
    }

    if(b > MAX_MOMENTUM_NONCE) {
        return false;
    }

    bool r = (getBirthdayHash(head, a) == getBirthdayHash(head, b));
    return r;
}

}
<|endoftext|>


<commit_before>#include <os>
#include <net/inet.hpp>
#include <net/util.hpp>
#include <stdlib.h>

/*
uint16_t net::checksum(uint16_t* buf, uint32_t len)
{
  union sum
  {
    uint32_t whole;
    uint16_t part[2];
  } sum32{0};

  // Iterate in short int steps.
  for (uint16_t* i = buf; i < buf + len / 2; i++){
    sum32.whole += *i;
  }

  // odd-length case
  if (len & 1)
  {
    //printf("odd case\n");
    sum32.whole += ((uint8_t*) buf)[len-1];
  }

  return ~(sum32.part[0]+sum32.part[1]);
}
*/

/**
 * http://www.microhowto.info/howto/calculate_an_internet_protocol_checksum_in_c.html
 * by Graham Shaw, some rights reserved.
**/

uint16_t net::checksum(void* vdata, size_t length)
{
    // Cast the data pointer to one that can be indexed.
    char* data=(char*)vdata;

    // Initialise the accumulator.
    uint64_t acc=0xffff;

    // Handle any partial block at the start of the data.
    unsigned int offset=((uintptr_t)data)&3;
    if (offset) {
        size_t count=4-offset;
        if (count>length) count=length;
        uint32_t word=0;
        memcpy(offset+(char*)&word,data,count);
        acc+=ntohl(word);
        data+=count;
        length-=count;
    }

    // Handle any complete 32-bit blocks.
    char* data_end=data+(length&~3);
    while (data!=data_end) {
        uint32_t word;
        memcpy(&word,data,4);
        acc+=ntohl(word);
        data+=4;
    }
    length&=3;

    // Handle any partial block at the end of the data.
    if (length) {
        uint32_t word=0;
        memcpy(&word,data,length);
        acc+=ntohl(word);
    }

    // Handle deferred carries.
    acc=(acc&0xffffffff)+(acc>>32);
    while (acc>>16) {
        acc=(acc&0xffff)+(acc>>16);
    }

    // If the data began at an odd byte address
    // then reverse the byte order to compensate.
    if (offset&1) {
        acc=((acc&0xff00)>>8)|((acc&0x00ff)<<8);
    }

    // Return the checksum in network byte order.
    return htons(~acc);
}
<commit_msg>Reverted to old checksum. It's faster, see #189<commit_after>#include <os>
#include <net/inet.hpp>
#include <net/util.hpp>
#include <stdlib.h>

// Should be pretty much like the example in RFC 1071, but using a uinon for readability
uint16_t net::checksum(void* data, size_t len)
{
  uint16_t* buf = (uint16_t*)data;

  union sum
  {
    uint32_t whole;
    uint16_t part[2];
  } sum32{0};

  // Iterate in short int steps.
  for (uint16_t* i = buf; i < buf + len / 2; i++)
    sum32.whole += *i;

  // odd-length case
  if (len & 1)
    sum32.whole += ((uint8_t*) buf)[len-1];

  return ~(sum32.part[0]+sum32.part[1]);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dsselect.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 12:32:54 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBAUI_ODBC_CONFIG_HXX_
#include "odbcconfig.hxx"
#endif

#ifndef _DBAUI_DSSELECT_HXX_
#include "dsselect.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HRC_
#include "dsselect.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif

#if defined( WIN ) || defined( WNT )
#define HWND    void*
#define HMENU   void*
    // was unable to include windows.h, that's why this direct define
#endif
#ifndef _SV_SYSDATA_HXX
#include <vcl/sysdata.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCREATECATALOG_HPP_
#include <com/sun/star/sdbcx/XCreateCatalog.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::comphelper;
//==================================================================
ODatasourceSelectDialog::ODatasourceSelectDialog(Window* _pParent, const StringBag& _rDatasources, DATASOURCE_TYPE _eType,SfxItemSet* _pOutputSet)
     :ModalDialog(_pParent, ModuleRes(DLG_DATASOURCE_SELECTION))
     ,m_aDescription        (this, ResId(FT_DESCRIPTION))
     ,m_aDatasource         (this, ResId(LB_DATASOURCE))
     ,m_aOk                 (this, ResId(PB_OK))
     ,m_aCancel             (this, ResId(PB_CANCEL))
     ,m_aHelp               (this, ResId(PB_HELP))
     ,m_aManageDatasources  (this, ResId(PB_MANAGE))
     ,m_aCreateAdabasDB     (this, ResId(PB_CREATE))
     ,m_pOutputSet(_pOutputSet)
{
    if (DST_ADABAS == _eType)
    {   // set a new title (indicating that we're browsing local data sources only)
        SetText(ResId(STR_LOCAL_DATASOURCES));
        m_aDescription.SetText(ResId(STR_DESCRIPTION2));

        m_aCreateAdabasDB.Show();
        m_aCreateAdabasDB.SetClickHdl(LINK(this,ODatasourceSelectDialog,CreateDBClickHdl));

        // resize the dialog a little bit, 'cause Adabas data source names are usually somewhat shorter
        // than ODBC ones are

        // shrink the listbox
        Size aOldSize = m_aDatasource.GetSizePixel();
        Size aNewSize(3 * aOldSize.Width() / 4, aOldSize.Height());
        m_aDatasource.SetSizePixel(aNewSize);

        sal_Int32 nLostPixels = aOldSize.Width() - aNewSize.Width();

        // shrink the fixed text
        aOldSize = m_aDescription.GetSizePixel();
        m_aDescription.SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));

        // move the buttons
        PushButton* pButtons[] = { &m_aOk, &m_aCancel, &m_aHelp ,&m_aCreateAdabasDB};
        for (sal_Int32 i=0; i<sizeof(pButtons)/sizeof(pButtons[0]); ++i)
        {
            Point aOldPos = pButtons[i]->GetPosPixel();
            pButtons[i]->SetPosPixel(Point(aOldPos.X() - nLostPixels, aOldPos.Y()));
        }

        // resize the dialog itself
        aOldSize = GetSizePixel();
        SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));
    }

    fillListBox(_rDatasources);

    // allow ODBC datasource managenment
    if ( DST_ODBC == _eType || DST_MYSQL_ODBC == _eType )
    {
        m_aManageDatasources.Show();
        m_aManageDatasources.Enable();
        m_aManageDatasources.SetClickHdl(LINK(this,ODatasourceSelectDialog,ManageClickHdl));
    }

    m_aDatasource.SetDoubleClickHdl(LINK(this,ODatasourceSelectDialog,ListDblClickHdl));
    FreeResource();
}

// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ListDblClickHdl, ListBox *, pListBox )
{
    if (pListBox->GetSelectEntryCount())
        EndDialog(RET_OK);
    return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, CreateDBClickHdl, PushButton*, pButton )
{
    try
    {
        OSL_ENSURE(m_pOutputSet,"No itemset given!");
        Reference< ::com::sun::star::lang::XMultiServiceFactory > xORB = ::comphelper::getProcessServiceFactory();
        Reference<XCreateCatalog> xCatalog(xORB->createInstance(SERVICE_EXTENDED_ADABAS_DRIVER),UNO_QUERY);
        if ( xCatalog.is() && m_pOutputSet )
        {
            Sequence< Any > aArgs(2);
            aArgs[0] <<= PropertyValue(::rtl::OUString::createFromAscii("CreateCatalog"), 0,makeAny(xCatalog) , PropertyState_DIRECT_VALUE);
            aArgs[1] <<= PropertyValue(PROPERTY_PARENTWINDOW, 0, makeAny(VCLUnoHelper::GetInterface(this)), PropertyState_DIRECT_VALUE);

            Reference< XExecutableDialog > xDialog(
                xORB->createInstanceWithArguments(SERVICE_SDB_ADABASCREATIONDIALOG, aArgs), UNO_QUERY);
            if (!xDialog.is())
            {
                //  ShowServiceNotAvailableError(this, String(SERVICE_SDB_ADABASCREATIONDIALOG), sal_True);
                return 0L;
            }

            if ( xDialog->execute() == RET_OK )
            {
                Reference<XPropertySet> xProp(xDialog,UNO_QUERY);
                if(xProp.is())
                {
                    Reference<XPropertySetInfo> xPropInfo(xProp->getPropertySetInfo());
                    if(xPropInfo->hasPropertyByName(PROPERTY_DATABASENAME))
                    {
                        String sDatabaseName;
                        sDatabaseName = String(::comphelper::getString(xProp->getPropertyValue(PROPERTY_DATABASENAME)));
                        m_aDatasource.SelectEntry(m_aDatasource.InsertEntry( sDatabaseName ));

                    }
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLUSER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLUSER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLUSER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLPASSWORD) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLPWD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLPASSWORD))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_USER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_USER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_USER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_PASSWORD) )
                        m_pOutputSet->Put(SfxStringItem(DSID_PASSWORD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_PASSWORD))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CACHESIZE) )
                        m_pOutputSet->Put(SfxInt32Item(DSID_CONN_CACHESIZE, ::comphelper::getINT32(xProp->getPropertyValue(PROPERTY_CACHESIZE))));
                }
            }
        }
    }
    catch(Exception&)
    {
    }
    return 0L;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ManageClickHdl, PushButton*, pButton )
{
    OOdbcManagement aOdbcConfig;
#ifdef HAVE_ODBC_ADMINISTRATION
    if (!aOdbcConfig.isLoaded())
    {
#endif
        // show an error message
        OLocalResourceAccess aLocRes(DLG_DATASOURCE_SELECTION, RSC_MODALDIALOG);
        String sError(ModuleRes(STR_COULDNOTLOAD_CONFIGLIB));
        sError.SearchAndReplaceAscii("#lib#", aOdbcConfig.getLibraryName());
        ErrorBox aDialog(this, WB_OK, sError);
        aDialog.Execute();
        m_aDatasource.GrabFocus();
        m_aManageDatasources.Disable();
        return 1L;
#ifdef HAVE_ODBC_ADMINISTRATION
    }

    aOdbcConfig.manageDataSources(GetSystemData()->hWnd);
    // now we have to look if there are any new datasources added
    StringBag aOdbcDatasources;
    OOdbcEnumeration aEnumeration;
    aEnumeration.getDatasourceNames(aOdbcDatasources);
    fillListBox(aOdbcDatasources);

    return 0L;
#endif
}
// -----------------------------------------------------------------------------
void ODatasourceSelectDialog::fillListBox(const StringBag& _rDatasources)
{
    m_aDatasource.Clear();
    // fill the list
    for (   ConstStringBagIterator aDS = _rDatasources.begin();
            aDS != _rDatasources.end();
            ++aDS
        )
    {
        m_aDatasource.InsertEntry( *aDS );
    }

    // select the first entry
    if (m_aDatasource.GetEntryCount())
        m_aDatasource.SelectEntryPos(0);
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

<commit_msg>INTEGRATION: CWS presentationengine01 (1.8.28); FILE MERGED 2004/11/17 14:57:21 thb 1.8.28.2: RESYNC: (1.8-1.9); FILE MERGED 2004/09/22 21:30:03 cl 1.8.28.1: fixed header problem with vcl/sysdata.hxx<commit_after>/*************************************************************************
 *
 *  $RCSfile: dsselect.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-26 18:19:18 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBAUI_ODBC_CONFIG_HXX_
#include "odbcconfig.hxx"
#endif

#ifndef _DBAUI_DSSELECT_HXX_
#include "dsselect.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HRC_
#include "dsselect.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif

#if defined( WIN ) || defined( WNT )
#define HWND    void*
#define HMENU   void*
typedef void*               HDC;
    // was unable to include windows.h, that's why this direct define
#endif
#ifndef _SV_SYSDATA_HXX
#include <vcl/sysdata.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCREATECATALOG_HPP_
#include <com/sun/star/sdbcx/XCreateCatalog.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::comphelper;
//==================================================================
ODatasourceSelectDialog::ODatasourceSelectDialog(Window* _pParent, const StringBag& _rDatasources, DATASOURCE_TYPE _eType,SfxItemSet* _pOutputSet)
     :ModalDialog(_pParent, ModuleRes(DLG_DATASOURCE_SELECTION))
     ,m_aDescription        (this, ResId(FT_DESCRIPTION))
     ,m_aDatasource         (this, ResId(LB_DATASOURCE))
     ,m_aOk                 (this, ResId(PB_OK))
     ,m_aCancel             (this, ResId(PB_CANCEL))
     ,m_aHelp               (this, ResId(PB_HELP))
     ,m_aManageDatasources  (this, ResId(PB_MANAGE))
     ,m_aCreateAdabasDB     (this, ResId(PB_CREATE))
     ,m_pOutputSet(_pOutputSet)
{
    if (DST_ADABAS == _eType)
    {   // set a new title (indicating that we're browsing local data sources only)
        SetText(ResId(STR_LOCAL_DATASOURCES));
        m_aDescription.SetText(ResId(STR_DESCRIPTION2));

        m_aCreateAdabasDB.Show();
        m_aCreateAdabasDB.SetClickHdl(LINK(this,ODatasourceSelectDialog,CreateDBClickHdl));

        // resize the dialog a little bit, 'cause Adabas data source names are usually somewhat shorter
        // than ODBC ones are

        // shrink the listbox
        Size aOldSize = m_aDatasource.GetSizePixel();
        Size aNewSize(3 * aOldSize.Width() / 4, aOldSize.Height());
        m_aDatasource.SetSizePixel(aNewSize);

        sal_Int32 nLostPixels = aOldSize.Width() - aNewSize.Width();

        // shrink the fixed text
        aOldSize = m_aDescription.GetSizePixel();
        m_aDescription.SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));

        // move the buttons
        PushButton* pButtons[] = { &m_aOk, &m_aCancel, &m_aHelp ,&m_aCreateAdabasDB};
        for (sal_Int32 i=0; i<sizeof(pButtons)/sizeof(pButtons[0]); ++i)
        {
            Point aOldPos = pButtons[i]->GetPosPixel();
            pButtons[i]->SetPosPixel(Point(aOldPos.X() - nLostPixels, aOldPos.Y()));
        }

        // resize the dialog itself
        aOldSize = GetSizePixel();
        SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));
    }

    fillListBox(_rDatasources);

    // allow ODBC datasource managenment
    if ( DST_ODBC == _eType || DST_MYSQL_ODBC == _eType )
    {
        m_aManageDatasources.Show();
        m_aManageDatasources.Enable();
        m_aManageDatasources.SetClickHdl(LINK(this,ODatasourceSelectDialog,ManageClickHdl));
    }

    m_aDatasource.SetDoubleClickHdl(LINK(this,ODatasourceSelectDialog,ListDblClickHdl));
    FreeResource();
}

// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ListDblClickHdl, ListBox *, pListBox )
{
    if (pListBox->GetSelectEntryCount())
        EndDialog(RET_OK);
    return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, CreateDBClickHdl, PushButton*, pButton )
{
    try
    {
        OSL_ENSURE(m_pOutputSet,"No itemset given!");
        Reference< ::com::sun::star::lang::XMultiServiceFactory > xORB = ::comphelper::getProcessServiceFactory();
        Reference<XCreateCatalog> xCatalog(xORB->createInstance(SERVICE_EXTENDED_ADABAS_DRIVER),UNO_QUERY);
        if ( xCatalog.is() && m_pOutputSet )
        {
            Sequence< Any > aArgs(2);
            aArgs[0] <<= PropertyValue(::rtl::OUString::createFromAscii("CreateCatalog"), 0,makeAny(xCatalog) , PropertyState_DIRECT_VALUE);
            aArgs[1] <<= PropertyValue(PROPERTY_PARENTWINDOW, 0, makeAny(VCLUnoHelper::GetInterface(this)), PropertyState_DIRECT_VALUE);

            Reference< XExecutableDialog > xDialog(
                xORB->createInstanceWithArguments(SERVICE_SDB_ADABASCREATIONDIALOG, aArgs), UNO_QUERY);
            if (!xDialog.is())
            {
                //  ShowServiceNotAvailableError(this, String(SERVICE_SDB_ADABASCREATIONDIALOG), sal_True);
                return 0L;
            }

            if ( xDialog->execute() == RET_OK )
            {
                Reference<XPropertySet> xProp(xDialog,UNO_QUERY);
                if(xProp.is())
                {
                    Reference<XPropertySetInfo> xPropInfo(xProp->getPropertySetInfo());
                    if(xPropInfo->hasPropertyByName(PROPERTY_DATABASENAME))
                    {
                        String sDatabaseName;
                        sDatabaseName = String(::comphelper::getString(xProp->getPropertyValue(PROPERTY_DATABASENAME)));
                        m_aDatasource.SelectEntry(m_aDatasource.InsertEntry( sDatabaseName ));

                    }
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLUSER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLUSER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLUSER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLPASSWORD) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLPWD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLPASSWORD))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_USER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_USER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_USER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_PASSWORD) )
                        m_pOutputSet->Put(SfxStringItem(DSID_PASSWORD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_PASSWORD))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CACHESIZE) )
                        m_pOutputSet->Put(SfxInt32Item(DSID_CONN_CACHESIZE, ::comphelper::getINT32(xProp->getPropertyValue(PROPERTY_CACHESIZE))));
                }
            }
        }
    }
    catch(Exception&)
    {
    }
    return 0L;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ManageClickHdl, PushButton*, pButton )
{
    OOdbcManagement aOdbcConfig;
#ifdef HAVE_ODBC_ADMINISTRATION
    if (!aOdbcConfig.isLoaded())
    {
#endif
        // show an error message
        OLocalResourceAccess aLocRes(DLG_DATASOURCE_SELECTION, RSC_MODALDIALOG);
        String sError(ModuleRes(STR_COULDNOTLOAD_CONFIGLIB));
        sError.SearchAndReplaceAscii("#lib#", aOdbcConfig.getLibraryName());
        ErrorBox aDialog(this, WB_OK, sError);
        aDialog.Execute();
        m_aDatasource.GrabFocus();
        m_aManageDatasources.Disable();
        return 1L;
#ifdef HAVE_ODBC_ADMINISTRATION
    }

    aOdbcConfig.manageDataSources(GetSystemData()->hWnd);
    // now we have to look if there are any new datasources added
    StringBag aOdbcDatasources;
    OOdbcEnumeration aEnumeration;
    aEnumeration.getDatasourceNames(aOdbcDatasources);
    fillListBox(aOdbcDatasources);

    return 0L;
#endif
}
// -----------------------------------------------------------------------------
void ODatasourceSelectDialog::fillListBox(const StringBag& _rDatasources)
{
    m_aDatasource.Clear();
    // fill the list
    for (   ConstStringBagIterator aDS = _rDatasources.begin();
            aDS != _rDatasources.end();
            ++aDS
        )
    {
        m_aDatasource.InsertEntry( *aDS );
    }

    // select the first entry
    if (m_aDatasource.GetEntryCount())
        m_aDatasource.SelectEntryPos(0);
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int p[50]={0};

void Init(){

	p[2]=p[3]=p[5]=p[7]=p[11]=p[13]=p[17]=p[23]=p[29]=p[31]=1;

	return ;
}

int a[30]={0};
int count1;
int add(int cur,int i){
	if(p[a[cur-3]+a[cur-2]+a[cur-1]+a[cur]]==1){
		return 1;
	}
	else{
		return 0;
	}

}
int n;

int dfs(int cur){
	REP(i,0,9){
		if(add(cur,i)){
			if(cur==n+5){
				count++;
			}else{
				a[cur++]=i
				dfs(cur);
			}

		}
	}
}
void Solve(){
	dfs(5);
	cout<<count<<endl;
	return ;
}

int main(){
#ifdef LOCAL
	freopen("uoj18025.in","r",stdin);
#endif

	Init(),Solve();
	return 0;
}<commit_msg>update uoj18025<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int p[50]={0};

void Init(){

	p[2]=p[3]=p[5]=p[7]=p[11]=p[13]=p[17]=p[23]=p[29]=p[31]=1;

	return ;
}

int a[30]={0};
int count1;
int add(int cur,int i){
	if(p[a[cur-3]+a[cur-2]+a[cur-1]+a[cur]]==1){
		return 1;
	}
	else{
		return 0;
	}

}
int n;

int dfs(int cur){
	REP(i,0,9){
		if(add(cur,i)){
			if(cur==n+5){
				count1++;
			}else{
				a[cur++]=i;
				dfs(cur);
			}

		}
	}
}
void Solve(){
	dfs(5);
	cout<<count1<<endl;
	return ;
}

int main(){
#ifdef LOCAL
	freopen("uoj18025.in","r",stdin);
#endif

	Init(),Solve();
	return 0;
}<|endoftext|>


<commit_before>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;
    MTL M;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);

    init_time_at(time,"# read target, SS, SF files",t);
    MTL Targ=read_MTLfile(F.Targfile,F,0,0);
    MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
    MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
    print_time(time,"# ... took :");
    //combine the three input files
    M=Targ;
    printf(" Target size %d \n",M.size());
    M.insert(M.end(),SStars.begin(),SStars.end());
    printf(" Standard Star size %d \n",M.size());
    M.insert(M.end(),SkyF.begin(),SkyF.end());
    printf(" Sky Fiber size %d \n",M.size());

    F.Ngal = M.size();
    assign_priority_class(M);
    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        if(!M[i].SS&&!M[i].SF){
            count_class[M[i].priority_class]+=1;
        }
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }
    print_time(time,"# ... took :");

    // fiber positioners
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F);
    pp.compute_fibsofsp(F);

    //P is original list of plates
	Plates P = read_plate_centers(F);
	F.Nplate=P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct target> T(M,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect galaxies at ",t);

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(M,T,P,pp,F);
    print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect available tile-fibers at",t);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(M,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
	Assignment A(M,F);
    // Make a plan ----------------------------------------------------
	print_time(t,"# Start assignment at : ");
    simple_assign(M,P,pp,F,A);

    //check to see if there are tiles with no galaxies
    //need to keep mapping of old tile list to new tile list
    //and inverse map
    A.inv_order=initList(F.Nplate,-1);
    int inv_count=0;
    for (int j=0;j<F.Nplate ;++j){

        bool not_done=true;
        for(int k=0;k<F.Nfiber && not_done;++k){
            if(A.TF[j][k]!=-1){
                A.suborder.push_back(j);//suborder[jused] is jused-th used plate
                not_done=false;
                A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
                inv_count++;
            }
        }
    }
    F.NUsedplate=A.suborder.size();
    printf(" Plates actually used %d \n",F.NUsedplate);
    for(int i=0;i<F.NUsedplate;i++)printf(" jused  %d  j  %d\n",i,A.suborder[i]);

    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs

    // Smooth out distribution of free fibers, and increase the number of assignments

    for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
    for (int i=0; i<3; i++) {
        improve(M,P,pp,F,A,0);
        redistribute_tf(M,P,pp,F,A,0);
    }
    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
    //try assigning SF and SS before real time assignment
    for (int jused=0;jused<F.NUsedplate;++jused){

        int j=A.suborder[jused];
        assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
        assign_unused(j,M,P,pp,F,A);
    }

	// Results -------------------------------------------------------*/
    std::vector <int> total_used_by_class(M.priority_list.size(),0);
    int total_used_SS=0;
    int total_used_SF=0;
    for (int jused=0;jused<F.NUsedplate;++jused){
        std::vector <int> used_by_class(M.priority_list.size(),0);
        int used_SS=0;
        int used_SF=0;
        int j=A.suborder[jused];
        for(int k=0;k<F.Nfiber;++k){
            int g=A.TF[j][k];
            if(g!=-1){
                if(M[g].SS){
                    total_used_SS++;
                    used_SS++;
                    }
                    else if(M[g].SF){
                        used_SF++;
                        total_used_SF++;
                    }
                    else{
                        used_by_class[M[g].priority_class]++;
                        total_used_by_class[M[g].priority_class]++;
                    }
            }
        }
        printf(" plate jused %5d j %5d  SS   %4d    SF   %4d",jused,j,used_SS,used_SF);
        for (int pr=0;pr<M.priority_list.size();++pr){
            printf(" class %2d   %5d",pr,used_by_class[pr]);
        }
        printf("\n");
    }
    printf(" Totals SS   %4d    SF   %4d",total_used_SS,total_used_SF);
    for (int pr=0;pr<M.priority_list.size();++pr){
        printf(" class %2d   %5d",pr,total_used_by_class[pr]);
    }
    printf("\n");

    if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
        }

    if (F.PrintFits) for (int jused=0; jused<F.Nusedplate; jused++){
        int j=A.suborder[jused];
        fa_write(j,F.outDir,M,P,pp,F,A); // Write output
    }
    /*
	display_results("doc/figs/",G,M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
     */

    print_time(t,"# Finished !... in");

    return(0);
}
<commit_msg>jused only in ascii write<commit_after>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;
    MTL M;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);

    init_time_at(time,"# read target, SS, SF files",t);
    MTL Targ=read_MTLfile(F.Targfile,F,0,0);
    MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
    MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
    print_time(time,"# ... took :");
    //combine the three input files
    M=Targ;
    printf(" Target size %d \n",M.size());
    M.insert(M.end(),SStars.begin(),SStars.end());
    printf(" Standard Star size %d \n",M.size());
    M.insert(M.end(),SkyF.begin(),SkyF.end());
    printf(" Sky Fiber size %d \n",M.size());

    F.Ngal = M.size();
    assign_priority_class(M);
    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        if(!M[i].SS&&!M[i].SF){
            count_class[M[i].priority_class]+=1;
        }
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }
    print_time(time,"# ... took :");

    // fiber positioners
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F);
    pp.compute_fibsofsp(F);

    //P is original list of plates
	Plates P = read_plate_centers(F);
	F.Nplate=P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct target> T(M,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect galaxies at ",t);

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(M,T,P,pp,F);
    print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect available tile-fibers at",t);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(M,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
	Assignment A(M,F);
    // Make a plan ----------------------------------------------------
	print_time(t,"# Start assignment at : ");
    simple_assign(M,P,pp,F,A);

    //check to see if there are tiles with no galaxies
    //need to keep mapping of old tile list to new tile list
    //and inverse map
    A.inv_order=initList(F.Nplate,-1);
    int inv_count=0;
    for (int j=0;j<F.Nplate ;++j){

        bool not_done=true;
        for(int k=0;k<F.Nfiber && not_done;++k){
            if(A.TF[j][k]!=-1){
                A.suborder.push_back(j);//suborder[jused] is jused-th used plate
                not_done=false;
                A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
                inv_count++;
            }
        }
    }
    F.NUsedplate=A.suborder.size();
    printf(" Plates actually used %d \n",F.NUsedplate);
    for(int i=0;i<F.NUsedplate;i++)printf(" jused  %d  j  %d\n",i,A.suborder[i]);

    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs

    // Smooth out distribution of free fibers, and increase the number of assignments

    for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
    for (int i=0; i<3; i++) {
        improve(M,P,pp,F,A,0);
        redistribute_tf(M,P,pp,F,A,0);
    }
    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
    //try assigning SF and SS before real time assignment
    for (int jused=0;jused<F.NUsedplate;++jused){

        int j=A.suborder[jused];
        assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
        assign_unused(j,M,P,pp,F,A);
    }

	// Results -------------------------------------------------------*/
    std::vector <int> total_used_by_class(M.priority_list.size(),0);
    int total_used_SS=0;
    int total_used_SF=0;
    for (int jused=0;jused<F.NUsedplate;++jused){
        std::vector <int> used_by_class(M.priority_list.size(),0);
        int used_SS=0;
        int used_SF=0;
        int j=A.suborder[jused];
        for(int k=0;k<F.Nfiber;++k){
            int g=A.TF[j][k];
            if(g!=-1){
                if(M[g].SS){
                    total_used_SS++;
                    used_SS++;
                    }
                    else if(M[g].SF){
                        used_SF++;
                        total_used_SF++;
                    }
                    else{
                        used_by_class[M[g].priority_class]++;
                        total_used_by_class[M[g].priority_class]++;
                    }
            }
        }
        printf(" plate jused %5d j %5d  SS   %4d    SF   %4d",jused,j,used_SS,used_SF);
        for (int pr=0;pr<M.priority_list.size();++pr){
            printf(" class %2d   %5d",pr,used_by_class[pr]);
        }
        printf("\n");
    }
    printf(" Totals SS   %4d    SF   %4d",total_used_SS,total_used_SF);
    for (int pr=0;pr<M.priority_list.size();++pr){
        printf(" class %2d   %5d",pr,total_used_by_class[pr]);
    }
    printf("\n");

    if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
        }

    if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        fa_write(j,F.outDir,M,P,pp,F,A); // Write output
    }
    /*
	display_results("doc/figs/",G,M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
     */

    print_time(t,"# Finished !... in");

    return(0);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2009, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. 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.
 */

#include <stdint.h>

#include <OGRE/OgreCamera.h>
#include <OGRE/OgreQuaternion.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreVector3.h>
#include <OGRE/OgreViewport.h>

#include <rviz/display_context.h>
#include <rviz/geometry.h>
#include <rviz/ogre_helpers/shape.h>
#include <rviz/properties/bool_property.h>
#include <rviz/properties/float_property.h>
#include <rviz/properties/vector_property.h>
#include <rviz/uniform_string_stream.h>
#include <rviz/viewport_mouse_event.h>
#include <rviz/load_resource.h>
#include <rviz/render_panel.h>

#include <rviz/default_plugin/view_controllers/orbit_view_controller.h>

static const float PITCH_START = Ogre::Math::HALF_PI / 2.0;
static const float YAW_START = Ogre::Math::HALF_PI * 0.5;
static const float DISTANCE_START = 10;
static const float FOV_START = Ogre::Math::HALF_PI / 2.0;
static const float FOCAL_SHAPE_SIZE_START = 0.05;
static const bool FOCAL_SHAPE_FIXED_SIZE = true;

namespace rviz
{
OrbitViewController::OrbitViewController() : dragging_(false)
{
  distance_property_ =
      new FloatProperty("Distance", DISTANCE_START, "Distance from the focal point.", this);
  distance_property_->setMin(0.001);

  focal_shape_size_property_ =
      new FloatProperty("Focal Shape Size", FOCAL_SHAPE_SIZE_START, "Focal shape size.", this);
  focal_shape_size_property_->setMin(0.001);

  focal_shape_fixed_size_property_ =
      new BoolProperty("Focal Shape Fixed Size", FOCAL_SHAPE_FIXED_SIZE, "Focal shape size.", this);

  yaw_property_ =
      new FloatProperty("Yaw", YAW_START, "Rotation of the camera around the Z (up) axis.", this);

  pitch_property_ =
      new FloatProperty("Pitch", PITCH_START, "How much the camera is tipped downward.", this);
  pitch_property_->setMax(Ogre::Math::HALF_PI - 0.001);
  pitch_property_->setMin(-pitch_property_->getMax());

  fov_property_ =
      new FloatProperty("Field of View", FOV_START, "The field of view of the camera.", this);
  fov_property_->setMin(0.001);
  fov_property_->setMax(Ogre::Math::HALF_PI);

  focal_point_property_ = new VectorProperty("Focal Point", Ogre::Vector3::ZERO,
                                             "The center point which the camera orbits.", this);
}

void OrbitViewController::onInitialize()
{
  FramePositionTrackingViewController::onInitialize();

  camera_->setProjectionType(Ogre::PT_PERSPECTIVE);

  focal_shape_ = new Shape(Shape::Sphere, context_->getSceneManager(), target_scene_node_);
  updateFocalShapeSize();
  focal_shape_->setColor(1.0f, 1.0f, 0.0f, 0.5f);
  focal_shape_->getRootNode()->setVisible(false);
}

OrbitViewController::~OrbitViewController()
{
  delete focal_shape_;
}

void OrbitViewController::reset()
{
  dragging_ = false;
  yaw_property_->setFloat(YAW_START);
  pitch_property_->setFloat(PITCH_START);
  distance_property_->setFloat(DISTANCE_START);
  fov_property_->setFloat(FOV_START);
  focal_shape_size_property_->setFloat(FOCAL_SHAPE_SIZE_START);
  focal_shape_fixed_size_property_->setBool(false);
  updateFocalShapeSize();
  focal_point_property_->setVector(Ogre::Vector3::ZERO);
}

void OrbitViewController::handleMouseEvent(ViewportMouseEvent& event)
{
  if (event.shift())
  {
    setStatus(
        "Left-Click: Move X/Y.  Right-Click:: Move Z.  Mouse Wheel:: Zoom.  ");
  }
  else
  {
    setStatus("Left-Click: Rotate.  Middle-Click: Move X/Y.  Right-Click/Mouse "
              "Wheel:: Zoom.  Shift: More options.");
  }

  float distance = distance_property_->getFloat();
  updateFocalShapeSize();

  int32_t diff_x = 0;
  int32_t diff_y = 0;

  bool moved = false;

  if (event.type == QEvent::MouseButtonPress)
  {
    focal_shape_->getRootNode()->setVisible(true);
    moved = true;
    dragging_ = true;
  }
  else if (event.type == QEvent::MouseButtonRelease)
  {
    focal_shape_->getRootNode()->setVisible(false);
    moved = true;
    dragging_ = false;
  }
  else if (dragging_ && event.type == QEvent::MouseMove)
  {
    diff_x = event.x - event.last_x;
    diff_y = event.y - event.last_y;
    moved = true;
  }

  // regular left-button drag
  if (event.left() && !event.shift())
  {
    setCursor(Rotate3D);
    yaw(diff_x * 0.005);
    pitch(-diff_y * 0.005);
  }
  // middle or shift-left drag
  else if (event.middle() || (event.shift() && event.left()))
  {
    setCursor(MoveXY);
    float fovY = camera_->getFOVy().valueRadians();
    float fovX = 2.0f * std::atan(std::tan(fovY / 2.0f) * camera_->getAspectRatio());

    int width = camera_->getViewport()->getActualWidth();
    int height = camera_->getViewport()->getActualHeight();

    move(-((float)diff_x / (float)width) * distance * std::tan(fovX / 2.0f) * 2.0f,
         ((float)diff_y / (float)height) * distance * std::tan(fovY / 2.0f) * 2.0f, 0.0f);
  }
  else if (event.right())
  {
    if (event.shift())
    {
      // move in z direction
      setCursor(MoveZ);
      move(0.0f, 0.0f, diff_y * 0.1 * (distance / 10.0f));
    }
    else
    {
      // zoom
      setCursor(Zoom);
      zoom(-diff_y * 0.1 * (distance / 10.0f));
    }
  }
  else
  {
    setCursor(event.shift() ? MoveXY : Rotate3D);
  }

  moved = true;

  if (event.wheel_delta != 0)
  {
    int diff = event.wheel_delta;
    if (event.shift())
    {
      move(0, 0, -diff * 0.001 * distance);
    }
    else
    {
      zoom(diff * 0.001 * distance);
    }

    moved = true;
  }

  if (moved)
  {
    context_->queueRender();
  }
}

void OrbitViewController::mimic(ViewController* source_view)
{
  FramePositionTrackingViewController::mimic(source_view);

  Ogre::Camera* source_camera = source_view->getCamera();
  Ogre::Vector3 position = source_camera->getPosition();
  Ogre::Quaternion orientation = source_camera->getOrientation();

  if (source_view->getClassId() == "rviz/Orbit")
  {
    // If I'm initializing from another instance of this same class, get the distance exactly.
    distance_property_->setFloat(source_view->subProp("Distance")->getValue().toFloat());
    updateFocalShapeSize();
  }
  else
  {
    // Determine the distance from here to the reference frame, and use
    // that as the distance our focal point should be at.
    distance_property_->setFloat(position.length());
    updateFocalShapeSize();
  }

  Ogre::Vector3 direction =
      orientation * (Ogre::Vector3::NEGATIVE_UNIT_Z * distance_property_->getFloat());
  focal_point_property_->setVector(position + direction);

  calculatePitchYawFromPosition(position);
}

void OrbitViewController::update(float dt, float ros_dt)
{
  FramePositionTrackingViewController::update(dt, ros_dt);
  updateCamera();
}

void OrbitViewController::lookAt(const Ogre::Vector3& point)
{
  Ogre::Vector3 camera_position = camera_->getPosition();
  focal_point_property_->setVector(target_scene_node_->getOrientation().Inverse() *
                                   (point - target_scene_node_->getPosition()));
  distance_property_->setFloat(focal_point_property_->getVector().distance(camera_position));
  updateFocalShapeSize();
  calculatePitchYawFromPosition(camera_position);
}

void OrbitViewController::onTargetFrameChanged(const Ogre::Vector3& old_reference_position,
                                               const Ogre::Quaternion& /*old_reference_orientation*/)
{
  focal_point_property_->add(old_reference_position - reference_position_);
}

void OrbitViewController::updateCamera()
{
  float distance = distance_property_->getFloat();
  float yaw = yaw_property_->getFloat();
  float pitch = pitch_property_->getFloat();
  float fov = fov_property_->getFloat();
  Ogre::Vector3 camera_z = Ogre::Vector3::UNIT_Z;

  // If requested, turn the world upside down.
  if (this->invert_z_->getBool())
  {
    yaw = -yaw;
    pitch = -pitch;
    camera_z = -camera_z;
  }

  Ogre::Vector3 focal_point = focal_point_property_->getVector();

  float x = distance * std::cos(yaw) * std::cos(pitch) + focal_point.x;
  float y = distance * std::sin(yaw) * std::cos(pitch) + focal_point.y;
  float z = distance * std::sin(pitch) + focal_point.z;

  Ogre::Vector3 pos(x, y, z);

  camera_->setPosition(pos);
  camera_->setFixedYawAxis(true, target_scene_node_->getOrientation() * camera_z);
  camera_->setDirection(target_scene_node_->getOrientation() * (focal_point - pos));
  camera_->setFOVy(Ogre::Radian(fov));

  focal_shape_->setPosition(focal_point);
}

void OrbitViewController::yaw(float angle)
{
  yaw_property_->setFloat(mapAngleTo0_2Pi(yaw_property_->getFloat() - angle));
}

void OrbitViewController::pitch(float angle)
{
  pitch_property_->add(-angle);
}

void OrbitViewController::calculatePitchYawFromPosition(const Ogre::Vector3& position)
{
  Ogre::Vector3 diff = position - focal_point_property_->getVector();
  pitch_property_->setFloat(std::asin(diff.z / distance_property_->getFloat()));
  yaw_property_->setFloat(atan2(diff.y, diff.x));
}

void OrbitViewController::updateFocalShapeSize()
{
  const double fshape_size(focal_shape_size_property_->getFloat());
  double distance_property(distance_property_->getFloat());
  if (focal_shape_fixed_size_property_->getBool())
    distance_property = 1;

  focal_shape_->setScale(Ogre::Vector3(fshape_size * distance_property, fshape_size * distance_property,
                                       fshape_size * distance_property / 5.0));
}

void OrbitViewController::zoom(float amount)
{
  distance_property_->add(-amount);
  updateFocalShapeSize();
}

void OrbitViewController::move(float x, float y, float z)
{
  focal_point_property_->add(camera_->getOrientation() * Ogre::Vector3(x, y, z));
}

} // end namespace rviz

#include <cmath>

#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS(rviz::OrbitViewController, rviz::ViewController)
<commit_msg>fix clang-tidy: unused value<commit_after>/*
 * Copyright (c) 2009, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. 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.
 */

#include <stdint.h>

#include <OGRE/OgreCamera.h>
#include <OGRE/OgreQuaternion.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreVector3.h>
#include <OGRE/OgreViewport.h>

#include <rviz/display_context.h>
#include <rviz/geometry.h>
#include <rviz/ogre_helpers/shape.h>
#include <rviz/properties/bool_property.h>
#include <rviz/properties/float_property.h>
#include <rviz/properties/vector_property.h>
#include <rviz/uniform_string_stream.h>
#include <rviz/viewport_mouse_event.h>
#include <rviz/load_resource.h>
#include <rviz/render_panel.h>

#include <rviz/default_plugin/view_controllers/orbit_view_controller.h>

static const float PITCH_START = Ogre::Math::HALF_PI / 2.0;
static const float YAW_START = Ogre::Math::HALF_PI * 0.5;
static const float DISTANCE_START = 10;
static const float FOV_START = Ogre::Math::HALF_PI / 2.0;
static const float FOCAL_SHAPE_SIZE_START = 0.05;
static const bool FOCAL_SHAPE_FIXED_SIZE = true;

namespace rviz
{
OrbitViewController::OrbitViewController() : dragging_(false)
{
  distance_property_ =
      new FloatProperty("Distance", DISTANCE_START, "Distance from the focal point.", this);
  distance_property_->setMin(0.001);

  focal_shape_size_property_ =
      new FloatProperty("Focal Shape Size", FOCAL_SHAPE_SIZE_START, "Focal shape size.", this);
  focal_shape_size_property_->setMin(0.001);

  focal_shape_fixed_size_property_ =
      new BoolProperty("Focal Shape Fixed Size", FOCAL_SHAPE_FIXED_SIZE, "Focal shape size.", this);

  yaw_property_ =
      new FloatProperty("Yaw", YAW_START, "Rotation of the camera around the Z (up) axis.", this);

  pitch_property_ =
      new FloatProperty("Pitch", PITCH_START, "How much the camera is tipped downward.", this);
  pitch_property_->setMax(Ogre::Math::HALF_PI - 0.001);
  pitch_property_->setMin(-pitch_property_->getMax());

  fov_property_ =
      new FloatProperty("Field of View", FOV_START, "The field of view of the camera.", this);
  fov_property_->setMin(0.001);
  fov_property_->setMax(Ogre::Math::HALF_PI);

  focal_point_property_ = new VectorProperty("Focal Point", Ogre::Vector3::ZERO,
                                             "The center point which the camera orbits.", this);
}

void OrbitViewController::onInitialize()
{
  FramePositionTrackingViewController::onInitialize();

  camera_->setProjectionType(Ogre::PT_PERSPECTIVE);

  focal_shape_ = new Shape(Shape::Sphere, context_->getSceneManager(), target_scene_node_);
  updateFocalShapeSize();
  focal_shape_->setColor(1.0f, 1.0f, 0.0f, 0.5f);
  focal_shape_->getRootNode()->setVisible(false);
}

OrbitViewController::~OrbitViewController()
{
  delete focal_shape_;
}

void OrbitViewController::reset()
{
  dragging_ = false;
  yaw_property_->setFloat(YAW_START);
  pitch_property_->setFloat(PITCH_START);
  distance_property_->setFloat(DISTANCE_START);
  fov_property_->setFloat(FOV_START);
  focal_shape_size_property_->setFloat(FOCAL_SHAPE_SIZE_START);
  focal_shape_fixed_size_property_->setBool(false);
  updateFocalShapeSize();
  focal_point_property_->setVector(Ogre::Vector3::ZERO);
}

void OrbitViewController::handleMouseEvent(ViewportMouseEvent& event)
{
  if (event.shift())
  {
    setStatus(
        "Left-Click: Move X/Y.  Right-Click:: Move Z.  Mouse Wheel:: Zoom.  ");
  }
  else
  {
    setStatus("Left-Click: Rotate.  Middle-Click: Move X/Y.  Right-Click/Mouse "
              "Wheel:: Zoom.  Shift: More options.");
  }

  float distance = distance_property_->getFloat();
  updateFocalShapeSize();

  int32_t diff_x = 0;
  int32_t diff_y = 0;

  if (event.type == QEvent::MouseButtonPress)
  {
    focal_shape_->getRootNode()->setVisible(true);
    dragging_ = true;
  }
  else if (event.type == QEvent::MouseButtonRelease)
  {
    focal_shape_->getRootNode()->setVisible(false);
    dragging_ = false;
  }
  else if (dragging_ && event.type == QEvent::MouseMove)
  {
    diff_x = event.x - event.last_x;
    diff_y = event.y - event.last_y;
  }

  // regular left-button drag
  if (event.left() && !event.shift())
  {
    setCursor(Rotate3D);
    yaw(diff_x * 0.005);
    pitch(-diff_y * 0.005);
  }
  // middle or shift-left drag
  else if (event.middle() || (event.shift() && event.left()))
  {
    setCursor(MoveXY);
    float fovY = camera_->getFOVy().valueRadians();
    float fovX = 2.0f * std::atan(std::tan(fovY / 2.0f) * camera_->getAspectRatio());

    int width = camera_->getViewport()->getActualWidth();
    int height = camera_->getViewport()->getActualHeight();

    move(-((float)diff_x / (float)width) * distance * std::tan(fovX / 2.0f) * 2.0f,
         ((float)diff_y / (float)height) * distance * std::tan(fovY / 2.0f) * 2.0f, 0.0f);
  }
  else if (event.right())
  {
    if (event.shift())
    {
      // move in z direction
      setCursor(MoveZ);
      move(0.0f, 0.0f, diff_y * 0.1 * (distance / 10.0f));
    }
    else
    {
      // zoom
      setCursor(Zoom);
      zoom(-diff_y * 0.1 * (distance / 10.0f));
    }
  }
  else
  {
    setCursor(event.shift() ? MoveXY : Rotate3D);
  }

  if (event.wheel_delta != 0)
  {
    int diff = event.wheel_delta;
    if (event.shift())
    {
      move(0, 0, -diff * 0.001 * distance);
    }
    else
    {
      zoom(diff * 0.001 * distance);
    }
  }

  context_->queueRender();
}

void OrbitViewController::mimic(ViewController* source_view)
{
  FramePositionTrackingViewController::mimic(source_view);

  Ogre::Camera* source_camera = source_view->getCamera();
  Ogre::Vector3 position = source_camera->getPosition();
  Ogre::Quaternion orientation = source_camera->getOrientation();

  if (source_view->getClassId() == "rviz/Orbit")
  {
    // If I'm initializing from another instance of this same class, get the distance exactly.
    distance_property_->setFloat(source_view->subProp("Distance")->getValue().toFloat());
    updateFocalShapeSize();
  }
  else
  {
    // Determine the distance from here to the reference frame, and use
    // that as the distance our focal point should be at.
    distance_property_->setFloat(position.length());
    updateFocalShapeSize();
  }

  Ogre::Vector3 direction =
      orientation * (Ogre::Vector3::NEGATIVE_UNIT_Z * distance_property_->getFloat());
  focal_point_property_->setVector(position + direction);

  calculatePitchYawFromPosition(position);
}

void OrbitViewController::update(float dt, float ros_dt)
{
  FramePositionTrackingViewController::update(dt, ros_dt);
  updateCamera();
}

void OrbitViewController::lookAt(const Ogre::Vector3& point)
{
  Ogre::Vector3 camera_position = camera_->getPosition();
  focal_point_property_->setVector(target_scene_node_->getOrientation().Inverse() *
                                   (point - target_scene_node_->getPosition()));
  distance_property_->setFloat(focal_point_property_->getVector().distance(camera_position));
  updateFocalShapeSize();
  calculatePitchYawFromPosition(camera_position);
}

void OrbitViewController::onTargetFrameChanged(const Ogre::Vector3& old_reference_position,
                                               const Ogre::Quaternion& /*old_reference_orientation*/)
{
  focal_point_property_->add(old_reference_position - reference_position_);
}

void OrbitViewController::updateCamera()
{
  float distance = distance_property_->getFloat();
  float yaw = yaw_property_->getFloat();
  float pitch = pitch_property_->getFloat();
  float fov = fov_property_->getFloat();
  Ogre::Vector3 camera_z = Ogre::Vector3::UNIT_Z;

  // If requested, turn the world upside down.
  if (this->invert_z_->getBool())
  {
    yaw = -yaw;
    pitch = -pitch;
    camera_z = -camera_z;
  }

  Ogre::Vector3 focal_point = focal_point_property_->getVector();

  float x = distance * std::cos(yaw) * std::cos(pitch) + focal_point.x;
  float y = distance * std::sin(yaw) * std::cos(pitch) + focal_point.y;
  float z = distance * std::sin(pitch) + focal_point.z;

  Ogre::Vector3 pos(x, y, z);

  camera_->setPosition(pos);
  camera_->setFixedYawAxis(true, target_scene_node_->getOrientation() * camera_z);
  camera_->setDirection(target_scene_node_->getOrientation() * (focal_point - pos));
  camera_->setFOVy(Ogre::Radian(fov));

  focal_shape_->setPosition(focal_point);
}

void OrbitViewController::yaw(float angle)
{
  yaw_property_->setFloat(mapAngleTo0_2Pi(yaw_property_->getFloat() - angle));
}

void OrbitViewController::pitch(float angle)
{
  pitch_property_->add(-angle);
}

void OrbitViewController::calculatePitchYawFromPosition(const Ogre::Vector3& position)
{
  Ogre::Vector3 diff = position - focal_point_property_->getVector();
  pitch_property_->setFloat(std::asin(diff.z / distance_property_->getFloat()));
  yaw_property_->setFloat(atan2(diff.y, diff.x));
}

void OrbitViewController::updateFocalShapeSize()
{
  const double fshape_size(focal_shape_size_property_->getFloat());
  double distance_property(distance_property_->getFloat());
  if (focal_shape_fixed_size_property_->getBool())
    distance_property = 1;

  focal_shape_->setScale(Ogre::Vector3(fshape_size * distance_property, fshape_size * distance_property,
                                       fshape_size * distance_property / 5.0));
}

void OrbitViewController::zoom(float amount)
{
  distance_property_->add(-amount);
  updateFocalShapeSize();
}

void OrbitViewController::move(float x, float y, float z)
{
  focal_point_property_->add(camera_->getOrientation() * Ogre::Vector3(x, y, z));
}

} // end namespace rviz

#include <cmath>

#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS(rviz::OrbitViewController, rviz::ViewController)
<|endoftext|>