<commit_before>/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#include <yaml-cpp/yaml.h>

#include "cyber/common/log.h"
#include "modules/perception/camera/common/util.h"
#include "modules/perception/camera/tools/offline/transform_server.h"

namespace apollo {
namespace perception {
namespace camera {

bool TransformServer::Init(const std::vector<std::string> &camera_names,
                           const std::string &params_path) {
  std::string params_dir = params_path;
  // 1. init lidar height
  try {
    YAML::Node lidar_height =
      YAML::LoadFile(params_dir + "/" + "velodyne64_height.yaml");
    Eigen::Affine3d trans;
    trans.linear() = Eigen::Matrix3d::Identity();
    AINFO << trans.translation() << " "
             << lidar_height["vehicle"]["parameters"]["height"];
    trans.translation() << 0.0, 0.0,
      lidar_height["vehicle"]["parameters"]["height"].as<double>();
    AddTransform("velodyne64", "ground", trans);
  } catch (YAML::InvalidNode &in) {
    AERROR << "load velodyne64 extrisic file error"
              << " YAML::InvalidNode exception";
    return false;
  } catch (YAML::TypedBadConversion<float> &bc) {
    AERROR << "load velodyne64 extrisic file error, "
              << "YAML::TypedBadConversion exception";
    return false;
  } catch (YAML::Exception &e) {
    AERROR << "load velodyne64 extrisic file "
              << " error, YAML exception:" << e.what();
    return false;
  }
  // 2. init lidar and camera extrinsic
  std::vector<std::string> extrinsic_filelist;
  extrinsic_filelist.push_back(
    params_dir + "/velodyne64_novatel_extrinsics.yaml");
  for (const auto &camera_name : camera_names) {
    extrinsic_filelist.push_back(
      params_dir + "/" + camera_name + "_extrinsics.yaml");
  }

  for (const auto &yaml_file : extrinsic_filelist) {
    try {
      YAML::Node node = YAML::LoadFile(yaml_file);
      if (node.IsNull()) {
        AINFO << "Load " << yaml_file << " failed! please check!";
        return false;
      }
      std::string child_frame_id = node["child_frame_id"].as<std::string>();
      std::string frame_id = node["header"]["frame_id"].as<std::string>();
      double q[4] = {node["transform"]["rotation"]["w"].as<double>(),
                     node["transform"]["rotation"]["x"].as<double>(),
                     node["transform"]["rotation"]["y"].as<double>(),
                     node["transform"]["rotation"]["z"].as<double>()};
      double t[3] = {node["transform"]["translation"]["x"].as<double>(),
                     node["transform"]["translation"]["y"].as<double>(),
                     node["transform"]["translation"]["z"].as<double>()};
      Eigen::Quaterniond qq(q[0], q[1], q[2], q[3]);
      Eigen::Affine3d trans;
      trans.linear() = qq.matrix();
      trans.translation() << t[0], t[1], t[2];
      bool added = AddTransform(child_frame_id, frame_id, trans);
      if (!added) {
        AINFO << "failed to add transform from "
                 << child_frame_id << " to " << frame_id << std::endl;
      }
    } catch (YAML::InvalidNode &in) {
      AERROR << "load camera extrisic file " << yaml_file
                << " with error, YAML::InvalidNode exception";
      return false;
    } catch (YAML::TypedBadConversion<double> &bc) {
      AERROR << "load camera extrisic file " << yaml_file
                << " with error, YAML::TypedBadConversion exception";
      return false;
    } catch (YAML::Exception &e) {
      AERROR << "load camera extrisic file " << yaml_file
                << " with error, YAML exception:" << e.what();
      return false;
    }
  }
  return true;
}

bool TransformServer::LoadFromFile(const std::string &tf_input,
                                  float frequency) {
  if (frequency <= 0) {
    AERROR << "Error frequency value:" << frequency;
    return false;
  }
  std::ifstream fin(tf_input);
  Transform tf;
  int64_t ts;
  while (fin >> ts) {
    tf.timestamp = static_cast<double>(ts) * 1e-9;
    fin >> tf.tx;
    fin >> tf.ty;
    fin >> tf.tz;
    fin >> tf.qx;
    fin >> tf.qy;
    fin >> tf.qz;
    fin >> tf.qw;
    tf_.push_back(tf);
  }
  fin.close();
  error_limit_ = 1 / frequency / 2.0f;
  AINFO << "Load tf successfully. count: " << tf_.size()
           << " error limit:" << error_limit_;
  return true;
}

bool TransformServer::QueryPos(double timestamp, Eigen::Affine3d *pose) {
  for (auto &&tf : tf_) {
    if (Equal(timestamp, tf.timestamp, error_limit_)) {
      Eigen::Quaterniond rotation(tf.qw, tf.qx, tf.qy, tf.qz);
      pose->linear() = rotation.matrix();
      pose->translation() << tf.tx, tf.ty, tf.tz;
      AINFO << "Get Pose:\n" << pose->matrix();
      return true;
    }
  }
  return false;
}

bool TransformServer::AddTransform(const std::string &child_frame_id,
                                   const std::string &frame_id,
                                   const Eigen::Affine3d &transform) {
  vertices_.insert(child_frame_id);
  vertices_.insert(frame_id);

  auto begin = edges_.lower_bound(child_frame_id);
  auto end = edges_.upper_bound(child_frame_id);

  for (auto iter = begin; iter != end; ++iter) {
    if (iter->second.frame_id == frame_id) {
      return false;
    }
  }

  Edge e;
  e.child_frame_id = child_frame_id;
  e.frame_id = frame_id;
  e.transform = transform;

  Edge e_inv;
  e_inv.child_frame_id = frame_id;
  e_inv.frame_id = child_frame_id;
  e_inv.transform = transform.inverse();
  ADEBUG
  << "Add transform between " << frame_id << " and " << child_frame_id;
  edges_.insert({child_frame_id, e});
  edges_.insert({frame_id, e_inv});

  return true;
}

bool TransformServer::QueryTransform(const std::string &child_frame_id,
                                     const std::string &frame_id,
                                     Eigen::Affine3d *transform) {
  *transform = Eigen::Affine3d::Identity();

  if (child_frame_id == frame_id) {
    return true;
  }

  auto cf_iter = vertices_.find(child_frame_id);
  auto f_iter = vertices_.find(frame_id);

  // vertices do not exist
  if (cf_iter == vertices_.end() || f_iter == vertices_.end()) {
    return false;
  }

  std::map<std::string, bool> visited;
  for (const auto &item : vertices_) {
    visited[item] = false;
  }

  bool bfound = FindTransform(child_frame_id, frame_id, transform, &visited);
  return bfound;
}

bool TransformServer::FindTransform(const std::string &child_frame_id,
                                    const std::string &frame_id,
                                    Eigen::Affine3d *transform,
                                    std::map<std::string, bool> *visited) {
  Eigen::Affine3d loc_transform = Eigen::Affine3d::Identity();

  auto begin = edges_.lower_bound(child_frame_id);
  auto end = edges_.upper_bound(child_frame_id);

  (*visited)[child_frame_id] = true;
  for (auto iter = begin; iter != end; ++iter) {
    auto &edge = iter->second;
    if ((*visited)[edge.frame_id]) {
      continue;
    }

    ADEBUG
    << "from " << edge.child_frame_id << " to " << edge.frame_id << std::endl;

    loc_transform = edge.transform * loc_transform;

    if (edge.frame_id == frame_id) {
      *transform = loc_transform;
      return true;
    }

    Eigen::Affine3d tr = Eigen::Affine3d::Identity();
    bool bfound = FindTransform(edge.frame_id, frame_id, &tr, visited);
    if (bfound) {
      loc_transform = tr * loc_transform;
      *transform = loc_transform;
      return true;
    }

    loc_transform = edge.transform.inverse() * loc_transform;
  }
  return false;
}

void TransformServer::print() {
  for (auto item : edges_) {
    AINFO << "----------------" << std::endl;
    AINFO << item.first << std::endl;
    AINFO << "edge: " << std::endl;
    AINFO << "from " << item.second.child_frame_id << " to "
             << item.second.frame_id << std::endl;
    Eigen::Affine3d trans = item.second.transform;
    Eigen::Quaterniond quat(trans.linear());
    AINFO << "rot: " << quat.x() << " " << quat.y() << " " << quat.z() << " "
             << quat.w() << std::endl;
    AINFO << "trans: "
             << trans.translation()[0] << " "
             << trans.translation()[1] << " "
             << trans.translation()[2] << std::endl;
  }
}

}  // namespace camera
}  // namespace perception
}  // namespace apollo
<commit_msg>Perception: nitpick, remove unnecessay bFound variable (#6768)<commit_after>/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#include <yaml-cpp/yaml.h>

#include "cyber/common/log.h"
#include "modules/perception/camera/common/util.h"
#include "modules/perception/camera/tools/offline/transform_server.h"

namespace apollo {
namespace perception {
namespace camera {

bool TransformServer::Init(const std::vector<std::string> &camera_names,
                           const std::string &params_path) {
  std::string params_dir = params_path;
  // 1. init lidar height
  try {
    YAML::Node lidar_height =
      YAML::LoadFile(params_dir + "/" + "velodyne64_height.yaml");
    Eigen::Affine3d trans;
    trans.linear() = Eigen::Matrix3d::Identity();
    AINFO << trans.translation() << " "
             << lidar_height["vehicle"]["parameters"]["height"];
    trans.translation() << 0.0, 0.0,
      lidar_height["vehicle"]["parameters"]["height"].as<double>();
    AddTransform("velodyne64", "ground", trans);
  } catch (YAML::InvalidNode &in) {
    AERROR << "load velodyne64 extrisic file error"
              << " YAML::InvalidNode exception";
    return false;
  } catch (YAML::TypedBadConversion<float> &bc) {
    AERROR << "load velodyne64 extrisic file error, "
              << "YAML::TypedBadConversion exception";
    return false;
  } catch (YAML::Exception &e) {
    AERROR << "load velodyne64 extrisic file "
              << " error, YAML exception:" << e.what();
    return false;
  }
  // 2. init lidar and camera extrinsic
  std::vector<std::string> extrinsic_filelist;
  extrinsic_filelist.push_back(
    params_dir + "/velodyne64_novatel_extrinsics.yaml");
  for (const auto &camera_name : camera_names) {
    extrinsic_filelist.push_back(
      params_dir + "/" + camera_name + "_extrinsics.yaml");
  }

  for (const auto &yaml_file : extrinsic_filelist) {
    try {
      YAML::Node node = YAML::LoadFile(yaml_file);
      if (node.IsNull()) {
        AINFO << "Load " << yaml_file << " failed! please check!";
        return false;
      }
      std::string child_frame_id = node["child_frame_id"].as<std::string>();
      std::string frame_id = node["header"]["frame_id"].as<std::string>();
      double q[4] = {node["transform"]["rotation"]["w"].as<double>(),
                     node["transform"]["rotation"]["x"].as<double>(),
                     node["transform"]["rotation"]["y"].as<double>(),
                     node["transform"]["rotation"]["z"].as<double>()};
      double t[3] = {node["transform"]["translation"]["x"].as<double>(),
                     node["transform"]["translation"]["y"].as<double>(),
                     node["transform"]["translation"]["z"].as<double>()};
      Eigen::Quaterniond qq(q[0], q[1], q[2], q[3]);
      Eigen::Affine3d trans;
      trans.linear() = qq.matrix();
      trans.translation() << t[0], t[1], t[2];
      bool added = AddTransform(child_frame_id, frame_id, trans);
      if (!added) {
        AINFO << "failed to add transform from "
                 << child_frame_id << " to " << frame_id << std::endl;
      }
    } catch (YAML::InvalidNode &in) {
      AERROR << "load camera extrisic file " << yaml_file
                << " with error, YAML::InvalidNode exception";
      return false;
    } catch (YAML::TypedBadConversion<double> &bc) {
      AERROR << "load camera extrisic file " << yaml_file
                << " with error, YAML::TypedBadConversion exception";
      return false;
    } catch (YAML::Exception &e) {
      AERROR << "load camera extrisic file " << yaml_file
                << " with error, YAML exception:" << e.what();
      return false;
    }
  }
  return true;
}

bool TransformServer::LoadFromFile(const std::string &tf_input,
                                  float frequency) {
  if (frequency <= 0) {
    AERROR << "Error frequency value:" << frequency;
    return false;
  }
  std::ifstream fin(tf_input);
  Transform tf;
  int64_t ts;
  while (fin >> ts) {
    tf.timestamp = static_cast<double>(ts) * 1e-9;
    fin >> tf.tx;
    fin >> tf.ty;
    fin >> tf.tz;
    fin >> tf.qx;
    fin >> tf.qy;
    fin >> tf.qz;
    fin >> tf.qw;
    tf_.push_back(tf);
  }
  fin.close();
  error_limit_ = 1 / frequency / 2.0f;
  AINFO << "Load tf successfully. count: " << tf_.size()
           << " error limit:" << error_limit_;
  return true;
}

bool TransformServer::QueryPos(double timestamp, Eigen::Affine3d *pose) {
  for (auto &&tf : tf_) {
    if (Equal(timestamp, tf.timestamp, error_limit_)) {
      Eigen::Quaterniond rotation(tf.qw, tf.qx, tf.qy, tf.qz);
      pose->linear() = rotation.matrix();
      pose->translation() << tf.tx, tf.ty, tf.tz;
      AINFO << "Get Pose:\n" << pose->matrix();
      return true;
    }
  }
  return false;
}

bool TransformServer::AddTransform(const std::string &child_frame_id,
                                   const std::string &frame_id,
                                   const Eigen::Affine3d &transform) {
  vertices_.insert(child_frame_id);
  vertices_.insert(frame_id);

  auto begin = edges_.lower_bound(child_frame_id);
  auto end = edges_.upper_bound(child_frame_id);

  for (auto iter = begin; iter != end; ++iter) {
    if (iter->second.frame_id == frame_id) {
      return false;
    }
  }

  Edge e;
  e.child_frame_id = child_frame_id;
  e.frame_id = frame_id;
  e.transform = transform;

  Edge e_inv;
  e_inv.child_frame_id = frame_id;
  e_inv.frame_id = child_frame_id;
  e_inv.transform = transform.inverse();
  ADEBUG
  << "Add transform between " << frame_id << " and " << child_frame_id;
  edges_.insert({child_frame_id, e});
  edges_.insert({frame_id, e_inv});

  return true;
}

bool TransformServer::QueryTransform(const std::string &child_frame_id,
                                     const std::string &frame_id,
                                     Eigen::Affine3d *transform) {
  *transform = Eigen::Affine3d::Identity();

  if (child_frame_id == frame_id) {
    return true;
  }

  auto cf_iter = vertices_.find(child_frame_id);
  auto f_iter = vertices_.find(frame_id);

  // vertices do not exist
  if (cf_iter == vertices_.end() || f_iter == vertices_.end()) {
    return false;
  }

  std::map<std::string, bool> visited;
  for (const auto &item : vertices_) {
    visited[item] = false;
  }

  return FindTransform(child_frame_id, frame_id, transform, &visited);
}

bool TransformServer::FindTransform(const std::string &child_frame_id,
                                    const std::string &frame_id,
                                    Eigen::Affine3d *transform,
                                    std::map<std::string, bool> *visited) {
  Eigen::Affine3d loc_transform = Eigen::Affine3d::Identity();

  auto begin = edges_.lower_bound(child_frame_id);
  auto end = edges_.upper_bound(child_frame_id);

  (*visited)[child_frame_id] = true;
  for (auto iter = begin; iter != end; ++iter) {
    auto &edge = iter->second;
    if ((*visited)[edge.frame_id]) {
      continue;
    }

    ADEBUG
    << "from " << edge.child_frame_id << " to " << edge.frame_id << std::endl;

    loc_transform = edge.transform * loc_transform;

    if (edge.frame_id == frame_id) {
      *transform = loc_transform;
      return true;
    }

    Eigen::Affine3d tr = Eigen::Affine3d::Identity();
    bool bfound = FindTransform(edge.frame_id, frame_id, &tr, visited);
    if (bfound) {
      loc_transform = tr * loc_transform;
      *transform = loc_transform;
      return true;
    }

    loc_transform = edge.transform.inverse() * loc_transform;
  }
  return false;
}

void TransformServer::print() {
  for (auto item : edges_) {
    AINFO << "----------------" << std::endl;
    AINFO << item.first << std::endl;
    AINFO << "edge: " << std::endl;
    AINFO << "from " << item.second.child_frame_id << " to "
             << item.second.frame_id << std::endl;
    Eigen::Affine3d trans = item.second.transform;
    Eigen::Quaterniond quat(trans.linear());
    AINFO << "rot: " << quat.x() << " " << quat.y() << " " << quat.z() << " "
             << quat.w() << std::endl;
    AINFO << "trans: "
             << trans.translation()[0] << " "
             << trans.translation()[1] << " "
             << trans.translation()[2] << std::endl;
  }
}

}  // namespace camera
}  // namespace perception
}  // namespace apollo
<|endoftext|>


<commit_before>/*****************************************************************************
// * This source file is part of ArkGameFrame                                *
// * For the latest info, see https://github.com/ArkGame                     *
// *                                                                         *
// * Copyright(c) 2013 - 2017 ArkGame authors.                               *
// *                                                                         *
// * 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      AFPlatform.h                                                *
// * @author    Ark Game Tech                                                *
// * @date      2015-12-15                                                   *
// * @brief     AFPlatform                                                  *
*****************************************************************************/
#pragma once

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <deque>
#include <limits>
#include <algorithm>
#include <utility>
#include <functional>
#include <cctype>
#include <iterator>
#include <unordered_map>
#include <stdint.h>
#include <functional>
#include <memory>
#include <signal.h>
#include <chrono>
#include <sstream>
#include <random>
#include <thread>

#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
// only windows include
#include <io.h>
#include <time.h>
#ifndef WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <MSWSock.h>
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <windows.h>
#define _SCL_SECURE_NO_WARNINGS

#define SIGHUP  1
#define SIGINT  2
#define SIGQUIT 3
#define SIGUSR1 10
#define SIGPIPE 13
#define SIGCHLD 17
#define SIGSYS  32

#else
// only other unix/linux include
#include <sys/socket.h>
#endif

#define ARK_LITTLE_ENDIAN
#define ARK_BIG_ENDIAN

#if !defined(ARK_ENDIAN)
#  if defined(USE_BIG_ENDIAN)
#    define ARK_ENDIAN ARK_BIG_ENDIAN
#  else
#     define ARK_ENDIAN ARK_LITTLE_ENDIAN
#  endif
#endif // !defined(ARK_ENDIAN)

#define PLATFORM_WIN    0
#define PLATFORM_UNIX   1
#define PLATFORM_APPLE  2

#define UNIX_FLAVOUR_LINUX  1
#define UNIX_FLAVOUR_BSD    2
#define UNIX_FLAVOUR_OTHER  3
#define UNIX_FLAVOUR_OSX    4

#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
#  define ARK_PLATFORM PLATFORM_WIN
#elif defined(__APPLE_CC__)
#  define ARK_PLATFORM PLATFORM_APPLE
#else
#  define ARK_PLATFORM PLATFORM_UNIX
#endif

#define COMPILER_MICROSOFT  0
#define COMPILER_GNU        1
#define COMPILER_BORLAND    2
#define COMPILER_INTEL      3
#define COMPILER_CLANG      4

#define GOOGLE_STRIP_LOG    2

#ifdef _MSC_VER
#  define ARK_COMPILER COMPILER_MICROSOFT
#elif defined(__INTEL_COMPILER)
#  define ARK_COMPILER COMPILER_INTEL
#elif defined(__BORLANDC__)
#  define ARK_COMPILER COMPILER_BORLAND
#elif defined(__GNUC__)
#  define ARK_COMPILER COMPILER_GNU
#elif defined( __clang__ )
#  define ARK_COMPILER COMPILER_CLANG
#else
#  pragma error "FATAL ERROR: Unknown compiler."
#endif

#if ARK_PLATFORM == PLATFORM_UNIX || ARK_PLATFORM == PLATFORM_APPLE
#  if defined(HAVE_DARWIN)
#    define ARK_PLATFORM_NAME "MacOSX"
#    define UNIX_FLAVOUR UNIX_FLAVOUR_OSX
#  elif defined(USE_KQUEUE)
#    define ARK_PLATFORM_NAME "FreeBSD"
#    define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
#  elif defined(USE_KQUEUE_DFLY)
#    define ARK_PLATFORM_NAME "DragonFlyBSD"
#    define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
#  else
#    define ARK_PLATFORM_NAME "Linux"
#    define UNIX_FLAVOUR UNIX_FLAVOUR_LINUX
#  endif
#elif ARK_PLATFORM == PLATFORM_WIN
#  define ARK_PLATFORM_NAME "Windows"
#else
#  pragma error "FATAL ERROR: Unknown platform."
#endif

#define ARK_RUN_MODE_DEBUG      0
#define ARK_RUN_MODE_RELEASE    1

#ifndef ARK_RUN_MODE
#  if defined(DEBUG) || defined(_DEBUG)
#    define ARK_RUN_MODE ARK_RUN_MODE_DEBUG
#    define ARK_RUN_MODE_NAME "Debug"
#  else
#    define ARK_RUN_MODE ARK_RUN_MODE_RELEASE
#    define ARK_RUN_MODE_NAME "Release"
#  endif // DEBUG
#endif

#ifndef X64
#  if defined(_WIN64) || defined(__x86_64__) || defined(__amd64) || defined(__LP64__)
#    define X64
#  endif
#endif

#ifdef X64
#  define ARK_ARCH_NAME "X64"
#else
#  define ARK_ARCH_NAME "X86"
#endif // X64

#define ARK_LITTLE_ENDIAN

#ifndef ARK_DYNAMIC_PLUGIN
#define ARK_DYNAMIC_PLUGIN
#endif

<commit_msg>remove netmodule log<commit_after>/*****************************************************************************
// * This source file is part of ArkGameFrame                                *
// * For the latest info, see https://github.com/ArkGame                     *
// *                                                                         *
// * Copyright(c) 2013 - 2017 ArkGame authors.                               *
// *                                                                         *
// * 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      AFPlatform.h                                                *
// * @author    Ark Game Tech                                                *
// * @date      2015-12-15                                                   *
// * @brief     AFPlatform                                                  *
*****************************************************************************/
#pragma once

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <deque>
#include <limits>
#include <algorithm>
#include <utility>
#include <functional>
#include <cctype>
#include <iterator>
#include <unordered_map>
#include <stdint.h>
#include <functional>
#include <memory>
#include <signal.h>
#include <chrono>
#include <sstream>
#include <random>
#include <thread>

#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
// only windows include
#include <io.h>
#include <time.h>
#ifndef WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <MSWSock.h>
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <windows.h>
#define _SCL_SECURE_NO_WARNINGS

#define SIGHUP  1
#define SIGINT  2
#define SIGQUIT 3
#define SIGUSR1 10
#define SIGPIPE 13
#define SIGCHLD 17
#define SIGSYS  32

#else
// only other unix/linux include
#include <sys/socket.h>
#endif

#define ARK_LITTLE_ENDIAN
#define ARK_BIG_ENDIAN

#if !defined(ARK_ENDIAN)
#  if defined(USE_BIG_ENDIAN)
#    define ARK_ENDIAN ARK_BIG_ENDIAN
#  else
#     define ARK_ENDIAN ARK_LITTLE_ENDIAN
#  endif
#endif // !defined(ARK_ENDIAN)

#define PLATFORM_WIN    0
#define PLATFORM_UNIX   1
#define PLATFORM_APPLE  2

#define UNIX_FLAVOUR_LINUX  1
#define UNIX_FLAVOUR_BSD    2
#define UNIX_FLAVOUR_OTHER  3
#define UNIX_FLAVOUR_OSX    4

#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)
#  define ARK_PLATFORM PLATFORM_WIN
#elif defined(__APPLE_CC__)
#  define ARK_PLATFORM PLATFORM_APPLE
#else
#  define ARK_PLATFORM PLATFORM_UNIX
#endif

#define COMPILER_MICROSOFT  0
#define COMPILER_GNU        1
#define COMPILER_BORLAND    2
#define COMPILER_INTEL      3
#define COMPILER_CLANG      4

#ifdef _MSC_VER
#  define ARK_COMPILER COMPILER_MICROSOFT
#elif defined(__INTEL_COMPILER)
#  define ARK_COMPILER COMPILER_INTEL
#elif defined(__BORLANDC__)
#  define ARK_COMPILER COMPILER_BORLAND
#elif defined(__GNUC__)
#  define ARK_COMPILER COMPILER_GNU
#elif defined( __clang__ )
#  define ARK_COMPILER COMPILER_CLANG
#else
#  pragma error "FATAL ERROR: Unknown compiler."
#endif

#if ARK_PLATFORM == PLATFORM_UNIX || ARK_PLATFORM == PLATFORM_APPLE
#  if defined(HAVE_DARWIN)
#    define ARK_PLATFORM_NAME "MacOSX"
#    define UNIX_FLAVOUR UNIX_FLAVOUR_OSX
#  elif defined(USE_KQUEUE)
#    define ARK_PLATFORM_NAME "FreeBSD"
#    define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
#  elif defined(USE_KQUEUE_DFLY)
#    define ARK_PLATFORM_NAME "DragonFlyBSD"
#    define UNIX_FLAVOUR UNIX_FLAVOUR_BSD
#  else
#    define ARK_PLATFORM_NAME "Linux"
#    define UNIX_FLAVOUR UNIX_FLAVOUR_LINUX
#  endif
#elif ARK_PLATFORM == PLATFORM_WIN
#  define ARK_PLATFORM_NAME "Windows"
#else
#  pragma error "FATAL ERROR: Unknown platform."
#endif

#define ARK_RUN_MODE_DEBUG      0
#define ARK_RUN_MODE_RELEASE    1

#ifndef ARK_RUN_MODE
#  if defined(DEBUG) || defined(_DEBUG)
#    define ARK_RUN_MODE ARK_RUN_MODE_DEBUG
#    define ARK_RUN_MODE_NAME "Debug"
#  else
#    define ARK_RUN_MODE ARK_RUN_MODE_RELEASE
#    define ARK_RUN_MODE_NAME "Release"
#  endif // DEBUG
#endif

#ifndef X64
#  if defined(_WIN64) || defined(__x86_64__) || defined(__amd64) || defined(__LP64__)
#    define X64
#  endif
#endif

#ifdef X64
#  define ARK_ARCH_NAME "X64"
#else
#  define ARK_ARCH_NAME "X86"
#endif // X64

#define ARK_LITTLE_ENDIAN

#ifndef ARK_DYNAMIC_PLUGIN
#define ARK_DYNAMIC_PLUGIN
#endif

<|endoftext|>


<commit_before>/**
 *  \file RMF/Category.h
 *  \brief Handle read/write of Model data from/to files.
 *
 *  Copyright 2007-2013 IMP Inventors. All rights reserved.
 *
 */

#include "HDF5SharedData.h"
#include <RMF/NodeHandle.h>
#include <RMF/Validator.h>
#include <boost/unordered_set.hpp>
#include <RMF/HDF5/Group.h>
#include <RMF/log.h>
#include <algorithm>

RMF_ENABLE_WARNINGS

namespace RMF {
namespace hdf5_backend {

#define RMF_CLOSE(lcname, Ucname, PassValue, ReturnValue, PassValues, \
                  ReturnValues)                                       \
  lcname##_data_sets_ = DataDataSetCache2D<Ucname##Traits>();         \
  per_frame_##lcname##_data_sets_ = DataDataSetCache3D<Ucname##Traits>()

void HDF5SharedData::close_things() {
  node_names_.reset();
  free_ids_.clear();
  node_data_.reset();
  index_cache_ = IndexCache();
  key_name_data_sets_ = KeyNameDataSetCache();
  category_names_.reset();
  frame_names_.reset();
  max_cache_.clear();
  RMF_FOREACH_BACKWARDS_TYPE(RMF_CLOSE);
  flush();
  file_ = HDF5::Group();
  H5garbage_collect();
}

void HDF5SharedData::open_things(bool create, bool read_only) {
  read_only_ = read_only;
  if (create) {
    file_ = HDF5::create_file(get_file_path());
    file_.set_attribute<HDF5::CharTraits>("version", std::string("rmf 1"));
    {
      HDF5::DataSetCreationPropertiesD<HDF5::StringTraits, 1> props;
      props.set_compression(HDF5::GZIP_COMPRESSION);
      (file_.add_child_data_set<HDF5::StringTraits,
                                1>)(get_node_name_data_set_name(), props);
    }
    {
      HDF5::DataSetCreationPropertiesD<HDF5::IndexTraits, 2> props;
      props.set_compression(HDF5::GZIP_COMPRESSION);
      props.set_chunk_size(RMF::HDF5::DataSetIndexD<2>(128, 4));
      (file_.add_child_data_set<HDF5::IndexTraits,
                                2>)(get_node_data_data_set_name(), props);
    }
  } else {
    if (read_only) {
      // walk around type checking
      file_ = HDF5::open_file_read_only_returning_nonconst(get_file_path());
    } else {
      file_ = HDF5::open_file(get_file_path());
    }
    std::string version;
    version = file_.get_attribute<HDF5::CharTraits>("version");
    RMF_USAGE_CHECK(version == "rmf 1",
                    internal::get_error_message(
                        "Unsupported rmf version ", "string found: \"", version,
                        "\" expected \"", "rmf 1", "\""));
  }
  node_names_.set(file_, get_node_name_data_set_name());
  node_data_.set(file_, get_node_data_data_set_name());
  initialize_categories();
  initialize_free_nodes();
  initialize_keys(0);
  std::string frn = get_frame_name_data_set_name();
  frame_names_.set(file_, frn);
}

#define RMF_LIST_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues, \
                      ReturnValues)                                       \
  initialize_keys(cat, #lcname, Ucname##Traits());

void HDF5SharedData::initialize_keys(int) {
  Categories cats = get_categories();
  RMF_FOREACH(Category cat, cats) {
    RMF_FOREACH_BACKWARDS_TYPE(RMF_LIST_KEYS);
  }
}

void HDF5SharedData::initialize_free_nodes() {
  HDF5::DataSetIndexD<2> dim = node_data_.get_size();
  for (unsigned int i = 0; i < dim[0]; ++i) {
    if (IndexTraits::get_is_null_value(
            node_data_.get_value(HDF5::DataSetIndexD<2>(i, 0)))) {
      free_ids_.push_back(i);
    }
  }
}

void HDF5SharedData::initialize_categories() {
  std::string nm = get_category_name_data_set_name();
  category_names_.set(file_, nm);
  HDF5::DataSetIndex1D sz = category_names_.get_size();
  for (unsigned int i = 0; i < sz[0]; ++i) {
    std::string name = category_names_.get_value(HDF5::DataSetIndex1D(i));
    Category cat(i);
    name_category_map_[name] = cat;
    category_data_map_[cat].name = name;
    category_data_map_[cat].index = i;
  }
}

HDF5SharedData::HDF5SharedData(std::string g, bool create, bool read_only)
    : BackwardsIOBase(g), frames_hint_(0) {
  open_things(create, read_only);
  link_category_ = get_category("link");
  link_key_ = get_key(link_category_, "linked", NodeIDTraits());
  if (create) {
    add_node("root", ROOT);
  } else {
    RMF_USAGE_CHECK(get_name(NodeID(0)) == "root", "Root node is not so named");
  }
}

HDF5SharedData::~HDF5SharedData() { close_things(); }

void HDF5SharedData::flush() {
  RMF_HDF5_CALL(H5Fflush(file_.get_handle(), H5F_SCOPE_GLOBAL));
  // SharedData::validate();
  node_names_.flush();
  frame_names_.flush();
  category_names_.flush();
  node_data_.flush();
}

void HDF5SharedData::check_node(NodeID node) const {
  RMF_USAGE_CHECK(
      node_names_.get_size()[0] > node.get_index(),
      internal::get_error_message("Invalid node specified: ", node));
}

NodeID HDF5SharedData::add_node(std::string name, NodeType type) {
  NodeID ret;
  if (free_ids_.empty()) {
    HDF5::DataSetIndexD<1> nsz = node_names_.get_size();
    ret = NodeID(nsz[0]);
    ++nsz[0];
    node_names_.set_size(nsz);
    HDF5::DataSetIndexD<2> dsz = node_data_.get_size();
    dsz[0] = ret.get_index() + 1;
    dsz[1] = std::max<hsize_t>(3, dsz[1]);
    node_data_.set_size(dsz);
  } else {
    ret = NodeID(free_ids_.back());
    free_ids_.pop_back();
  }
  node_names_.set_value(HDF5::DataSetIndexD<1>(ret.get_index()), name);
  node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), TYPE), type);
  node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), CHILD),
                       IndexTraits::get_null_value());
  node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), SIBLING),
                       IndexTraits::get_null_value());
  return ret;
}
NodeID HDF5SharedData::get_first_child(NodeID node) const {
  check_node(node);
  int child =
      node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD));
  if (child == -1)
    return NodeID();
  else
    return NodeID(child);
}
NodeID HDF5SharedData::get_sibling(NodeID node) const {
  check_node(node);
  int sib =
      node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING));
  if (sib == -1) {
    return NodeID();
  } else {
    return NodeID(sib);
  }
}
void HDF5SharedData::set_first_child(NodeID node, NodeID c) {
  check_node(node);
  return node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD),
                              c.get_index());
}
void HDF5SharedData::set_sibling(NodeID node, NodeID c) {
  check_node(node);
  if (c == NodeID()) {
    node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING), -1);
  } else {
    node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING),
                         c.get_index());
  }
}
std::string HDF5SharedData::get_name(NodeID node) const {
  if (static_cast<unsigned int>(node.get_index()) < get_number_of_nodes()) {
    check_node(node);
    return node_names_.get_value(HDF5::DataSetIndexD<1>(node.get_index()));
  } else {
    return "bond";
  }
}
NodeType HDF5SharedData::get_type(NodeID index) const {
  if (static_cast<unsigned int>(index.get_index()) < get_number_of_nodes()) {
    check_node(index);
    return NodeType(
        node_data_.get_value(HDF5::DataSetIndexD<2>(index.get_index(), TYPE)));
  } else {
    return BOND;
  }
}

NodeID HDF5SharedData::add_child(NodeID node, std::string name, NodeType t) {
  NodeID old_child = get_first_child(node);
  NodeID nn = add_node(name, t);
  set_first_child(node, nn);
  set_sibling(nn, old_child);
  return nn;
}

void HDF5SharedData::add_child(NodeID node, NodeID child_node) {
  RMF_INTERNAL_CHECK(NodeID() != child_node, "Bad child being added");
  NodeID link = add_child(node, "link", LINK);
  get_category_index_create(link_category_);
  set_static_value(link, link_key_, child_node);
  RMF_INTERNAL_CHECK(get_linked(link) == child_node, "Return does not match");
}

NodeID HDF5SharedData::get_linked(NodeID node) const {
  NodeID ret = get_static_value(node, link_key_);
  RMF_INTERNAL_CHECK(ret != NodeID(), "Bad link value found");
  return ret;
}

NodeIDs HDF5SharedData::get_children(NodeID node) const {
  NodeID cur = get_first_child(node);
  NodeIDs ret;
  while (!NodeIDTraits::get_is_null_value(cur)) {
    if (get_type(cur) != LINK) {
      ret.push_back(cur);
      cur = get_sibling(cur);
    } else {
      ret.push_back(get_linked(cur));
      cur = get_sibling(cur);
    }
  }
  std::reverse(ret.begin(), ret.end());

  return ret;
}

unsigned int HDF5SharedData::add_category_impl(std::string name) {
  // fill in later
  int sz = category_names_.get_size()[0];
  category_names_.set_size(HDF5::DataSetIndex1D(sz + 1));
  category_names_.set_value(HDF5::DataSetIndex1D(sz), name);
  return sz;
}

Categories HDF5SharedData::get_categories() const {
  Categories ret;
  for (CategoryDataMap::const_iterator it = category_data_map_.begin();
       it != category_data_map_.end(); ++it) {
    if (it->second.name == "link") continue;
    ret.push_back(it->first);
  }
  return ret;
}

Category HDF5SharedData::get_category(std::string name) {
  NameCategoryMap::const_iterator it = name_category_map_.find(name);
  if (it == name_category_map_.end()) {
    Category cat(name_category_map_.size());
    name_category_map_[name] = cat;
    category_data_map_[cat].index = -1;
    category_data_map_[cat].name = name;
    return cat;
  } else {
    return it->second;
  }
}

#define RMF_SEARCH_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues,    \
                        ReturnValues)                                          \
  {                                                                            \
    int category_index = get_category_index(cats[i]);                          \
    if (category_index == -1) continue;                                        \
    ret = std::max<int>(ret,                                                   \
                        get_number_of_frames<Ucname##Traits>(category_index)); \
  }

unsigned int HDF5SharedData::get_number_of_frames() const {
  Categories cats = get_categories();
  int ret = 0;
  for (unsigned int i = 0; i < cats.size(); ++i) {
    RMF_FOREACH_BACKWARDS_TYPE(RMF_SEARCH_KEYS);
  }
  return std::max<int>(frame_names_.get_size()[0], ret);
}

std::string HDF5SharedData::get_description() const {
  if (!get_group().get_has_attribute("description")) {
    return std::string();
  } else
    return get_group().get_char_attribute("description");
}
void HDF5SharedData::set_description(std::string str) {
  RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\n',
                  "Description should end in a newline.");
  get_group().set_char_attribute("description", str);
}

std::string HDF5SharedData::get_producer() const {
  if (!get_group().get_has_attribute("producer")) {
    return std::string();
  } else
    return get_group().get_char_attribute("producer");
}
void HDF5SharedData::set_producer(std::string str) {
  RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\n',
                  "Producer should end in a newline.");
  get_group().set_char_attribute("producer", str);
}

void HDF5SharedData::set_name(FrameID i, std::string str) {
  RMF_USAGE_CHECK(i != ALL_FRAMES,
                  "Cannot set the name frame name for static data");
  if (frame_names_.get_size()[0] <= i.get_index()) {
    frame_names_.set_size(HDF5::DataSetIndexD<1>(i.get_index() + 1));
  }
  frame_names_.set_value(HDF5::DataSetIndexD<1>(i.get_index()), str);
}
std::string HDF5SharedData::get_loaded_frame_name() const {
  FrameID i = get_loaded_frame();
  if (frame_names_.get_size()[0] > i.get_index()) {
    return frame_names_.get_value(HDF5::DataSetIndexD<1>(i.get_index()));
  } else {
    return std::string();
  }
}

void HDF5SharedData::reload() {
  close_things();
  open_things(false, read_only_);
}

#define RMF_HDF5_SET_FRAME(lcname, Ucname, PassValue, ReturnValue, PassValues, \
                           ReturnValues)                                       \
  per_frame_##lcname##_data_sets_.set_current_frame(frame);

void HDF5SharedData::set_loaded_frame(FrameID frame) {
  RMF_TRACE(get_logger(), "Loading frame " << frame);
  BackwardsIOBase::set_loaded_frame(frame);
  RMF_FOREACH_BACKWARDS_TYPE(RMF_HDF5_SET_FRAME);
}
}  // namespace hdf5_backend
} /* namespace RMF */

RMF_DISABLE_WARNINGS
<commit_msg>make sure to load link keys<commit_after>/**
 *  \file RMF/Category.h
 *  \brief Handle read/write of Model data from/to files.
 *
 *  Copyright 2007-2013 IMP Inventors. All rights reserved.
 *
 */

#include "HDF5SharedData.h"
#include <RMF/NodeHandle.h>
#include <RMF/Validator.h>
#include <boost/unordered_set.hpp>
#include <RMF/HDF5/Group.h>
#include <RMF/log.h>
#include <algorithm>

RMF_ENABLE_WARNINGS

namespace RMF {
namespace hdf5_backend {

#define RMF_CLOSE(lcname, Ucname, PassValue, ReturnValue, PassValues, \
                  ReturnValues)                                       \
  lcname##_data_sets_ = DataDataSetCache2D<Ucname##Traits>();         \
  per_frame_##lcname##_data_sets_ = DataDataSetCache3D<Ucname##Traits>()

void HDF5SharedData::close_things() {
  node_names_.reset();
  free_ids_.clear();
  node_data_.reset();
  index_cache_ = IndexCache();
  key_name_data_sets_ = KeyNameDataSetCache();
  category_names_.reset();
  frame_names_.reset();
  max_cache_.clear();
  RMF_FOREACH_BACKWARDS_TYPE(RMF_CLOSE);
  flush();
  file_ = HDF5::Group();
  H5garbage_collect();
}

void HDF5SharedData::open_things(bool create, bool read_only) {
  read_only_ = read_only;
  if (create) {
    file_ = HDF5::create_file(get_file_path());
    file_.set_attribute<HDF5::CharTraits>("version", std::string("rmf 1"));
    {
      HDF5::DataSetCreationPropertiesD<HDF5::StringTraits, 1> props;
      props.set_compression(HDF5::GZIP_COMPRESSION);
      (file_.add_child_data_set<HDF5::StringTraits,
                                1>)(get_node_name_data_set_name(), props);
    }
    {
      HDF5::DataSetCreationPropertiesD<HDF5::IndexTraits, 2> props;
      props.set_compression(HDF5::GZIP_COMPRESSION);
      props.set_chunk_size(RMF::HDF5::DataSetIndexD<2>(128, 4));
      (file_.add_child_data_set<HDF5::IndexTraits,
                                2>)(get_node_data_data_set_name(), props);
    }
  } else {
    if (read_only) {
      // walk around type checking
      file_ = HDF5::open_file_read_only_returning_nonconst(get_file_path());
    } else {
      file_ = HDF5::open_file(get_file_path());
    }
    std::string version;
    version = file_.get_attribute<HDF5::CharTraits>("version");
    RMF_USAGE_CHECK(version == "rmf 1",
                    internal::get_error_message(
                        "Unsupported rmf version ", "string found: \"", version,
                        "\" expected \"", "rmf 1", "\""));
  }
  node_names_.set(file_, get_node_name_data_set_name());
  node_data_.set(file_, get_node_data_data_set_name());
  initialize_categories();
  initialize_free_nodes();
  initialize_keys(0);
  std::string frn = get_frame_name_data_set_name();
  frame_names_.set(file_, frn);
}

#define RMF_LIST_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues, \
                      ReturnValues)                                       \
  initialize_keys(cat, #lcname, Ucname##Traits());

void HDF5SharedData::initialize_keys(int) {
  Categories cats = get_categories();
  RMF_FOREACH(Category cat, cats) {
    RMF_FOREACH_BACKWARDS_TYPE(RMF_LIST_KEYS);
  }
  initialize_keys(get_category("link"), "nodeid", NodeIDTraits());
}

void HDF5SharedData::initialize_free_nodes() {
  HDF5::DataSetIndexD<2> dim = node_data_.get_size();
  for (unsigned int i = 0; i < dim[0]; ++i) {
    if (IndexTraits::get_is_null_value(
            node_data_.get_value(HDF5::DataSetIndexD<2>(i, 0)))) {
      free_ids_.push_back(i);
    }
  }
}

void HDF5SharedData::initialize_categories() {
  std::string nm = get_category_name_data_set_name();
  category_names_.set(file_, nm);
  HDF5::DataSetIndex1D sz = category_names_.get_size();
  for (unsigned int i = 0; i < sz[0]; ++i) {
    std::string name = category_names_.get_value(HDF5::DataSetIndex1D(i));
    Category cat(i);
    name_category_map_[name] = cat;
    category_data_map_[cat].name = name;
    category_data_map_[cat].index = i;
  }
}

HDF5SharedData::HDF5SharedData(std::string g, bool create, bool read_only)
    : BackwardsIOBase(g), frames_hint_(0) {
  open_things(create, read_only);
  link_category_ = get_category("link");
  link_key_ = get_key(link_category_, "linked", NodeIDTraits());
  if (create) {
    add_node("root", ROOT);
  } else {
    RMF_INFO(get_logger(), "Found " << node_names_.get_size() << " nodes");
    RMF_USAGE_CHECK(
        get_name(NodeID(0)) == "root",
        std::string("Root node is not so named ") + get_name(NodeID(0)));
  }
}

HDF5SharedData::~HDF5SharedData() { close_things(); }

void HDF5SharedData::flush() {
  RMF_HDF5_CALL(H5Fflush(file_.get_handle(), H5F_SCOPE_GLOBAL));
  // SharedData::validate();
  node_names_.flush();
  frame_names_.flush();
  category_names_.flush();
  node_data_.flush();
}

void HDF5SharedData::check_node(NodeID node) const {
  RMF_USAGE_CHECK(
      node_names_.get_size()[0] > node.get_index(),
      internal::get_error_message("Invalid node specified: ", node));
}

NodeID HDF5SharedData::add_node(std::string name, NodeType type) {
  NodeID ret;
  if (free_ids_.empty()) {
    HDF5::DataSetIndexD<1> nsz = node_names_.get_size();
    ret = NodeID(nsz[0]);
    ++nsz[0];
    node_names_.set_size(nsz);
    HDF5::DataSetIndexD<2> dsz = node_data_.get_size();
    dsz[0] = ret.get_index() + 1;
    dsz[1] = std::max<hsize_t>(3, dsz[1]);
    node_data_.set_size(dsz);
  } else {
    ret = NodeID(free_ids_.back());
    free_ids_.pop_back();
  }
  node_names_.set_value(HDF5::DataSetIndexD<1>(ret.get_index()), name);
  node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), TYPE), type);
  node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), CHILD),
                       IndexTraits::get_null_value());
  node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), SIBLING),
                       IndexTraits::get_null_value());
  return ret;
}
NodeID HDF5SharedData::get_first_child(NodeID node) const {
  check_node(node);
  int child =
      node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD));
  if (child == -1)
    return NodeID();
  else
    return NodeID(child);
}
NodeID HDF5SharedData::get_sibling(NodeID node) const {
  check_node(node);
  int sib =
      node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING));
  if (sib == -1) {
    return NodeID();
  } else {
    return NodeID(sib);
  }
}
void HDF5SharedData::set_first_child(NodeID node, NodeID c) {
  check_node(node);
  return node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD),
                              c.get_index());
}
void HDF5SharedData::set_sibling(NodeID node, NodeID c) {
  check_node(node);
  if (c == NodeID()) {
    node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING), -1);
  } else {
    node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING),
                         c.get_index());
  }
}
std::string HDF5SharedData::get_name(NodeID node) const {
  if (static_cast<unsigned int>(node.get_index()) < get_number_of_nodes()) {
    check_node(node);
    return node_names_.get_value(HDF5::DataSetIndexD<1>(node.get_index()));
  } else {
    return "bond";
  }
}
NodeType HDF5SharedData::get_type(NodeID index) const {
  if (static_cast<unsigned int>(index.get_index()) < get_number_of_nodes()) {
    check_node(index);
    return NodeType(
        node_data_.get_value(HDF5::DataSetIndexD<2>(index.get_index(), TYPE)));
  } else {
    return BOND;
  }
}

NodeID HDF5SharedData::add_child(NodeID node, std::string name, NodeType t) {
  NodeID old_child = get_first_child(node);
  NodeID nn = add_node(name, t);
  set_first_child(node, nn);
  set_sibling(nn, old_child);
  return nn;
}

void HDF5SharedData::add_child(NodeID node, NodeID child_node) {
  RMF_INTERNAL_CHECK(NodeID() != child_node, "Bad child being added");
  NodeID link = add_child(node, "link", LINK);
  get_category_index_create(link_category_);
  set_static_value(link, link_key_, child_node);
  RMF_INTERNAL_CHECK(get_linked(link) == child_node, "Return does not match");
}

NodeID HDF5SharedData::get_linked(NodeID node) const {
  NodeID ret = get_static_value(node, link_key_);
  RMF_INTERNAL_CHECK(ret != NodeID(), "Bad link value found");
  return ret;
}

NodeIDs HDF5SharedData::get_children(NodeID node) const {
  NodeID cur = get_first_child(node);
  NodeIDs ret;
  while (!NodeIDTraits::get_is_null_value(cur)) {
    if (get_type(cur) != LINK) {
      ret.push_back(cur);
      cur = get_sibling(cur);
    } else {
      ret.push_back(get_linked(cur));
      cur = get_sibling(cur);
    }
  }
  std::reverse(ret.begin(), ret.end());

  return ret;
}

unsigned int HDF5SharedData::add_category_impl(std::string name) {
  // fill in later
  int sz = category_names_.get_size()[0];
  category_names_.set_size(HDF5::DataSetIndex1D(sz + 1));
  category_names_.set_value(HDF5::DataSetIndex1D(sz), name);
  return sz;
}

Categories HDF5SharedData::get_categories() const {
  Categories ret;
  for (CategoryDataMap::const_iterator it = category_data_map_.begin();
       it != category_data_map_.end(); ++it) {
    if (it->second.name == "link") continue;
    ret.push_back(it->first);
  }
  return ret;
}

Category HDF5SharedData::get_category(std::string name) {
  NameCategoryMap::const_iterator it = name_category_map_.find(name);
  if (it == name_category_map_.end()) {
    Category cat(name_category_map_.size());
    name_category_map_[name] = cat;
    category_data_map_[cat].index = -1;
    category_data_map_[cat].name = name;
    return cat;
  } else {
    return it->second;
  }
}

#define RMF_SEARCH_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues,    \
                        ReturnValues)                                          \
  {                                                                            \
    int category_index = get_category_index(cats[i]);                          \
    if (category_index == -1) continue;                                        \
    ret = std::max<int>(ret,                                                   \
                        get_number_of_frames<Ucname##Traits>(category_index)); \
  }

unsigned int HDF5SharedData::get_number_of_frames() const {
  Categories cats = get_categories();
  int ret = 0;
  for (unsigned int i = 0; i < cats.size(); ++i) {
    RMF_FOREACH_BACKWARDS_TYPE(RMF_SEARCH_KEYS);
  }
  return std::max<int>(frame_names_.get_size()[0], ret);
}

std::string HDF5SharedData::get_description() const {
  if (!get_group().get_has_attribute("description")) {
    return std::string();
  } else
    return get_group().get_char_attribute("description");
}
void HDF5SharedData::set_description(std::string str) {
  RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\n',
                  "Description should end in a newline.");
  get_group().set_char_attribute("description", str);
}

std::string HDF5SharedData::get_producer() const {
  if (!get_group().get_has_attribute("producer")) {
    return std::string();
  } else
    return get_group().get_char_attribute("producer");
}
void HDF5SharedData::set_producer(std::string str) {
  RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\n',
                  "Producer should end in a newline.");
  get_group().set_char_attribute("producer", str);
}

void HDF5SharedData::set_name(FrameID i, std::string str) {
  RMF_USAGE_CHECK(i != ALL_FRAMES,
                  "Cannot set the name frame name for static data");
  if (frame_names_.get_size()[0] <= i.get_index()) {
    frame_names_.set_size(HDF5::DataSetIndexD<1>(i.get_index() + 1));
  }
  frame_names_.set_value(HDF5::DataSetIndexD<1>(i.get_index()), str);
}
std::string HDF5SharedData::get_loaded_frame_name() const {
  FrameID i = get_loaded_frame();
  if (frame_names_.get_size()[0] > i.get_index()) {
    return frame_names_.get_value(HDF5::DataSetIndexD<1>(i.get_index()));
  } else {
    return std::string();
  }
}

void HDF5SharedData::reload() {
  close_things();
  open_things(false, read_only_);
}

#define RMF_HDF5_SET_FRAME(lcname, Ucname, PassValue, ReturnValue, PassValues, \
                           ReturnValues)                                       \
  per_frame_##lcname##_data_sets_.set_current_frame(frame);

void HDF5SharedData::set_loaded_frame(FrameID frame) {
  RMF_TRACE(get_logger(), "Loading frame " << frame);
  BackwardsIOBase::set_loaded_frame(frame);
  RMF_FOREACH_BACKWARDS_TYPE(RMF_HDF5_SET_FRAME);
}
}  // namespace hdf5_backend
} /* namespace RMF */

RMF_DISABLE_WARNINGS
<|endoftext|>


<commit_before>#include <bits/stdc++.h>
#define NUM_NODES 8
using namespace std;

vector < int > g[NUM_NODES];
int d[NUM_NODES];

void show(){
    for (int i = 0; i < NUM_NODES; i++){
        cout << i << " " << d[i] << endl;
    }
}
/*
 * s -> origin
 * n -> number of nodes
 */
void bfs(int o, int n){
    for (int i = 0; i<=n;  i++) d[i] = -1;
    queue < int > q;
    q.push(o);
    d[o]  = 0;
    while(q.size() > 0){
        int  cur  = q.front(); q.pop();
        for ( int i = 0; i < g[cur].size(); i++){
            int next = g[cur][i];
            if(d[next] == -1){
                d[next] = d[cur] +1;
                q.push(next);
            }
        }
    }
}

int main(){

    g[0].push_back(1);
    g[0].push_back(2);
    g[0].push_back(3);
    g[1].push_back(4);
    g[1].push_back(5);
    g[2].push_back(6);
    g[3].push_back(7);

    bfs(0, NUM_NODES);

    show();

    return 0 ;
}
<commit_msg>Improve implementation bfs.<commit_after>#include <bits/stdc++.h>
#define pb push_back

using namespace std;

typedef vector < int > vi;
vi dis;
vector < vi > graph;

void show_distances(){
    for( int i = 0; i< dis.size(); i++){
        cout << i << " : " << dis[i] << "\n";
    }
}

void bfs(int origin){
    queue < int > q;
    dis[origin] = 0;
    q.push(origin);

    while( q.size() > 0){
        int front = q.front(); q.pop();
        for(int son: graph[front]){
            if(dis[son] == -1){
                dis[son] = dis[front] +1;
                q.push(son);
            }
        }
    }
}

int main(){
    int num_nodes = 5;
    dis.assign(num_nodes, -1);

    graph.resize(num_nodes);

    graph[0].pb(1);
    graph[0].pb(2);
    graph[0].pb(3);

    graph[1].pb(4);

    bfs(0);
    show_distances();

    return 0;
}

<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "RCRequests.h"

#include "RCReplies.h"
#include "RCRobotPlayer.h"
#include "MessageUtilities.h"
#include "BZDBCache.h"
#include "Roster.h"
#include "World.h"
#include "playing.h"

#include "version.h"

bool ExecuteReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  rrp->lastTickAt = TimeKeeper::getCurrent().getSeconds();

  if (rrp->pendingUpdates[RCRobotPlayer::speedUpdate])
    rrp->speed = rrp->nextSpeed;
  if (rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate])
    rrp->turnRate = rrp->nextTurnRate;

  if (rrp->pendingUpdates[RCRobotPlayer::distanceUpdate])
  {
    if (rrp->nextDistance < 0.0f)
      rrp->distanceForward = false;
    else
      rrp->distanceForward = true;
    rrp->distanceRemaining = (rrp->distanceForward ? 1 : -1) * rrp->nextDistance;
  }
  if (rrp->pendingUpdates[RCRobotPlayer::turnUpdate])
  {
    if (rrp->nextTurn < 0.0f)
      rrp->turnLeft = false;
    else
      rrp->turnLeft = true;
    rrp->turnRemaining = (rrp->turnLeft ? 1 : -1) * rrp->nextTurn * M_PI/180.0f; /* We have to convert to radians! */
  }

  for (int i = 0; i < RCRobotPlayer::updateCount; ++i)
    rrp->pendingUpdates[i] = false;

  if (rrp->shoot)
  {
    rrp->shoot = false;
    rrp->fireShot();
  }

  return true;
}

bool SetSpeedReq::process(RCRobotPlayer *rrp)
{
  rrp->nextSpeed = speed;
  rrp->pendingUpdates[RCRobotPlayer::speedUpdate] = true;
  return true;
}

bool SetTurnRateReq::process(RCRobotPlayer *rrp)
{
  rrp->nextTurnRate = rate;
  rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate] = true;
  return true;
}

bool SetAheadReq::process(RCRobotPlayer *rrp)
{
  rrp->pendingUpdates[RCRobotPlayer::distanceUpdate] = true;
  rrp->nextDistance = distance;
  return true;
}

bool SetTurnLeftReq::process(RCRobotPlayer *rrp)
{
  rrp->pendingUpdates[RCRobotPlayer::turnUpdate] = true;
  rrp->nextTurn = turn;
  return true;
}

bool SetFireReq::process(RCRobotPlayer *rrp)
{
  rrp->shoot = true;
  return true;
}

bool SetResumeReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  if (rrp->hasStopped)
  {
    rrp->hasStopped = false;
    rrp->distanceRemaining = rrp->stoppedDistance;
    rrp->turnRemaining = rrp->stoppedTurn;
    rrp->distanceForward = rrp->stoppedForward;
    rrp->turnLeft = rrp->stoppedLeft;
  }
  return true;
}

bool GetGunHeatReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  link->send(GunHeatReply(rrp->getReloadTime()));
  return true;
}

bool GetDistanceRemainingReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  link->send(DistanceRemainingReply(rrp->distanceRemaining));
  return true;
}

bool GetTurnRemainingReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  link->send(TurnRemainingReply(rrp->turnRemaining * 180.0f/M_PI));
  return true;
}

bool GetTickDurationReq::process(RCRobotPlayer *rrp)
{
  link->sendf("GetTickDuration %f\n", rrp->tickDuration);
  return true;
}

bool SetTickDurationReq::process(RCRobotPlayer *rrp)
{
  rrp->tickDuration = duration;
  return true;
}

bool GetTickRemainingReq::process(RCRobotPlayer *rrp)
{
  if (rrp->isSteadyState())
    link->sendf("GetTickRemaining %f\n", (rrp->lastTickAt + rrp->tickDuration) - TimeKeeper::getCurrent().getSeconds());
  else
    link->send("GetTickRemaining 0.0\n");

  return true;
}

bool GetBattleFieldSizeReq::process(RCRobotPlayer *)
{
  link->send(BattleFieldSizeReply(BZDBCache::worldSize));
  return true;
}

bool GetTeamsReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetBasesReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetObstaclesReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetFlagsReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetShotsReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetMyTanksReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetOtherTanksReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetConstantsReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}

bool GetXReq::process(RCRobotPlayer *rrp)
{
  link->send(XReply(rrp->getPosition()[0]));
  return true;
}
bool GetYReq::process(RCRobotPlayer *rrp)
{
  link->send(YReply(rrp->getPosition()[1]));
  return true;
}
bool GetZReq::process(RCRobotPlayer *rrp)
{
  link->send(ZReply(rrp->getPosition()[2]));
  return true;
}

bool GetWidthReq::process(RCRobotPlayer *rrp)
{
  link->send(WidthReply(rrp->getDimensions()[0]));
  return true;
}
bool GetLengthReq::process(RCRobotPlayer *rrp)
{
  link->send(LengthReply(rrp->getDimensions()[1]));
  return true;
}
bool GetHeightReq::process(RCRobotPlayer *rrp)
{
  link->send(HeightReply(rrp->getDimensions()[2]));
  return true;
}
bool GetHeadingReq::process(RCRobotPlayer *rrp)
{
  link->send(HeadingReply(rrp->getAngle()*180.0f/M_PI));
  return true;
}

bool SetStopReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  if (!rrp->hasStopped || overwrite)
  {
    rrp->hasStopped = true;
    rrp->stoppedDistance = rrp->distanceRemaining;
    rrp->stoppedTurn = rrp->turnRemaining;
    rrp->stoppedForward = rrp->distanceForward;
    rrp->stoppedLeft = rrp->turnLeft;
  }
  return true;
}

bool GetPlayersReq::process(RCRobotPlayer *)
{
  link->send(PlayersBeginReply());
  for (int i = 0; i < curMaxPlayers; i++) {
    if (!player[i])
      continue;
    if (robots[0]->getId() == player[i]->getId())
      continue;

    TeamColor team = player[i]->getTeam();
    if (team == ObserverTeam)
      continue;
    if (team == startupInfo.team && startupInfo.team != AutomaticTeam)
      continue;

    link->send(PlayersReply(player[i]));
  }

  return true;
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>don't need version.h<commit_after>/* bzflag
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "RCRequests.h"

#include "RCReplies.h"
#include "RCRobotPlayer.h"
#include "MessageUtilities.h"
#include "BZDBCache.h"
#include "Roster.h"
#include "World.h"
#include "playing.h"

bool ExecuteReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  rrp->lastTickAt = TimeKeeper::getCurrent().getSeconds();

  if (rrp->pendingUpdates[RCRobotPlayer::speedUpdate])
    rrp->speed = rrp->nextSpeed;
  if (rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate])
    rrp->turnRate = rrp->nextTurnRate;

  if (rrp->pendingUpdates[RCRobotPlayer::distanceUpdate])
  {
    if (rrp->nextDistance < 0.0f)
      rrp->distanceForward = false;
    else
      rrp->distanceForward = true;
    rrp->distanceRemaining = (rrp->distanceForward ? 1 : -1) * rrp->nextDistance;
  }
  if (rrp->pendingUpdates[RCRobotPlayer::turnUpdate])
  {
    if (rrp->nextTurn < 0.0f)
      rrp->turnLeft = false;
    else
      rrp->turnLeft = true;
    rrp->turnRemaining = (rrp->turnLeft ? 1 : -1) * rrp->nextTurn * M_PI/180.0f; /* We have to convert to radians! */
  }

  for (int i = 0; i < RCRobotPlayer::updateCount; ++i)
    rrp->pendingUpdates[i] = false;

  if (rrp->shoot)
  {
    rrp->shoot = false;
    rrp->fireShot();
  }

  return true;
}

bool SetSpeedReq::process(RCRobotPlayer *rrp)
{
  rrp->nextSpeed = speed;
  rrp->pendingUpdates[RCRobotPlayer::speedUpdate] = true;
  return true;
}

bool SetTurnRateReq::process(RCRobotPlayer *rrp)
{
  rrp->nextTurnRate = rate;
  rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate] = true;
  return true;
}

bool SetAheadReq::process(RCRobotPlayer *rrp)
{
  rrp->pendingUpdates[RCRobotPlayer::distanceUpdate] = true;
  rrp->nextDistance = distance;
  return true;
}

bool SetTurnLeftReq::process(RCRobotPlayer *rrp)
{
  rrp->pendingUpdates[RCRobotPlayer::turnUpdate] = true;
  rrp->nextTurn = turn;
  return true;
}

bool SetFireReq::process(RCRobotPlayer *rrp)
{
  rrp->shoot = true;
  return true;
}

bool SetResumeReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  if (rrp->hasStopped)
  {
    rrp->hasStopped = false;
    rrp->distanceRemaining = rrp->stoppedDistance;
    rrp->turnRemaining = rrp->stoppedTurn;
    rrp->distanceForward = rrp->stoppedForward;
    rrp->turnLeft = rrp->stoppedLeft;
  }
  return true;
}

bool GetGunHeatReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  link->send(GunHeatReply(rrp->getReloadTime()));
  return true;
}

bool GetDistanceRemainingReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  link->send(DistanceRemainingReply(rrp->distanceRemaining));
  return true;
}

bool GetTurnRemainingReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  link->send(TurnRemainingReply(rrp->turnRemaining * 180.0f/M_PI));
  return true;
}

bool GetTickDurationReq::process(RCRobotPlayer *rrp)
{
  link->sendf("GetTickDuration %f\n", rrp->tickDuration);
  return true;
}

bool SetTickDurationReq::process(RCRobotPlayer *rrp)
{
  rrp->tickDuration = duration;
  return true;
}

bool GetTickRemainingReq::process(RCRobotPlayer *rrp)
{
  if (rrp->isSteadyState())
    link->sendf("GetTickRemaining %f\n", (rrp->lastTickAt + rrp->tickDuration) - TimeKeeper::getCurrent().getSeconds());
  else
    link->send("GetTickRemaining 0.0\n");

  return true;
}

bool GetBattleFieldSizeReq::process(RCRobotPlayer *)
{
  link->send(BattleFieldSizeReply(BZDBCache::worldSize));
  return true;
}

bool GetTeamsReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetBasesReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetObstaclesReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetFlagsReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetShotsReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetMyTanksReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetOtherTanksReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}
bool GetConstantsReq::process(RCRobotPlayer *)
{
  // TODO: Implement this. :p
  return true;
}

bool GetXReq::process(RCRobotPlayer *rrp)
{
  link->send(XReply(rrp->getPosition()[0]));
  return true;
}
bool GetYReq::process(RCRobotPlayer *rrp)
{
  link->send(YReply(rrp->getPosition()[1]));
  return true;
}
bool GetZReq::process(RCRobotPlayer *rrp)
{
  link->send(ZReply(rrp->getPosition()[2]));
  return true;
}

bool GetWidthReq::process(RCRobotPlayer *rrp)
{
  link->send(WidthReply(rrp->getDimensions()[0]));
  return true;
}
bool GetLengthReq::process(RCRobotPlayer *rrp)
{
  link->send(LengthReply(rrp->getDimensions()[1]));
  return true;
}
bool GetHeightReq::process(RCRobotPlayer *rrp)
{
  link->send(HeightReply(rrp->getDimensions()[2]));
  return true;
}
bool GetHeadingReq::process(RCRobotPlayer *rrp)
{
  link->send(HeadingReply(rrp->getAngle()*180.0f/M_PI));
  return true;
}

bool SetStopReq::process(RCRobotPlayer *rrp)
{
  if (!rrp->isSteadyState())
    return false;

  if (!rrp->hasStopped || overwrite)
  {
    rrp->hasStopped = true;
    rrp->stoppedDistance = rrp->distanceRemaining;
    rrp->stoppedTurn = rrp->turnRemaining;
    rrp->stoppedForward = rrp->distanceForward;
    rrp->stoppedLeft = rrp->turnLeft;
  }
  return true;
}

bool GetPlayersReq::process(RCRobotPlayer *)
{
  link->send(PlayersBeginReply());
  for (int i = 0; i < curMaxPlayers; i++) {
    if (!player[i])
      continue;
    if (robots[0]->getId() == player[i]->getId())
      continue;

    TeamColor team = player[i]->getTeam();
    if (team == ObserverTeam)
      continue;
    if (team == startupInfo.team && startupInfo.team != AutomaticTeam)
      continue;

    link->send(PlayersReply(player[i]));
  }

  return true;
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIGeometryBuffer.cpp
    created:    Wed Jan 13 2010
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/ShaderParameterBindings.h"

#include <vector>

namespace CEGUI
{
//---------------------------------------------------------------------------//
GeometryBuffer::GeometryBuffer(RefCounted<RenderMaterial> renderMaterial)
    : d_translation(0, 0, 0)
    , d_rotation(Quaternion::IDENTITY)
    , d_scale(1.0f, 1.0f, 1.0f)
    , d_pivot(0, 0, 0)
    , d_customTransform(1.0f)
    , d_effect(0)
    , d_matrixValid(false)
    , d_blendMode(BM_NORMAL)
    , d_renderMaterial(renderMaterial)
    , d_polygonFillRule(PFR_NONE)
    , d_postStencilVertexCount(0)
{
}

//---------------------------------------------------------------------------//
GeometryBuffer::~GeometryBuffer()
{
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setBlendMode(const BlendMode mode)
{
    d_blendMode = mode;
}

//---------------------------------------------------------------------------//
BlendMode GeometryBuffer::getBlendMode() const
{
    return d_blendMode;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<ColouredVertex>& coloured_vertices)
{
    if(coloured_vertices.empty())
        return;

    appendGeometry(&coloured_vertices[0], coloured_vertices.size());
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array,
                                    uint vertex_count)
{
    // Add the vertex data in their default order into an array
    std::vector<float> vertexData;
    const ColouredVertex* vs = vertex_array;
    for (uint i = 0; i < vertex_count; ++i, ++vs)
    {
        // Add all the elements in the default order for textured and coloured
        // geometry into the vector
        vertexData.push_back(vs->d_position.x);
        vertexData.push_back(vs->d_position.y);
        vertexData.push_back(vs->d_position.z);
        vertexData.push_back(vs->d_colour.getRed());
        vertexData.push_back(vs->d_colour.getGreen());
        vertexData.push_back(vs->d_colour.getBlue());
        vertexData.push_back(vs->d_colour.getAlpha());
    }

    // Append the prepared geometry data
    appendGeometry(vertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<TexturedColouredVertex>& textured_vertices)
{
    if(textured_vertices.empty())
        return;

    appendGeometry(&textured_vertices[0], textured_vertices.size());
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array,
                                    uint vertex_count)
{
    // Add the vertex data in their default order into an array
    std::vector<float> vertexData;
    const TexturedColouredVertex* vs = vertex_array;
    for (uint i = 0; i < vertex_count; ++i, ++vs)
    {
        // Add all the elements in the default order for textured and coloured
        // geometry into the vector
        vertexData.push_back(vs->d_position.x);
        vertexData.push_back(vs->d_position.y);
        vertexData.push_back(vs->d_position.z);
        vertexData.push_back(vs->d_colour.getRed());
        vertexData.push_back(vs->d_colour.getGreen());
        vertexData.push_back(vs->d_colour.getBlue());
        vertexData.push_back(vs->d_colour.getAlpha());
        vertexData.push_back(vs->d_texCoords.x);
        vertexData.push_back(vs->d_texCoords.y);
    }

    // Append the prepared geometry data
    appendGeometry(vertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const float* const vertex_data,
                                    uint array_size)
{
    std::vector<float> vectorVertexData(vertex_data, vertex_data + array_size);
    appendGeometry(vectorVertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex)
{
    // Add the vertex data in their default order into an array
    float vertexData[9];

    // Copy the vertex attributes into the array
    vertexData[0] = vertex.d_position.x;
    vertexData[1] = vertex.d_position.y;
    vertexData[2] = vertex.d_position.z;
    vertexData[3] = vertex.d_colour.getRed();
    vertexData[4] = vertex.d_colour.getGreen();
    vertexData[5] = vertex.d_colour.getBlue();
    vertexData[6] = vertex.d_colour.getAlpha();
    vertexData[7] = vertex.d_texCoords.x;
    vertexData[8] = vertex.d_texCoords.y;

    appendGeometry(vertexData, 9);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const ColouredVertex& vertex)
{
    // Add the vertex data in their default order into an array
    float vertexData[7];

    // Copy the vertex attributes into the array
    vertexData[0] = vertex.d_position.x;
    vertexData[1] = vertex.d_position.y;
    vertexData[2] = vertex.d_position.z;
    vertexData[3] = vertex.d_colour.getRed();
    vertexData[4] = vertex.d_colour.getGreen();
    vertexData[5] = vertex.d_colour.getBlue();
    vertexData[6] = vertex.d_colour.getAlpha();

    appendGeometry(vertexData, 7);
}

//---------------------------------------------------------------------------//
int GeometryBuffer::getVertexAttributeElementCount() const
{
    int count = 0;

    const unsigned int attribute_count = d_vertexAttributes.size();
    for (unsigned int i = 0; i < attribute_count; ++i)
    {
        switch(d_vertexAttributes.at(i))
        {
            case VAT_POSITION0:
                count += 3;
                break;
            case VAT_COLOUR0:
                count += 4;
                break;
            case VAT_TEXCOORD0:
                count += 2;
                break;
            default:
                break;
        }
    }

    return count;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::resetVertexAttributes()
{
    d_vertexAttributes.clear();
}

//---------------------------------------------------------------------------//
void GeometryBuffer::addVertexAttribute(VertexAttributeType attribute)
{
    d_vertexAttributes.push_back(attribute);
}

//---------------------------------------------------------------------------//
RefCounted<RenderMaterial> GeometryBuffer::getRenderMaterial() const
{
    return d_renderMaterial;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setRenderMaterial(RefCounted<RenderMaterial> render_material)
{
    d_renderMaterial = render_material;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setStencilRenderingActive(PolygonFillRule fill_rule)
{
    d_polygonFillRule = fill_rule;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setStencilPostRenderingVertexCount(unsigned int vertex_count)
{
    d_postStencilVertexCount = vertex_count;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setRenderEffect(RenderEffect* effect)
{
    d_effect = effect;
}

//----------------------------------------------------------------------------//
RenderEffect* GeometryBuffer::getRenderEffect()
{
    return d_effect;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setTranslation(const Vector3f& translation)
{
    if(d_translation != translation)
    {
        d_translation = translation;
        d_matrixValid = false;
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setRotation(const Quaternion& rotationQuat)
{
    if(d_rotation != rotationQuat)
    {
        d_rotation = rotationQuat;
        d_matrixValid = false;
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setScale(const Vector3f& scale)
{
    if(d_scale != scale)
    {
        d_scale = scale;
        d_matrixValid = false;
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setScale(const Vector2f& scale)
{
    setScale(Vector3f(scale, 0.f));
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setPivot(const Vector3f& p)
{
    if(d_pivot != p)
    {
        d_pivot = Vector3f(p.d_x, p.d_y, p.d_z);
        d_matrixValid = false;
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setCustomTransform(const glm::mat4x4& transformation)
{
    if(d_customTransform != transformation)
    {
        d_customTransform = transformation;
        d_matrixValid = false;
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setClippingActive(const bool active)
{
    d_clippingActive = active;
}

//----------------------------------------------------------------------------//
bool GeometryBuffer::isClippingActive() const
{
    return d_clippingActive;
}

//----------------------------------------------------------------------------//
uint GeometryBuffer::getVertexCount() const
{
    return d_vertexCount;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::reset()
{
    d_vertexData.clear();
    d_clippingActive = true;
    setTexture(0);
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setTexture(Texture* texture)
{
    CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings();
    shaderParameterBindings->setParameter("texture0", texture);
}

//---------------------------------------------------------------------------//
}

<commit_msg>MOD: Fixed an issue with shader parameters and the GeomBuffer reset function Thanks to timotei for reporting this<commit_after>/***********************************************************************
    filename:   CEGUIGeometryBuffer.cpp
    created:    Wed Jan 13 2010
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/ShaderParameterBindings.h"

#include <vector>

namespace CEGUI
{
//---------------------------------------------------------------------------//
GeometryBuffer::GeometryBuffer(RefCounted<RenderMaterial> renderMaterial)
    : d_translation(0, 0, 0)
    , d_rotation(Quaternion::IDENTITY)
    , d_scale(1.0f, 1.0f, 1.0f)
    , d_pivot(0, 0, 0)
    , d_customTransform(1.0f)
    , d_effect(0)
    , d_matrixValid(false)
    , d_blendMode(BM_NORMAL)
    , d_renderMaterial(renderMaterial)
    , d_polygonFillRule(PFR_NONE)
    , d_postStencilVertexCount(0)
{
}

//---------------------------------------------------------------------------//
GeometryBuffer::~GeometryBuffer()
{
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setBlendMode(const BlendMode mode)
{
    d_blendMode = mode;
}

//---------------------------------------------------------------------------//
BlendMode GeometryBuffer::getBlendMode() const
{
    return d_blendMode;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<ColouredVertex>& coloured_vertices)
{
    if(coloured_vertices.empty())
        return;

    appendGeometry(&coloured_vertices[0], coloured_vertices.size());
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array,
                                    uint vertex_count)
{
    // Add the vertex data in their default order into an array
    std::vector<float> vertexData;
    const ColouredVertex* vs = vertex_array;
    for (uint i = 0; i < vertex_count; ++i, ++vs)
    {
        // Add all the elements in the default order for textured and coloured
        // geometry into the vector
        vertexData.push_back(vs->d_position.x);
        vertexData.push_back(vs->d_position.y);
        vertexData.push_back(vs->d_position.z);
        vertexData.push_back(vs->d_colour.getRed());
        vertexData.push_back(vs->d_colour.getGreen());
        vertexData.push_back(vs->d_colour.getBlue());
        vertexData.push_back(vs->d_colour.getAlpha());
    }

    // Append the prepared geometry data
    appendGeometry(vertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<TexturedColouredVertex>& textured_vertices)
{
    if(textured_vertices.empty())
        return;

    appendGeometry(&textured_vertices[0], textured_vertices.size());
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array,
                                    uint vertex_count)
{
    // Add the vertex data in their default order into an array
    std::vector<float> vertexData;
    const TexturedColouredVertex* vs = vertex_array;
    for (uint i = 0; i < vertex_count; ++i, ++vs)
    {
        // Add all the elements in the default order for textured and coloured
        // geometry into the vector
        vertexData.push_back(vs->d_position.x);
        vertexData.push_back(vs->d_position.y);
        vertexData.push_back(vs->d_position.z);
        vertexData.push_back(vs->d_colour.getRed());
        vertexData.push_back(vs->d_colour.getGreen());
        vertexData.push_back(vs->d_colour.getBlue());
        vertexData.push_back(vs->d_colour.getAlpha());
        vertexData.push_back(vs->d_texCoords.x);
        vertexData.push_back(vs->d_texCoords.y);
    }

    // Append the prepared geometry data
    appendGeometry(vertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const float* const vertex_data,
                                    uint array_size)
{
    std::vector<float> vectorVertexData(vertex_data, vertex_data + array_size);
    appendGeometry(vectorVertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex)
{
    // Add the vertex data in their default order into an array
    float vertexData[9];

    // Copy the vertex attributes into the array
    vertexData[0] = vertex.d_position.x;
    vertexData[1] = vertex.d_position.y;
    vertexData[2] = vertex.d_position.z;
    vertexData[3] = vertex.d_colour.getRed();
    vertexData[4] = vertex.d_colour.getGreen();
    vertexData[5] = vertex.d_colour.getBlue();
    vertexData[6] = vertex.d_colour.getAlpha();
    vertexData[7] = vertex.d_texCoords.x;
    vertexData[8] = vertex.d_texCoords.y;

    appendGeometry(vertexData, 9);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const ColouredVertex& vertex)
{
    // Add the vertex data in their default order into an array
    float vertexData[7];

    // Copy the vertex attributes into the array
    vertexData[0] = vertex.d_position.x;
    vertexData[1] = vertex.d_position.y;
    vertexData[2] = vertex.d_position.z;
    vertexData[3] = vertex.d_colour.getRed();
    vertexData[4] = vertex.d_colour.getGreen();
    vertexData[5] = vertex.d_colour.getBlue();
    vertexData[6] = vertex.d_colour.getAlpha();

    appendGeometry(vertexData, 7);
}

//---------------------------------------------------------------------------//
int GeometryBuffer::getVertexAttributeElementCount() const
{
    int count = 0;

    const unsigned int attribute_count = d_vertexAttributes.size();
    for (unsigned int i = 0; i < attribute_count; ++i)
    {
        switch(d_vertexAttributes.at(i))
        {
            case VAT_POSITION0:
                count += 3;
                break;
            case VAT_COLOUR0:
                count += 4;
                break;
            case VAT_TEXCOORD0:
                count += 2;
                break;
            default:
                break;
        }
    }

    return count;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::resetVertexAttributes()
{
    d_vertexAttributes.clear();
}

//---------------------------------------------------------------------------//
void GeometryBuffer::addVertexAttribute(VertexAttributeType attribute)
{
    d_vertexAttributes.push_back(attribute);
}

//---------------------------------------------------------------------------//
RefCounted<RenderMaterial> GeometryBuffer::getRenderMaterial() const
{
    return d_renderMaterial;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setRenderMaterial(RefCounted<RenderMaterial> render_material)
{
    d_renderMaterial = render_material;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setStencilRenderingActive(PolygonFillRule fill_rule)
{
    d_polygonFillRule = fill_rule;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setStencilPostRenderingVertexCount(unsigned int vertex_count)
{
    d_postStencilVertexCount = vertex_count;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setRenderEffect(RenderEffect* effect)
{
    d_effect = effect;
}

//----------------------------------------------------------------------------//
RenderEffect* GeometryBuffer::getRenderEffect()
{
    return d_effect;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setTranslation(const Vector3f& translation)
{
    if(d_translation != translation)
    {
        d_translation = translation;
        d_matrixValid = false;
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setRotation(const Quaternion& rotationQuat)
{
    if(d_rotation != rotationQuat)
    {
        d_rotation = rotationQuat;
        d_matrixValid = false;
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setScale(const Vector3f& scale)
{
    if(d_scale != scale)
    {
        d_scale = scale;
        d_matrixValid = false;
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setScale(const Vector2f& scale)
{
    setScale(Vector3f(scale, 0.f));
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setPivot(const Vector3f& p)
{
    if(d_pivot != p)
    {
        d_pivot = Vector3f(p.d_x, p.d_y, p.d_z);
        d_matrixValid = false;
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setCustomTransform(const glm::mat4x4& transformation)
{
    if(d_customTransform != transformation)
    {
        d_customTransform = transformation;
        d_matrixValid = false;
    }
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setClippingActive(const bool active)
{
    d_clippingActive = active;
}

//----------------------------------------------------------------------------//
bool GeometryBuffer::isClippingActive() const
{
    return d_clippingActive;
}

//----------------------------------------------------------------------------//
uint GeometryBuffer::getVertexCount() const
{
    return d_vertexCount;
}

//----------------------------------------------------------------------------//
void GeometryBuffer::reset()
{
    d_vertexData.clear();
    d_clippingActive = true;

    // If the used render material uses a texture we will reset it in our shader parameter bindings
    if((*d_renderMaterial).getShaderParamBindings()->getParameter("texture0") != 0)
        setTexture(0);
}

//----------------------------------------------------------------------------//
void GeometryBuffer::setTexture(Texture* texture)
{
    CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings();
    shaderParameterBindings->setParameter("texture0", texture);
}

//---------------------------------------------------------------------------//
}

<|endoftext|>