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

/**
 * @file dp_st_cost.cc
 **/

#include "modules/planning/tasks/dp_st_speed/dp_st_cost.h"

#include <limits>

#include "modules/planning/common/speed/st_point.h"

namespace apollo {
namespace planning {
namespace {
constexpr double kInf = std::numeric_limits<double>::infinity();
}

DpStCost::DpStCost(const DpStSpeedConfig& config,
                   const std::vector<const PathObstacle*>& obstacles,
                   const common::TrajectoryPoint& init_point)
    : config_(config),
      obstacles_(obstacles),
      init_point_(init_point),
      unit_s_(config_.total_path_length() / config_.matrix_dimension_s()),
      unit_t_(config_.total_time() / config_.matrix_dimension_t()),
      unit_v_(unit_s_ / unit_t_) {}

double DpStCost::GetObstacleCost(const StGraphPoint& st_graph_point) const {
  const double s = st_graph_point.point().s();
  const double t = st_graph_point.point().t();

  double cost = 0.0;
  for (const auto* obstacle : obstacles_) {
    auto boundary = obstacle->st_boundary();
    const double kIgnoreDistance = 200.0;
    if (boundary.min_s() > kIgnoreDistance) {
      continue;
    }
    if (t < boundary.min_t() || t > boundary.max_t()) {
      continue;
    }
    if (obstacle->IsBlockingObstacle() &&
        boundary.IsPointInBoundary(STPoint(s, t))) {
      return kInf;
    }
    double s_upper = 0.0;
    double s_lower = 0.0;
    boundary.GetBoundarySRange(t, &s_upper, &s_lower);
    if (s < s_lower) {
      constexpr double kSafeTimeBuffer = 3.0;
      const double len = obstacle->obstacle()->Speed() * kSafeTimeBuffer;
      if (s + len < s_lower) {
        continue;
      } else {
        cost += config_.obstacle_weight() * config_.default_obstacle_cost() *
                std::pow((len - s_lower + s), 2);
      }
    } else if (s > s_upper) {
      const double kSafeDistance = 20.0;  // or calculated from velocity
      if (s > s_upper + kSafeDistance) {
        continue;
      } else {
        cost += config_.obstacle_weight() *
                std::pow((kSafeDistance + s_upper - s), 2);
      }
    }
  }
  return cost * unit_t_;
}

double DpStCost::GetReferenceCost(const STPoint& point,
                                  const STPoint& reference_point) const {
  return config_.reference_weight() * (point.s() - reference_point.s()) *
         (point.s() - reference_point.s()) * unit_t_;
}

double DpStCost::GetSpeedCost(const STPoint& first, const STPoint& second,
                              const double speed_limit) const {
  double cost = 0.0;
  const double speed = (second.s() - first.s()) / unit_t_;
  if (speed < 0) {
    return kInf;
  }
  double det_speed = (speed - speed_limit) / speed_limit;
  if (det_speed > 0) {
    cost = config_.exceed_speed_penalty() * config_.default_speed_cost() *
           fabs(speed * speed) * unit_t_;
  } else if (det_speed < 0) {
    cost = config_.low_speed_penalty() * config_.default_speed_cost() *
           -det_speed * unit_t_;
  } else {
    cost = 0.0;
  }
  return cost;
}

double DpStCost::GetAccelCost(const double accel) const {
  const double accel_sq = accel * accel;
  double max_acc = config_.max_acceleration();
  double max_dec = config_.max_deceleration();
  double accel_penalty = config_.accel_penalty();
  double decel_penalty = config_.decel_penalty();
  double cost = 0.0;
  if (accel > 0.0) {
    cost = accel_penalty * accel_sq;
  } else {
    cost = decel_penalty * accel_sq;
  }
  cost += accel_sq * decel_penalty * decel_penalty /
              (1 + std::exp(1.0 * (accel - max_dec))) +
          accel_sq * accel_penalty * accel_penalty /
              (1 + std::exp(-1.0 * (accel - max_acc)));
  return cost * unit_t_;
}

double DpStCost::GetAccelCostByThreePoints(const STPoint& first,
                                           const STPoint& second,
                                           const STPoint& third) const {
  double accel = (first.s() + third.s() - 2 * second.s()) / (unit_t_ * unit_t_);
  return GetAccelCost(accel);
}

double DpStCost::GetAccelCostByTwoPoints(const double pre_speed,
                                         const STPoint& pre_point,
                                         const STPoint& curr_point) const {
  double current_speed = (curr_point.s() - pre_point.s()) / unit_t_;
  double accel = (current_speed - pre_speed) / unit_t_;
  return GetAccelCost(accel);
}

double DpStCost::JerkCost(const double jerk) const {
  double jerk_sq = jerk * jerk;
  double cost = 0.0;
  if (jerk > 0) {
    cost = config_.positive_jerk_coeff() * jerk_sq * unit_t_;
  } else {
    cost = config_.negative_jerk_coeff() * jerk_sq * unit_t_;
  }
  return cost;
}

double DpStCost::GetJerkCostByFourPoints(const STPoint& first,
                                         const STPoint& second,
                                         const STPoint& third,
                                         const STPoint& fourth) const {
  double jerk = (fourth.s() - 3 * third.s() + 3 * second.s() - first.s()) /
                (unit_t_ * unit_t_ * unit_t_);
  return JerkCost(jerk);
}

double DpStCost::GetJerkCostByTwoPoints(const double pre_speed,
                                        const double pre_acc,
                                        const STPoint& pre_point,
                                        const STPoint& curr_point) const {
  const double curr_speed = (curr_point.s() - pre_point.s()) / unit_t_;
  const double curr_accel = (curr_speed - pre_speed) / unit_t_;
  const double jerk = (curr_accel - pre_acc) / unit_t_;
  return JerkCost(jerk);
}

double DpStCost::GetJerkCostByThreePoints(const double first_speed,
                                          const STPoint& first,
                                          const STPoint& second,
                                          const STPoint& third) const {
  const double pre_speed = (second.s() - first.s()) / unit_t_;
  const double pre_acc = (pre_speed - first_speed) / unit_t_;
  const double curr_speed = (third.s() - second.s()) / unit_t_;
  const double curr_acc = (curr_speed - pre_speed) / unit_t_;
  const double jerk = (curr_acc - pre_acc) / unit_t_;
  return JerkCost(jerk);
}

}  // namespace planning
}  // namespace apollo
<commit_msg>Planning: added default obstacle cost for overtake. (#2207)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file dp_st_cost.cc
 **/

#include "modules/planning/tasks/dp_st_speed/dp_st_cost.h"

#include <limits>

#include "modules/planning/common/speed/st_point.h"

namespace apollo {
namespace planning {
namespace {
constexpr double kInf = std::numeric_limits<double>::infinity();
}

DpStCost::DpStCost(const DpStSpeedConfig& config,
                   const std::vector<const PathObstacle*>& obstacles,
                   const common::TrajectoryPoint& init_point)
    : config_(config),
      obstacles_(obstacles),
      init_point_(init_point),
      unit_s_(config_.total_path_length() / config_.matrix_dimension_s()),
      unit_t_(config_.total_time() / config_.matrix_dimension_t()),
      unit_v_(unit_s_ / unit_t_) {}

double DpStCost::GetObstacleCost(const StGraphPoint& st_graph_point) const {
  const double s = st_graph_point.point().s();
  const double t = st_graph_point.point().t();

  double cost = 0.0;
  for (const auto* obstacle : obstacles_) {
    auto boundary = obstacle->st_boundary();
    const double kIgnoreDistance = 200.0;
    if (boundary.min_s() > kIgnoreDistance) {
      continue;
    }
    if (t < boundary.min_t() || t > boundary.max_t()) {
      continue;
    }
    if (obstacle->IsBlockingObstacle() &&
        boundary.IsPointInBoundary(STPoint(s, t))) {
      return kInf;
    }
    double s_upper = 0.0;
    double s_lower = 0.0;
    boundary.GetBoundarySRange(t, &s_upper, &s_lower);
    if (s < s_lower) {
      constexpr double kSafeTimeBuffer = 3.0;
      const double len = obstacle->obstacle()->Speed() * kSafeTimeBuffer;
      if (s + len < s_lower) {
        continue;
      } else {
        cost += config_.obstacle_weight() * config_.default_obstacle_cost() *
                std::pow((len - s_lower + s), 2);
      }
    } else if (s > s_upper) {
      const double kSafeDistance = 20.0;  // or calculated from velocity
      if (s > s_upper + kSafeDistance) {
        continue;
      } else {
        cost += config_.obstacle_weight() * config_.default_obstacle_cost() *
                std::pow((kSafeDistance + s_upper - s), 2);
      }
    }
  }
  return cost * unit_t_;
}

double DpStCost::GetReferenceCost(const STPoint& point,
                                  const STPoint& reference_point) const {
  return config_.reference_weight() * (point.s() - reference_point.s()) *
         (point.s() - reference_point.s()) * unit_t_;
}

double DpStCost::GetSpeedCost(const STPoint& first, const STPoint& second,
                              const double speed_limit) const {
  double cost = 0.0;
  const double speed = (second.s() - first.s()) / unit_t_;
  if (speed < 0) {
    return kInf;
  }
  double det_speed = (speed - speed_limit) / speed_limit;
  if (det_speed > 0) {
    cost = config_.exceed_speed_penalty() * config_.default_speed_cost() *
           fabs(speed * speed) * unit_t_;
  } else if (det_speed < 0) {
    cost = config_.low_speed_penalty() * config_.default_speed_cost() *
           -det_speed * unit_t_;
  } else {
    cost = 0.0;
  }
  return cost;
}

double DpStCost::GetAccelCost(const double accel) const {
  const double accel_sq = accel * accel;
  double max_acc = config_.max_acceleration();
  double max_dec = config_.max_deceleration();
  double accel_penalty = config_.accel_penalty();
  double decel_penalty = config_.decel_penalty();
  double cost = 0.0;
  if (accel > 0.0) {
    cost = accel_penalty * accel_sq;
  } else {
    cost = decel_penalty * accel_sq;
  }
  cost += accel_sq * decel_penalty * decel_penalty /
              (1 + std::exp(1.0 * (accel - max_dec))) +
          accel_sq * accel_penalty * accel_penalty /
              (1 + std::exp(-1.0 * (accel - max_acc)));
  return cost * unit_t_;
}

double DpStCost::GetAccelCostByThreePoints(const STPoint& first,
                                           const STPoint& second,
                                           const STPoint& third) const {
  double accel = (first.s() + third.s() - 2 * second.s()) / (unit_t_ * unit_t_);
  return GetAccelCost(accel);
}

double DpStCost::GetAccelCostByTwoPoints(const double pre_speed,
                                         const STPoint& pre_point,
                                         const STPoint& curr_point) const {
  double current_speed = (curr_point.s() - pre_point.s()) / unit_t_;
  double accel = (current_speed - pre_speed) / unit_t_;
  return GetAccelCost(accel);
}

double DpStCost::JerkCost(const double jerk) const {
  double jerk_sq = jerk * jerk;
  double cost = 0.0;
  if (jerk > 0) {
    cost = config_.positive_jerk_coeff() * jerk_sq * unit_t_;
  } else {
    cost = config_.negative_jerk_coeff() * jerk_sq * unit_t_;
  }
  return cost;
}

double DpStCost::GetJerkCostByFourPoints(const STPoint& first,
                                         const STPoint& second,
                                         const STPoint& third,
                                         const STPoint& fourth) const {
  double jerk = (fourth.s() - 3 * third.s() + 3 * second.s() - first.s()) /
                (unit_t_ * unit_t_ * unit_t_);
  return JerkCost(jerk);
}

double DpStCost::GetJerkCostByTwoPoints(const double pre_speed,
                                        const double pre_acc,
                                        const STPoint& pre_point,
                                        const STPoint& curr_point) const {
  const double curr_speed = (curr_point.s() - pre_point.s()) / unit_t_;
  const double curr_accel = (curr_speed - pre_speed) / unit_t_;
  const double jerk = (curr_accel - pre_acc) / unit_t_;
  return JerkCost(jerk);
}

double DpStCost::GetJerkCostByThreePoints(const double first_speed,
                                          const STPoint& first,
                                          const STPoint& second,
                                          const STPoint& third) const {
  const double pre_speed = (second.s() - first.s()) / unit_t_;
  const double pre_acc = (pre_speed - first_speed) / unit_t_;
  const double curr_speed = (third.s() - second.s()) / unit_t_;
  const double curr_acc = (curr_speed - pre_speed) / unit_t_;
  const double jerk = (curr_acc - pre_acc) / unit_t_;
  return JerkCost(jerk);
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: whiter.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:16:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#ifndef _SFX_WHITER_HXX
#define _SFX_WHITER_HXX

#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif

#ifndef INCLUDED_LIMITS_H
#include <limits.h>
#define INCLUDED_LIMITS_H
#endif

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

class SfxItemSet;

// INCLUDE ---------------------------------------------------------------

class SVL_DLLPUBLIC SfxWhichIter
{
    const USHORT *pRanges, *pStart;
    USHORT nOfst, nFrom, nTo;

public:
    SfxWhichIter( const SfxItemSet& rSet, USHORT nFrom = 0, USHORT nTo = USHRT_MAX );
    ~SfxWhichIter();

    USHORT  GetCurWhich() const { return *pRanges + nOfst; }
    USHORT  NextWhich();
    USHORT  PrevWhich();

    USHORT  FirstWhich();
    USHORT  LastWhich();
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.774); FILE MERGED 2008/04/01 15:44:25 thb 1.3.774.3: #i85898# Stripping all external header guards 2008/04/01 12:43:09 thb 1.3.774.2: #i85898# Stripping all external header guards 2008/03/31 13:00:58 rt 1.3.774.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: whiter.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SFX_WHITER_HXX
#define _SFX_WHITER_HXX

#include "svtools/svldllapi.h"

#ifndef INCLUDED_LIMITS_H
#include <limits.h>
#define INCLUDED_LIMITS_H
#endif
#include <tools/solar.h>

class SfxItemSet;

// INCLUDE ---------------------------------------------------------------

class SVL_DLLPUBLIC SfxWhichIter
{
    const USHORT *pRanges, *pStart;
    USHORT nOfst, nFrom, nTo;

public:
    SfxWhichIter( const SfxItemSet& rSet, USHORT nFrom = 0, USHORT nTo = USHRT_MAX );
    ~SfxWhichIter();

    USHORT  GetCurWhich() const { return *pRanges + nOfst; }
    USHORT  NextWhich();
    USHORT  PrevWhich();

    USHORT  FirstWhich();
    USHORT  LastWhich();
};

#endif
<|endoftext|>


<commit_before>#include "OpenniWrapperNode.h"

#include <sstream>

using namespace openni;
using namespace std;
using namespace cv;

const int OpenniWrapperNode::openni_wrapper_max_devices = 1;

OpenniWrapperNode::OpenniWrapperNode(ros::NodeHandle nh, ros::NodeHandle private_nh)
//    m_ColorCallback(nh,"rgb/image_raw","rgb/camera_info", true, false),
//    m_DepthCallback(nh, true, false)
{
    m_nodeHandle = nh;
    m_privateNodeHandle = private_nh;

    // check how many cameras have been defined
    m_DevicesDefined = 0;

    for (size_t i=0; i<openni_wrapper_max_devices;i++)
    {
        std::string deviceName;
        ostringstream deviceNameStream;
        deviceNameStream<<"camera";
        if (i>0) {    deviceNameStream<<i; }

        bool found = m_privateNodeHandle.getParam(deviceNameStream.str(),deviceName);
        if (found)
        {
            if (deviceName != "false")
            {
                m_DevicesDefined++;
                m_vCameraNamespace.push_back(deviceName);
            }
        } else {
//            break;
        }
    }

    if (m_vCameraNamespace.size() == 0)
    {
        cout<<"---------------------------- No devices defined. Exitting.-------------------------------"<<endl;
        exit(-1);
    }

    cout<<"Devices defined "<<m_DevicesDefined<<endl;
    for (size_t i=0; i<m_DevicesDefined;i++)
    {
        cout<<m_vCameraNamespace[i]<<endl;
        ColorCallback* colorCB = new ColorCallback(nh, m_vCameraNamespace[i], true, false);
        DepthCallback* depthCB = new DepthCallback(nh, m_vCameraNamespace[i], true, false);

        m_vDepthCallback.push_back(depthCB);
        m_vColorCallback.push_back(colorCB);
    }

}

OpenniWrapperNode::~OpenniWrapperNode()
{

}

void OpenniWrapperNode::initializeOpenni()
{
    Status rc = OpenNI::initialize();
    if (rc != STATUS_OK)
    {
        printf("Initialize failed\n%s\n", OpenNI::getExtendedError());
        return 1;
    } else {
        cout<<"Openni initialized"<<endl;
    }

    OpenNI::addDeviceConnectedListener(&m_devicePrinter);
    OpenNI::addDeviceDisconnectedListener(&m_devicePrinter);
    OpenNI::addDeviceStateChangedListener(&m_devicePrinter);

    openni::Array<openni::DeviceInfo> deviceList;
    openni::OpenNI::enumerateDevices(&deviceList);
    for (int i = 0; i < deviceList.getSize(); ++i)
    {
        printf("Device \"%s\" already connected\n", deviceList[i].getUri());
    }

    m_vDevice.resize(deviceList.getSize());
    m_vColor.resize(deviceList.getSize());
    m_vDepth.resize(deviceList.getSize());

    cout<<"Number of devices connected "<<deviceList.getSize()<<endl;

    for (size_t i=0; i<m_DevicesDefined;i++)
    {
        if (i+1>deviceList.getSize())
        {
            cout<<"Name "<<m_vCameraNamespace[i]<<" defined but the device is not connected."<<endl;
            break;
        }

        m_vDevice[i] = new Device();
        rc = m_vDevice[i]->open(deviceList[i].getUri());
        if (rc != STATUS_OK)
        {
            printf("Couldn't open device\n%s\n", OpenNI::getExtendedError());
            return 2;
        } else {
            cout<<"Opened device "<<deviceList[0].getUri()<<"   namespace "<<m_vCameraNamespace[i]<<endl;
        }

        cout<<"This device supports the following sensors ";
        bool sensor = m_vDevice[i]->hasSensor(SENSOR_IR); if (sensor) cout <<"IR ";
        sensor = m_vDevice[i]->hasSensor(SENSOR_COLOR); if (sensor) cout <<"COLOR ";
        sensor = m_vDevice[i]->hasSensor(SENSOR_DEPTH); if (sensor) cout <<"DEPTH ";
        cout<<endl;

        rc = m_vDevice[i]->setDepthColorSyncEnabled(true);
        // handle rc
        if (rc != STATUS_OK)
        {
            std::cout<<"Could not set the depth-color sync. Some error occured"<<std::endl;
        }

        if (m_vDevice[i]->getSensorInfo(SENSOR_DEPTH) != NULL)
        {
            m_vDepth[i] = new VideoStream;
            rc = m_vDepth[i]->create(*m_vDevice[i], SENSOR_DEPTH);
            if (rc != STATUS_OK)
            {
                printf("Couldn't create depth stream\n%s\n", OpenNI::getExtendedError());
            }
        }
        VideoMode depthVideoMode = m_vDepth[i]->getVideoMode();
        depthVideoMode.setResolution(640,480);
        rc = m_vDepth[i]->setVideoMode(depthVideoMode);
        if (rc != STATUS_OK)
        {
            printf("Couldn't set increased resolution for depth stream\n%s\n", OpenNI::getExtendedError());
        }

        rc = m_vDepth[i]->start();
        if (rc != STATUS_OK)
        {
            printf("Couldn't start the depth stream\n%s\n", OpenNI::getExtendedError());
        }

        if (m_vDevice[i]->getSensorInfo(SENSOR_COLOR) != NULL)
        {
            m_vColor[i] = new VideoStream;
            rc = m_vColor[i]->create(*m_vDevice[i], SENSOR_COLOR);
            if (rc != STATUS_OK)
            {
                printf("Couldn't create color stream\n%s\n", OpenNI::getExtendedError());
            }
        }
        VideoMode colorVideoMode = m_vColor[i]->getVideoMode();
        colorVideoMode.setResolution(640,480);
        rc = m_vColor[i]->setVideoMode(colorVideoMode);
        if (rc != STATUS_OK)
        {
            printf("Couldn't set increased resolution for color stream\n%s\n", OpenNI::getExtendedError());
        }

        rc = m_vColor[i]->start();
        if (rc != STATUS_OK)
        {
            printf("Couldn't start the color stream\n%s\n", OpenNI::getExtendedError());
        }

        // Register to new frame
        m_vDepth[i]->addNewFrameListener(m_vDepthCallback[i]);
        m_vColor[i]->addNewFrameListener(m_vColorCallback[i]);

	ImageRegistrationMode mode = IMAGE_REGISTRATION_DEPTH_TO_COLOR;
        bool registrationSupported = m_vDevice[i]->isImageRegistrationModeSupported(mode);
        if(registrationSupported)
        {
            cout<<"Image registration SUPPORTED"<<endl;
            rc = m_vDevice[i]->setImageRegistrationMode(mode);
            // handle ret
            if (rc != STATUS_OK)
            {
                std::cout<<"Could not set the image registration on. Some error occured  "<<rc<<std::endl;
            }
        } else {
            cout<<"Image registration NOT SUPPORTED"<<endl;
        }
    }
}

void OpenniWrapperNode::terminateOpenni()
{
    std::cout<<"Shutting down Openni driver "<<std::endl;

    for (size_t i=0; i<m_DevicesDefined; i++)
    {
        m_vDepth[i]->removeNewFrameListener(m_vDepthCallback[i]);
        m_vColor[i]->removeNewFrameListener(m_vColorCallback[i]);

        m_vDepth[i]->stop();
        m_vDepth[i]->destroy();
        m_vColor[i]->stop();
        m_vColor[i]->destroy();
        m_vDevice[i]->close();

        delete m_vDepth[i];
        delete m_vColor[i];
        delete m_vDevice[i];

        delete m_vColorCallback[i];
        delete m_vDepthCallback[i];
    }

    OpenNI::shutdown();
}
<commit_msg>Removed incorrect return values.<commit_after>#include "OpenniWrapperNode.h"

#include <sstream>

using namespace openni;
using namespace std;
using namespace cv;

const int OpenniWrapperNode::openni_wrapper_max_devices = 1;

OpenniWrapperNode::OpenniWrapperNode(ros::NodeHandle nh, ros::NodeHandle private_nh)
//    m_ColorCallback(nh,"rgb/image_raw","rgb/camera_info", true, false),
//    m_DepthCallback(nh, true, false)
{
    m_nodeHandle = nh;
    m_privateNodeHandle = private_nh;

    // check how many cameras have been defined
    m_DevicesDefined = 0;

    for (size_t i=0; i<openni_wrapper_max_devices;i++)
    {
        std::string deviceName;
        ostringstream deviceNameStream;
        deviceNameStream<<"camera";
        if (i>0) {    deviceNameStream<<i; }

        bool found = m_privateNodeHandle.getParam(deviceNameStream.str(),deviceName);
        if (found)
        {
            if (deviceName != "false")
            {
                m_DevicesDefined++;
                m_vCameraNamespace.push_back(deviceName);
            }
        } else {
//            break;
        }
    }

    if (m_vCameraNamespace.size() == 0)
    {
        cout<<"---------------------------- No devices defined. Exitting.-------------------------------"<<endl;
        exit(-1);
    }

    cout<<"Devices defined "<<m_DevicesDefined<<endl;
    for (size_t i=0; i<m_DevicesDefined;i++)
    {
        cout<<m_vCameraNamespace[i]<<endl;
        ColorCallback* colorCB = new ColorCallback(nh, m_vCameraNamespace[i], true, false);
        DepthCallback* depthCB = new DepthCallback(nh, m_vCameraNamespace[i], true, false);

        m_vDepthCallback.push_back(depthCB);
        m_vColorCallback.push_back(colorCB);
    }

}

OpenniWrapperNode::~OpenniWrapperNode()
{

}

void OpenniWrapperNode::initializeOpenni()
{
    Status rc = OpenNI::initialize();
    if (rc != STATUS_OK)
    {
        printf("Initialize failed\n%s\n", OpenNI::getExtendedError());
        return;
    } else {
        cout<<"Openni initialized"<<endl;
    }

    OpenNI::addDeviceConnectedListener(&m_devicePrinter);
    OpenNI::addDeviceDisconnectedListener(&m_devicePrinter);
    OpenNI::addDeviceStateChangedListener(&m_devicePrinter);

    openni::Array<openni::DeviceInfo> deviceList;
    openni::OpenNI::enumerateDevices(&deviceList);
    for (int i = 0; i < deviceList.getSize(); ++i)
    {
        printf("Device \"%s\" already connected\n", deviceList[i].getUri());
    }

    m_vDevice.resize(deviceList.getSize());
    m_vColor.resize(deviceList.getSize());
    m_vDepth.resize(deviceList.getSize());

    cout<<"Number of devices connected "<<deviceList.getSize()<<endl;

    for (size_t i=0; i<m_DevicesDefined;i++)
    {
        if (i+1>deviceList.getSize())
        {
            cout<<"Name "<<m_vCameraNamespace[i]<<" defined but the device is not connected."<<endl;
            break;
        }

        m_vDevice[i] = new Device();
        rc = m_vDevice[i]->open(deviceList[i].getUri());
        if (rc != STATUS_OK)
        {
            printf("Couldn't open device\n%s\n", OpenNI::getExtendedError());
            return;
        } else {
            cout<<"Opened device "<<deviceList[0].getUri()<<"   namespace "<<m_vCameraNamespace[i]<<endl;
        }

        cout<<"This device supports the following sensors ";
        bool sensor = m_vDevice[i]->hasSensor(SENSOR_IR); if (sensor) cout <<"IR ";
        sensor = m_vDevice[i]->hasSensor(SENSOR_COLOR); if (sensor) cout <<"COLOR ";
        sensor = m_vDevice[i]->hasSensor(SENSOR_DEPTH); if (sensor) cout <<"DEPTH ";
        cout<<endl;

        rc = m_vDevice[i]->setDepthColorSyncEnabled(true);
        // handle rc
        if (rc != STATUS_OK)
        {
            std::cout<<"Could not set the depth-color sync. Some error occured"<<std::endl;
        }

        if (m_vDevice[i]->getSensorInfo(SENSOR_DEPTH) != NULL)
        {
            m_vDepth[i] = new VideoStream;
            rc = m_vDepth[i]->create(*m_vDevice[i], SENSOR_DEPTH);
            if (rc != STATUS_OK)
            {
                printf("Couldn't create depth stream\n%s\n", OpenNI::getExtendedError());
            }
        }
        VideoMode depthVideoMode = m_vDepth[i]->getVideoMode();
        depthVideoMode.setResolution(640,480);
        rc = m_vDepth[i]->setVideoMode(depthVideoMode);
        if (rc != STATUS_OK)
        {
            printf("Couldn't set increased resolution for depth stream\n%s\n", OpenNI::getExtendedError());
        }

        rc = m_vDepth[i]->start();
        if (rc != STATUS_OK)
        {
            printf("Couldn't start the depth stream\n%s\n", OpenNI::getExtendedError());
        }

        if (m_vDevice[i]->getSensorInfo(SENSOR_COLOR) != NULL)
        {
            m_vColor[i] = new VideoStream;
            rc = m_vColor[i]->create(*m_vDevice[i], SENSOR_COLOR);
            if (rc != STATUS_OK)
            {
                printf("Couldn't create color stream\n%s\n", OpenNI::getExtendedError());
            }
        }
        VideoMode colorVideoMode = m_vColor[i]->getVideoMode();
        colorVideoMode.setResolution(640,480);
        rc = m_vColor[i]->setVideoMode(colorVideoMode);
        if (rc != STATUS_OK)
        {
            printf("Couldn't set increased resolution for color stream\n%s\n", OpenNI::getExtendedError());
        }

        rc = m_vColor[i]->start();
        if (rc != STATUS_OK)
        {
            printf("Couldn't start the color stream\n%s\n", OpenNI::getExtendedError());
        }

        // Register to new frame
        m_vDepth[i]->addNewFrameListener(m_vDepthCallback[i]);
        m_vColor[i]->addNewFrameListener(m_vColorCallback[i]);

	ImageRegistrationMode mode = IMAGE_REGISTRATION_DEPTH_TO_COLOR;
        bool registrationSupported = m_vDevice[i]->isImageRegistrationModeSupported(mode);
        if(registrationSupported)
        {
            cout<<"Image registration SUPPORTED"<<endl;
            rc = m_vDevice[i]->setImageRegistrationMode(mode);
            // handle ret
            if (rc != STATUS_OK)
            {
                std::cout<<"Could not set the image registration on. Some error occured  "<<rc<<std::endl;
            }
        } else {
            cout<<"Image registration NOT SUPPORTED"<<endl;
        }
    }
}

void OpenniWrapperNode::terminateOpenni()
{
    std::cout<<"Shutting down Openni driver "<<std::endl;

    for (size_t i=0; i<m_DevicesDefined; i++)
    {
        m_vDepth[i]->removeNewFrameListener(m_vDepthCallback[i]);
        m_vColor[i]->removeNewFrameListener(m_vColorCallback[i]);

        m_vDepth[i]->stop();
        m_vDepth[i]->destroy();
        m_vColor[i]->stop();
        m_vColor[i]->destroy();
        m_vDevice[i]->close();

        delete m_vDepth[i];
        delete m_vColor[i];
        delete m_vDevice[i];

        delete m_vColorCallback[i];
        delete m_vDepthCallback[i];
    }

    OpenNI::shutdown();
}
<|endoftext|>


<commit_before>#include "SequenceRowEditor.h"
#include "SequenceRow.h"
#include "Sequence.h"
#include "Song.h"
#include "EditorState.h"
#include "Renderer.h"
#include "Color.h"

SequenceRowEditor::SequenceRowEditor(EditorState& editorState, Song& song)
	: ColumnEditor(editorState, editorState.sequenceEditor, SequenceRow::maxTracks, 2), mSong(song)
{
	mTrackEditorState.currentRow.addListener(this);
	mTrackEditorState.currentColumn.addListener(this);
	mTrackEditorState.currentTrack.addListener(this);
}

SequenceRowEditor::~SequenceRowEditor()
{
}

void SequenceRowEditor::insertRow(bool allTracks, int flags)
{
	mSong.getSequence().insertRow(mTrackEditorState.currentRow, allTracks);

	if (mSong.getSequenceLength() < Song::maxSequenceRows)
		mSong.setSequenceLength(mSong.getSequenceLength() + 1);

	mTrackEditorState.currentRow.notify();
}

void SequenceRowEditor::deleteRow(bool allTracks, int flags)
{
	mSong.getSequence().deleteRow(mTrackEditorState.currentRow, allTracks);

	if (mSong.getSequenceLength() > 1)
		mSong.setSequenceLength(mSong.getSequenceLength() - 1);

	if (mTrackEditorState.currentRow >= mSong.getSequenceLength())
	{
		mTrackEditorState.currentRow = mSong.getSequenceLength() - 1;
	}

	mTrackEditorState.currentRow.notify();
}

void SequenceRowEditor::emptyRow(bool allTracks, int flags)
{
	//mSong.getSequence().emptyRow(mEditorState.currentRow);
}

bool SequenceRowEditor::onEvent(SDL_Event& event)
{
	switch (event.type)
	{
		case SDL_KEYDOWN:

			switch (event.key.keysym.sym)
			{
				case SDLK_DOWN:
					scrollView(1, false);

					return true;
					break;

				case SDLK_UP:
					scrollView(-1, false);

					return true;
					break;

				case SDLK_LEFT:
					changeColumn(-1);
					return true;

				case SDLK_RIGHT:
					changeColumn(1);
					return true;

				case SDLK_HOME:
					mTrackEditorState.currentRow = 0;

					return true;
					break;

				case SDLK_END:
					mTrackEditorState.currentRow = mSong.getSequenceLength() - 1;

					return true;
					break;

				case SDLK_BACKSPACE:
					if (mTrackEditorState.currentRow == 0)
						break;
					scrollView(-1, false);
					deleteRow(false, 0);
					return true;
					break;

				case SDLK_DELETE:
					deleteRow(false, 0);
					return true;
					break;

				case SDLK_INSERT:
					insertRow(false, 0);
					return true;
					break;

				case SDLK_RETURN:
					/*if (mTrackEditorState.currentRow == mSong.getSequenceLength() - 1)
						break;*/
					insertRow(false, 0);

					scrollView(1, false);
					return true;
					break;

				default:
				{
					if (event.key.keysym.mod & KMOD_CTRL)
					{
						if (event.key.keysym.sym == SDLK_d)
						{
							duplicateRow();
							return true;
						}

						break;
					}

					if (!mEditorState.editMode)
						break;

					SequenceRow& sequenceRow = mSong.getSequence().getRow(mTrackEditorState.currentRow);

					int hex = getHexFromKey(event.key.keysym.sym);
					if (hex != -1)
					{
						int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

						if (mTrackEditorState.currentColumn == 0)
						{
							pattern = (pattern & 0x0f) | (hex << 4);
						}
						else
						{
							pattern = (pattern & 0xf0) | hex;
						}

						scrollView(1, false);

						return true;
					}
				}
					break;

			}
			break;

			case SDL_CONTROLLERBUTTONDOWN:
			{
				bool aPressed = SDL_GameControllerGetButton(SDL_GameControllerFromInstanceID(event.cbutton.which), SDL_CONTROLLER_BUTTON_A);
				SequenceRow& sequenceRow = mSong.getSequence().getRow(mTrackEditorState.currentRow);

				switch (event.cbutton.button)
				{
					case SDL_CONTROLLER_BUTTON_DPAD_LEFT:
					case SDL_CONTROLLER_BUTTON_DPAD_RIGHT:
						if (!aPressed)
						{
							changeColumn(event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ? -1 : 1);
						}
						else
						{
							int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

							pattern = std::min(Song::maxPatterns - 1, std::max(0, pattern + (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ? -1 : 1)));

							// We need to signal the listeners that the sequence has changed (i.e. tell PatternEditor to redraw)
							// Otherwise this is automatically caused by scrollView() when typing in numbers
							mTrackEditorState.currentRow.notify();
						}

						break;

					case SDL_CONTROLLER_BUTTON_DPAD_UP:
					case SDL_CONTROLLER_BUTTON_DPAD_DOWN:
						if (!aPressed)
						{
							scrollView(event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP ? -1 : 1);
						}
						else
						{
							int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

							pattern = std::min(Song::maxPatterns - 1, std::max(0, pattern + (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN ? -16 : 16)));

							// We need to signal the listeners that the sequence has changed (i.e. tell PatternEditor to redraw)
							// Otherwise this is automatically caused by scrollView() when typing in numbers
							mTrackEditorState.currentRow.notify();
						}

						break;
				}
				break;
			}
	}
	return false;
}

void SequenceRowEditor::onDraw(Renderer& renderer, const SDL_Rect& area)
{
	setDirty(false);

	renderer.renderBackground(area);

	int rowNumberWidth = 2 * 8 + 2;
	int trackWidth = 8 * 2;
	int rowHeight = 8;

	int countVisible = area.h / 8;
	int firstVisible = mTrackEditorState.currentRow - countVisible / 2;
	int lastVisible = mTrackEditorState.currentRow + countVisible / 2;

	int centerY = (area.h / 2) & ~7;

	if (firstVisible < 0)
		firstVisible = 0;

	if (lastVisible >= mSong.getSequenceLength())
		lastVisible = mSong.getSequenceLength() - 1;

	if (hasFocus())
	{
		int columnWidth = 8;

		int columnX = 8 * mTrackEditorState.currentColumn;

		SDL_Rect textArea = {mTrackEditorState.currentTrack * trackWidth + area.x + rowNumberWidth + columnX, area.y + centerY, columnWidth, rowHeight};
		renderer.renderRect(textArea, Color::getColor(mEditorState.editMode ? Color::ColorType::EditCursor : Color::ColorType::NonEditCursor));
	}

	for (int row = firstVisible ; row <= lastVisible ; ++row)
	{
		SDL_Rect textArea = {area.x, (row - mTrackEditorState.currentRow) * rowHeight + area.y + centerY, trackWidth, rowHeight};
		Color color = Color::getColor(Color::ColorType::RowCounter);

		if (row == mTrackEditorState.currentRow)
			color = Color(0,0,0);

		renderer.renderTextV(textArea, color, "%02d", row);
	}

	for (int row = firstVisible ; row <= lastVisible ; ++row)
	{
		SequenceRow& sequenceRow = mSong.getSequence().getRow(row);
		for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
		{
			SDL_Rect textArea = {track * trackWidth + area.x + rowNumberWidth, (row - mTrackEditorState.currentRow) * rowHeight + area.y + centerY, trackWidth, rowHeight};

			Color color;

			if (row == mTrackEditorState.currentRow)
				color = Color(0,0,0);

			renderer.renderTextV(textArea, color, "%02x", sequenceRow.pattern[track]);
		}
	}
}

void SequenceRowEditor::duplicateRow()
{
	if (mTrackEditorState.currentRow >= Sequence::maxRows && mSong.getSequenceLength() < Song::maxSequenceRows)
		return;

	mSong.getSequence().insertRow(mTrackEditorState.currentRow, true);

	SequenceRow& destination = mSong.getSequence().getRow(mTrackEditorState.currentRow);
	SequenceRow& source = mSong.getSequence().getRow(mTrackEditorState.currentRow + 1);

	for (int track = 0 ; track <= SequenceRow::maxTracks ; ++track)
	{
		destination.pattern[track] = source.pattern[track];
	}

	mSong.setSequenceLength(mSong.getSequenceLength() + 1);

	mTrackEditorState.currentRow.notify();
}
<commit_msg>Duplicating row had a overflow<commit_after>#include "SequenceRowEditor.h"
#include "SequenceRow.h"
#include "Sequence.h"
#include "Song.h"
#include "EditorState.h"
#include "Renderer.h"
#include "Color.h"

SequenceRowEditor::SequenceRowEditor(EditorState& editorState, Song& song)
	: ColumnEditor(editorState, editorState.sequenceEditor, SequenceRow::maxTracks, 2), mSong(song)
{
	mTrackEditorState.currentRow.addListener(this);
	mTrackEditorState.currentColumn.addListener(this);
	mTrackEditorState.currentTrack.addListener(this);
}

SequenceRowEditor::~SequenceRowEditor()
{
}

void SequenceRowEditor::insertRow(bool allTracks, int flags)
{
	mSong.getSequence().insertRow(mTrackEditorState.currentRow, allTracks);

	if (mSong.getSequenceLength() < Song::maxSequenceRows)
		mSong.setSequenceLength(mSong.getSequenceLength() + 1);

	mTrackEditorState.currentRow.notify();
}

void SequenceRowEditor::deleteRow(bool allTracks, int flags)
{
	mSong.getSequence().deleteRow(mTrackEditorState.currentRow, allTracks);

	if (mSong.getSequenceLength() > 1)
		mSong.setSequenceLength(mSong.getSequenceLength() - 1);

	if (mTrackEditorState.currentRow >= mSong.getSequenceLength())
	{
		mTrackEditorState.currentRow = mSong.getSequenceLength() - 1;
	}

	mTrackEditorState.currentRow.notify();
}

void SequenceRowEditor::emptyRow(bool allTracks, int flags)
{
	//mSong.getSequence().emptyRow(mEditorState.currentRow);
}

bool SequenceRowEditor::onEvent(SDL_Event& event)
{
	switch (event.type)
	{
		case SDL_KEYDOWN:

			switch (event.key.keysym.sym)
			{
				case SDLK_DOWN:
					scrollView(1, false);

					return true;
					break;

				case SDLK_UP:
					scrollView(-1, false);

					return true;
					break;

				case SDLK_LEFT:
					changeColumn(-1);
					return true;

				case SDLK_RIGHT:
					changeColumn(1);
					return true;

				case SDLK_HOME:
					mTrackEditorState.currentRow = 0;

					return true;
					break;

				case SDLK_END:
					mTrackEditorState.currentRow = mSong.getSequenceLength() - 1;

					return true;
					break;

				case SDLK_BACKSPACE:
					if (mTrackEditorState.currentRow == 0)
						break;
					scrollView(-1, false);
					deleteRow(false, 0);
					return true;
					break;

				case SDLK_DELETE:
					deleteRow(false, 0);
					return true;
					break;

				case SDLK_INSERT:
					insertRow(false, 0);
					return true;
					break;

				case SDLK_RETURN:
					/*if (mTrackEditorState.currentRow == mSong.getSequenceLength() - 1)
						break;*/
					insertRow(false, 0);

					scrollView(1, false);
					return true;
					break;

				default:
				{
					if (event.key.keysym.mod & KMOD_CTRL)
					{
						if (event.key.keysym.sym == SDLK_d)
						{
							duplicateRow();
							return true;
						}

						break;
					}

					if (!mEditorState.editMode)
						break;

					SequenceRow& sequenceRow = mSong.getSequence().getRow(mTrackEditorState.currentRow);

					int hex = getHexFromKey(event.key.keysym.sym);
					if (hex != -1)
					{
						int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

						if (mTrackEditorState.currentColumn == 0)
						{
							pattern = (pattern & 0x0f) | (hex << 4);
						}
						else
						{
							pattern = (pattern & 0xf0) | hex;
						}

						scrollView(1, false);

						return true;
					}
				}
					break;

			}
			break;

			case SDL_CONTROLLERBUTTONDOWN:
			{
				bool aPressed = SDL_GameControllerGetButton(SDL_GameControllerFromInstanceID(event.cbutton.which), SDL_CONTROLLER_BUTTON_A);
				SequenceRow& sequenceRow = mSong.getSequence().getRow(mTrackEditorState.currentRow);

				switch (event.cbutton.button)
				{
					case SDL_CONTROLLER_BUTTON_DPAD_LEFT:
					case SDL_CONTROLLER_BUTTON_DPAD_RIGHT:
						if (!aPressed)
						{
							changeColumn(event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ? -1 : 1);
						}
						else
						{
							int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

							pattern = std::min(Song::maxPatterns - 1, std::max(0, pattern + (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ? -1 : 1)));

							// We need to signal the listeners that the sequence has changed (i.e. tell PatternEditor to redraw)
							// Otherwise this is automatically caused by scrollView() when typing in numbers
							mTrackEditorState.currentRow.notify();
						}

						break;

					case SDL_CONTROLLER_BUTTON_DPAD_UP:
					case SDL_CONTROLLER_BUTTON_DPAD_DOWN:
						if (!aPressed)
						{
							scrollView(event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP ? -1 : 1);
						}
						else
						{
							int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

							pattern = std::min(Song::maxPatterns - 1, std::max(0, pattern + (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN ? -16 : 16)));

							// We need to signal the listeners that the sequence has changed (i.e. tell PatternEditor to redraw)
							// Otherwise this is automatically caused by scrollView() when typing in numbers
							mTrackEditorState.currentRow.notify();
						}

						break;
				}
				break;
			}
	}
	return false;
}

void SequenceRowEditor::onDraw(Renderer& renderer, const SDL_Rect& area)
{
	setDirty(false);

	renderer.renderBackground(area);

	int rowNumberWidth = 2 * 8 + 2;
	int trackWidth = 8 * 2;
	int rowHeight = 8;

	int countVisible = area.h / 8;
	int firstVisible = mTrackEditorState.currentRow - countVisible / 2;
	int lastVisible = mTrackEditorState.currentRow + countVisible / 2;

	int centerY = (area.h / 2) & ~7;

	if (firstVisible < 0)
		firstVisible = 0;

	if (lastVisible >= mSong.getSequenceLength())
		lastVisible = mSong.getSequenceLength() - 1;

	if (hasFocus())
	{
		int columnWidth = 8;

		int columnX = 8 * mTrackEditorState.currentColumn;

		SDL_Rect textArea = {mTrackEditorState.currentTrack * trackWidth + area.x + rowNumberWidth + columnX, area.y + centerY, columnWidth, rowHeight};
		renderer.renderRect(textArea, Color::getColor(mEditorState.editMode ? Color::ColorType::EditCursor : Color::ColorType::NonEditCursor));
	}

	for (int row = firstVisible ; row <= lastVisible ; ++row)
	{
		SDL_Rect textArea = {area.x, (row - mTrackEditorState.currentRow) * rowHeight + area.y + centerY, trackWidth, rowHeight};
		Color color = Color::getColor(Color::ColorType::RowCounter);

		if (row == mTrackEditorState.currentRow)
			color = Color(0,0,0);

		renderer.renderTextV(textArea, color, "%02d", row);
	}

	for (int row = firstVisible ; row <= lastVisible ; ++row)
	{
		SequenceRow& sequenceRow = mSong.getSequence().getRow(row);
		for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
		{
			SDL_Rect textArea = {track * trackWidth + area.x + rowNumberWidth, (row - mTrackEditorState.currentRow) * rowHeight + area.y + centerY, trackWidth, rowHeight};

			Color color;

			if (row == mTrackEditorState.currentRow)
				color = Color(0,0,0);

			renderer.renderTextV(textArea, color, "%02x", sequenceRow.pattern[track]);
		}
	}
}

void SequenceRowEditor::duplicateRow()
{
	if (mTrackEditorState.currentRow >= Sequence::maxRows && mSong.getSequenceLength() < Song::maxSequenceRows)
		return;

	mSong.getSequence().insertRow(mTrackEditorState.currentRow, true);

	SequenceRow& destination = mSong.getSequence().getRow(mTrackEditorState.currentRow);
	SequenceRow& source = mSong.getSequence().getRow(mTrackEditorState.currentRow + 1);

	for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
	{
		destination.pattern[track] = source.pattern[track];
	}

	mSong.setSequenceLength(mSong.getSequenceLength() + 1);

	mTrackEditorState.currentRow.notify();
}
<|endoftext|>


<commit_before>/*
 * System_folderSync.cpp
 *
 *  Created on: Jun 23, 2014
 *      Author: Pimenta
 */

<commit_msg>Adding definitions of folder sync methods<commit_after>/*
 * System_folderSync.cpp
 *
 *  Created on: Jun 23, 2014
 *      Author: Pimenta
 */

// this
#include "System.hpp"

using namespace std;
using namespace concurrency;

void System::createFolder(const string& fullPath) {
  Thread([]() {

  }).start();
}

void System::updateFolder(const string& fullPath, const string& newName) {

}

void System::deleteFolder(const string& fullPath) {

}
<|endoftext|>


<commit_before>#pragma once

// `krbn::cf_utility::run_loop_thread` can be used safely in a multi-threaded environment.

#include "boost_defs.hpp"

#include "dispatcher.hpp"
#include "logger.hpp"
#include <CoreFoundation/CoreFoundation.h>
#include <boost/optional.hpp>
#include <mutex>
#include <string>
#include <thread>

namespace krbn {
class cf_utility final {
public:
  template <typename T>
  class cf_ptr final {
  public:
    cf_ptr(void) : cf_ptr(nullptr) {
    }

    cf_ptr(T _Nullable p) : p_(p) {
      if (p_) {
        CFRetain(p_);
      }
    }

    cf_ptr(const cf_ptr& other) : p_(nullptr) {
      *this = other;
    }

    cf_ptr& operator=(const cf_ptr& other) {
      auto old = p_;

      p_ = other.p_;
      if (p_) {
        CFRetain(p_);
      }

      if (old) {
        CFRelease(old);
      }

      return *this;
    }

    ~cf_ptr(void) {
      reset();
    }

    T get(void) {
      return p_;
    }

    void reset(void) {
      if (p_) {
        CFRelease(p_);
        p_ = nullptr;
      }
    }

    T operator*(void) {
      return p_;
    }

  private:
    T _Nullable p_;
  };

  // ========================================
  // Converts
  // ========================================

  static boost::optional<std::string> to_string(CFTypeRef _Nullable value) {
    if (!value) {
      return boost::none;
    }

    if (CFStringGetTypeID() != CFGetTypeID(value)) {
      return boost::none;
    }

    auto cfstring = static_cast<CFStringRef>(value);

    std::string string;
    if (auto p = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8)) {
      string = p;
    } else {
      auto length = CFStringGetLength(cfstring);
      auto max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
      char* buffer = new char[max_size];
      if (CFStringGetCString(cfstring, buffer, max_size, kCFStringEncodingUTF8)) {
        string = buffer;
      }
      delete[] buffer;
    }

    return string;
  }

  static CFStringRef _Nullable create_cfstring(const std::string& string) {
    return CFStringCreateWithCString(kCFAllocatorDefault,
                                     string.c_str(),
                                     kCFStringEncodingUTF8);
  }

  static boost::optional<int64_t> to_int64_t(CFTypeRef _Nullable value) {
    if (!value) {
      return boost::none;
    }

    if (CFNumberGetTypeID() != CFGetTypeID(value)) {
      return boost::none;
    }

    auto cfnumber = static_cast<CFNumberRef>(value);

    int64_t result;
    if (CFNumberGetValue(cfnumber, kCFNumberSInt64Type, &result)) {
      return result;
    }

    return boost::none;
  }

  // ========================================
  // CFArray, CFMutableArray
  // ========================================

  static CFArrayRef _Nonnull create_empty_cfarray(void) {
    return CFArrayCreate(nullptr, nullptr, 0, &kCFTypeArrayCallBacks);
  }

  static CFMutableArrayRef _Nonnull create_cfmutablearray(CFIndex capacity = 0) {
    return CFArrayCreateMutable(nullptr, capacity, &kCFTypeArrayCallBacks);
  }

  template <typename T>
  static T _Nullable get_value(CFArrayRef _Nonnull array, CFIndex index) {
    if (array && index < CFArrayGetCount(array)) {
      return static_cast<T>(const_cast<void*>(CFArrayGetValueAtIndex(array, index)));
    }
    return nullptr;
  }

  template <typename T>
  static bool exists(CFArrayRef _Nonnull array, T _Nonnull value) {
    if (array) {
      CFRange range = {0, CFArrayGetCount(array)};
      if (CFArrayContainsValue(array, range, value)) {
        return true;
      }
    }
    return false;
  }

  // ========================================
  // CFDictionary, CFMutableDictionary
  // ========================================

  static CFMutableDictionaryRef _Nonnull create_cfmutabledictionary(CFIndex capacity = 0) {
    return CFDictionaryCreateMutable(nullptr,
                                     capacity,
                                     &kCFTypeDictionaryKeyCallBacks,
                                     &kCFTypeDictionaryValueCallBacks);
  }

  static void set_cfmutabledictionary_value(CFMutableDictionaryRef _Nonnull dictionary,
                                            CFStringRef _Nonnull key,
                                            int64_t value) {
    if (auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &value)) {
      CFDictionarySetValue(dictionary, key, number);
      CFRelease(number);
    }
  }

  // ========================================
  // CFRunLoop
  // ========================================

  /**
   * Create a thread and then run CFRunLoop on the thread.
   */
  class run_loop_thread final {
  public:
    run_loop_thread(void) : run_loop_(nullptr) {
      running_wait_ = pqrs::dispatcher::make_wait();

      thread_ = std::thread([this] {
        run_loop_ = CFRunLoopGetCurrent();
        CFRetain(run_loop_);

        // Append empty source to prevent immediately quitting of `CFRunLoopRun`.

        auto context = CFRunLoopSourceContext();
        context.perform = perform;
        auto source = CFRunLoopSourceCreate(kCFAllocatorDefault,
                                            0,
                                            &context);

        CFRunLoopAddSource(run_loop_,
                           source,
                           kCFRunLoopCommonModes);

        // Run

        CFRunLoopPerformBlock(run_loop_,
                              kCFRunLoopCommonModes,
                              ^{
                                running_wait_->notify();
                              });

        CFRunLoopRun();

        // Remove source

        CFRunLoopRemoveSource(run_loop_,
                              source,
                              kCFRunLoopCommonModes);

        CFRelease(source);
      });
    }

    ~run_loop_thread(void) {
      if (thread_.joinable()) {
        logger::get_logger().error("Call `cf_utility::run_loop_thread::terminate` before destroy `cf_utility::run_loop_thread`");
        terminate();
      }

      if (run_loop_) {
        CFRelease(run_loop_);
      }
    }

    void terminate(void) {
      enqueue(^{
        CFRunLoopStop(run_loop_);
      });

      if (thread_.joinable()) {
        thread_.join();
      }
    }

    CFRunLoopRef _Nonnull get_run_loop(void) const {
      // We wait until running to avoid a segmentation fault which is described in `enqueue`.

      wait_until_running();

      return run_loop_;
    }

    void wake(void) const {
      // Do not touch run_loop_ until `CFRunLoopRun` is called.
      // A segmentation fault occurs if we touch `run_loop_` while `CFRunLoopRun' is processing.

      wait_until_running();

      CFRunLoopWakeUp(run_loop_);
    }

    void enqueue_and_wait(const std::function<void(void)>& function) const {
      auto wait = pqrs::dispatcher::make_wait();

      enqueue(^{
        function();

        wait->notify();
      });

      wait->wait_notice();
    }

  private:
    void enqueue(void (^_Nonnull block)(void)) const {
      // Do not call `CFRunLoopPerformBlock` until `CFRunLoopRun` is called.
      // A segmentation fault occurs if we call `CFRunLoopPerformBlock` while `CFRunLoopRun' is processing.

      wait_until_running();

      CFRunLoopPerformBlock(run_loop_,
                            kCFRunLoopCommonModes,
                            block);

      CFRunLoopWakeUp(run_loop_);
    }

    void wait_until_running(void) const {
      running_wait_->wait_notice();
    }

    static void perform(void* _Nullable info) {
    }

    std::thread thread_;

    CFRunLoopRef _Nullable run_loop_;
    std::shared_ptr<pqrs::dispatcher::wait> running_wait_;
  };
};
} // namespace krbn
<commit_msg>update cf_ptr<commit_after>#pragma once

// `krbn::cf_utility::run_loop_thread` can be used safely in a multi-threaded environment.

#include "boost_defs.hpp"

#include "dispatcher.hpp"
#include "logger.hpp"
#include <CoreFoundation/CoreFoundation.h>
#include <boost/optional.hpp>
#include <mutex>
#include <string>
#include <thread>

namespace krbn {
class cf_utility final {
public:
  template <typename T>
  class cf_ptr final {
  public:
    cf_ptr(void) : cf_ptr(nullptr) {
    }

    cf_ptr(T _Nullable p) : p_(p) {
      if (p_) {
        CFRetain(p_);
      }
    }

    cf_ptr(const cf_ptr& other) : p_(nullptr) {
      *this = other;
    }

    cf_ptr& operator=(const cf_ptr& other) {
      auto old = p_;

      p_ = other.p_;
      if (p_) {
        CFRetain(p_);
      }

      if (old) {
        CFRelease(old);
      }

      return *this;
    }

    ~cf_ptr(void) {
      reset();
    }

    const T& get(void) const {
      return p_;
    }

    T& get(void) {
      return const_cast<T&>((static_cast<const cf_ptr&>(*this)).get());
    }

    void reset(void) {
      if (p_) {
        CFRelease(p_);
        p_ = nullptr;
      }
    }

    const T& operator*(void)const {
      return p_;
    }

    T& operator*(void) {
      return const_cast<T&>(*(static_cast<const cf_ptr&>(*this)));
    }

  private:
    T _Nullable p_;
  };

  // ========================================
  // Converts
  // ========================================

  static boost::optional<std::string> to_string(CFTypeRef _Nullable value) {
    if (!value) {
      return boost::none;
    }

    if (CFStringGetTypeID() != CFGetTypeID(value)) {
      return boost::none;
    }

    auto cfstring = static_cast<CFStringRef>(value);

    std::string string;
    if (auto p = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8)) {
      string = p;
    } else {
      auto length = CFStringGetLength(cfstring);
      auto max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
      char* buffer = new char[max_size];
      if (CFStringGetCString(cfstring, buffer, max_size, kCFStringEncodingUTF8)) {
        string = buffer;
      }
      delete[] buffer;
    }

    return string;
  }

  static CFStringRef _Nullable create_cfstring(const std::string& string) {
    return CFStringCreateWithCString(kCFAllocatorDefault,
                                     string.c_str(),
                                     kCFStringEncodingUTF8);
  }

  static boost::optional<int64_t> to_int64_t(CFTypeRef _Nullable value) {
    if (!value) {
      return boost::none;
    }

    if (CFNumberGetTypeID() != CFGetTypeID(value)) {
      return boost::none;
    }

    auto cfnumber = static_cast<CFNumberRef>(value);

    int64_t result;
    if (CFNumberGetValue(cfnumber, kCFNumberSInt64Type, &result)) {
      return result;
    }

    return boost::none;
  }

  // ========================================
  // CFArray, CFMutableArray
  // ========================================

  static CFArrayRef _Nonnull create_empty_cfarray(void) {
    return CFArrayCreate(nullptr, nullptr, 0, &kCFTypeArrayCallBacks);
  }

  static CFMutableArrayRef _Nonnull create_cfmutablearray(CFIndex capacity = 0) {
    return CFArrayCreateMutable(nullptr, capacity, &kCFTypeArrayCallBacks);
  }

  template <typename T>
  static T _Nullable get_value(CFArrayRef _Nonnull array, CFIndex index) {
    if (array && index < CFArrayGetCount(array)) {
      return static_cast<T>(const_cast<void*>(CFArrayGetValueAtIndex(array, index)));
    }
    return nullptr;
  }

  template <typename T>
  static bool exists(CFArrayRef _Nonnull array, T _Nonnull value) {
    if (array) {
      CFRange range = {0, CFArrayGetCount(array)};
      if (CFArrayContainsValue(array, range, value)) {
        return true;
      }
    }
    return false;
  }

  // ========================================
  // CFDictionary, CFMutableDictionary
  // ========================================

  static CFMutableDictionaryRef _Nonnull create_cfmutabledictionary(CFIndex capacity = 0) {
    return CFDictionaryCreateMutable(nullptr,
                                     capacity,
                                     &kCFTypeDictionaryKeyCallBacks,
                                     &kCFTypeDictionaryValueCallBacks);
  }

  static void set_cfmutabledictionary_value(CFMutableDictionaryRef _Nonnull dictionary,
                                            CFStringRef _Nonnull key,
                                            int64_t value) {
    if (auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &value)) {
      CFDictionarySetValue(dictionary, key, number);
      CFRelease(number);
    }
  }

  // ========================================
  // CFRunLoop
  // ========================================

  /**
   * Create a thread and then run CFRunLoop on the thread.
   */
  class run_loop_thread final {
  public:
    run_loop_thread(void) : run_loop_(nullptr) {
      running_wait_ = pqrs::dispatcher::make_wait();

      thread_ = std::thread([this] {
        run_loop_ = CFRunLoopGetCurrent();
        CFRetain(run_loop_);

        // Append empty source to prevent immediately quitting of `CFRunLoopRun`.

        auto context = CFRunLoopSourceContext();
        context.perform = perform;
        auto source = CFRunLoopSourceCreate(kCFAllocatorDefault,
                                            0,
                                            &context);

        CFRunLoopAddSource(run_loop_,
                           source,
                           kCFRunLoopCommonModes);

        // Run

        CFRunLoopPerformBlock(run_loop_,
                              kCFRunLoopCommonModes,
                              ^{
                                running_wait_->notify();
                              });

        CFRunLoopRun();

        // Remove source

        CFRunLoopRemoveSource(run_loop_,
                              source,
                              kCFRunLoopCommonModes);

        CFRelease(source);
      });
    }

    ~run_loop_thread(void) {
      if (thread_.joinable()) {
        logger::get_logger().error("Call `cf_utility::run_loop_thread::terminate` before destroy `cf_utility::run_loop_thread`");
        terminate();
      }

      if (run_loop_) {
        CFRelease(run_loop_);
      }
    }

    void terminate(void) {
      enqueue(^{
        CFRunLoopStop(run_loop_);
      });

      if (thread_.joinable()) {
        thread_.join();
      }
    }

    CFRunLoopRef _Nonnull get_run_loop(void) const {
      // We wait until running to avoid a segmentation fault which is described in `enqueue`.

      wait_until_running();

      return run_loop_;
    }

    void wake(void) const {
      // Do not touch run_loop_ until `CFRunLoopRun` is called.
      // A segmentation fault occurs if we touch `run_loop_` while `CFRunLoopRun' is processing.

      wait_until_running();

      CFRunLoopWakeUp(run_loop_);
    }

    void enqueue_and_wait(const std::function<void(void)>& function) const {
      auto wait = pqrs::dispatcher::make_wait();

      enqueue(^{
        function();

        wait->notify();
      });

      wait->wait_notice();
    }

  private:
    void enqueue(void (^_Nonnull block)(void)) const {
      // Do not call `CFRunLoopPerformBlock` until `CFRunLoopRun` is called.
      // A segmentation fault occurs if we call `CFRunLoopPerformBlock` while `CFRunLoopRun' is processing.

      wait_until_running();

      CFRunLoopPerformBlock(run_loop_,
                            kCFRunLoopCommonModes,
                            block);

      CFRunLoopWakeUp(run_loop_);
    }

    void wait_until_running(void) const {
      running_wait_->wait_notice();
    }

    static void perform(void* _Nullable info) {
    }

    std::thread thread_;

    CFRunLoopRef _Nullable run_loop_;
    std::shared_ptr<pqrs::dispatcher::wait> running_wait_;
  };
};
} // namespace krbn
<|endoftext|>


<commit_before>// TRENTO: Reduced Thickness Event-by-event Nuclear Topology
// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland
// MIT License

#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/program_options.hpp>

#include "collider.h"
#include "fwd_decl.h"

// CMake sets this definition.
// Fall back to a sane default.
#ifndef TRENTO_VERSION_STRING
#define TRENTO_VERSION_STRING "dev"
#endif

namespace trento {

namespace {

void print_version() {
  std::cout << "trento " << TRENTO_VERSION_STRING << '\n';
}

void print_bibtex() {
  std::cout <<
    "@article{Moreland:2014oya,\n"
    "      author         = \"Moreland, J. Scott and Bernhard, Jonah E. and Bass,\n"
    "                        Steffen A.\",\n"
    "      title          = \"{Alternative ansatz to wounded nucleon and binary\n"
    "                        collision scaling in high-energy nuclear collisions}\",\n"
    "      journal        = \"Phys.Rev.\",\n"
    "      number         = \"1\",\n"
    "      volume         = \"C92\",\n"
    "      pages          = \"011901\",\n"
    "      doi            = \"10.1103/PhysRevC.92.011901\",\n"
    "      year           = \"2015\",\n"
    "      eprint         = \"1412.4708\",\n"
    "      archivePrefix  = \"arXiv\",\n"
    "      primaryClass   = \"nucl-th\",\n"
    "      SLACcitation   = \"%%CITATION = ARXIV:1412.4708;%%\",\n"
    "}\n";
}

// TODO
// void print_default_config() {
//   std::cout << "to do\n";
// }

}  // unnamed namespace

}  // namespace trento

int main(int argc, char* argv[]) {
  using namespace trento;

  // Parse options with boost::program_options.
  // There are quite a few options, so let's separate them into logical groups.
  using OptDesc = po::options_description;

  using VecStr = std::vector<std::string>;
  OptDesc main_opts{};
  main_opts.add_options()
    ("projectile", po::value<VecStr>()->required()->
     notifier(  // use a lambda to verify there are exactly two projectiles
         [](const VecStr& projectiles) {
           if (projectiles.size() != 2)
            throw po::required_option{"projectile"};
           }),
     "projectile symbols")
    ("number-events", po::value<int>()->default_value(1),
     "number of events");

  // Make all main arguments positional.
  po::positional_options_description positional_opts{};
  positional_opts
    .add("projectile", 2)
    .add("number-events", 1);

  using VecPath = std::vector<fs::path>;
  OptDesc general_opts{"general options"};
  general_opts.add_options()
    ("help,h", "show this help message and exit")
    ("version", "print version information and exit")
    ("bibtex", "print bibtex entry and exit")
    // ("default-config", "print a config file with default settings and exit")
    ("config-file,c", po::value<VecPath>()->value_name("FILE"),
     "configuration file\n(can be passed multiple times)");

  OptDesc output_opts{"output options"};
  output_opts.add_options()
    ("quiet,q", po::bool_switch(),
     "do not print event properties to stdout")
    ("output,o", po::value<fs::path>()->value_name("PATH"),
     "HDF5 file or directory for text files")
    ("no-header", po::bool_switch(),
     "do not write headers to text files");

  OptDesc phys_opts{"physical options"};
  phys_opts.add_options()
    ("reduced-thickness,p",
     po::value<double>()->value_name("FLOAT")->default_value(0., "0"),
     "reduced thickness parameter")
    ("fluctuation,k",
     po::value<double>()->value_name("FLOAT")->default_value(1., "1"),
     "gamma fluctuation shape parameter")
    ("nucleon-width,w",
     po::value<double>()->value_name("FLOAT")->default_value(.5, "0.5"),
     "Gaussian nucleon width [fm]")
    ("nucleon-min-dist,d",
     po::value<double>()->value_name("FLOAT")->default_value(0., "0"),
     "minimum nucleon-nucleon distance [fm]")
    ("beam-energy,e",
     po::value<double>()->value_name("FLOAT")->default_value(2760, "2760"),
     "collision beam energy sqrt(s) [GeV], initializes cross section")
    ("cross-section,x",
     po::value<double>()->value_name("FLOAT")->default_value(-1, "off"),
     "manual inelastic nucleon-nucleon cross section sigma_NN [fm^2]")
    ("mean-coeff,m",
     po::value<double>()->value_name("FLOAT")->default_value(1., "1."),
     "rapidity mean coefficient")
    ("std-coeff,s",
     po::value<double>()->value_name("FLOAT")->default_value(4., "4."),
     "rapidity std coefficient")
    ("skew-coeff,t",
     po::value<double>()->value_name("FLOAT")->default_value(1., "1."),
     "rapidity skew coefficient")
    ("jacobian,j",
     po::value<double>()->value_name("FLOAT")->default_value(0.8, "0.8"),
     "<pt>/<mt> used in Jacobian")
    ("normalization,n",
     po::value<double>()->value_name("FLOAT")->default_value(1., "1"),
     "normalization factor")
    ("b-min",
     po::value<double>()->value_name("FLOAT")->default_value(0., "0"),
     "minimum impact parameter [fm]")
    ("b-max",
     po::value<double>()->value_name("FLOAT")->default_value(-1., "auto"),
     "maximum impact parameter [fm]")
    ("random-seed",
     po::value<int64_t>()->value_name("INT")->default_value(-1, "auto"),
     "random seed");

  OptDesc grid_opts{"grid options"};
  grid_opts.add_options()
    ("xy-max",
     po::value<double>()->value_name("FLOAT")->default_value(10., "10.0"),
     "xy max [fm]\n(transverse grid extends from -max to +max)")
    ("eta-max",
     po::value<double>()->value_name("FLOAT")->default_value(0., "0.0"),
     "pseudorapidity max \n(eta grid extends from -max to +max)")
    ("xy-step",
     po::value<double>()->value_name("FLOAT")->default_value(0.2, "0.2"),
     "transverse step size [fm]")
    ("eta-step",
     po::value<double>()->value_name("FLOAT")->default_value(0.5, "0.5"),
     "pseudorapidity step size");

  // Make a meta-group containing all the option groups except the main
  // positional options (don't want the auto-generated usage info for those).
  OptDesc usage_opts{};
  usage_opts
    .add(general_opts)
    .add(output_opts)
    .add(phys_opts)
    .add(grid_opts);

  // Now a meta-group containing _all_ options.
  OptDesc all_opts{};
  all_opts
    .add(usage_opts)
    .add(main_opts);

  // Will be used several times.
  const std::string usage_str{
    "usage: trento [options] projectile projectile [number-events = 1]\n"};

  try {
    // Initialize a VarMap (boost::program_options::variables_map).
    // It will contain all configuration values.
    VarMap var_map{};

    // Parse command line options.
    po::store(po::command_line_parser(argc, argv)
        .options(all_opts).positional(positional_opts).run(), var_map);

    // Handle options that imply immediate exit.
    // Must do this _before_ po::notify() since that can throw exceptions.
    if (var_map.count("help")) {
      std::cout
        << usage_str
        << "\n"
           "projectile = { p | d | Cu | Cu2 | Au | Au2 | Pb | U | U2 | U3 }\n"
        << usage_opts
        << "\n"
           "see the online documentation for complete usage information\n";
      return 0;
    }
    if (var_map.count("version")) {
      print_version();
      return 0;
    }
    if (var_map.count("bibtex")) {
      print_bibtex();
      return 0;
    }
    // if (var_map.count("default-config")) {
    //   print_default_config();
    //   return 0;
    // }

    // Merge any config files.
    if (var_map.count("config-file")) {
      // Everything except general_opts.
      OptDesc config_file_opts{};
      config_file_opts
        .add(main_opts)
        .add(output_opts)
        .add(phys_opts)
        .add(grid_opts);

      for (const auto& path : var_map["config-file"].as<VecPath>()) {
        if (!fs::exists(path)) {
          throw po::error{
            "configuration file '" + path.string() + "' not found"};
        }
        fs::ifstream ifs{path};
        po::store(po::parse_config_file(ifs, config_file_opts), var_map);
      }
    }

    // Save all the final values into var_map.
    // Exceptions may occur here.
    po::notify(var_map);

    // Go!
    Collider collider{var_map};
    collider.run_events();
  }
  catch (const po::required_option&) {
    // Handle this exception separately from others.
    // This occurs e.g. when the program is excuted with no arguments.
    std::cerr << usage_str << "run 'trento --help' for more information\n";
    return 1;
  }
  catch (const std::exception& e) {
    // For all other exceptions just output the error message.
    std::cerr << e.what() << '\n';
    return 1;
  }

  return 0;
}
<commit_msg>restructure command line options<commit_after>// TRENTO: Reduced Thickness Event-by-event Nuclear Topology
// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland
// MIT License

#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/program_options.hpp>

#include "collider.h"
#include "fwd_decl.h"

// CMake sets this definition.
// Fall back to a sane default.
#ifndef TRENTO_VERSION_STRING
#define TRENTO_VERSION_STRING "dev"
#endif

namespace trento {

namespace {

void print_version() {
  std::cout << "trento " << TRENTO_VERSION_STRING << '\n';
}

void print_bibtex() {
  std::cout <<
    "@article{Moreland:2014oya,\n"
    "      author         = \"Moreland, J. Scott and Bernhard, Jonah E. and Bass,\n"
    "                        Steffen A.\",\n"
    "      title          = \"{Alternative ansatz to wounded nucleon and binary\n"
    "                        collision scaling in high-energy nuclear collisions}\",\n"
    "      journal        = \"Phys.Rev.\",\n"
    "      number         = \"1\",\n"
    "      volume         = \"C92\",\n"
    "      pages          = \"011901\",\n"
    "      doi            = \"10.1103/PhysRevC.92.011901\",\n"
    "      year           = \"2015\",\n"
    "      eprint         = \"1412.4708\",\n"
    "      archivePrefix  = \"arXiv\",\n"
    "      primaryClass   = \"nucl-th\",\n"
    "      SLACcitation   = \"%%CITATION = ARXIV:1412.4708;%%\",\n"
    "}\n";
}

// TODO
// void print_default_config() {
//   std::cout << "to do\n";
// }

}  // unnamed namespace

}  // namespace trento

int main(int argc, char* argv[]) {
  using namespace trento;

  // Parse options with boost::program_options.
  // There are quite a few options, so let's separate them into logical groups.
  using OptDesc = po::options_description;

  using VecStr = std::vector<std::string>;
  OptDesc main_opts{};
  main_opts.add_options()
    ("projectile", po::value<VecStr>()->required()->
     notifier(  // use a lambda to verify there are exactly two projectiles
         [](const VecStr& projectiles) {
           if (projectiles.size() != 2)
            throw po::required_option{"projectile"};
           }),
     "projectile symbols")
    ("number-events", po::value<int>()->default_value(1),
     "number of events");

  // Make all main arguments positional.
  po::positional_options_description positional_opts{};
  positional_opts
    .add("projectile", 2)
    .add("number-events", 1);

  using VecPath = std::vector<fs::path>;
  OptDesc general_opts{"general options"};
  general_opts.add_options()
    ("help,h", "show this help message and exit")
    ("version", "print version information and exit")
    ("bibtex", "print bibtex entry and exit")
    // ("default-config", "print a config file with default settings and exit")
    ("config-file,c", po::value<VecPath>()->value_name("FILE"),
     "configuration file\n(can be passed multiple times)");

  OptDesc output_opts{"output options"};
  output_opts.add_options()
    ("quiet,q", po::bool_switch(),
     "do not print event properties to stdout")
    ("output,o", po::value<fs::path>()->value_name("PATH"),
     "HDF5 file or directory for text files")
    ("no-header", po::bool_switch(),
     "do not write headers to text files");

  OptDesc phys_opts{"physical options"};
  phys_opts.add_options()
    ("reduced-thickness,p",
     po::value<double>()->value_name("FLOAT")->default_value(0., "0"),
     "reduced thickness parameter")
    ("fluctuation,k",
     po::value<double>()->value_name("FLOAT")->default_value(1., "1"),
     "gamma fluctuation shape parameter")
    ("nucleon-width,w",
     po::value<double>()->value_name("FLOAT")->default_value(.5, "0.5"),
     "Gaussian nucleon width [fm]")
    ("nucleon-min-dist,d",
     po::value<double>()->value_name("FLOAT")->default_value(0., "0"),
     "minimum nucleon-nucleon distance [fm]")
    ("mean-coeff,m",
     po::value<double>()->value_name("FLOAT")->default_value(1., "1."),
     "rapidity mean coefficient")
    ("std-coeff,s",
     po::value<double>()->value_name("FLOAT")->default_value(4., "4."),
     "rapidity std coefficient")
    ("skew-coeff,t",
     po::value<double>()->value_name("FLOAT")->default_value(1., "1."),
     "rapidity skew coefficient")
    ("jacobian,j",
     po::value<double>()->value_name("FLOAT")->default_value(0.8, "0.8"),
     "<pt>/<mt> used in Jacobian")
    ("normalization,n",
     po::value<double>()->value_name("FLOAT")->default_value(1., "1"),
     "normalization factor");

  OptDesc coll_opts{"collision options"};
  coll_opts.add_options()
    ("beam-energy,e",
     po::value<double>()->value_name("FLOAT")->default_value(2760, "2760"),
     "collision beam energy sqrt(s) [GeV], initializes cross section")
    ("cross-section,x",
     po::value<double>()->value_name("FLOAT")->default_value(-1, "off"),
     "manual inelastic nucleon-nucleon cross section sigma_NN [fm^2]")
    ("b-min",
     po::value<double>()->value_name("FLOAT")->default_value(0., "0"),
     "minimum impact parameter [fm]")
    ("b-max",
     po::value<double>()->value_name("FLOAT")->default_value(-1., "auto"),
     "maximum impact parameter [fm]")
    ("random-seed",
     po::value<int64_t>()->value_name("INT")->default_value(-1, "auto"),
     "random seed");

  OptDesc grid_opts{"grid options"};
  grid_opts.add_options()
    ("xy-max",
     po::value<double>()->value_name("FLOAT")->default_value(10., "10.0"),
     "xy max [fm]\n(transverse grid from -max to +max)")
    ("xy-step",
     po::value<double>()->value_name("FLOAT")->default_value(0.2, "0.2"),
     "transverse step size [fm]")
    ("eta-max",
     po::value<double>()->value_name("FLOAT")->default_value(0., "0.0"),
     "pseudorapidity max \n(eta grid from -max to +max)")
    ("eta-step",
     po::value<double>()->value_name("FLOAT")->default_value(0.5, "0.5"),
     "pseudorapidity step size");

  // Make a meta-group containing all the option groups except the main
  // positional options (don't want the auto-generated usage info for those).
  OptDesc usage_opts{};
  usage_opts
    .add(general_opts)
    .add(output_opts)
    .add(phys_opts)
    .add(coll_opts)
    .add(grid_opts);

  // Now a meta-group containing _all_ options.
  OptDesc all_opts{};
  all_opts
    .add(usage_opts)
    .add(main_opts);

  // Will be used several times.
  const std::string usage_str{
    "usage: trento [options] projectile projectile [number-events = 1]\n"};

  try {
    // Initialize a VarMap (boost::program_options::variables_map).
    // It will contain all configuration values.
    VarMap var_map{};

    // Parse command line options.
    po::store(po::command_line_parser(argc, argv)
        .options(all_opts).positional(positional_opts).run(), var_map);

    // Handle options that imply immediate exit.
    // Must do this _before_ po::notify() since that can throw exceptions.
    if (var_map.count("help")) {
      std::cout
        << usage_str
        << "\n"
           "projectile = { p | d | Cu | Cu2 | Au | Au2 | Pb | U | U2 | U3 }\n"
        << usage_opts
        << "\n"
           "see the online documentation for complete usage information\n";
      return 0;
    }
    if (var_map.count("version")) {
      print_version();
      return 0;
    }
    if (var_map.count("bibtex")) {
      print_bibtex();
      return 0;
    }
    // if (var_map.count("default-config")) {
    //   print_default_config();
    //   return 0;
    // }

    // Merge any config files.
    if (var_map.count("config-file")) {
      // Everything except general_opts.
      OptDesc config_file_opts{};
      config_file_opts
        .add(main_opts)
        .add(output_opts)
        .add(phys_opts)
        .add(grid_opts);

      for (const auto& path : var_map["config-file"].as<VecPath>()) {
        if (!fs::exists(path)) {
          throw po::error{
            "configuration file '" + path.string() + "' not found"};
        }
        fs::ifstream ifs{path};
        po::store(po::parse_config_file(ifs, config_file_opts), var_map);
      }
    }

    // Save all the final values into var_map.
    // Exceptions may occur here.
    po::notify(var_map);

    // Go!
    Collider collider{var_map};
    collider.run_events();
  }
  catch (const po::required_option&) {
    // Handle this exception separately from others.
    // This occurs e.g. when the program is excuted with no arguments.
    std::cerr << usage_str << "run 'trento --help' for more information\n";
    return 1;
  }
  catch (const std::exception& e) {
    // For all other exceptions just output the error message.
    std::cerr << e.what() << '\n';
    return 1;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <osg/Notify>
#include <osg/Types>

#include "GliderManipulator.h"

using namespace osg;
using namespace osgUtil;

GliderManipulator::GliderManipulator()
{
    _modelScale = 0.01f;
    _velocity = 0.0f;
    _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED;
}

GliderManipulator::~GliderManipulator()
{
}

void GliderManipulator::setNode(osg::Node* node)
{
    _node = node;
    if (_node.get())
    {
        const osg::BoundingSphere& boundingSphere=_node->getBound();
        _modelScale = boundingSphere._radius;
    }
}

const osg::Node* GliderManipulator::getNode() const
{
    return _node.get();
}

void GliderManipulator::home(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    if(_node.get() && _camera.get())
    {

        const osg::BoundingSphere& boundingSphere=_node->getBound();

        osg::Vec3 eye = boundingSphere._center+osg::Vec3(-boundingSphere._radius*0.15f,-boundingSphere._radius*0.15f,-boundingSphere._radius*0.03f);

        _camera->setView(eye,
            eye+osg::Vec3(1.0f,1.0f,-0.1f),
            osg::Vec3(0.0f,0.0f,1.0f));

        _velocity = boundingSphere._radius*0.01f;

        us.requestRedraw();

        us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2,(ea.getYmin()+ea.getYmax())/2);

        flushMouseEventStack();

    }

}

void GliderManipulator::init(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    flushMouseEventStack();

    us.requestContinuousUpdate(false);

    const osg::BoundingSphere& boundingSphere=_node->getBound();
    _velocity = boundingSphere._radius*0.01f;

    us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2,(ea.getYmin()+ea.getYmax())/2);

}

bool GliderManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    if(!_camera.get()) return false;

    switch(ea.getEventType())
    {
        case(GUIEventAdapter::PUSH):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();

        }
        return true;
        case(GUIEventAdapter::RELEASE):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();

        }
        return true;
        case(GUIEventAdapter::DRAG):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();

        }
        return true;
        case(GUIEventAdapter::MOVE):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();

        }
        return true;

        case(GUIEventAdapter::KEYBOARD):
            if (ea.getKey()==' ')
            {
                flushMouseEventStack();
                home(ea,us);
                us.requestRedraw();
                us.requestContinuousUpdate(false);
                return true;
            }
            return false;
        case(GUIEventAdapter::FRAME):
            addMouseEvent(ea);
            if (calcMovement()) us.requestRedraw();
            return true;
        case(GUIEventAdapter::RESIZE):
        {
            init(ea,us);
            us.requestRedraw();
        }
        return true;
        default:
            return false;
    }
}

void GliderManipulator::flushMouseEventStack()
{
    _ga_t1 = NULL;
    _ga_t0 = NULL;
}

void GliderManipulator::addMouseEvent(const GUIEventAdapter& ea)
{
    _ga_t1 = _ga_t0;
    _ga_t0 = &ea;
}

bool GliderManipulator::calcMovement()
{
    // return if less then two events have been added.
    if (_ga_t0.get()==NULL || _ga_t1.get()==NULL) return false;

    float dt = _ga_t0->time()-_ga_t1->time();

    if (dt<0.0f)
    {
        notify(WARN) << "warning dt = "<<dt<<endl;
        dt = 0.0f;
    }

    unsigned int buttonMask = _ga_t1->getButtonMask();
    if (buttonMask==GUIEventAdapter::LEFT_BUTTON)
    {
        // pan model.

        _velocity += dt*_modelScale*0.05f;

    }
    else if (buttonMask==GUIEventAdapter::MIDDLE_BUTTON ||
        buttonMask==(GUIEventAdapter::LEFT_BUTTON|GUIEventAdapter::RIGHT_BUTTON))
    {

        _velocity = 0.0f;

    }
    else if (buttonMask==GUIEventAdapter::RIGHT_BUTTON)
    {

        _velocity -= dt*_modelScale*0.05f;

    }

    float mx = (_ga_t0->getXmin()+_ga_t0->getXmax())/2.0f;
    float my = (_ga_t0->getYmin()+_ga_t0->getYmax())/2.0f;

    float dx = _ga_t0->getX()-mx;
    float dy = _ga_t0->getY()-my;

    osg::Vec3 center = _camera->getEyePoint();
    osg::Vec3 sv = _camera->getSideVector();
    osg::Vec3 lv = _camera->getLookVector();

    float pitch = inDegrees(-dy*0.15f*dt);
    float roll = inDegrees(-dx*0.1f*dt);

    osg::Matrix mat;
    mat.makeTrans(-center);
    mat *= Matrix::rotate(pitch,sv.x(),sv.y(),sv.z());
    mat *= Matrix::rotate(roll,lv.x(),lv.y(),lv.z());
    if (_yawMode==YAW_AUTOMATICALLY_WHEN_BANKED)
    {
        float bank = asinf(sv.z());
        float yaw = inRadians(-bank)*dt;
        mat *= Matrix::rotate(yaw,0.0f,0.0f,1.0f);
    }

    lv *= (_velocity*dt);

    mat *= Matrix::trans(center + lv);

    _camera->transformLookAt(mat);

    return true;
}
<commit_msg>Fixed rotations to account to the fixes made to Quat and Matrix related to right hand rule rotation.<commit_after>#include <osg/Notify>
#include <osg/Types>

#include "GliderManipulator.h"

using namespace osg;
using namespace osgUtil;

GliderManipulator::GliderManipulator()
{
    _modelScale = 0.01f;
    _velocity = 0.0f;
    _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED;
}

GliderManipulator::~GliderManipulator()
{
}

void GliderManipulator::setNode(osg::Node* node)
{
    _node = node;
    if (_node.get())
    {
        const osg::BoundingSphere& boundingSphere=_node->getBound();
        _modelScale = boundingSphere._radius;
    }
}

const osg::Node* GliderManipulator::getNode() const
{
    return _node.get();
}

void GliderManipulator::home(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    if(_node.get() && _camera.get())
    {

        const osg::BoundingSphere& boundingSphere=_node->getBound();

        osg::Vec3 eye = boundingSphere._center+osg::Vec3(-boundingSphere._radius*0.15f,-boundingSphere._radius*0.15f,-boundingSphere._radius*0.03f);

        _camera->setView(eye,
            eye+osg::Vec3(1.0f,1.0f,-0.1f),
            osg::Vec3(0.0f,0.0f,1.0f));

        _velocity = boundingSphere._radius*0.01f;

        us.requestRedraw();

        us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2,(ea.getYmin()+ea.getYmax())/2);

        flushMouseEventStack();

    }

}

void GliderManipulator::init(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    flushMouseEventStack();

    us.requestContinuousUpdate(false);

    const osg::BoundingSphere& boundingSphere=_node->getBound();
    _velocity = boundingSphere._radius*0.01f;

    us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2,(ea.getYmin()+ea.getYmax())/2);

}

bool GliderManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    if(!_camera.get()) return false;

    switch(ea.getEventType())
    {
        case(GUIEventAdapter::PUSH):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();

        }
        return true;
        case(GUIEventAdapter::RELEASE):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();

        }
        return true;
        case(GUIEventAdapter::DRAG):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();

        }
        return true;
        case(GUIEventAdapter::MOVE):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();

        }
        return true;

        case(GUIEventAdapter::KEYBOARD):
            if (ea.getKey()==' ')
            {
                flushMouseEventStack();
                home(ea,us);
                us.requestRedraw();
                us.requestContinuousUpdate(false);
                return true;
            }
            return false;
        case(GUIEventAdapter::FRAME):
            addMouseEvent(ea);
            if (calcMovement()) us.requestRedraw();
            return true;
        case(GUIEventAdapter::RESIZE):
        {
            init(ea,us);
            us.requestRedraw();
        }
        return true;
        default:
            return false;
    }
}

void GliderManipulator::flushMouseEventStack()
{
    _ga_t1 = NULL;
    _ga_t0 = NULL;
}

void GliderManipulator::addMouseEvent(const GUIEventAdapter& ea)
{
    _ga_t1 = _ga_t0;
    _ga_t0 = &ea;
}

bool GliderManipulator::calcMovement()
{
    // return if less then two events have been added.
    if (_ga_t0.get()==NULL || _ga_t1.get()==NULL) return false;

    float dt = _ga_t0->time()-_ga_t1->time();

    if (dt<0.0f)
    {
        notify(WARN) << "warning dt = "<<dt<<endl;
        dt = 0.0f;
    }

    unsigned int buttonMask = _ga_t1->getButtonMask();
    if (buttonMask==GUIEventAdapter::LEFT_BUTTON)
    {
        // pan model.

        _velocity += dt*_modelScale*0.05f;

    }
    else if (buttonMask==GUIEventAdapter::MIDDLE_BUTTON ||
        buttonMask==(GUIEventAdapter::LEFT_BUTTON|GUIEventAdapter::RIGHT_BUTTON))
    {

        _velocity = 0.0f;

    }
    else if (buttonMask==GUIEventAdapter::RIGHT_BUTTON)
    {

        _velocity -= dt*_modelScale*0.05f;

    }

    float mx = (_ga_t0->getXmin()+_ga_t0->getXmax())/2.0f;
    float my = (_ga_t0->getYmin()+_ga_t0->getYmax())/2.0f;

    float dx = _ga_t0->getX()-mx;
    float dy = _ga_t0->getY()-my;

    osg::Vec3 center = _camera->getEyePoint();
    osg::Vec3 sv = _camera->getSideVector();
    osg::Vec3 lv = _camera->getLookVector();

    float pitch = inDegrees(dy*0.15f*dt);
    float roll = inDegrees(dx*0.1f*dt);

    osg::Matrix mat;
    mat.makeTrans(-center);
    mat *= Matrix::rotate(pitch,sv.x(),sv.y(),sv.z());
    mat *= Matrix::rotate(roll,lv.x(),lv.y(),lv.z());
    if (_yawMode==YAW_AUTOMATICALLY_WHEN_BANKED)
    {
        float bank = asinf(sv.z());
        float yaw = inRadians(bank)*dt;
        mat *= Matrix::rotate(yaw,0.0f,0.0f,1.0f);
    }

    lv *= (_velocity*dt);

    mat *= Matrix::trans(center + lv);

    _camera->transformLookAt(mat);

    return true;
}
<|endoftext|>