<commit_before>#include <cmath>

#include <vector>
#include <algorithm>
#include <thread>

#include "Python.h"
#include "numpy/arrayobject.h"

#include "kdtree.h"
#include "geometry.h"

typedef geometry::Point<double, 3> Point;

static char module_docstring[] = "Discrete natural neighbor interpolation in 3D.";

static char griddata_docstring[] = "Calculate the natural neighbor interpolation of a dataset.";

static PyObject* cnaturalneighbor_griddata(PyObject* self, PyObject* args);

static PyMethodDef module_methods[] = {
    {"griddata", cnaturalneighbor_griddata, METH_VARARGS, griddata_docstring},
    {NULL, NULL, 0, NULL}
};

/*
The macros below are for backward compatibility with Python 2.
Here, the functions used to creating and initializing modules
differ in both their names and their signatures.

Module initialization
    2: init<name>, void function (does not return a value)
    3: PyInit_<name>, returns either PyObject/NULL for success/failure
Module creation
    2: Py_InitModule3, takes three input arguments
    3: PyModule_Create, takes input args in a single struct

For more, see http://python3porting.com/cextensions.html
*/
#if PY_MAJOR_VERSION >= 3
    #define MOD_ERROR_VAL NULL
    #define MOD_SUCCESS_VAL(val) val
    #define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void)
    #define MOD_DEF(ob, name, doc, methods) \
        static struct PyModuleDef module = { \
            PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
        ob = PyModule_Create(&module);
#else
    #define MOD_ERROR_VAL
    #define MOD_SUCCESS_VAL(val)
    #define MOD_INIT(name) PyMODINIT_FUNC init##name(void)
    #define MOD_DEF(ob, name, doc, methods) \
        ob = Py_InitModule3(name, methods, doc);
#endif

MOD_INIT(cnaturalneighbor)
{
    PyObject* m;

    MOD_DEF(m, "cnaturalneighbor", module_docstring,
            module_methods)

    if (m == NULL)
        return MOD_ERROR_VAL;

    import_array();

    return MOD_SUCCESS_VAL(m);
}

inline long clamp(long val, long min, long max) {
    return std::min(max, std::max(min, val));
}

void inner_loop(
        int thread_number,
        std::size_t ni,
        std::size_t nj,
        std::size_t nk,
        kdtree::kdtree<double> *tree,
        double* interp_values_ptr,
        unsigned long *contribution_counter) {

    for (std::size_t i = 0; i < ni; i++) {
        for (std::size_t j = 0; j < nj; j++) {
            for (std::size_t k = 0; k < nk; k++) {
                auto query_point = Point(i, j, k);
                auto nearest_known_point = tree->nearest_iterative(query_point);

                double distance_sq_query_to_known = nearest_known_point.distance;
                int roi_radius = ceil(sqrt(distance_sq_query_to_known));

                // TODO: ask the programming gods for forgiveness, and then
                // refactor this; this threading model only makes sense for
                // very specific input shapes
                std::size_t i_roi_min, i_roi_max;
                std::size_t i_middle = floor(ni/2);
                if ((thread_number >> 0) % 2) {
                    i_roi_min = clamp(i - roi_radius, 0, i_middle);
                    i_roi_max = clamp(i + roi_radius, 0, i_middle);
                } else {
                    i_roi_min = clamp(i - roi_radius, i_middle + 1, ni - 1);
                    i_roi_max = clamp(i + roi_radius, i_middle + 1, ni - 1);
                }

                std::size_t j_roi_min, j_roi_max;
                std::size_t j_middle = floor(nj/2);
                if ((thread_number >> 1) % 2) {
                    j_roi_min = clamp(j - roi_radius, 0, j_middle);
                    j_roi_max = clamp(j + roi_radius, 0, j_middle);
                } else {
                    j_roi_min = clamp(j - roi_radius, j_middle + 1, nj - 1);
                    j_roi_max = clamp(j + roi_radius, j_middle + 1, nj - 1);
                }

                std::size_t k_roi_min, k_roi_max;
                std::size_t k_middle = floor(nk/2);
                if ((thread_number >> 2) % 2) {
                    k_roi_min = clamp(k - roi_radius, 0, k_middle);
                    k_roi_max = clamp(k + roi_radius, 0, k_middle);
                } else {
                    k_roi_min = clamp(k - roi_radius, k_middle + 1, nk - 1);
                    k_roi_max = clamp(k + roi_radius, k_middle + 1, nk - 1);
                }

                for (std::size_t i_roi = i_roi_min; i_roi <= i_roi_max; i_roi++) {
                    double deltai_2 = (i - i_roi)*(i - i_roi);
                    std::size_t indice_i_component = nj*nk*i_roi;
                    for (std::size_t j_roi = j_roi_min; j_roi <= j_roi_max; j_roi++) {
                        double deltaj_2 = (j - j_roi)*(j - j_roi);
                        std::size_t indice_j_component = nk*j_roi;
                        for (std::size_t k_roi = k_roi_min; k_roi <= k_roi_max; k_roi++) {
                            double deltak_2 = (k - k_roi)*(k - k_roi);
                            double distance_sq_roi_to_known = deltai_2 + deltaj_2 + deltak_2;

                            if (distance_sq_roi_to_known == 0 || distance_sq_roi_to_known < distance_sq_query_to_known) {
                                std::size_t indice = indice_i_component + indice_j_component + k_roi;
                                interp_values_ptr[indice] += nearest_known_point.value;
                                contribution_counter[indice] += 1;
                            }
                        }
                    }
                }
            }
        }
    }
}

static PyObject* cnaturalneighbor_griddata(PyObject* self, PyObject* args) {
    PyArrayObject *known_points_ijk, *known_values, *interp_values;

    if (!PyArg_ParseTuple(args, "O!O!O!",
                &PyArray_Type, &known_points_ijk,
                &PyArray_Type, &known_values,
                &PyArray_Type, &interp_values)) {
        return NULL;
    }

    npy_intp* known_points_ijk_dims = PyArray_DIMS(known_points_ijk);
    std::size_t num_known_points = known_points_ijk_dims[0];

    npy_intp* interp_values_shape = PyArray_DIMS(interp_values);
    std::size_t ni = interp_values_shape[0];
    std::size_t nj = interp_values_shape[1];
    std::size_t nk = interp_values_shape[2];

    double* interp_values_ptr = (double*)PyArray_GETPTR1(interp_values, 0);

    kdtree::kdtree<double> *tree = new kdtree::kdtree<double>();
    for (std::size_t i = 0; i < num_known_points; i++) {
        Point p {
            *(double*)PyArray_GETPTR2(known_points_ijk, i, 0),
            *(double*)PyArray_GETPTR2(known_points_ijk, i, 1),
            *(double*)PyArray_GETPTR2(known_points_ijk, i, 2)
        };
        double v {*(double*)PyArray_GETPTR1(known_values, i)};
        tree->add(p, v);
    }
    tree->build();

    auto contribution_counter = new unsigned long[ni*nj*nk]();

    std::vector<std::thread> threads;
    std::size_t num_threads = 8;  // you can't change this at the moment!
    for (std::size_t thread_number = 0; thread_number < num_threads; thread_number++) {
        threads.push_back(std::thread(&inner_loop,
                thread_number,
                ni,
                nj,
                nk,
                tree,
                interp_values_ptr,
                contribution_counter));
    }

    for (auto& th : threads) {
        th.join();
    }

    for (std::size_t i = 0; i < ni; i++) {
        for (std::size_t j = 0; j < nj; j++) {
            for (std::size_t k = 0; k < nk; k++) {
                auto indice = nj*nk*i + nk*j + k;
                if (contribution_counter[indice] != 0) {
                    interp_values_ptr[indice] /= contribution_counter[indice];
                }
            }
        }
    }

    delete[] contribution_counter;
    delete tree;

    Py_RETURN_NONE;
}
<commit_msg>Conform to coding/style conventions<commit_after>#include <cmath>

#include <vector>
#include <algorithm>
#include <thread>

#include "Python.h"
#include "numpy/arrayobject.h"

#include "kdtree.h"
#include "geometry.h"

typedef geometry::Point<double, 3> Point;

static char module_docstring[] = "Discrete natural neighbor interpolation in 3D.";

static char griddata_docstring[] = "Calculate the natural neighbor interpolation of a dataset.";

static PyObject* cnaturalneighbor_griddata(PyObject* self, PyObject* args);

static PyMethodDef module_methods[] = {
    {"griddata", cnaturalneighbor_griddata, METH_VARARGS, griddata_docstring},
    {NULL, NULL, 0, NULL}
};

/*
The macros below are for backward compatibility with Python 2.
Here, the functions used to creating and initializing modules
differ in both their names and their signatures.

Module initialization
    2: init<name>, void function (does not return a value)
    3: PyInit_<name>, returns either PyObject/NULL for success/failure
Module creation
    2: Py_InitModule3, takes three input arguments
    3: PyModule_Create, takes input args in a single struct

For more, see http://python3porting.com/cextensions.html
*/
#if PY_MAJOR_VERSION >= 3
    #define MOD_ERROR_VAL NULL
    #define MOD_SUCCESS_VAL(val) val
    #define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void)
    #define MOD_DEF(ob, name, doc, methods) \
        static struct PyModuleDef module = { \
            PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
        ob = PyModule_Create(&module);
#else
    #define MOD_ERROR_VAL
    #define MOD_SUCCESS_VAL(val)
    #define MOD_INIT(name) PyMODINIT_FUNC init##name(void)
    #define MOD_DEF(ob, name, doc, methods) \
        ob = Py_InitModule3(name, methods, doc);
#endif

MOD_INIT(cnaturalneighbor) {
    PyObject* m;

    MOD_DEF(m, "cnaturalneighbor", module_docstring, module_methods);

    if (m == NULL) {
        return MOD_ERROR_VAL;
    }

    import_array();

    return MOD_SUCCESS_VAL(m);
}

inline long clamp(long val, long min, long max) {
    return std::min(max, std::max(min, val));
}

void inner_loop(
        int thread_number,
        std::size_t ni,
        std::size_t nj,
        std::size_t nk,
        kdtree::kdtree<double> *tree,
        double* interp_values_ptr,
        unsigned long *contribution_counter) {

    for (std::size_t i = 0; i < ni; i++) {
        for (std::size_t j = 0; j < nj; j++) {
            for (std::size_t k = 0; k < nk; k++) {
                auto query_point = Point(i, j, k);
                auto nearest_known_point = tree->nearest_iterative(query_point);

                double distance_sq_query_to_known = nearest_known_point.distance;
                int roi_radius = ceil(sqrt(distance_sq_query_to_known));

                // TODO: ask the programming gods for forgiveness, and then
                // refactor this; this threading model only makes sense for
                // very specific input shapes
                std::size_t i_roi_min, i_roi_max;
                std::size_t i_middle = floor(ni/2);
                if ((thread_number >> 0) % 2) {
                    i_roi_min = clamp(i - roi_radius, 0, i_middle);
                    i_roi_max = clamp(i + roi_radius, 0, i_middle);
                } else {
                    i_roi_min = clamp(i - roi_radius, i_middle + 1, ni - 1);
                    i_roi_max = clamp(i + roi_radius, i_middle + 1, ni - 1);
                }

                std::size_t j_roi_min, j_roi_max;
                std::size_t j_middle = floor(nj/2);
                if ((thread_number >> 1) % 2) {
                    j_roi_min = clamp(j - roi_radius, 0, j_middle);
                    j_roi_max = clamp(j + roi_radius, 0, j_middle);
                } else {
                    j_roi_min = clamp(j - roi_radius, j_middle + 1, nj - 1);
                    j_roi_max = clamp(j + roi_radius, j_middle + 1, nj - 1);
                }

                std::size_t k_roi_min, k_roi_max;
                std::size_t k_middle = floor(nk/2);
                if ((thread_number >> 2) % 2) {
                    k_roi_min = clamp(k - roi_radius, 0, k_middle);
                    k_roi_max = clamp(k + roi_radius, 0, k_middle);
                } else {
                    k_roi_min = clamp(k - roi_radius, k_middle + 1, nk - 1);
                    k_roi_max = clamp(k + roi_radius, k_middle + 1, nk - 1);
                }

                for (std::size_t i_roi = i_roi_min; i_roi <= i_roi_max; i_roi++) {
                    double deltai_2 = (i - i_roi)*(i - i_roi);
                    std::size_t indice_i_component = nj*nk*i_roi;
                    for (std::size_t j_roi = j_roi_min; j_roi <= j_roi_max; j_roi++) {
                        double deltaj_2 = (j - j_roi)*(j - j_roi);
                        std::size_t indice_j_component = nk*j_roi;
                        for (std::size_t k_roi = k_roi_min; k_roi <= k_roi_max; k_roi++) {
                            double deltak_2 = (k - k_roi)*(k - k_roi);
                            double distance_sq_roi_to_known = deltai_2 + deltaj_2 + deltak_2;

                            if (distance_sq_roi_to_known == 0 || distance_sq_roi_to_known < distance_sq_query_to_known) {
                                std::size_t indice = indice_i_component + indice_j_component + k_roi;
                                interp_values_ptr[indice] += nearest_known_point.value;
                                contribution_counter[indice] += 1;
                            }
                        }
                    }
                }
            }
        }
    }
}

static PyObject* cnaturalneighbor_griddata(PyObject* self, PyObject* args) {
    PyArrayObject *known_points_ijk, *known_values, *interp_values;

    if (!PyArg_ParseTuple(args, "O!O!O!",
                &PyArray_Type, &known_points_ijk,
                &PyArray_Type, &known_values,
                &PyArray_Type, &interp_values)) {
        return NULL;
    }

    npy_intp* known_points_ijk_dims = PyArray_DIMS(known_points_ijk);
    std::size_t num_known_points = known_points_ijk_dims[0];

    npy_intp* interp_values_shape = PyArray_DIMS(interp_values);
    std::size_t ni = interp_values_shape[0];
    std::size_t nj = interp_values_shape[1];
    std::size_t nk = interp_values_shape[2];

    double* interp_values_ptr = (double*)PyArray_GETPTR1(interp_values, 0);

    kdtree::kdtree<double> *tree = new kdtree::kdtree<double>();
    for (std::size_t i = 0; i < num_known_points; i++) {
        Point p {
            *(double*)PyArray_GETPTR2(known_points_ijk, i, 0),
            *(double*)PyArray_GETPTR2(known_points_ijk, i, 1),
            *(double*)PyArray_GETPTR2(known_points_ijk, i, 2)
        };
        double v {*(double*)PyArray_GETPTR1(known_values, i)};
        tree->add(p, v);
    }
    tree->build();

    auto contribution_counter = new unsigned long[ni*nj*nk]();

    std::vector<std::thread> threads;
    std::size_t num_threads = 8;  // you can't change this at the moment!
    for (std::size_t thread_number = 0; thread_number < num_threads; thread_number++) {
        threads.push_back(std::thread(&inner_loop,
                thread_number,
                ni,
                nj,
                nk,
                tree,
                interp_values_ptr,
                contribution_counter));
    }

    for (auto& th : threads) {
        th.join();
    }

    for (std::size_t i = 0; i < ni; i++) {
        for (std::size_t j = 0; j < nj; j++) {
            for (std::size_t k = 0; k < nk; k++) {
                auto indice = nj*nk*i + nk*j + k;
                if (contribution_counter[indice] != 0) {
                    interp_values_ptr[indice] /= contribution_counter[indice];
                }
            }
        }
    }

    delete[] contribution_counter;
    delete tree;

    Py_RETURN_NONE;
}
<|endoftext|>


<commit_before>#include "ModelObject.h"

// getters
const ModelObject::Vector3D ModelObject::Position() const
{
  return position_;
}

const ModelObject::Vector3D ModelObject::Velocity() const
{
  return velocity_;
}
const ModelObject::Vector3D ModelObject::Force() const
{
  return force_;
}

const double   ModelObject::Mass() const
{
  return mass_;
}

const double   ModelObject::Radius() const
{
  return radius_;
}

// setters
void ModelObject::SetPosition(Vector3D position)
{
  position_ = position;
}

void ModelObject::SetVelocity(Vector3D velocity)
{
  velocity_ = velocity;
}

void ModelObject::SetForce(Vector3D force)
{
  force_ = force;
}

void ModelObject::SetMass(double mass)
{
  mass_ = mass;
}
<commit_msg>Implemented constructors and Advance<commit_after>#include "ModelObject.h"
#include <cmath>

// default ctor
ModelObject::ModelObject()
  : position_(0, 0, 0), velocity_(0, 0, 0), force_(0, 0, 0), mass_(0), radius_(0)
{}

// position, velocity, force, mass, radius
ModelObject::ModelObject(
  Vector3D position,
  Vector3D velocity,
  Vector3D force,
  double mass,
  double radius)
  : position_(position),
    velocity_(velocity),
    force_(force),
    mass_(mass),
    radius_(radius)
{}

void ModelObject::Advance(double time)
{
  Vector3 acceleration = force_ * (1.0f / mass_);

  position_ += velocity_ * time; // v(0) * t
  position_ += acceleration * 0.5 * std::pow(time, 2.0); // 1/2 * a * t^2

  velocity_ += acceleration * time; // v(t) = v(0) + at
}

// getters
const ModelObject::Vector3D ModelObject::Position() const
{
  return position_;
}

const ModelObject::Vector3D ModelObject::Velocity() const
{
  return velocity_;
}
const ModelObject::Vector3D ModelObject::Force() const
{
  return force_;
}

const double   ModelObject::Mass() const
{
  return mass_;
}

const double   ModelObject::Radius() const
{
  return radius_;
}

// setters
void ModelObject::SetPosition(Vector3D position)
{
  position_ = position;
}

void ModelObject::SetVelocity(Vector3D velocity)
{
  velocity_ = velocity;
}

void ModelObject::SetForce(Vector3D force)
{
  force_ = force;
}

void ModelObject::SetMass(double mass)
{
  mass_ = mass;
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <ros/console.h>

#include <math.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/CameraInfo.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Int8.h>
#include <std_msgs/UInt16MultiArray.h>
#include <std_msgs/Int32MultiArray.h>

// Customized message
#include <drv_msgs/target_info.h>

#include <stdio.h>

#include "targetselecter.h"
#include "facelistener.h"
#include "targetlistener.h"

using namespace std;
using namespace std_msgs;

/* Global params */
// Feedback
// 0:not working, 1:working, 2:failed, 3:finished with success
string param_vision_feedback = "/comm/param/feedback/vision/overall";
// 0:wandering, 1:searching, 2:tracking
string param_vision_feedback_mode = "/comm/param/feedback/vision/mode";
// 0:no search, 1:found, -1:current not found. -2:around not found
string param_vision_feedback_search = "/comm/param/feedback/vision/search";
// 0:no track, 1:tracking, -1:lost
string param_vision_feedback_track = "/comm/param/feedback/vision/track";
// 0:no grasp, 1:found location, -1:can't find location
string param_vision_feedback_grasp = "/comm/param/feedback/vision/grasp";
// 0:no face recognize, 1:found faces, -1:failed to recognize
string param_vision_feedback_face = "/comm/param/feedback/vision/face";
// vision shared
// true:switch on to execute tasks, false:switch off and run in wander mode
string param_vision_shared_switch = "/comm/param/shared/vision/switch";

bool centralSwitch_ = true; // main switch

// Target properties
bool targetSetTemp_ = false;
// Param inside vision system
string param_target_label = "/vision/target/label";

enum TargetType{t_null, t_onTable, t_onGround, t_onHead, t_onHand};
string targetTypeName[5] = {"in air", "on the table", "on the ground",
                            "on the face", "in the hand"};
int tgtType_ = t_null;
string param_target_type = "/status/target/type";

string param_comm_target_set =   "/comm/param/control/target/is_set";
string param_comm_target_label = "/comm/param/control/target/label";
string param_comm_is_put = "/comm/param/ctrl/is_put";  // Is put down object in hand

// Target status control
bool isTargetSet_ = false;
string targetLabel_ = "";
bool isPut_ = false;

// Target status feedback
bool foundTarget_ = false;
int putSuccess_ = 0;

// Publish servo initial position
ros::Publisher servoPub_;
bool servo_initialized_ = false;

// Servo initial angles
int pitchAngle_ = 70;
int yawAngle_ = 90;
// Range of servo angles
int pitch_min_ = 60;
int pitch_max_ = 140;
int yaw_min_ = 0;
int yaw_max_ = 180;
// The rosparam that store pitch and yaw values
string param_servo_pitch = "/status/servo/pitch";
string param_servo_yaw = "/status/servo/yaw";

// Mode control params
enum ModeType{m_wander, m_search, m_track, m_put};
int modeType_ = m_wander;
int modeTypeTemp_ = -1;
string modeName[4] = {"wandering", "searching", "tracking", "putting"};
string param_running_mode = "/status/running_mode";
ros::Publisher drvPubMode_; // vision system mode publisher

// General information publisher
ros::Publisher drvPubInfo_;

// Result publisher
ros::Publisher drvPubPutResult_;

void resetStatus()
{
  // Reset global params
  ros::param::set(param_vision_feedback, 0);
  ros::param::set(param_vision_feedback_search, 0);
  ros::param::set(param_vision_feedback_track, 0);
  ros::param::set(param_vision_feedback_grasp, 0);
  ros::param::set(param_vision_feedback_face, 0);

  tgtType_ = t_null;
  targetLabel_ = "";

  isTargetSet_ = false;
  foundTarget_ = false;
  putSuccess_ = 0;

  modeType_ = m_wander;

  ros::param::set(param_comm_target_set, false);
  ros::param::set(param_comm_target_label, "");
  ros::param::set(param_comm_is_put, false);
}

/**
 * @brief pubServo This function is used for servo initialization and
 *                 publishing servo angles received from cellphone
 * @param pitch_angle
 * @param yaw_angle
 * @param power multiplies with basic speed
 */
void pubServo(int pitch_angle, int yaw_angle, int power)
{
  std_msgs::UInt16MultiArray array;
  array.data.push_back(pitch_angle);
  array.data.push_back(yaw_angle);
  // The basic speed is 10 (0~255)
  array.data.push_back(10 * power);
  servoPub_.publish(array);
}

/**
 * @brief pubInfo Publish info for Android display
 * @param info
 */
void pubInfo(string info)
{
  ROS_INFO(info.c_str());
  String msg;
  msg.data = info;
  drvPubInfo_.publish(msg);
}

/**
 * @brief teleOpCallback
 * Receive servo value from JARVIS the Android App
 * @param msg
 * Contains 2 int representing increment in x and y direction
 * with range in [-1, 1]
 */
void teleOpCallback(const Int32MultiArrayConstPtr &msg)
{
  if (msg->data.empty() || (msg->data[0] == 0 && msg->data[1] == 0))
    return;

  int pitch_temp = pitchAngle_ + msg->data[0];
  if (pitch_temp < pitch_min_ || pitch_temp > pitch_max_)
    return;
  else
    pitchAngle_ = pitch_temp;

  int yaw_temp = yawAngle_ - msg->data[1];
  if (yaw_temp < yaw_min_ || yaw_temp > yaw_max_)
    return;
  else
    yawAngle_ = yaw_temp;

  int power = 4;
  pubServo(pitchAngle_, yawAngle_, power);
}

void servoCallback(const UInt16MultiArrayConstPtr &msg)
{
  // This callback should always active
  pitchAngle_ = msg->data[0];
  yawAngle_ = msg->data[1];

  ros::param::set(param_servo_pitch, pitchAngle_);
  ros::param::set(param_servo_yaw, yawAngle_);
}

void searchCallback(const Int8ConstPtr &msg)
{
  if (modeType_ == m_search) {
    if (msg->data == -1) {
      pubInfo("Search report: Search around didn't find target.");
      foundTarget_ = false;
      ros::param::set(param_vision_feedback_search, -2);
      ros::param::set(param_vision_feedback, 2);
    }
    else if (msg->data == 0) {
      pubInfo("Search report: In searching...");
      ros::param::set(param_vision_feedback_search, -1);
      ros::param::set(param_vision_feedback, 1);
      foundTarget_ = false;
    }
    else {
      pubInfo("Search report: Found target.");
      foundTarget_ = true;
      ros::param::set(param_vision_feedback_search, 1);
      ros::param::set(param_vision_feedback, 1);
    }
  }
}

void trackCallback(const BoolConstPtr &msg)
{
  if (modeType_ == m_track) {
    if (!msg->data) {
      ROS_INFO("Track report: Target lost!");
      foundTarget_ = false;
      ros::param::set(param_vision_feedback_track, -1);
      ros::param::set(param_vision_feedback, 1);
    }
    else {
      ROS_INFO_THROTTLE(7, "Track report: Tracking...");
      foundTarget_ = true;
      ros::param::set(param_vision_feedback_track, 1);
      ros::param::set(param_vision_feedback, 1);
    }
  }
}

void graspCallback(const Int8ConstPtr &msg)
{
  if (modeType_ == m_track) {
    if (!msg->data) {
      ROS_INFO_THROTTLE(3, "Grasp report: Failed.");
      ros::param::set(param_vision_feedback_grasp, -1);
      ros::param::set(param_vision_feedback, 1);
    }
    else if (msg->data == 1) {
      ROS_INFO_THROTTLE(3, "Grasp report: Reaching to the target...");
      ros::param::set(param_vision_feedback_grasp, 1);
      ros::param::set(param_vision_feedback, 1);
    }
    else {
      ROS_INFO("Grasp report: Target in reach.");
      // Reset if grasping has been performed
      resetStatus();
    }
  }
}

void putCallback(const Int8ConstPtr &msg)
{
  if (modeType_ == m_put) {
    if (msg->data < 0) {
      ROS_INFO_THROTTLE(3, "Put report: Failed.");
      drvPubPutResult_.publish(msg);
    }
    else if (msg->data == 1) {
      ROS_INFO_THROTTLE(3, "Put report: Succeeded.");
      drvPubPutResult_.publish(msg);
    }
    else {
      ROS_INFO_THROTTLE(11, "Put report: Putting the target...");
    }
    putSuccess_ = msg->data;
  }
}

void faceRecognizeCallback(const BoolConstPtr &msg)
{
  if (modeType_ == m_wander) {
    if (!msg->data) {
      pubInfo("Face report: Failed.");
      ros::param::set(param_vision_feedback_face, -1);
      ros::param::set(param_vision_feedback, 2);
    }
    else {
      pubInfo("Face report: Succeeded.");
      ros::param::set(param_vision_feedback_face, 1);
      ros::param::set(param_vision_feedback, 3);
    }
  }
}

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

  ros::NodeHandle nh;
  ros::NodeHandle pnh("~");

  // Servo's max angle to rotate
  pnh.getParam("pitch_min", pitch_min_);
  pnh.getParam("pitch_max", pitch_max_);
  pnh.getParam("yaw_min", yaw_min_);
  pnh.getParam("yaw_max", yaw_max_);

  servoPub_ = nh.advertise<UInt16MultiArray>("servo", 1, true);
  // For publishing mode info
  drvPubMode_ = nh.advertise<String>("/comm/msg/vision/mode", 1);
  drvPubInfo_ = nh.advertise<String>("/comm/msg/vision/info", 1);

  // Function feedback publishers
  drvPubPutResult_ = nh.advertise<Int8>("/feed/vision/put/result", 1);

  // Don't change the order without reason
  ros::Subscriber sub_servo_ctrl = nh.subscribe<Int32MultiArray>("/joy_teleop/servo", 1, teleOpCallback);
  ros::Subscriber sub_servo = nh.subscribe<UInt16MultiArray>("servo", 1, servoCallback);
  //ros::Subscriber sub_tgt = nh.subscribe<drv_msgs::target_info>("recognize/target", 1, targetCallback);
  ros::Subscriber sub_sh = nh.subscribe<Int8>("status/search/feedback", 1, searchCallback);
  ros::Subscriber sub_tk = nh.subscribe<Bool>("status/track/feedback", 1, trackCallback);
  ros::Subscriber sub_gp = nh.subscribe<Int8>("status/grasp/feedback", 1, graspCallback);
  ros::Subscriber sub_pt = nh.subscribe<Int8>("status/put/feedback", 1, putCallback);
  ros::Subscriber sub_fr = nh.subscribe<Bool>("status/face/feedback", 1, faceRecognizeCallback);

  FaceListener fl;
  TargetListener tl;
  TargetSelecter ts;

  resetStatus();

  pubInfo("Deep Robot Vision system initialized!");

  while (ros::ok()) {
    // Main on/off control
    if (ros::param::has(param_vision_shared_switch)) {
      bool temp = true;
      ros::param::get(param_vision_shared_switch, temp);
      if (temp)
        ROS_WARN_COND(!centralSwitch_, "Brain: Central switch is ON.");
      centralSwitch_ = temp;
    }

    if (!centralSwitch_) {
      ROS_WARN_THROTTLE(9, "Brain: Central switch is OFF.");
      resetStatus();
      continue;
    }

    // Initialize servo position
    if (!servo_initialized_) {
      pubServo(90, 90, 1);
      servo_initialized_ = true;
      ROS_INFO("Brain: Servo reset.");
    }

    // Get feedback to determine whether target were found
    ros::spinOnce();

    // Get target label if the params were set
    tl.getTargetStatus(isTargetSet_, targetLabel_, isPut_);
    ros::param::set(param_target_label, targetLabel_);

    if (isTargetSet_ != targetSetTemp_) {
      if (isTargetSet_)
        pubInfo("Brain: Target set to be '" + targetLabel_ + "'.");
      else {
        pubInfo("Brain: Target cancelled.");
        resetStatus();
      }
      targetSetTemp_ = isTargetSet_;
    }

    // If user selects target on cellphone, publish the target
    ts.publishOnceIfTargetSelected(isTargetSet_, foundTarget_);

    // Mode selection, notice that modeType_ should only be set by central control
    if (isTargetSet_) {
      if (foundTarget_) {
        // No matter whether the target is searched or selected by user,
        // as long as it was found, track it.
        modeType_ = m_track;
      }
      else {
        if (targetLabel_ == "user selected object") {
          // If the target is selected by user but no more been found,
          // which means tracking has lost it, reset.
          pubInfo("Brain: Tracking did not follow.");
          resetStatus();
        }
        else
          modeType_ = m_search;
      }
    }
    else {
      if (isPut_) {
        if (putSuccess_ == 0) {
          modeType_ = m_put;
        }
      }
      modeType_ = m_wander;
      fl.isNeedRecognizeFace(); // Only recognize face in wander mode
    }

    // Set private running mode
    ros::param::set(param_running_mode, modeType_);

    if (modeType_ != modeTypeTemp_) {
      String mode_msg;
      mode_msg.data = modeName[modeType_];
      drvPubMode_.publish(mode_msg);
      ROS_INFO("Brain: Current mode: %s.", modeName[modeType_].c_str());
      modeTypeTemp_ = modeType_;
      if (modeType_ == m_wander) {
        // Reset head pose
        servo_initialized_ = false;
      }
    }
  }

  return 0;
}

<commit_msg>bug fix<commit_after>#include <ros/ros.h>
#include <ros/console.h>

#include <math.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/CameraInfo.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Int8.h>
#include <std_msgs/UInt16MultiArray.h>
#include <std_msgs/Int32MultiArray.h>

// Customized message
#include <drv_msgs/target_info.h>

#include <stdio.h>

#include "targetselecter.h"
#include "facelistener.h"
#include "targetlistener.h"

using namespace std;
using namespace std_msgs;

/* Global params */
// Feedback
// 0:not working, 1:working, 2:failed, 3:finished with success
string param_vision_feedback = "/comm/param/feedback/vision/overall";
// 0:wandering, 1:searching, 2:tracking
string param_vision_feedback_mode = "/comm/param/feedback/vision/mode";
// 0:no search, 1:found, -1:current not found. -2:around not found
string param_vision_feedback_search = "/comm/param/feedback/vision/search";
// 0:no track, 1:tracking, -1:lost
string param_vision_feedback_track = "/comm/param/feedback/vision/track";
// 0:no grasp, 1:found location, -1:can't find location
string param_vision_feedback_grasp = "/comm/param/feedback/vision/grasp";
// 0:no face recognize, 1:found faces, -1:failed to recognize
string param_vision_feedback_face = "/comm/param/feedback/vision/face";
// vision shared
// true:switch on to execute tasks, false:switch off and run in wander mode
string param_vision_shared_switch = "/comm/param/shared/vision/switch";

bool centralSwitch_ = true; // main switch

// Target properties
bool targetSetTemp_ = false;
// Param inside vision system
string param_target_label = "/vision/target/label";

enum TargetType{t_null, t_onTable, t_onGround, t_onHead, t_onHand};
string targetTypeName[5] = {"in air", "on the table", "on the ground",
                            "on the face", "in the hand"};
int tgtType_ = t_null;
string param_target_type = "/status/target/type";

string param_comm_target_set =   "/comm/param/control/target/is_set";
string param_comm_target_label = "/comm/param/control/target/label";
string param_comm_is_put = "/comm/param/ctrl/is_put";  // Is put down object in hand

// Target status control
bool isTargetSet_ = false;
string targetLabel_ = "";
bool isPut_ = false;

// Target status feedback
bool foundTarget_ = false;
int putSuccess_ = 0;

// Publish servo initial position
ros::Publisher servoPub_;
bool servo_initialized_ = false;

// Servo initial angles
int pitchAngle_ = 70;
int yawAngle_ = 90;
// Range of servo angles
int pitch_min_ = 60;
int pitch_max_ = 140;
int yaw_min_ = 0;
int yaw_max_ = 180;
// The rosparam that store pitch and yaw values
string param_servo_pitch = "/status/servo/pitch";
string param_servo_yaw = "/status/servo/yaw";

// Mode control params
enum ModeType{m_wander, m_search, m_track, m_put};
int modeType_ = m_wander;
int modeTypeTemp_ = -1;
string modeName[4] = {"wandering", "searching", "tracking", "putting"};
string param_running_mode = "/status/running_mode";
ros::Publisher drvPubMode_; // vision system mode publisher

// General information publisher
ros::Publisher drvPubInfo_;

// Result publisher
ros::Publisher drvPubPutResult_;

void resetStatus()
{
  // Reset global params
  ros::param::set(param_vision_feedback, 0);
  ros::param::set(param_vision_feedback_search, 0);
  ros::param::set(param_vision_feedback_track, 0);
  ros::param::set(param_vision_feedback_grasp, 0);
  ros::param::set(param_vision_feedback_face, 0);

  tgtType_ = t_null;
  targetLabel_ = "";

  isTargetSet_ = false;
  foundTarget_ = false;
  putSuccess_ = 0;

  modeType_ = m_wander;

  ros::param::set(param_comm_target_set, false);
  ros::param::set(param_comm_target_label, "");
  ros::param::set(param_comm_is_put, false);
}

/**
 * @brief pubServo This function is used for servo initialization and
 *                 publishing servo angles received from cellphone
 * @param pitch_angle
 * @param yaw_angle
 * @param power multiplies with basic speed
 */
void pubServo(int pitch_angle, int yaw_angle, int power)
{
  std_msgs::UInt16MultiArray array;
  array.data.push_back(pitch_angle);
  array.data.push_back(yaw_angle);
  // The basic speed is 10 (0~255)
  array.data.push_back(10 * power);
  servoPub_.publish(array);
}

/**
 * @brief pubInfo Publish info for Android display
 * @param info
 */
void pubInfo(string info)
{
  ROS_INFO(info.c_str());
  String msg;
  msg.data = info;
  drvPubInfo_.publish(msg);
}

/**
 * @brief teleOpCallback
 * Receive servo value from JARVIS the Android App
 * @param msg
 * Contains 2 int representing increment in x and y direction
 * with range in [-1, 1]
 */
void teleOpCallback(const Int32MultiArrayConstPtr &msg)
{
  if (msg->data.empty() || (msg->data[0] == 0 && msg->data[1] == 0))
    return;

  int pitch_temp = pitchAngle_ + msg->data[0];
  if (pitch_temp < pitch_min_ || pitch_temp > pitch_max_)
    return;
  else
    pitchAngle_ = pitch_temp;

  int yaw_temp = yawAngle_ - msg->data[1];
  if (yaw_temp < yaw_min_ || yaw_temp > yaw_max_)
    return;
  else
    yawAngle_ = yaw_temp;

  int power = 4;
  pubServo(pitchAngle_, yawAngle_, power);
}

void servoCallback(const UInt16MultiArrayConstPtr &msg)
{
  // This callback should always active
  pitchAngle_ = msg->data[0];
  yawAngle_ = msg->data[1];

  ros::param::set(param_servo_pitch, pitchAngle_);
  ros::param::set(param_servo_yaw, yawAngle_);
}

void searchCallback(const Int8ConstPtr &msg)
{
  if (modeType_ == m_search) {
    if (msg->data == -1) {
      pubInfo("Search report: Search around didn't find target.");
      foundTarget_ = false;
      ros::param::set(param_vision_feedback_search, -2);
      ros::param::set(param_vision_feedback, 2);
    }
    else if (msg->data == 0) {
      pubInfo("Search report: In searching...");
      ros::param::set(param_vision_feedback_search, -1);
      ros::param::set(param_vision_feedback, 1);
      foundTarget_ = false;
    }
    else {
      pubInfo("Search report: Found target.");
      foundTarget_ = true;
      ros::param::set(param_vision_feedback_search, 1);
      ros::param::set(param_vision_feedback, 1);
    }
  }
}

void trackCallback(const BoolConstPtr &msg)
{
  if (modeType_ == m_track) {
    if (!msg->data) {
      ROS_INFO("Track report: Target lost!");
      foundTarget_ = false;
      ros::param::set(param_vision_feedback_track, -1);
      ros::param::set(param_vision_feedback, 1);
    }
    else {
      ROS_INFO_THROTTLE(7, "Track report: Tracking...");
      foundTarget_ = true;
      ros::param::set(param_vision_feedback_track, 1);
      ros::param::set(param_vision_feedback, 1);
    }
  }
}

void graspCallback(const Int8ConstPtr &msg)
{
  if (modeType_ == m_track) {
    if (!msg->data) {
      ROS_INFO_THROTTLE(3, "Grasp report: Failed.");
      ros::param::set(param_vision_feedback_grasp, -1);
      ros::param::set(param_vision_feedback, 1);
    }
    else if (msg->data == 1) {
      ROS_INFO_THROTTLE(3, "Grasp report: Reaching to the target...");
      ros::param::set(param_vision_feedback_grasp, 1);
      ros::param::set(param_vision_feedback, 1);
    }
    else {
      ROS_INFO("Grasp report: Target in reach.");
      // Reset if grasping has been performed
      resetStatus();
    }
  }
}

void putCallback(const Int8ConstPtr &msg)
{
  if (modeType_ == m_put) {
    if (msg->data < 0) {
      ROS_INFO_THROTTLE(3, "Put report: Failed.");
      drvPubPutResult_.publish(msg);
    }
    else if (msg->data == 1) {
      ROS_INFO_THROTTLE(3, "Put report: Succeeded.");
      drvPubPutResult_.publish(msg);
    }
    else {
      ROS_INFO_THROTTLE(11, "Put report: Putting the target...");
    }
    putSuccess_ = msg->data;
  }
}

void faceRecognizeCallback(const BoolConstPtr &msg)
{
  if (modeType_ == m_wander) {
    if (!msg->data) {
      pubInfo("Face report: Failed.");
      ros::param::set(param_vision_feedback_face, -1);
      ros::param::set(param_vision_feedback, 2);
    }
    else {
      pubInfo("Face report: Succeeded.");
      ros::param::set(param_vision_feedback_face, 1);
      ros::param::set(param_vision_feedback, 3);
    }
  }
}

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

  ros::NodeHandle nh;
  ros::NodeHandle pnh("~");

  // Servo's max angle to rotate
  pnh.getParam("pitch_min", pitch_min_);
  pnh.getParam("pitch_max", pitch_max_);
  pnh.getParam("yaw_min", yaw_min_);
  pnh.getParam("yaw_max", yaw_max_);

  servoPub_ = nh.advertise<UInt16MultiArray>("servo", 1, true);
  // For publishing mode info
  drvPubMode_ = nh.advertise<String>("/comm/msg/vision/mode", 1);
  drvPubInfo_ = nh.advertise<String>("/comm/msg/vision/info", 1);

  // Function feedback publishers
  drvPubPutResult_ = nh.advertise<Int8>("/feed/vision/put/result", 1);

  // Don't change the order without reason
  ros::Subscriber sub_servo_ctrl = nh.subscribe<Int32MultiArray>("/joy_teleop/servo", 1, teleOpCallback);
  ros::Subscriber sub_servo = nh.subscribe<UInt16MultiArray>("servo", 1, servoCallback);
  //ros::Subscriber sub_tgt = nh.subscribe<drv_msgs::target_info>("recognize/target", 1, targetCallback);
  ros::Subscriber sub_sh = nh.subscribe<Int8>("status/search/feedback", 1, searchCallback);
  ros::Subscriber sub_tk = nh.subscribe<Bool>("status/track/feedback", 1, trackCallback);
  ros::Subscriber sub_gp = nh.subscribe<Int8>("status/grasp/feedback", 1, graspCallback);
  ros::Subscriber sub_pt = nh.subscribe<Int8>("status/put/feedback", 1, putCallback);
  ros::Subscriber sub_fr = nh.subscribe<Bool>("status/face/feedback", 1, faceRecognizeCallback);

  FaceListener fl;
  TargetListener tl;
  TargetSelecter ts;

  resetStatus();

  pubInfo("Deep Robot Vision system initialized!");

  while (ros::ok()) {
    // Main on/off control
    if (ros::param::has(param_vision_shared_switch)) {
      bool temp = true;
      ros::param::get(param_vision_shared_switch, temp);
      if (temp)
        ROS_WARN_COND(!centralSwitch_, "Brain: Central switch is ON.");
      centralSwitch_ = temp;
    }

    if (!centralSwitch_) {
      ROS_WARN_THROTTLE(9, "Brain: Central switch is OFF.");
      resetStatus();
      continue;
    }

    // Initialize servo position
    if (!servo_initialized_) {
      pubServo(90, 90, 1);
      servo_initialized_ = true;
      ROS_INFO("Brain: Servo reset.");
    }

    // Get feedback to determine whether target were found
    ros::spinOnce();

    // Get target label if the params were set
    tl.getTargetStatus(isTargetSet_, targetLabel_, isPut_);
    ros::param::set(param_target_label, targetLabel_);

    if (isTargetSet_ != targetSetTemp_) {
      if (isTargetSet_)
        pubInfo("Brain: Target set to be '" + targetLabel_ + "'.");
      else {
        pubInfo("Brain: Target cancelled.");
        resetStatus();
      }
      targetSetTemp_ = isTargetSet_;
    }

    // If user selects target on cellphone, publish the target
    ts.publishOnceIfTargetSelected(isTargetSet_, foundTarget_);

    // Mode selection, notice that modeType_ should only be set by central control
    if (isTargetSet_) {
      if (foundTarget_) {
        // No matter whether the target is searched or selected by user,
        // as long as it was found, track it.
        modeType_ = m_track;
      }
      else {
        if (targetLabel_ == "user selected object") {
          // If the target is selected by user but no more been found,
          // which means tracking has lost it, reset.
          pubInfo("Brain: Tracking did not follow.");
          resetStatus();
        }
        else
          modeType_ = m_search;
      }
    }
    else {
      if (isPut_) {
        if (putSuccess_ == 0) {
          modeType_ = m_put;
        }
        else
          modeType_ = m_wander;
      }
      else {
        modeType_ = m_wander;
        fl.isNeedRecognizeFace(); // Only recognize face in wander mode
      }
    }

    // Set private running mode
    ros::param::set(param_running_mode, modeType_);

    if (modeType_ != modeTypeTemp_) {
      String mode_msg;
      mode_msg.data = modeName[modeType_];
      drvPubMode_.publish(mode_msg);
      ROS_INFO("Brain: Current mode: %s.", modeName[modeType_].c_str());
      modeTypeTemp_ = modeType_;
      if (modeType_ == m_wander) {
        // Reset head pose
        servo_initialized_ = false;
      }
    }
  }

  return 0;
}

<|endoftext|>


<commit_before>/*
  main.c
  The Knights from Porto

  Created by Daniel Monteiro on 11/26/14.
  Copyright (c) 2014 Daniel Monteiro. All rights reserved.
*/

#include <string>
#include <iostream>
#include <vector>
#include <memory>
#include <ncurses.h>

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CMap.h"
#include "IRenderer.h"
#include "CConsoleRenderer.h"

namespace Knights {

    static const char directions[4] = { '^', '>', 'V', '<'};

    CConsoleRenderer::CConsoleRenderer() {
        initscr();
        clear();
        start_color();
        keypad (stdscr, TRUE);
        noecho();
        cbreak();
        init_pair(1, COLOR_YELLOW, COLOR_BLACK);
        init_pair(2, COLOR_RED, COLOR_BLACK);
        init_pair(3, COLOR_CYAN, COLOR_BLACK);
        init_pair(4, COLOR_GREEN, COLOR_BLACK);
        init_pair(5, COLOR_WHITE, COLOR_BLACK);
    }

    CConsoleRenderer::~CConsoleRenderer() {
        endwin();
    }

    void CConsoleRenderer::drawMap(CMap &map, std::shared_ptr<CActor> current) {

        for (int y = 0; y < 20; ++y) {
            for (int x = 0; x < 20; ++x) {
                move( y, x );

                auto actor = map.getActorAt( Vec2i{ x, y } );

                if (actor != nullptr) {
                    if (actor == current && current != nullptr) {
                        attron(COLOR_PAIR(1));
                        addch(directions[static_cast<int>(current->getDirection()) ]);
                    } else {
                        if ( current != nullptr && actor != nullptr && actor->getTeam() == current->getTeam() ) {
                            attron(COLOR_PAIR(5));
                        } else {
                            attron(COLOR_PAIR(2));
                        }
                        addch(directions[static_cast<int>(actor->getDirection()) ]);
                    }

                } else {
                    if (map.isBlockAt( x, y )) {
                        attron(COLOR_PAIR(3));
                        addch(map.getElementAt( x, y ) );
                    } else {
                        attron(COLOR_PAIR(4));
                        addch('.');
                    }
                }

            }
        }

        attron(COLOR_PAIR(4));
        mvprintw( 22, 0, "-=-=-=-=-=-=-" );

        char buffer[ 7 ];

        if (current != nullptr) {

            snprintf( buffer, 6, "HP: %d", current->getHP() );
            mvprintw( 23,0, buffer );

            snprintf( buffer, 6, "AT: %d", current->getAttack() );
            mvprintw( 24,0, buffer );

            snprintf( buffer, 6, "DF: %d", current->getDefense() );
            mvprintw( 25,0, buffer );

            snprintf( buffer, 6, "AP: %d", current->getAP() );
            mvprintw( 26,0, buffer );
        }
        mvprintw( 27,0, "-//-" );

        refresh();
    }

    char CConsoleRenderer::getInput() {
        int ch = getch();
        switch ( ch ) {
            case KEY_LEFT:
                return 'i';
            case KEY_RIGHT:
                return 'p';
            case KEY_UP:
                return 'o';
            default:
                return ch;
        }
    }
}<commit_msg>Add a silly splash<commit_after>/*
  main.c
  The Knights from Porto

  Created by Daniel Monteiro on 11/26/14.
  Copyright (c) 2014 Daniel Monteiro. All rights reserved.
*/

#include <string>
#include <iostream>
#include <vector>
#include <memory>
#include <ncurses.h>

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CMap.h"
#include "IRenderer.h"
#include "CConsoleRenderer.h"

namespace Knights {

    static const char directions[4] = { '^', '>', 'V', '<'};

    CConsoleRenderer::CConsoleRenderer() {
        initscr();
        clear();
        start_color();
        keypad (stdscr, TRUE);
        noecho();
        cbreak();
        init_pair(1, COLOR_YELLOW, COLOR_BLACK);
        init_pair(2, COLOR_RED, COLOR_BLACK);
        init_pair(3, COLOR_CYAN, COLOR_BLACK);
        init_pair(4, COLOR_GREEN, COLOR_BLACK);
        init_pair(5, COLOR_WHITE, COLOR_BLACK);

        printw( "Dungeons Of Noudar\nCore edition.\nPress any key");
    }

    CConsoleRenderer::~CConsoleRenderer() {
        endwin();
    }

    void CConsoleRenderer::drawMap(CMap &map, std::shared_ptr<CActor> current) {

        for (int y = 0; y < 20; ++y) {
            for (int x = 0; x < 20; ++x) {
                move( y, x );

                auto actor = map.getActorAt( Vec2i{ x, y } );

                if (actor != nullptr) {
                    if (actor == current && current != nullptr) {
                        attron(COLOR_PAIR(1));
                        addch(directions[static_cast<int>(current->getDirection()) ]);
                    } else {
                        if ( current != nullptr && actor != nullptr && actor->getTeam() == current->getTeam() ) {
                            attron(COLOR_PAIR(5));
                        } else {
                            attron(COLOR_PAIR(2));
                        }
                        addch(directions[static_cast<int>(actor->getDirection()) ]);
                    }

                } else {
                    if (map.isBlockAt( x, y )) {
                        attron(COLOR_PAIR(3));
                        addch(map.getElementAt( x, y ) );
                    } else {
                        attron(COLOR_PAIR(4));
                        addch('.');
                    }
                }

            }
        }

        attron(COLOR_PAIR(4));
        mvprintw( 22, 0, "-=-=-=-=-=-=-" );

        char buffer[ 7 ];

        if (current != nullptr) {

            snprintf( buffer, 6, "HP: %d", current->getHP() );
            mvprintw( 23,0, buffer );

            snprintf( buffer, 6, "AT: %d", current->getAttack() );
            mvprintw( 24,0, buffer );

            snprintf( buffer, 6, "DF: %d", current->getDefense() );
            mvprintw( 25,0, buffer );

            snprintf( buffer, 6, "AP: %d", current->getAP() );
            mvprintw( 26,0, buffer );
        }
        mvprintw( 27,0, "-//-" );

        refresh();
    }

    char CConsoleRenderer::getInput() {
        int ch = getch();
        switch ( ch ) {
            case KEY_LEFT:
                return 'i';
            case KEY_RIGHT:
                return 'p';
            case KEY_UP:
                return 'o';
            default:
                return ch;
        }
    }
}<|endoftext|>


<commit_before>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  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.                                   */
/*                                                                                */
/*  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 HOLDER 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.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef VisualizationLibrary_INCLUDE_ONCE
#define VisualizationLibrary_INCLUDE_ONCE

#include <vl/VirtualFile.hpp>
#include <vl/version.hpp>

namespace vl
{
  class FileSystem;
  class ResourceDatabase;
  class KeyValues;
  class StandardLog;
  class FontManager;
  class LoadWriterManager;
  class RenderingAbstract;

  //! Global application settings controlling how Visualization Library behaves.
  class Settings: public Object
  {
    friend class VisualizationLibrary;
  public:
    Settings()
    {
      #ifndef NDEBUG
        mVerbosityLevel  = vl::VEL_VERBOSITY_NORMAL;
        mCheckOpenGLStates = true;
        mCheckTransformSiblings = true;
      #else
        mVerbosityLevel  = vl::VEL_VERBOSITY_ERROR;
        mCheckOpenGLStates = false;
        mCheckTransformSiblings = false;
      #endif
    }

    /** If \p true VL checks at the beginning of each rendering that the OpenGL states are
      * clean and ready to be used by VL. If the test fails it can mean that either there
      * is a bug in VL or that the user did not restore the OpenGL states to a VL friendly
      * state after modifying them.
      * \note This can slow down the rendering. Enabled by default in DEBUG mode only. */
    void setCheckOpenGLStates(bool check_clean) { mCheckOpenGLStates = check_clean; }

    /** If \p true VL checks at the beginning of each rendering that the OpenGL states are
      * clean and ready to be used by VL. If the test fails it can mean that either there
      * is a bug in VL or that the user did not restore the OpenGL states to a VL friendly
      * state after modifying them.
      * \note This can slow down the rendering. Enabled by default in DEBUG mode only. */
    bool checkOpenGLStates() const { return mCheckOpenGLStates; }

    /** If \p true VL checks that there are no duplicates in a Transform children list.
      * \note This can slow down considerably the insertion of new child Transforms.
      * Enabled by default in DEBUG mode only. */
    bool setCheckTransformSiblings(bool check_on) { mCheckTransformSiblings = check_on; }

    /** If \p true VL checks that there are no duplicates in a Transform children list.
      * \note This can slow down considerably the insertion of new child Transforms.
      * Enabled by default in DEBUG mode only. */
    bool checkTransformSiblings() const { return mCheckTransformSiblings; }

    /** The verbosity level of VL. This applies to all the logs generated via vl::Log::*. */
    void setVerbosityLevel(EVerbosityLevel verb_level) { mVerbosityLevel = verb_level; }

    /** The verbosity level of VL. This applies to all the logs generated via vl::Log::*. */
    EVerbosityLevel verbosityLevel() const { return mVerbosityLevel; }

    /** The path of the default log file. */
    const String& defaultLogPath() const { return mDefaultLogPath; }

    /** The path of the default data directory. */
    const String& defaultDataPath() const { return mDefaultDataPath; }

  protected:
    EVerbosityLevel mVerbosityLevel;
    bool mCheckOpenGLStates;
    bool mCheckTransformSiblings;
    String mDefaultLogPath;
    String mDefaultDataPath;
  };

  //! Used to initialize/shutdown VisualizationLibrary and to access important global data.
  class VisualizationLibrary
  {
  public:
    //! Initializes Visualization Library's internal data.
    static void init();

    //! Releases all the resources acquired by Visualization Library.
    static void shutdown();

    //! Returns true if init() has been called and shutdown() has not been called yet.
    static bool initialized();

    //! Returns the Visualization Library's version string.
    static const char* versionString();

    //! Returns Visualization Library's rendering root.
    static RenderingAbstract* rendering();
    static void setRendering(RenderingAbstract* rendering);

    //! Returns Visualization Library's default FileSystem.
    static FileSystem* fileSystem();

    //! Returns Visualization Library's default FontManager.
    static FontManager* fontManager();

    //! Returns Visualization Library's default LoadWriterManager.
    static LoadWriterManager* loadWriterManager();

    //! Returns the environment variables used by Visualization Library.
    //! Can also be used to globally pass parameters across different parts of an application.
    static KeyValues* envVars();

    //! Returns the default Log object.
    static StandardLog* logger();

    //! Returns the global settings of VL.
    static Settings* settings();

    //! For internal use only
    static void* freeTypeLibrary();

  protected:
    //! Initializes the environment variables
    static void initEnvVars();
  };

  //! Shows a console window that displays the standard output. This function is meant to be used only under Windows.
  void showWin32Console();
}

#endif
<commit_msg>fixed warning.<commit_after>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  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.                                   */
/*                                                                                */
/*  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 HOLDER 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.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef VisualizationLibrary_INCLUDE_ONCE
#define VisualizationLibrary_INCLUDE_ONCE

#include <vl/VirtualFile.hpp>
#include <vl/version.hpp>

namespace vl
{
  class FileSystem;
  class ResourceDatabase;
  class KeyValues;
  class StandardLog;
  class FontManager;
  class LoadWriterManager;
  class RenderingAbstract;

  //! Global application settings controlling how Visualization Library behaves.
  class Settings: public Object
  {
    friend class VisualizationLibrary;
  public:
    Settings()
    {
      #ifndef NDEBUG
        mVerbosityLevel  = vl::VEL_VERBOSITY_NORMAL;
        mCheckOpenGLStates = true;
        mCheckTransformSiblings = true;
      #else
        mVerbosityLevel  = vl::VEL_VERBOSITY_ERROR;
        mCheckOpenGLStates = false;
        mCheckTransformSiblings = false;
      #endif
    }

    /** If \p true VL checks at the beginning of each rendering that the OpenGL states are
      * clean and ready to be used by VL. If the test fails it can mean that either there
      * is a bug in VL or that the user did not restore the OpenGL states to a VL friendly
      * state after modifying them.
      * \note This can slow down the rendering. Enabled by default in DEBUG mode only. */
    void setCheckOpenGLStates(bool check_clean) { mCheckOpenGLStates = check_clean; }

    /** If \p true VL checks at the beginning of each rendering that the OpenGL states are
      * clean and ready to be used by VL. If the test fails it can mean that either there
      * is a bug in VL or that the user did not restore the OpenGL states to a VL friendly
      * state after modifying them.
      * \note This can slow down the rendering. Enabled by default in DEBUG mode only. */
    bool checkOpenGLStates() const { return mCheckOpenGLStates; }

    /** If \p true VL checks that there are no duplicates in a Transform children list.
      * \note This can slow down considerably the insertion of new child Transforms.
      * Enabled by default in DEBUG mode only. */
    void setCheckTransformSiblings(bool check_on) { mCheckTransformSiblings = check_on; }

    /** If \p true VL checks that there are no duplicates in a Transform children list.
      * \note This can slow down considerably the insertion of new child Transforms.
      * Enabled by default in DEBUG mode only. */
    bool checkTransformSiblings() const { return mCheckTransformSiblings; }

    /** The verbosity level of VL. This applies to all the logs generated via vl::Log::*. */
    void setVerbosityLevel(EVerbosityLevel verb_level) { mVerbosityLevel = verb_level; }

    /** The verbosity level of VL. This applies to all the logs generated via vl::Log::*. */
    EVerbosityLevel verbosityLevel() const { return mVerbosityLevel; }

    /** The path of the default log file. */
    const String& defaultLogPath() const { return mDefaultLogPath; }

    /** The path of the default data directory. */
    const String& defaultDataPath() const { return mDefaultDataPath; }

  protected:
    EVerbosityLevel mVerbosityLevel;
    bool mCheckOpenGLStates;
    bool mCheckTransformSiblings;
    String mDefaultLogPath;
    String mDefaultDataPath;
  };

  //! Used to initialize/shutdown VisualizationLibrary and to access important global data.
  class VisualizationLibrary
  {
  public:
    //! Initializes Visualization Library's internal data.
    static void init();

    //! Releases all the resources acquired by Visualization Library.
    static void shutdown();

    //! Returns true if init() has been called and shutdown() has not been called yet.
    static bool initialized();

    //! Returns the Visualization Library's version string.
    static const char* versionString();

    //! Returns Visualization Library's rendering root.
    static RenderingAbstract* rendering();
    static void setRendering(RenderingAbstract* rendering);

    //! Returns Visualization Library's default FileSystem.
    static FileSystem* fileSystem();

    //! Returns Visualization Library's default FontManager.
    static FontManager* fontManager();

    //! Returns Visualization Library's default LoadWriterManager.
    static LoadWriterManager* loadWriterManager();

    //! Returns the environment variables used by Visualization Library.
    //! Can also be used to globally pass parameters across different parts of an application.
    static KeyValues* envVars();

    //! Returns the default Log object.
    static StandardLog* logger();

    //! Returns the global settings of VL.
    static Settings* settings();

    //! For internal use only
    static void* freeTypeLibrary();

  protected:
    //! Initializes the environment variables
    static void initEnvVars();
  };

  //! Shows a console window that displays the standard output. This function is meant to be used only under Windows.
  void showWin32Console();
}

#endif
<|endoftext|>


<commit_before>

#include "GA.h"
#include "GAEnemySpawn.h"
#include "GAWaves.h"
#include "GAGameState.h"
#include "Net/UnrealNetwork.h"

AGAWaves::AGAWaves(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	IsFirstTick = true;
	IsSpawnSetActive = false;

	NextWaveTimer = 15;
	NextSpawnActiveTimer = 10;

	SpawnWaveIndex = 0;
	SpawnTimer = 0;

	// Replicate to Server / Clients
	bReplicates = true;
	bAlwaysRelevant = true;

	PrimaryActorTick.bCanEverTick = true;
}

void AGAWaves::Tick(float DeltaTime){
	Super::Tick(DeltaTime);
	InitReamingWaves();
	IncreaseSpawnTimer(DeltaTime);
	SetSpawnActive();
	SpawnNextWave();
}

// Initial Setting of Remaining Waves in Game State
void AGAWaves::InitReamingWaves(){
	if (IsFirstTick) {
		SetRemainingWaves();
		IsFirstTick = false;
	}
}

// Increases the SpawnTimer  *** Only Server Can Increase the Timer ***
void AGAWaves::IncreaseSpawnTimer(float DeltaTime){
	if (Role == ROLE_Authority){																		// Are we server?
		SpawnTimer += DeltaTime;																		// Add Frametime to SpawnTimer
	}
}
// Sets Remaining Waves in GameState  *** SERVER ONLY ***
void AGAWaves::SetRemainingWaves(){
	if (Role == ROLE_Authority){
		if (GetWorld()->GetGameState<AGAGameState>()) {
			GetWorld()->GetGameState<AGAGameState>()->SetRemainingWaves(Waves.Num() - SpawnWaveIndex);
		}
	}
}

void AGAWaves::SetSpawnActive(){
	if (Role == ROLE_Authority){
		if (SpawnTimer >= NextSpawnActiveTimer && !IsSpawnSetActive){
			// Use a random Spawnlocation
			RandIndex = FMath::RandRange(0, EnemySpawns.Num() - 1);
			((AGAEnemySpawn*)EnemySpawns[RandIndex])->SetSpawnActivationStatusTo(true);
			IsSpawnSetActive = true;
		}
	}
}

// Spawns the Next Wave  *** Only Server Can Spawn Waves ***
void AGAWaves::SpawnNextWave(){
	if (Role == ROLE_Authority){																		// Are we server?
		if (SpawnTimer >= NextWaveTimer && SpawnWaveIndex <= Waves.Num() - 1){							// If we have a Wave left and are allowed to spawn
			UE_LOG(LogClass, Log, TEXT("*** SERVER :: SPAWNING WAVE %d ***"),SpawnWaveIndex+1);

			((AGAEnemySpawn*)EnemySpawns[RandIndex])->SetCurrentWave(Waves[SpawnWaveIndex]);

			SpawnWaveIndex++;
			SpawnTimer = 0;
			IsSpawnSetActive = false;

			// Set Remaining Waves in GameState
			SetRemainingWaves();
		}
	}
}

// Replicates All Replicated Properties
void AGAWaves::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	// Wave Timer
	DOREPLIFETIME(AGAWaves, NextWaveTimer);

}
<commit_msg>~ fixed Spawn Active applying more Spawns than Waves<commit_after>

#include "GA.h"
#include "GAEnemySpawn.h"
#include "GAWaves.h"
#include "GAGameState.h"
#include "Net/UnrealNetwork.h"

AGAWaves::AGAWaves(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	IsFirstTick = true;
	IsSpawnSetActive = false;

	NextWaveTimer = 15;
	NextSpawnActiveTimer = 10;

	SpawnWaveIndex = 0;
	SpawnTimer = 0;

	// Replicate to Server / Clients
	bReplicates = true;
	bAlwaysRelevant = true;

	PrimaryActorTick.bCanEverTick = true;
}

void AGAWaves::Tick(float DeltaTime){
	Super::Tick(DeltaTime);
	InitReamingWaves();
	IncreaseSpawnTimer(DeltaTime);
	SetSpawnActive();
	SpawnNextWave();
}

// Initial Setting of Remaining Waves in Game State
void AGAWaves::InitReamingWaves(){
	if (IsFirstTick) {
		SetRemainingWaves();
		IsFirstTick = false;
	}
}

// Increases the SpawnTimer  *** Only Server Can Increase the Timer ***
void AGAWaves::IncreaseSpawnTimer(float DeltaTime){
	if (Role == ROLE_Authority){																		// Are we server?
		SpawnTimer += DeltaTime;																		// Add Frametime to SpawnTimer
	}
}
// Sets Remaining Waves in GameState  *** SERVER ONLY ***
void AGAWaves::SetRemainingWaves(){
	if (Role == ROLE_Authority){
		if (GetWorld()->GetGameState<AGAGameState>()) {
			GetWorld()->GetGameState<AGAGameState>()->SetRemainingWaves(Waves.Num() - SpawnWaveIndex);
		}
	}
}

void AGAWaves::SetSpawnActive(){
	if (Role == ROLE_Authority){
		if (SpawnTimer >= NextSpawnActiveTimer && !IsSpawnSetActive && SpawnWaveIndex <= Waves.Num() - 1){
			// Use a random Spawnlocation
			RandIndex = FMath::RandRange(0, EnemySpawns.Num() - 1);
			((AGAEnemySpawn*)EnemySpawns[RandIndex])->SetSpawnActivationStatusTo(true);
			IsSpawnSetActive = true;
		}
	}
}

// Spawns the Next Wave  *** Only Server Can Spawn Waves ***
void AGAWaves::SpawnNextWave(){
	if (Role == ROLE_Authority){																		// Are we server?
		if (SpawnTimer >= NextWaveTimer && SpawnWaveIndex <= Waves.Num() - 1){							// If we have a Wave left and are allowed to spawn
			UE_LOG(LogClass, Log, TEXT("*** SERVER :: SPAWNING WAVE %d ***"),SpawnWaveIndex+1);

			((AGAEnemySpawn*)EnemySpawns[RandIndex])->SetCurrentWave(Waves[SpawnWaveIndex]);

			SpawnWaveIndex++;
			SpawnTimer = 0;
			IsSpawnSetActive = false;

			// Set Remaining Waves in GameState
			SetRemainingWaves();
		}
	}
}

// Replicates All Replicated Properties
void AGAWaves::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	// Wave Timer
	DOREPLIFETIME(AGAWaves, NextWaveTimer);

}
<|endoftext|>


<commit_before>#include "item.h"

Item::Item(const char* itemName, const char* itemDescription, bool isPickable) : Entity(itemName, itemDescription)
{
	name = itemName;
	description = itemDescription;
	pickable = isPickable;
}

Item::~Item()
{
}<commit_msg>Items have the right entityType<commit_after>#include "item.h"

Item::Item(const char* itemName, const char* itemDescription, bool isPickable) : Entity(itemName, itemDescription)
{
	name = itemName;
	description = itemDescription;
	entityType = item;
	pickable = isPickable;
}

Item::~Item()
{
}<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// Class providing the calibration parameters by accessing the CDB           //
//                                                                           //
// Request an instance with AliTPCcalibDB::Instance()                        //
// If a new event is processed set the event number with SetRun              //
// Then request the calibration data                                         //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <AliCDBManager.h>
#include <AliCDBStorage.h>
#include <AliCDBEntry.h>
#include <AliLog.h>

#include "AliTPCcalibDB.h"

#include "AliTPCCalROC.h"
#include "AliTPCCalPad.h"
#include "AliTPCCalDet.h"

ClassImp(AliTPCcalibDB)

AliTPCcalibDB* AliTPCcalibDB::fgInstance = 0;
Bool_t AliTPCcalibDB::fgTerminated = kFALSE;

//_ singleton implementation __________________________________________________
AliTPCcalibDB* AliTPCcalibDB::Instance()
{
  //
  // Singleton implementation
  // Returns an instance of this class, it is created if neccessary
  //

  if (fgTerminated != kFALSE)
    return 0;

  if (fgInstance == 0)
    fgInstance = new AliTPCcalibDB();

  return fgInstance;
}

void AliTPCcalibDB::Terminate()
{
  //
  // Singleton implementation
  // Deletes the instance of this class and sets the terminated flag, instances cannot be requested anymore
  // This function can be called several times.
  //

  fgTerminated = kTRUE;

  if (fgInstance != 0)
  {
    delete fgInstance;
    fgInstance = 0;
  }
}

//_____________________________________________________________________________
AliTPCcalibDB::AliTPCcalibDB()
{
  //
  // constructor
  //
  fRun = -1;

  //
  //
  //
  fPadGainFactor = 0;
  fPadTime0      = 0;
  fPadPRFWidth   = 0;
  fPadNoise      = 0;
  fPedestals     = 0;
  fParam         =0;
  Update();    // temporary
}

//_____________________________________________________________________________
AliTPCcalibDB::~AliTPCcalibDB()
{
  //
  // destructor
  //

  // don't delete anything, CDB cache is active!
  //if (fPadGainFactor) delete fPadGainFactor;
  //if (fPadTime0) delete fPadTime0;
  //if (fPadPRFWidth) delete fPadPRFWidth;
  //if (fPadNoise) delete fPadNoise;
}

//_____________________________________________________________________________
AliCDBEntry* AliTPCcalibDB::GetCDBEntry(const char* cdbPath)
{
  //
  // Retrieves an entry with path <cdbPath> from the CDB.
  //
  char chinfo[1000];

  AliCDBEntry* entry = AliCDBManager::Instance()->Get(cdbPath, fRun);
  if (!entry)
  {
    sprintf(chinfo,"AliTPCcalibDB: Failed to get entry:\t%s ", cdbPath);
    AliError(chinfo);
    return 0;
  }
  return entry;
}

//_____________________________________________________________________________
void AliTPCcalibDB::SetRun(Long64_t run)
{
  //
  // Sets current run number. Calibration data is read from the corresponding file.
  //
  if (fRun == run)
    return;
  fRun = run;
  Update();
}

void AliTPCcalibDB::Update(){
  //
  AliCDBEntry * entry=0;

  Bool_t cdbCache = AliCDBManager::Instance()->GetCacheFlag(); // save cache status
  AliCDBManager::Instance()->SetCacheFlag(kTRUE); // activate CDB cache

  //
  entry          = GetCDBEntry("TPC/Calib/PadGainFactor");
  if (entry){
    //if (fPadGainFactor) delete fPadGainFactor;
    entry->SetOwner(kTRUE);
    fPadGainFactor = (AliTPCCalPad*)entry->GetObject();
  }
  //
  entry          = GetCDBEntry("TPC/Calib/PadTime0");
  if (entry){
    //if (fPadTime0) delete fPadTime0;
    entry->SetOwner(kTRUE);
    fPadTime0 = (AliTPCCalPad*)entry->GetObject();
  }
  //
  entry          = GetCDBEntry("TPC/Calib/PadPRF");
  if (entry){
    //if (fPadPRFWidth) delete fPadPRFWidth;
    entry->SetOwner(kTRUE);
    fPadPRFWidth = (AliTPCCalPad*)entry->GetObject();
  }
  //
  entry          = GetCDBEntry("TPC/Calib/PadNoise");
  if (entry){
    //if (fPadNoise) delete fPadNoise;
    entry->SetOwner(kTRUE);
    fPadNoise = (AliTPCCalPad*)entry->GetObject();
  }

  entry          = GetCDBEntry("TPC/Calib/Pedestals");
  if (entry){
    //if (fPedestals) delete fPedestals;
    entry->SetOwner(kTRUE);
    fPedestals = (AliTPCCalPad*)entry->GetObject();
  }

  entry          = GetCDBEntry("TPC/Calib/Parameters");
  if (entry){
    //if (fPadNoise) delete fPadNoise;
    entry->SetOwner(kTRUE);
    fParam = (AliTPCParam*)entry->GetObject();
  }

  //
  AliCDBManager::Instance()->SetCacheFlag(cdbCache); // reset original CDB cache

}
<commit_msg>Make copy of the TPC parameters (Marian)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// Class providing the calibration parameters by accessing the CDB           //
//                                                                           //
// Request an instance with AliTPCcalibDB::Instance()                        //
// If a new event is processed set the event number with SetRun              //
// Then request the calibration data                                         //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <AliCDBManager.h>
#include <AliCDBStorage.h>
#include <AliCDBEntry.h>
#include <AliLog.h>

#include "AliTPCcalibDB.h"

#include "AliTPCCalROC.h"
#include "AliTPCCalPad.h"
#include "AliTPCCalDet.h"

ClassImp(AliTPCcalibDB)

AliTPCcalibDB* AliTPCcalibDB::fgInstance = 0;
Bool_t AliTPCcalibDB::fgTerminated = kFALSE;

//_ singleton implementation __________________________________________________
AliTPCcalibDB* AliTPCcalibDB::Instance()
{
  //
  // Singleton implementation
  // Returns an instance of this class, it is created if neccessary
  //

  if (fgTerminated != kFALSE)
    return 0;

  if (fgInstance == 0)
    fgInstance = new AliTPCcalibDB();

  return fgInstance;
}

void AliTPCcalibDB::Terminate()
{
  //
  // Singleton implementation
  // Deletes the instance of this class and sets the terminated flag, instances cannot be requested anymore
  // This function can be called several times.
  //

  fgTerminated = kTRUE;

  if (fgInstance != 0)
  {
    delete fgInstance;
    fgInstance = 0;
  }
}

//_____________________________________________________________________________
AliTPCcalibDB::AliTPCcalibDB()
{
  //
  // constructor
  //
  fRun = -1;

  //
  //
  //
  fPadGainFactor = 0;
  fPadTime0      = 0;
  fPadPRFWidth   = 0;
  fPadNoise      = 0;
  fPedestals     = 0;
  fParam         =0;
  Update();    // temporary
}

//_____________________________________________________________________________
AliTPCcalibDB::~AliTPCcalibDB()
{
  //
  // destructor
  //

  // don't delete anything, CDB cache is active!
  //if (fPadGainFactor) delete fPadGainFactor;
  //if (fPadTime0) delete fPadTime0;
  //if (fPadPRFWidth) delete fPadPRFWidth;
  //if (fPadNoise) delete fPadNoise;
}

//_____________________________________________________________________________
AliCDBEntry* AliTPCcalibDB::GetCDBEntry(const char* cdbPath)
{
  //
  // Retrieves an entry with path <cdbPath> from the CDB.
  //
  char chinfo[1000];

  AliCDBEntry* entry = AliCDBManager::Instance()->Get(cdbPath, fRun);
  if (!entry)
  {
    sprintf(chinfo,"AliTPCcalibDB: Failed to get entry:\t%s ", cdbPath);
    AliError(chinfo);
    return 0;
  }
  return entry;
}

//_____________________________________________________________________________
void AliTPCcalibDB::SetRun(Long64_t run)
{
  //
  // Sets current run number. Calibration data is read from the corresponding file.
  //
  if (fRun == run)
    return;
  fRun = run;
  Update();
}

void AliTPCcalibDB::Update(){
  //
  AliCDBEntry * entry=0;

  Bool_t cdbCache = AliCDBManager::Instance()->GetCacheFlag(); // save cache status
  AliCDBManager::Instance()->SetCacheFlag(kTRUE); // activate CDB cache

  //
  entry          = GetCDBEntry("TPC/Calib/PadGainFactor");
  if (entry){
    //if (fPadGainFactor) delete fPadGainFactor;
    entry->SetOwner(kTRUE);
    fPadGainFactor = (AliTPCCalPad*)entry->GetObject();
  }
  //
  entry          = GetCDBEntry("TPC/Calib/PadTime0");
  if (entry){
    //if (fPadTime0) delete fPadTime0;
    entry->SetOwner(kTRUE);
    fPadTime0 = (AliTPCCalPad*)entry->GetObject();
  }
  //
  entry          = GetCDBEntry("TPC/Calib/PadPRF");
  if (entry){
    //if (fPadPRFWidth) delete fPadPRFWidth;
    entry->SetOwner(kTRUE);
    fPadPRFWidth = (AliTPCCalPad*)entry->GetObject();
  }
  //
  entry          = GetCDBEntry("TPC/Calib/PadNoise");
  if (entry){
    //if (fPadNoise) delete fPadNoise;
    entry->SetOwner(kTRUE);
    fPadNoise = (AliTPCCalPad*)entry->GetObject();
  }

  entry          = GetCDBEntry("TPC/Calib/Pedestals");
  if (entry){
    //if (fPedestals) delete fPedestals;
    entry->SetOwner(kTRUE);
    fPedestals = (AliTPCCalPad*)entry->GetObject();
  }

  entry          = GetCDBEntry("TPC/Calib/Parameters");
  if (entry){
    //if (fPadNoise) delete fPadNoise;
    entry->SetOwner(kTRUE);
    fParam = (AliTPCParam*)(entry->GetObject()->Clone());
  }

  //
  AliCDBManager::Instance()->SetCacheFlag(cdbCache); // reset original CDB cache

}
<|endoftext|>


<commit_before>//
//  Permutation.cpp
//  GroupTheory
//
//  Created by Donald Pinckney on 10/16/15.
//  Copyright © 2015 Donald Pinckney. All rights reserved.
//

#include "Permutation.h"

unsigned int factorial(unsigned int n) {
    unsigned int product = 1;
    for (unsigned int i = 2; i <= n; i++) {
        product *= i;
    }
    return product;
}

// NOTE: THIS ALLOCATES MEMORY! YOU MUST CALL DELETE WHEN DONE.
Permutation *Permutation::compose(const Permutation &x, const Permutation &y) {
    Permutation *r = new Permutation();
    r->count = x.count;
    r->values = new unsigned int[x.count];

    for (unsigned int i = 0; i < x.count; i++) {
        r->values[i] = x.values[y.values[i] - 1];
    }
    return r;
}

bool operator==(const Permutation &lhs, const Permutation &rhs) {
    if(lhs.count != rhs.count) {
        return false;
    }

    for (unsigned int i = 0; i < lhs.count; i++) {
        if(lhs.values[i] != rhs.values[i]) {
            return false;
        }
    }
    return true;
}

bool operator!=(const Permutation &lhs, const Permutation &rhs) {
    return !(lhs == rhs);
}

std::ostream & operator<<(std::ostream &lhs, const Permutation &rhs) {
    lhs << '(';
    for (unsigned int i = 0; i < rhs.count; i++) {
        lhs << rhs.values[i];
        if (i != rhs.count - 1) {
            lhs << ' ';
        }
    }
    lhs << ')';

    return lhs;
}

// NOTE: THIS ALLOCATES MEMORY! YOU MUST CALL DELETE WHEN DONE.
Permutation *Permutation::generatePermutations(unsigned int n, unsigned int *count) {
    *count = factorial(n);

    Permutation *newPerms = new Permutation[*count];

    unsigned int *nums = new unsigned int[n];
    for (unsigned int i = 0; i < n; i++) {
        nums[i] = i + 1;
    }

    unsigned int i = 0;
    do {
        newPerms[i].values = new unsigned int[n];
        memcpy(newPerms[i].values, nums, sizeof(unsigned int) * n);

        newPerms[i].count = n;

        i++;
    } while(std::next_permutation(nums, nums + n));

    if(i != *count) {
        printf("ERROR: count != factorial(n).\n");
    }

    delete [] nums;

    return newPerms;
}<commit_msg>Fixed another build error<commit_after>//
//  Permutation.cpp
//  GroupTheory
//
//  Created by Donald Pinckney on 10/16/15.
//  Copyright © 2015 Donald Pinckney. All rights reserved.
//

#include "Permutation.h"

unsigned int factorial(unsigned int n) {
    unsigned int product = 1;
    for (unsigned int i = 2; i <= n; i++) {
        product *= i;
    }
    return product;
}

// NOTE: THIS ALLOCATES MEMORY! YOU MUST CALL DELETE WHEN DONE.
Permutation *Permutation::compose(const Permutation &x, const Permutation &y) {
    Permutation *r = new Permutation();
    r->count = x.count;
    r->values = new unsigned int[x.count];

    for (unsigned int i = 0; i < x.count; i++) {
        r->values[i] = x.values[y.values[i] - 1];
    }
    return r;
}

bool operator==(const Permutation &lhs, const Permutation &rhs) {
    if(lhs.count != rhs.count) {
        return false;
    }

    for (unsigned int i = 0; i < lhs.count; i++) {
        if(lhs.values[i] != rhs.values[i]) {
            return false;
        }
    }
    return true;
}

bool operator!=(const Permutation &lhs, const Permutation &rhs) {
    return !(lhs == rhs);
}

std::ostream & operator<<(std::ostream &lhs, const Permutation &rhs) {
    lhs << '(';
    for (unsigned int i = 0; i < rhs.count; i++) {
        lhs << rhs.values[i];
        if (i != rhs.count - 1) {
            lhs << ' ';
        }
    }
    lhs << ')';

    return lhs;
}

// NOTE: THIS ALLOCATES MEMORY! YOU MUST CALL DELETE WHEN DONE.
Permutation *Permutation::generatePermutations(unsigned int n, unsigned int *count) {
    *count = factorial(n);

    Permutation *newPerms = new Permutation[*count];

    unsigned int *nums = new unsigned int[n];
    for (unsigned int i = 0; i < n; i++) {
        nums[i] = i + 1;
    }

    unsigned int i = 0;
    do {
        newPerms[i].values = new unsigned int[n];
        memcpy(newPerms[i].values, nums, sizeof(unsigned int) * n);

        newPerms[i].count = n;

        i++;
    } while(std::next_permutation(nums, nums + n));

    delete [] nums;

    return newPerms;
}<|endoftext|>