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

#include "modules/prediction/prediction.h"

#include <algorithm>
#include <cmath>
#include <vector>

#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"
#include "rosbag/bag.h"
#include "rosbag/view.h"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"

namespace apollo {
namespace prediction {

using ::apollo::common::ErrorCode;
using ::apollo::common::Status;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::adapter::AdapterManager;
using ::apollo::common::math::Vec2d;
using ::apollo::common::time::Clock;
using ::apollo::common::util::DirectoryExists;
using ::apollo::common::util::Glob;
using ::apollo::localization::LocalizationEstimate;
using ::apollo::perception::PerceptionObstacle;
using ::apollo::perception::PerceptionObstacles;

std::string Prediction::Name() const { return FLAGS_prediction_module_name; }

void GetBagFiles(const boost::filesystem::path& p,
                 std::vector<std::string>* bag_files) {
  CHECK(bag_files);
  if (!boost::filesystem::exists(p)) {
    return;
  }
  if (boost::filesystem::is_regular_file(p)) {
    const auto ext = p.extension();
    if (ext == ".bag" || ext == ".BAG") {
      AINFO << "Found bag file: " << p.c_str();
      bag_files->push_back(p.c_str());
    }
    return;
  }
  if (boost::filesystem::is_directory(p)) {
    for (auto& entry : boost::make_iterator_range(
             boost::filesystem::directory_iterator(p), {})) {
      GetBagFiles(entry.path(), bag_files);
    }
  }
}

std::vector<std::string> Prediction::LoadOfflineBags(
    const std::string& flag_input) {
  std::vector<std::string> bag_files;
  std::vector<std::string> inputs;
  apollo::common::util::split(flag_input, ';', &inputs);
  for (const auto& input : inputs) {
    GetBagFiles(boost::filesystem::path(input), &bag_files);
  }
  return bag_files;
}

Status Prediction::Init() {
  start_time_ = Clock::NowInSeconds();

  // Load prediction conf
  prediction_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
                                      &prediction_conf_)) {
    return OnError("Unable to load prediction conf file: " +
                   FLAGS_prediction_conf_file);
  } else {
    ADEBUG << "Prediction config file is loaded into: "
           << prediction_conf_.ShortDebugString();
  }

  adapter_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
                                      &adapter_conf_)) {
    return OnError("Unable to load adapter conf file: " +
                   FLAGS_prediction_adapter_config_filename);
  } else {
    ADEBUG << "Adapter config file is loaded into: "
           << adapter_conf_.ShortDebugString();
  }

  // Initialization of all managers
  AdapterManager::Init(adapter_conf_);
  ContainerManager::instance()->Init(adapter_conf_);
  EvaluatorManager::instance()->Init(prediction_conf_);
  PredictorManager::instance()->Init(prediction_conf_);

  CHECK(AdapterManager::GetLocalization()) << "Localization is not registered.";
  CHECK(AdapterManager::GetPerceptionObstacles())
      << "Perception is not registered.";

  // Set localization callback function
  AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this);
  // Set planning callback function
  AdapterManager::AddPlanningCallback(&Prediction::OnPlanning, this);
  // Set perception obstacle callback function
  AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this);

  if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    return OnError("Map cannot be loaded.");
  }

  if (FLAGS_prediction_offline_mode) {
    if (!FeatureOutput::Ready()) {
      return OnError("Feature output is not ready.");
    }
    if (FLAGS_prediction_offline_bags.empty()) {
      return Status::OK();  // use listen to ROS topic mode
    }

    auto offline_bags = LoadOfflineBags(FLAGS_prediction_offline_bags);
    if (offline_bags.empty()) {
      return OnError("Failed to find valid rosbag in provided list: " +
                     FLAGS_prediction_offline_bags);
    }
    std::vector<std::string> topics;
    topics.push_back(FLAGS_perception_obstacle_topic);
    topics.push_back(FLAGS_localization_topic);
    AINFO << "Have found " << offline_bags.size() << " rosbags to process";
    for (const auto& filename : offline_bags) {
      AINFO << "Processing: " << filename;
      rosbag::Bag bag;
      bag.open(filename, rosbag::bagmode::Read);
      rosbag::View view(bag, rosbag::TopicQuery(topics));
      for (auto it = view.begin(); it != view.end(); ++it) {
        if (it->getTopic() == FLAGS_localization_topic) {
          OnLocalization(*(it->instantiate<LocalizationEstimate>()));
        } else if (it->getTopic() == FLAGS_perception_obstacle_topic) {
          RunOnce(*(it->instantiate<PerceptionObstacles>()));
        }
      }
      bag.close();
    }
    Stop();
    ros::shutdown();
  }

  return Status::OK();
}

Status Prediction::Start() { return Status::OK(); }

void Prediction::Stop() {
  if (FLAGS_prediction_offline_mode) {
    FeatureOutput::Close();
  }
}

void Prediction::OnLocalization(const LocalizationEstimate& localization) {
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  CHECK_NOTNULL(pose_container);
  pose_container->Insert(localization);

  ADEBUG << "Received a localization message ["
         << localization.ShortDebugString() << "].";
}

void Prediction::OnPlanning(const planning::ADCTrajectory& adc_trajectory) {
  ADCTrajectoryContainer* adc_trajectory_container =
      dynamic_cast<ADCTrajectoryContainer*>(
          ContainerManager::instance()->GetContainer(
              AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(adc_trajectory_container);
  adc_trajectory_container->Insert(adc_trajectory);

  ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
         << "].";
}

void Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) {
  if (FLAGS_prediction_test_mode && FLAGS_prediction_test_duration > 0 &&
      (Clock::NowInSeconds() - start_time_ > FLAGS_prediction_test_duration)) {
    AINFO << "Prediction finished running in test mode";
    ros::shutdown();
  }

  // Update relative map if needed
  AdapterManager::Observe();
  if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    AERROR << "Relative map is empty.";
    return;
  }

  double start_timestamp = Clock::NowInSeconds();

  // Insert obstacle
  ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  CHECK_NOTNULL(obstacles_container);
  obstacles_container->Insert(perception_obstacles);

  ADEBUG << "Received a perception message ["
         << perception_obstacles.ShortDebugString() << "].";

  // Update ADC status
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(pose_container);
  CHECK_NOTNULL(adc_container);

  PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
  if (adc != nullptr) {
    obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
    double x = adc->position().x();
    double y = adc->position().y();
    ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
           << ", " << std::fixed << std::setprecision(6) << y << "].";
    Vec2d adc_position(x, y);
    adc_container->SetPosition(adc_position);
  }

  // Make evaluations
  EvaluatorManager::instance()->Run(perception_obstacles);

  // No prediction for offline mode
  if (FLAGS_prediction_offline_mode) {
    return;
  }

  // Make predictions
  PredictorManager::instance()->Run(perception_obstacles);

  auto prediction_obstacles =
      PredictorManager::instance()->prediction_obstacles();
  prediction_obstacles.set_start_timestamp(start_timestamp);
  prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());

  if (FLAGS_prediction_test_mode) {
    for (auto const& prediction_obstacle :
         prediction_obstacles.prediction_obstacle()) {
      for (auto const& trajectory : prediction_obstacle.trajectory()) {
        for (auto const& trajectory_point : trajectory.trajectory_point()) {
          if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
            AERROR << "Invalid trajectory point ["
                   << trajectory_point.ShortDebugString() << "]";
            return;
          }
        }
      }
    }
  }

  Publish(&prediction_obstacles);
}

Status Prediction::OnError(const std::string& error_msg) {
  return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}

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

#include "modules/prediction/prediction.h"

#include <algorithm>
#include <cmath>
#include <vector>

#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"
#include "rosbag/bag.h"
#include "rosbag/view.h"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"

namespace apollo {
namespace prediction {

using ::apollo::common::ErrorCode;
using ::apollo::common::Status;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::adapter::AdapterManager;
using ::apollo::common::math::Vec2d;
using ::apollo::common::time::Clock;
using ::apollo::common::util::DirectoryExists;
using ::apollo::common::util::Glob;
using ::apollo::localization::LocalizationEstimate;
using ::apollo::perception::PerceptionObstacle;
using ::apollo::perception::PerceptionObstacles;

std::string Prediction::Name() const { return FLAGS_prediction_module_name; }

void GetBagFiles(const boost::filesystem::path& p,
                 std::vector<std::string>* bag_files) {
  CHECK(bag_files);
  if (!boost::filesystem::exists(p)) {
    return;
  }
  if (boost::filesystem::is_regular_file(p)) {
    const auto ext = p.extension();
    if (ext == ".bag" || ext == ".BAG") {
      AINFO << "Found bag file: " << p.c_str();
      bag_files->push_back(p.c_str());
    }
    return;
  }
  if (boost::filesystem::is_directory(p)) {
    for (auto& entry : boost::make_iterator_range(
             boost::filesystem::directory_iterator(p), {})) {
      GetBagFiles(entry.path(), bag_files);
    }
  }
}

std::vector<std::string> Prediction::LoadOfflineBags(
    const std::string& flag_input) {
  std::vector<std::string> bag_files;
  std::vector<std::string> inputs;
  apollo::common::util::split(flag_input, ';', &inputs);
  for (const auto& input : inputs) {
    GetBagFiles(boost::filesystem::path(input), &bag_files);
  }
  std::sort(bag_files.begin(), bag_files.end());
  return bag_files;
}

Status Prediction::Init() {
  start_time_ = Clock::NowInSeconds();

  // Load prediction conf
  prediction_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
                                      &prediction_conf_)) {
    return OnError("Unable to load prediction conf file: " +
                   FLAGS_prediction_conf_file);
  } else {
    ADEBUG << "Prediction config file is loaded into: "
           << prediction_conf_.ShortDebugString();
  }

  adapter_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
                                      &adapter_conf_)) {
    return OnError("Unable to load adapter conf file: " +
                   FLAGS_prediction_adapter_config_filename);
  } else {
    ADEBUG << "Adapter config file is loaded into: "
           << adapter_conf_.ShortDebugString();
  }

  // Initialization of all managers
  AdapterManager::Init(adapter_conf_);
  ContainerManager::instance()->Init(adapter_conf_);
  EvaluatorManager::instance()->Init(prediction_conf_);
  PredictorManager::instance()->Init(prediction_conf_);

  CHECK(AdapterManager::GetLocalization()) << "Localization is not registered.";
  CHECK(AdapterManager::GetPerceptionObstacles())
      << "Perception is not registered.";

  // Set localization callback function
  AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this);
  // Set planning callback function
  AdapterManager::AddPlanningCallback(&Prediction::OnPlanning, this);
  // Set perception obstacle callback function
  AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this);

  if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    return OnError("Map cannot be loaded.");
  }

  if (FLAGS_prediction_offline_mode) {
    if (!FeatureOutput::Ready()) {
      return OnError("Feature output is not ready.");
    }
    if (FLAGS_prediction_offline_bags.empty()) {
      return Status::OK();  // use listen to ROS topic mode
    }

    auto offline_bags = LoadOfflineBags(FLAGS_prediction_offline_bags);
    if (offline_bags.empty()) {
      return OnError("Failed to find valid rosbag in provided list: " +
                     FLAGS_prediction_offline_bags);
    }
    std::vector<std::string> topics;
    topics.push_back(FLAGS_perception_obstacle_topic);
    topics.push_back(FLAGS_localization_topic);
    AINFO << "Have found " << offline_bags.size() << " rosbags to process";
    for (const auto& filename : offline_bags) {
      AINFO << "Processing: " << filename;
      rosbag::Bag bag;
      bag.open(filename, rosbag::bagmode::Read);
      rosbag::View view(bag, rosbag::TopicQuery(topics));
      for (auto it = view.begin(); it != view.end(); ++it) {
        if (it->getTopic() == FLAGS_localization_topic) {
          OnLocalization(*(it->instantiate<LocalizationEstimate>()));
        } else if (it->getTopic() == FLAGS_perception_obstacle_topic) {
          RunOnce(*(it->instantiate<PerceptionObstacles>()));
        }
      }
      bag.close();
    }
    Stop();
    ros::shutdown();
  }

  return Status::OK();
}

Status Prediction::Start() { return Status::OK(); }

void Prediction::Stop() {
  if (FLAGS_prediction_offline_mode) {
    FeatureOutput::Close();
  }
}

void Prediction::OnLocalization(const LocalizationEstimate& localization) {
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  CHECK_NOTNULL(pose_container);
  pose_container->Insert(localization);

  ADEBUG << "Received a localization message ["
         << localization.ShortDebugString() << "].";
}

void Prediction::OnPlanning(const planning::ADCTrajectory& adc_trajectory) {
  ADCTrajectoryContainer* adc_trajectory_container =
      dynamic_cast<ADCTrajectoryContainer*>(
          ContainerManager::instance()->GetContainer(
              AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(adc_trajectory_container);
  adc_trajectory_container->Insert(adc_trajectory);

  ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
         << "].";
}

void Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) {
  if (FLAGS_prediction_test_mode && FLAGS_prediction_test_duration > 0 &&
      (Clock::NowInSeconds() - start_time_ > FLAGS_prediction_test_duration)) {
    AINFO << "Prediction finished running in test mode";
    ros::shutdown();
  }

  // Update relative map if needed
  AdapterManager::Observe();
  if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    AERROR << "Relative map is empty.";
    return;
  }

  double start_timestamp = Clock::NowInSeconds();

  // Insert obstacle
  ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  CHECK_NOTNULL(obstacles_container);
  obstacles_container->Insert(perception_obstacles);

  ADEBUG << "Received a perception message ["
         << perception_obstacles.ShortDebugString() << "].";

  // Update ADC status
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(pose_container);
  CHECK_NOTNULL(adc_container);

  PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
  if (adc != nullptr) {
    obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
    double x = adc->position().x();
    double y = adc->position().y();
    ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
           << ", " << std::fixed << std::setprecision(6) << y << "].";
    Vec2d adc_position(x, y);
    adc_container->SetPosition(adc_position);
  }

  // Make evaluations
  EvaluatorManager::instance()->Run(perception_obstacles);

  // No prediction for offline mode
  if (FLAGS_prediction_offline_mode) {
    return;
  }

  // Make predictions
  PredictorManager::instance()->Run(perception_obstacles);

  auto prediction_obstacles =
      PredictorManager::instance()->prediction_obstacles();
  prediction_obstacles.set_start_timestamp(start_timestamp);
  prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());

  if (FLAGS_prediction_test_mode) {
    for (auto const& prediction_obstacle :
         prediction_obstacles.prediction_obstacle()) {
      for (auto const& trajectory : prediction_obstacle.trajectory()) {
        for (auto const& trajectory_point : trajectory.trajectory_point()) {
          if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
            AERROR << "Invalid trajectory point ["
                   << trajectory_point.ShortDebugString() << "]";
            return;
          }
        }
      }
    }
  }

  Publish(&prediction_obstacles);
}

Status Prediction::OnError(const std::string& error_msg) {
  return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}

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


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

#include "modules/prediction/prediction.h"

#include "modules/prediction/proto/prediction_obstacle.pb.h"

#include "modules/common/adapters/adapter_manager.h"
#include "modules/prediction/common/prediction_gflags.h"

namespace apollo {
namespace prediction {

using ::apollo::perception::PerceptionObstacles;
using ::apollo::common::adapter::AdapterManager;

std::string Prediction::Name() const { return FLAGS_prediction_module_name; }

apollo::common::Status Prediction::Init() {
  AdapterManager::instance()->Init();
  AdapterManager::SetPerceptionObstaclesCallback(&Prediction::OnPerception,
                                                 this);
  return apollo::common::Status::OK();
}

apollo::common::Status Prediction::Start() {
  return apollo::common::Status::OK();
}

void Prediction::Stop() {}

void Prediction::OnPerception(const PerceptionObstacles &perception_obstacles) {
  PredictionObstacles prediction_obstacles;
  AdapterManager::FillPredictionHeader(Name(),
                                       prediction_obstacles.mutable_header());
  AdapterManager::PublishPrediction(prediction_obstacles);

  ADEBUG << prediction_obstacles.ShortDebugString();
}

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

#include "modules/prediction/prediction.h"

#include "modules/prediction/proto/prediction_obstacle.pb.h"

#include "modules/common/adapters/adapter_manager.h"
#include "modules/prediction/common/prediction_gflags.h"

namespace apollo {
namespace prediction {

using ::apollo::perception::PerceptionObstacles;
using ::apollo::common::adapter::AdapterManager;

std::string Prediction::Name() const { return FLAGS_prediction_module_name; }

apollo::common::Status Prediction::Init() {
  AdapterManager::instance()->Init();
  AdapterManager::SetPerceptionObstaclesCallback(&Prediction::OnPerception,
                                                 this);
  return apollo::common::Status::OK();
}

apollo::common::Status Prediction::Start() {
  return apollo::common::Status::OK();
}

void Prediction::Stop() {}

void Prediction::OnPerception(const PerceptionObstacles &perception_obstacles) {
  PredictionObstacles prediction_obstacles;
  // TODO fulfill prediction_obstacles
  AdapterManager::FillPredictionHeader(Name(),
                                       prediction_obstacles.mutable_header());
  AdapterManager::PublishPrediction(prediction_obstacles);

  ADEBUG << prediction_obstacles.ShortDebugString();
}

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


<commit_before>#include "xinput.h"
#include "config.h"

#include <SDL/SDL.h>
#include <vector>
using namespace std;

bool active = true;
static vector<SDL_Joystick*> gamepads_sdl;

GUID GUID_NULL = {0,0,0,{0,0,0,0,0,0,0,0}};

void GamepadInitSDL()
{
	static bool inited = false;
	if (inited)
	{
		return;
	}
	inited = true;
	//init:
	SDL_Init(SDL_INIT_JOYSTICK);
	SDL_JoystickEventState(SDL_IGNORE);
	for(int i = 0; i < SDL_NumJoysticks(); ++i)
	{
		SDL_Joystick* joy = SDL_JoystickOpen(i);
		if (joy)
		{
			gamepads_sdl.push_back(joy);
		}
	}
}

void WINAPI XInputEnable(bool enable)
{
	active = enable;
}

unsigned WINAPI XInputGetAudioDeviceIds(unsigned dwUserIndex, short* pRenderDeviceId, unsigned *pRenderCount, short* pCaptureDeviceId, unsigned *pCaptureCount)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	/*
	 If there is no headset connected to the controller,
	 the function will also retrieve ERROR_SUCCESS with NULL as the values
	 for pRenderDeviceId and pCaptureDeviceId.
	 */
	*pRenderDeviceId = 0;
	*pCaptureDeviceId = 0;
	return ERROR_SUCCESS;
}

unsigned WINAPI XInputGetBatteryInformation(unsigned dwUserIndex, char devType, XINPUT_BATTERY_INFORMATION *pBatteryInformation)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	if (devType == BATTERY_DEVTYPE_GAMEPAD)
	{
		//sorry no real battery check
		pBatteryInformation->BatteryType  = BATTERY_TYPE_WIRED;
		pBatteryInformation->BatteryLevel = BATTERY_LEVEL_FULL;
	}
	else
	{
		pBatteryInformation->BatteryType  = BATTERY_TYPE_DISCONNECTED;
		pBatteryInformation->BatteryLevel = BATTERY_LEVEL_EMPTY;
	}
	return ERROR_SUCCESS;
}

unsigned WINAPI XInputGetCapabilities(unsigned dwUserIndex, unsigned dwFlags, XINPUT_CAPABILITIES *pCapabilities)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	pCapabilities->Type    = XINPUT_DEVTYPE_GAMEPAD;
	pCapabilities->SubType = XINPUT_DEVSUBTYPE_GAMEPAD;
	pCapabilities->Flags   = XINPUT_CAPS_FFB_SUPPORTED;
	pCapabilities->Gamepad.wButtons = 0xFFFF;
	pCapabilities->Gamepad.bLeftTrigger = 255;
	pCapabilities->Gamepad.bRightTrigger = 255;
	pCapabilities->Gamepad.sThumbLX = 32767;
	pCapabilities->Gamepad.sThumbLY = 32767;
	pCapabilities->Gamepad.xThumbRX = 32767;
	pCapabilities->Gamepad.xThumbRY = 32767;
	pCapabilities->Vibration.wLeftMotorSpeed  = 65535;
	pCapabilities->Vibration.wRightMotorSpeed = 65535;

	return ERROR_SUCCESS;
}

unsigned WINAPI XInputGetDSoundAudioDeviceGuids(unsigned dwUserIndex, GUID* pDSoundRenderGuid, GUID* pDSoundCaptureGuid)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	/*
	 If there is no headset connected to the controller,
	 the function also retrieves ERROR_SUCCESS with GUID_NULL as the values
	 for pDSoundRenderGuid and pDSoundCaptureGuid.
	 */
	*pDSoundRenderGuid  = GUID_NULL;
	*pDSoundCaptureGuid = GUID_NULL;
	return ERROR_SUCCESS;
}

unsigned WINAPI XInputGetKeystroke(unsigned dwUserIndex, unsigned dwReserved, XINPUT_KEYSTROKE* pKeystroke)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	//If no new keys have been pressed, the return value is ERROR_EMPTY.
	return ERROR_EMPTY;
}

unsigned WINAPI XInputGetState(unsigned dwUserIndex, XINPUT_STATE *pState)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	SDL_JoystickUpdate();
	//load data
	for(int i = 0; i < 20; ++i)
	{
		short value = 0;
		switch(settings[i].type)
		{
			case 'A':
				value = max(SDL_JoystickGetAxis(gamepads_sdl[dwUserIndex]   , settings[i].id-1)&settings[i].mask, -32767)*settings[i].scale;
				break;
			case 'H':
				value = max(SDL_JoystickGetHat(gamepads_sdl[dwUserIndex]    , settings[i].id-1)&settings[i].mask, -32767)*settings[i].scale;
				break;
			case 'B':
				value = max(SDL_JoystickGetButton(gamepads_sdl[dwUserIndex] , settings[i].id-1)&settings[i].mask, -32767)*settings[i].scale;
				break;
			default:
				//uhm
				break;
		}
		if (mapping[i].mask == 0)
		{
			*(mapping[i].addr) = value;
		}
		else if (value != 0)
		{
			*(mapping[i].addr) |= mapping[i].mask;
		}
		else
		{
			*(mapping[i].addr) &= (~mapping[i].mask);
		}
	}

	//set data
	static int dwPacketNumber = 0;
	pState->dwPacketNumber = ++dwPacketNumber;
	pState->Gamepad.wButtons     = *(reinterpret_cast<unsigned short*>(&gamepad.buttons));
	pState->Gamepad.bLeftTrigger  = gamepad.left_shoulder;
	pState->Gamepad.bRightTrigger = gamepad.right_shoulder;
	pState->Gamepad.sThumbLX      = gamepad.left_thumb_x;
	pState->Gamepad.sThumbLY      = gamepad.left_thumb_y;
	pState->Gamepad.xThumbRX      = gamepad.right_thumb_x;
	pState->Gamepad.xThumbRY      = gamepad.right_thumb_y;
	return ERROR_SUCCESS;
}

unsigned WINAPI XInputSetState(unsigned dwUserIndex, XINPUT_VIBRATION *pVibration)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	if (active)
	{
		//Sorry no vibration in SDL1.2, maybe SDL2
	}
	return ERROR_SUCCESS;
}
<commit_msg>Write default config, when no config exists<commit_after>#include "xinput.h"
#include "config.h"
#include "main.h"
#include <SDL/SDL.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <iomanip>
using namespace std;

bool active = true;
static vector<SDL_Joystick*> gamepads_sdl;

GUID GUID_NULL = {0,0,0,{0,0,0,0,0,0,0,0}};

void GamepadInitSDL()
{
	static bool inited = false;
	if (inited)
	{
		return;
	}
	inited = true;
	//init:
	SDL_Init(SDL_INIT_JOYSTICK);
	SDL_JoystickEventState(SDL_IGNORE);
	for(int i = 0; i < SDL_NumJoysticks(); ++i)
	{
		SDL_Joystick* joy = SDL_JoystickOpen(i);
		if (joy)
		{
			gamepads_sdl.push_back(joy);
		}
	}
	//load config:
	string path = string(getenv("HOME"))+"/.config/koku-xinput-wine.ini";
	ifstream iconfig(path.c_str(), ifstream::in);
	if (iconfig.is_open())
	{
		if (debug)
		{
			clog << "koku-xinput-wine: Load config \"" << path << "\"" << endl;
		}
		//load c

		iconfig.close();
	}
	else
	{
		if (debug)
		{
			clog << "koku-xinput-wine: Save default config \"" << path << "\"" << endl;
		}
		//write default config
		ofstream oconfig(path.c_str(), ifstream::out);
		if (oconfig.is_open())
		{
			oconfig << ";koku-xinput-wine config, for more information see https://github.com/KoKuToru/koku-xinput-wine" << endl;
			for(int i = 0; i < 20; ++i)
			{
				oconfig << left << setw(30) << mapping[i].name << " = " << right << settings[i].type << setfill('0') << setw(2) << int(settings[i].id);
				if (settings[i].mask != 0xFFFF)
				{
					oconfig << "&0x" << setfill('0') << setw(4) << hex << settings[i].mask << setfill(' ') << dec;
				}
				if (settings[i].scale != 1)
				{
					oconfig << "*" << settings[i].scale;
				}
				oconfig << endl;
			}
			oconfig.close();
		}else
		{
			clog << "koku-xinput-wine: couldn't open file" << endl;
		}
	}
}

void WINAPI XInputEnable(bool enable)
{
	active = enable;
}

unsigned WINAPI XInputGetAudioDeviceIds(unsigned dwUserIndex, short* pRenderDeviceId, unsigned *pRenderCount, short* pCaptureDeviceId, unsigned *pCaptureCount)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	/*
	 If there is no headset connected to the controller,
	 the function will also retrieve ERROR_SUCCESS with NULL as the values
	 for pRenderDeviceId and pCaptureDeviceId.
	 */
	*pRenderDeviceId = 0;
	*pCaptureDeviceId = 0;
	return ERROR_SUCCESS;
}

unsigned WINAPI XInputGetBatteryInformation(unsigned dwUserIndex, char devType, XINPUT_BATTERY_INFORMATION *pBatteryInformation)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	if (devType == BATTERY_DEVTYPE_GAMEPAD)
	{
		//sorry no real battery check
		pBatteryInformation->BatteryType  = BATTERY_TYPE_WIRED;
		pBatteryInformation->BatteryLevel = BATTERY_LEVEL_FULL;
	}
	else
	{
		pBatteryInformation->BatteryType  = BATTERY_TYPE_DISCONNECTED;
		pBatteryInformation->BatteryLevel = BATTERY_LEVEL_EMPTY;
	}
	return ERROR_SUCCESS;
}

unsigned WINAPI XInputGetCapabilities(unsigned dwUserIndex, unsigned dwFlags, XINPUT_CAPABILITIES *pCapabilities)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	pCapabilities->Type    = XINPUT_DEVTYPE_GAMEPAD;
	pCapabilities->SubType = XINPUT_DEVSUBTYPE_GAMEPAD;
	pCapabilities->Flags   = XINPUT_CAPS_FFB_SUPPORTED;
	pCapabilities->Gamepad.wButtons = 0xFFFF;
	pCapabilities->Gamepad.bLeftTrigger = 255;
	pCapabilities->Gamepad.bRightTrigger = 255;
	pCapabilities->Gamepad.sThumbLX = 32767;
	pCapabilities->Gamepad.sThumbLY = 32767;
	pCapabilities->Gamepad.xThumbRX = 32767;
	pCapabilities->Gamepad.xThumbRY = 32767;
	pCapabilities->Vibration.wLeftMotorSpeed  = 65535;
	pCapabilities->Vibration.wRightMotorSpeed = 65535;

	return ERROR_SUCCESS;
}

unsigned WINAPI XInputGetDSoundAudioDeviceGuids(unsigned dwUserIndex, GUID* pDSoundRenderGuid, GUID* pDSoundCaptureGuid)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	/*
	 If there is no headset connected to the controller,
	 the function also retrieves ERROR_SUCCESS with GUID_NULL as the values
	 for pDSoundRenderGuid and pDSoundCaptureGuid.
	 */
	*pDSoundRenderGuid  = GUID_NULL;
	*pDSoundCaptureGuid = GUID_NULL;
	return ERROR_SUCCESS;
}

unsigned WINAPI XInputGetKeystroke(unsigned dwUserIndex, unsigned dwReserved, XINPUT_KEYSTROKE* pKeystroke)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	//If no new keys have been pressed, the return value is ERROR_EMPTY.
	return ERROR_EMPTY;
}

unsigned WINAPI XInputGetState(unsigned dwUserIndex, XINPUT_STATE *pState)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	SDL_JoystickUpdate();
	//load data
	for(int i = 0; i < 20; ++i)
	{
		short value = 0;
		switch(settings[i].type)
		{
			case 'A':
				value = max(SDL_JoystickGetAxis(gamepads_sdl[dwUserIndex]   , settings[i].id-1)&settings[i].mask, -32767)*settings[i].scale;
				break;
			case 'H':
				value = max(SDL_JoystickGetHat(gamepads_sdl[dwUserIndex]    , settings[i].id-1)&settings[i].mask, -32767)*settings[i].scale;
				break;
			case 'B':
				value = max(SDL_JoystickGetButton(gamepads_sdl[dwUserIndex] , settings[i].id-1)&settings[i].mask, -32767)*settings[i].scale;
				break;
			default:
				//uhm
				break;
		}
		if (mapping[i].mask == 0)
		{
			*(mapping[i].addr) = value;
		}
		else if (value != 0)
		{
			*(mapping[i].addr) |= mapping[i].mask;
		}
		else
		{
			*(mapping[i].addr) &= (~mapping[i].mask);
		}
	}

	//set data
	static int dwPacketNumber = 0;
	pState->dwPacketNumber = ++dwPacketNumber;
	pState->Gamepad.wButtons     = *(reinterpret_cast<unsigned short*>(&gamepad.buttons));
	pState->Gamepad.bLeftTrigger  = gamepad.left_shoulder;
	pState->Gamepad.bRightTrigger = gamepad.right_shoulder;
	pState->Gamepad.sThumbLX      = gamepad.left_thumb_x;
	pState->Gamepad.sThumbLY      = gamepad.left_thumb_y;
	pState->Gamepad.xThumbRX      = gamepad.right_thumb_x;
	pState->Gamepad.xThumbRY      = gamepad.right_thumb_y;
	return ERROR_SUCCESS;
}

unsigned WINAPI XInputSetState(unsigned dwUserIndex, XINPUT_VIBRATION *pVibration)
{
	GamepadInitSDL();
	if (dwUserIndex >= gamepads_sdl.size())
	{
		return ERROR_DEVICE_NOT_CONNECTED;
	}

	if (active)
	{
		//Sorry no vibration in SDL1.2, maybe SDL2
	}
	return ERROR_SUCCESS;
}
<|endoftext|>


<commit_before>#include "png.h"

const unsigned char Png::header_magic[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };

size_t Png::Leanify(size_t size_leanified /*= 0*/)
{

    char *p_read, *p_write;

    // header
    p_read = fp;
    p_write = p_read - size_leanified;

    if (size_leanified)
    {
        memmove(p_write, p_read, sizeof(header_magic));
    }

    p_read += sizeof(header_magic);
    p_write += sizeof(header_magic);

    // chunk
    uint32_t chunk_type;

    do
    {

        // read chunk length
        // use bswap to convert Big-Endian to Little-Endian

        uint32_t chunk_lenth = bswap32(*(uint32_t *)p_read);

        // read chunk type
        chunk_type = *(uint32_t *)(p_read + 4);

        // judge the case of first letter
        // remove all ancillary chunks except tRNS and APNG chunks and npTc
        // tRNS has transparency information
        if (chunk_type & 0x20000000)
        {

            switch (chunk_type)
            {
            case 0x534E5274:    // tRNS     transparent
            case 0x4C546361:    // acTL     APNG
            case 0x4C546366:    // fcTL     APNG
            case 0x54416466:    // fdAT     APNG    TODO: use zopfli to recompress fdAT
            case 0x6354706E:    // npTc     Android 9Patch images (*.9.png)
                // move this chunk
                if (p_write != p_read)
                {
                    memmove(p_write, p_read, chunk_lenth + 12);
                }
                p_write += chunk_lenth + 12;
                break;

            default:
                // remove this chunk
                if (is_verbose)
                {
                    // chunk name
                    for (int i = 4; i < 8; i++)
                    {
                        std::cout << p_read[i];
                    }
                    std::cout << " chunk removed." << std::endl;
                }
                break;
            }

        }
        else
        {
            // move this chunk
            if (p_write != p_read)
            {
                memmove(p_write, p_read, chunk_lenth + 12);
            }
            p_write += chunk_lenth + 12;
        }

        // skip whole chunk
        p_read += chunk_lenth + 12;

    } while (chunk_type != 0x444E4549);     // IEND

    fp -= size_leanified;
    uint32_t png_size = p_write - fp;

    ZopfliPNGOptions zopflipng_options;
    zopflipng_options.use_zopfli = !is_fast;
    zopflipng_options.lossy_transparent = true;
    // see the switch above for information about these chunks
    zopflipng_options.keepchunks = { "acTL", "fcTL", "fdAT", "npTc" };
    zopflipng_options.num_iterations = iterations;
    zopflipng_options.num_iterations_large = iterations / 3 + 1;
    // trying both methods does not worth the time it spend
    // it's better to use the time for more iterations.
    // zopflipng_options.block_split_strategy = 3;

    const std::vector<unsigned char> origpng(fp, fp + png_size);
    std::vector<unsigned char> resultpng;

    if (!ZopfliPNGOptimize(origpng, zopflipng_options, is_verbose, &resultpng))
    {
        // only use the result PNG if it is smaller
        // sometimes the original PNG is already highly optimized
        // then maybe ZopfliPNG will produce bigger file
        if (resultpng.size() < png_size)
        {
            memcpy(fp, resultpng.data(), resultpng.size());
            return resultpng.size();
        }
    }

    return png_size;

}
<commit_msg>PNG: boundary check<commit_after>#include "png.h"

const unsigned char Png::header_magic[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };

size_t Png::Leanify(size_t size_leanified /*= 0*/)
{

    char *p_read, *p_write;

    // header
    p_read = fp;
    p_write = p_read - size_leanified;

    if (size_leanified)
    {
        memmove(p_write, p_read, sizeof(header_magic));
    }

    p_read += sizeof(header_magic);
    p_write += sizeof(header_magic);

    // chunk
    uint32_t chunk_type;

    do
    {

        // read chunk length
        // use bswap to convert Big-Endian to Little-Endian
        // 12 = length: 4 + type: 4 + crc: 4
        uint32_t chunk_lenth = bswap32(*(uint32_t *)p_read) + 12;

        // detect truncated file
        if (p_read + chunk_lenth > fp + size)
        {
            memmove(p_write, p_read, fp + size - p_read);
            p_write += fp + size - p_read;
            p_read = fp + size;
            break;
        }

        // read chunk type
        chunk_type = *(uint32_t *)(p_read + 4);

        // judge the case of first letter
        // remove all ancillary chunks except tRNS and APNG chunks and npTc
        // tRNS has transparency information
        if (chunk_type & 0x20000000)
        {

            switch (chunk_type)
            {
            case 0x534E5274:    // tRNS     transparent
            case 0x4C546361:    // acTL     APNG
            case 0x4C546366:    // fcTL     APNG
            case 0x54416466:    // fdAT     APNG    TODO: use zopfli to recompress fdAT
            case 0x6354706E:    // npTc     Android 9Patch images (*.9.png)
                break;

            default:
                // remove this chunk
                p_read += chunk_lenth;
                if (is_verbose)
                {
                    // chunk name
                    for (int i = 4; i < 8; i++)
                    {
                        std::cout << p_read[i];
                    }
                    std::cout << " chunk removed." << std::endl;
                }
                continue;
            }

        }

        // move this chunk
        if (p_write != p_read)
        {
            memmove(p_write, p_read, chunk_lenth);
        }

        // skip whole chunk
        p_write += chunk_lenth;
        p_read += chunk_lenth;

    } while (chunk_type != 0x444E4549);     // IEND

    fp -= size_leanified;
    uint32_t png_size = p_write - fp;

    ZopfliPNGOptions zopflipng_options;
    zopflipng_options.use_zopfli = !is_fast;
    zopflipng_options.lossy_transparent = true;
    // see the switch above for information about these chunks
    zopflipng_options.keepchunks = { "acTL", "fcTL", "fdAT", "npTc" };
    zopflipng_options.num_iterations = iterations;
    zopflipng_options.num_iterations_large = iterations / 3 + 1;
    // trying both methods does not worth the time it spend
    // it's better to use the time for more iterations.
    // zopflipng_options.block_split_strategy = 3;

    const std::vector<unsigned char> origpng(fp, fp + png_size);
    std::vector<unsigned char> resultpng;

    if (!ZopfliPNGOptimize(origpng, zopflipng_options, is_verbose, &resultpng))
    {
        // only use the result PNG if it is smaller
        // sometimes the original PNG is already highly optimized
        // then maybe ZopfliPNG will produce bigger file
        if (resultpng.size() < png_size)
        {
            memcpy(fp, resultpng.data(), resultpng.size());
            return resultpng.size();
        }
    }

    return png_size;

}
<|endoftext|>


<commit_before>#include "RTC_PCF8523.h"

/************************************************\
 * Name:    rtcTransfer
 * Purpose: Transfer data over TWI to an RTC
 *          Address is 0x68
 * Inputs:  reg
 *            -- value of the register to access
 *          flag
 *            -- read or write flag
 *          value
 *            -- if writing, the value to write
 * Outputs: returns a byte read from the register
 *          "reg" if doing a read.
 *
 * Pseudocode:
 *   Power on the TWI interface
 *   Begin a transmission to the RTC
 *   Write the register number
 *   If writing,
 *     write the value to write
 *   If reading,
 *     request one byte from the RTC
 *     assign the byte to value
 *   Power down the TWI interface
 *   Return value
\************************************************/

byte rtcTransfer(byte reg, byte flag, byte value)
{
  twiPowerUp();

  Wire.beginTransmission(deviceAddr);
  Wire.write(reg);
  if(flag == WRITE)
    Wire.write(value);
  Wire.endTransmission();

  if(flag == READ)
  {
    Wire.requestFrom(deviceAddr, byte(1));
    value = Wire.read();
  }

  twiPowerDown();

  return value;
}

/*********************************************\
 * Function Name: loadDateTime
 * Purpose:       Loads date and time info
 *                from RTC into Date_t struct
 * Inputs:        Pointer to Date_t struct
 * Outputs:       None (modifes Date_t struct)
 * Pseudocode:
 *  Read seconds from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Read minutes from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Read hours from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Read days from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Read months from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Read years from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Return
\*********************************************/

void loadDateTime(Date_t* Date)
{
  byte seconds  = rtcTransfer(reg_Seconds, READ, 0);
  byte second10 = seconds >> 4;
  byte second1  = seconds & 0x0F;
  Date->seconds = ((second10 * 10) + second1);

  byte minutes  = rtcTransfer(reg_Minutes, READ, 0);
  byte minute10 = minutes >> 4;
  byte minute1  = minutes & 0x0F;
  Date->minutes = ((minute10 * 10) + minute1);

  byte hours    = rtcTransfer(reg_Hours,   READ, 0);
  byte hour10   = hours >> 4;
  byte hour1    = hours & 0x0F;
  Date->hours   = ((hour10 * 10) + hour1);

  byte days     = rtcTransfer(reg_Days,    READ, 0);
  byte day10    = days >> 4;
  byte day1     = days & 0x0F;
  Date->days    = ((day10 * 10) + day1);

  byte months   = rtcTransfer(reg_Months,  READ, 0);
  byte month10  = months >> 4;
  byte month1   = months & 0x0F;
  Date->months  = ((month10 * 10) + month1);

  byte years    = rtcTransfer(reg_Years,   READ, 0);
  byte year10   = years >> 4;
  byte year1    = years & 0x0F;
  Date->years   = ((year10 * 10) + year1);

  return;
}
<commit_msg>Update RTC_PCF8523.cpp<commit_after>#include "RTC_PCF8523.h"

/************************************************\
 * Name:    rtcTransfer
 * Purpose: Transfer data over TWI to an RTC
 *          Address is 0x68
 * Inputs:  reg
 *            -- value of the register to access
 *          flag
 *            -- read or write flag
 *          value
 *            -- if writing, the value to write
 * Outputs: returns a byte read from the register
 *          "reg" if doing a read.
 *
 * Pseudocode:
 *   Power on the TWI interface
 *   Begin a transmission to the RTC
 *   Write the register number
 *   If writing,
 *     write the value to write
 *   If reading,
 *     request one byte from the RTC
 *     assign the byte to value
 *   Power down the TWI interface
 *   Return value
\************************************************/

byte rtcTransfer(byte reg, byte flag, byte value)
{
  twiPowerUp();

  Wire.beginTransmission(deviceAddr);
  Wire.write(reg);
  if(flag == WRITE)
    Wire.write(value);
  Wire.endTransmission();

  if(flag == READ)
  {
    Wire.requestFrom(deviceAddr, byte(1));
    value = Wire.read();
  }

  twiPowerDown();

  return value;
}

/*********************************************\
 * Function Name: loadDateTime
 * Purpose:       Loads date and time info
 *                from RTC into Date_t struct
 * Inputs:        Pointer to Date_t struct
 * Outputs:       None (modifes Date_t struct)
 * Pseudocode:
 *  Read seconds from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Read minutes from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Read hours from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Read days from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Read months from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Read years from RTC
 *  Convert from BCD to Binary byte
 *  Store in Date_t struct
 *
 *  Return
\*********************************************/

void loadDateTime(Date_t* Date)
{
  byte seconds  = rtcTransfer(reg_Seconds, READ, 0);
  byte second10 = seconds >> 4;
  byte second1  = seconds & 0x0F;
  Date->seconds = ((second10 * 10) + second1);

  byte minutes  = rtcTransfer(reg_Minutes, READ, 0);
  byte minute10 = minutes >> 4;
  byte minute1  = minutes & 0x0F;
  Date->minutes = ((minute10 * 10) + minute1);

  byte hours    = rtcTransfer(reg_Hours, READ, 0);
  byte hour10   = hours >> 4;
  byte hour1    = hours & 0x0F;
  Date->hours   = ((hour10 * 10) + hour1);

  byte days     = rtcTransfer(reg_Days, READ, 0);
  byte day10    = days >> 4;
  byte day1     = days & 0x0F;
  Date->days    = ((day10 * 10) + day1);

  byte months   = rtcTransfer(reg_Months, READ, 0);
  byte month10  = months >> 4;
  byte month1   = months & 0x0F;
  Date->months  = ((month10 * 10) + month1);

  byte years    = rtcTransfer(reg_Years, READ, 0);
  byte year10   = years >> 4;
  byte year1    = years & 0x0F;
  Date->years   = ((year10 * 10) + year1);

  return;
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// File: cmnserverimpl.hpp
//
// Desc: Common HTTP server - HTTP server for all application
//
// Copyright (c) 2014-2018 opencvr.com. All rights reserved.
//------------------------------------------------------------------------------
#ifndef __VSC_CMN_OAPI_SERVER_IMPL__H_
#define __VSC_CMN_OAPI_SERVER_IMPL__H_

/* Below is SSL */
OAPIServer::OAPIServer(Factory &pFactory)
:m_cmn(pFactory), m_ssl(pFactory)
{

}
OAPIServer::~OAPIServer()
{

}

CmnOAPIServer::CmnOAPIServer(Factory &pFactory)
{

}
CmnOAPIServer::~CmnOAPIServer()
{

}

void CmnOAPIServer::run()
{
        XSocket socket;

        socket.Bind(m_port);
        socket.Listen();

	while(1)
	{
		XRef<XSocket> clientSocket = socket.Accept();

		ServerSideRequest request;
		try
		{
			request.ReadRequest(clientSocket);

			const URI uri = request.GetURI();

			XString body = "<!DOCTYPE html>\
			\
			<title>OpenCVR</title>\
			\

Wellcome OpenCVR //TODO

\
			\
			";

			ServerSideResponse ssResponse;
			ssResponse.SetBody(body);
			ssResponse.SetContentType("text/html; charset=UTF-8");
			ssResponse.WriteResponse(clientSocket);
		}
		catch(XSDK::XException)
		{
		}

		clientSocket->Shutdown(SOCKET_SHUT_FLAGS);
		clientSocket->Close();
	}
}

/* Below is SSL */
CmnOAPISSLServer::CmnOAPISSLServer(Factory &pFactory)
{

}
CmnHttpsServer::~CmnOAPISSLServer()
{

}

void CmnHttpsServer::run()
{
        XSSLSocket socket;
        socket.UsePEMCertificateFile( "C:\\videodb\\ServerCRT1.crt" );
        socket.UsePEMRSAPrivateKeyFile( "C:\\videodb\\PrivateKey1.key" );

        socket.Bind(m_port);
        socket.Listen();

	while(1)
	{
		XRef<XSocket> clientSocket = socket.Accept();

		ServerSideRequest request;
		try
		{
			request.ReadRequest(clientSocket);

			const URI uri = request.GetURI();

			XString body = "<!DOCTYPE html>\
			\
			<title>OpenCVR</title>\
			\

Wellcome OpenCVR //TODO

\
			\
			";

			ServerSideResponse ssResponse;
			ssResponse.SetBody(body);
			ssResponse.SetContentType("text/html; charset=UTF-8");
			ssResponse.WriteResponse(clientSocket);
		}
		catch(XSDK::XException)
		{
		}

		clientSocket->Close();
	}
}
#endif /* __VSC_CMN_OAPI_SERVER_IMPL__H_ */

<commit_msg>fix build<commit_after>//------------------------------------------------------------------------------
// File: cmnserverimpl.hpp
//
// Desc: Common HTTP server - HTTP server for all application
//
// Copyright (c) 2014-2018 opencvr.com. All rights reserved.
//------------------------------------------------------------------------------
#ifndef __VSC_CMN_OAPI_SERVER_IMPL__H_
#define __VSC_CMN_OAPI_SERVER_IMPL__H_

/* Below is SSL */
OAPIServer::OAPIServer(Factory &pFactory)
:m_cmn(pFactory), m_ssl(pFactory)
{

}
OAPIServer::~OAPIServer()
{

}

CmnOAPIServer::CmnOAPIServer(Factory &pFactory)
{

}
CmnOAPIServer::~CmnOAPIServer()
{

}

void CmnOAPIServer::run()
{
	m_port = 9080;
        XSocket socket;

        socket.Bind(m_port);
        socket.Listen();

	while(1)
	{
		XRef<XSocket> clientSocket = socket.Accept();

		ServerSideRequest request;
		try
		{
			request.ReadRequest(clientSocket);

			const URI uri = request.GetURI();

			XString body = "<!DOCTYPE html>\
			\
			<title>OpenCVR</title>\
			\

Wellcome OpenCVR //TODO

\
			\
			";

			ServerSideResponse ssResponse;
			ssResponse.SetBody(body);
			ssResponse.SetContentType("text/html; charset=UTF-8");
			ssResponse.WriteResponse(clientSocket);
		}
		catch(XSDK::XException)
		{
		}

		clientSocket->Shutdown(SOCKET_SHUT_FLAGS);
		clientSocket->Close();
	}
}

/* Below is SSL */
CmnOAPISSLServer::CmnOAPISSLServer(Factory &pFactory)
{

}
CmnOAPISSLServer::~CmnOAPISSLServer()
{

}

void CmnOAPISSLServer::run()
{
	m_port = 9554;
	XSSLSocket socket;
	socket.UsePEMCertificateFile( "C:\\videodb\\ServerCRT1.crt" );
	socket.UsePEMRSAPrivateKeyFile( "C:\\videodb\\PrivateKey1.key" );

	socket.Bind(m_port);
	socket.Listen();

	while(1)
	{
		XRef<XSocket> clientSocket = socket.Accept();

		ServerSideRequest request;
		try
		{
			request.ReadRequest(clientSocket);

			const URI uri = request.GetURI();

			XString body = "<!DOCTYPE html>\
			\
			<title>OpenCVR</title>\
			\

Wellcome OpenCVR //TODO

\
			\
			";

			ServerSideResponse ssResponse;
			ssResponse.SetBody(body);
			ssResponse.SetContentType("text/html; charset=UTF-8");
			ssResponse.WriteResponse(clientSocket);
		}
		catch(XSDK::XException)
		{
		}

		clientSocket->Close();
	}
}
#endif /* __VSC_CMN_OAPI_SERVER_IMPL__H_ */

<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 7837 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include <mitkTestingMacros.h>

#include <mitkOverwriteSliceFilter.h>
#include <mitkExtractSliceFilter.h>
#include <mitkVtkImageMapReslice.h>
#include <mitkVtkImageIdxReslice.h>
#include <mitkImageCast.h>
#include <mitkGeometry3D.h>

#include <itkImage.h>
#include <itkImageRegionIterator.h>

#include <vtkImageData.h>
#include <vtkSmartPointer.h>

int VolumeSize = 128;

static void OverwriteByIndexShiftTest(mitk::Image* workingImage, mitk::Image* refImg)
{
	/* ============= setup plane ============*/
	int sliceindex = 55;//rand() % 32;
	bool isFrontside = true;
	bool isRotated = false;

	mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
	plane->InitializeStandardPlane(workingImage->GetGeometry(), mitk::PlaneGeometry::Transversal, sliceindex, isFrontside, isRotated);
	mitk::Point3D origin = plane->GetOrigin();
	mitk::Vector3D normal;
	normal = plane->GetNormal();
	normal.Normalize();
	origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5
	plane->SetOrigin(origin);

	/* ============= extract slice ============*/
	mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New();
	slicer->SetInput(workingImage);
	slicer->SetWorldGeometry(plane);
	slicer->SetVtkOutputRequest(true);
	slicer->Modified();
	slicer->Update();

	vtkSmartPointer<vtkImageData> slice = vtkSmartPointer<vtkImageData>::New();
	slice = slicer->GetVtkOutput();

  /* ============= extract map ============*/
	vtkSmartPointer<mitkVtkImageMapReslice> resliceMap = vtkSmartPointer<mitkVtkImageMapReslice>::New();
	mitk::ExtractSliceFilter::Pointer slicerMap = mitk::ExtractSliceFilter::New(resliceMap);
	slicerMap->SetInput(workingImage);
	slicerMap->SetWorldGeometry(plane);
	slicerMap->SetVtkOutputRequest(true);
	slicerMap->Modified();
	slicerMap->Update();

	vtkSmartPointer<vtkImageData> map = vtkSmartPointer<vtkImageData>::New();
	map = slicerMap->GetVtkOutput();
	MITK_TEST_CONDITION_REQUIRED( map->GetScalarSize() == sizeof(int), "min size of scalar");

	/* ============= overwrite slice ============*/
	mitk::OverwriteSliceFilter::Pointer overwriter = mitk::OverwriteSliceFilter::New();
	overwriter->SetInput(workingImage);
	overwriter->SetInputMap(map);
	overwriter->SetInputSlice(slice);
	overwriter->Modified();
	overwriter->Update();

	MITK_INFO<<slice->GetScalarType();
	MITK_INFO<<map->GetScalarType();

	/* ============= check ref == working ============*/
	bool areSame = true;
	mitk::Index3D id;
	id[0] = id[1] = id[2] = 0;
	for (int x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for (int y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for (int z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop;
			}
		}
	}
stop:
	MITK_TEST_CONDITION(areSame,"comparing images");

	/* ============= edit slice ============*/
	int idX = VolumeSize-20;
	int idY = VolumeSize-66;
	int idZ = 0;
	int component = 0;
	double val = 33.0;

	slice->SetScalarComponentFromDouble(idX,idY,idZ,component,val);

	/* ============= overwrite slice ============*/
	overwriter->Modified();
	overwriter->Update();

	/* ============= check ============*/
	areSame = true;

	int x,y,z;

	for ( x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for ( y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for ( z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop2;
			}
		}
	}
stop2:
	MITK_INFO << "index: [" << x << ", " << y << ", " << z << "]";
	MITK_TEST_CONDITION(x==idX && y==idY && z==sliceindex,"overwrited the right index");

}

static void OverwriteByPointerTest(mitk::Image* workingImage, mitk::Image* refImg)
{

	/* ============= setup plane ============*/
	int sliceindex = 55;//rand() % 32;
	bool isFrontside = true;
	bool isRotated = false;

	mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
	plane->InitializeStandardPlane(workingImage->GetGeometry(), mitk::PlaneGeometry::Transversal, sliceindex, isFrontside, isRotated);
	mitk::Point3D origin = plane->GetOrigin();
	mitk::Vector3D normal;
	normal = plane->GetNormal();
	normal.Normalize();
	origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5
	plane->SetOrigin(origin);

	/* ============= extract slice ============*/
	vtkSmartPointer<mitkVtkImageIdxReslice> resliceIdx = vtkSmartPointer<mitkVtkImageIdxReslice>::New();
	mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New(resliceIdx);
	slicer->SetInput(workingImage);
	slicer->SetWorldGeometry(plane);
	slicer->SetVtkOutputRequest(true);
	slicer->Modified();
	slicer->Update();

	vtkSmartPointer<vtkImageData> slice = vtkSmartPointer<vtkImageData>::New();
	slice = slicer->GetVtkOutput();

	/* ============= overwrite slice ============*/
	resliceIdx->SetOverwriteMode(true);
	resliceIdx->Modified();
	slicer->Modified();
	slicer->Update();//implicit overwrite

	/* ============= check ref == working ============*/
	bool areSame = true;
	mitk::Index3D id;
	id[0] = id[1] = id[2] = 0;
	for (int x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for (int y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for (int z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop;
			}
		}
	}
stop:
	MITK_TEST_CONDITION(areSame,"comparing images");

	/* ============= edit slice ============*/
	int idX = VolumeSize-20;
	int idY = VolumeSize-66;
	int idZ = 0;
	int component = 0;
	double val = 33.0;

	slice->SetScalarComponentFromDouble(idX,idY,idZ,component,val);

	/* ============= overwrite slice ============*/

	vtkSmartPointer<mitkVtkImageIdxReslice> resliceIdx2 = vtkSmartPointer<mitkVtkImageIdxReslice>::New();
	resliceIdx2->SetOverwriteMode(true);
	resliceIdx2->SetInputSlice(slice);
	mitk::ExtractSliceFilter::Pointer slicer2 = mitk::ExtractSliceFilter::New(resliceIdx2);
	slicer2->SetInput(workingImage);
	slicer2->SetWorldGeometry(plane);
	slicer2->SetVtkOutputRequest(true);
	slicer2->Modified();
	slicer2->Update();

	/* ============= check ============*/
	areSame = true;

	int x,y,z;

	for ( x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for ( y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for ( z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop2;
			}
		}
	}
stop2:
	MITK_INFO << "index: [" << x << ", " << y << ", " << z << "]";
	MITK_TEST_CONDITION(x==idX && y==idY && z==sliceindex,"overwrited the right index");
}

/*================ #BEGIN test main ================*/
int mitkOverwriteSliceFilterTest(int argc, char* argv[])
{

	MITK_TEST_BEGIN("mitkOverwriteSliceFilterTest")

		typedef itk::Image<unsigned short, 3> ImageType;

		typedef itk::ImageRegionConstIterator< ImageType > ImageIterator;

		ImageType::Pointer image = ImageType::New();

		ImageType::IndexType start;
		start[0] = start[1] = start[2] = 0;

		ImageType::SizeType size;
		size[0] = size[1] = size[2] = VolumeSize;

		ImageType::RegionType imgRegion;
		imgRegion.SetSize(size);
		imgRegion.SetIndex(start);

		image->SetRegions(imgRegion);
		image->SetSpacing(1.0);
		image->Allocate();

		ImageIterator imageIterator( image, image->GetLargestPossibleRegion() );
		imageIterator.GoToBegin();

		unsigned short pixelValue = 0;

		//fill the image with distinct values
		while ( !imageIterator.IsAtEnd() )
		{
			image->SetPixel(imageIterator.GetIndex(), pixelValue);
			++imageIterator;
			++pixelValue;
		}
		/* end setup itk image */

		mitk::Image::Pointer refImage;
		CastToMitkImage(image, refImage);
		mitk::Image::Pointer workingImg;
		CastToMitkImage(image, workingImg);
		OverwriteByPointerTest(workingImg, refImage);

		mitk::Image::Pointer refImage2;
		CastToMitkImage(image, refImage2);
		mitk::Image::Pointer workingImg2;
		CastToMitkImage(image, workingImg2);
		OverwriteByIndexShiftTest(workingImg2, refImage2);

	MITK_TEST_END()
}
<commit_msg>added a test for overwriting in oblique directions<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 7837 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include <mitkTestingMacros.h>

#include <mitkOverwriteSliceFilter.h>
#include <mitkExtractSliceFilter.h>
#include <mitkVtkImageMapReslice.h>
#include <mitkVtkImageIdxReslice.h>
#include <mitkImageCast.h>
#include <mitkGeometry3D.h>
#include <mitkRotationOperation.h>
#include <mitkInteractionConst.h>

#include <itkImage.h>
#include <itkImageRegionIterator.h>

#include <vtkImageData.h>
#include <vtkSmartPointer.h>

int VolumeSize = 128;

static void OverwriteByIndexShiftTest(mitk::Image* workingImage, mitk::Image* refImg)
{
	/* ============= setup plane ============*/
	int sliceindex = 55;//rand() % 32;
	bool isFrontside = true;
	bool isRotated = false;

	mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
	plane->InitializeStandardPlane(workingImage->GetGeometry(), mitk::PlaneGeometry::Transversal, sliceindex, isFrontside, isRotated);
	mitk::Point3D origin = plane->GetOrigin();
	mitk::Vector3D normal;
	normal = plane->GetNormal();
	normal.Normalize();
	origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5
	plane->SetOrigin(origin);

	/* ============= extract slice ============*/
	mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New();
	slicer->SetInput(workingImage);
	slicer->SetWorldGeometry(plane);
	slicer->SetVtkOutputRequest(true);
	slicer->Modified();
	slicer->Update();

	vtkSmartPointer<vtkImageData> slice = vtkSmartPointer<vtkImageData>::New();
	slice = slicer->GetVtkOutput();

  /* ============= extract map ============*/
	vtkSmartPointer<mitkVtkImageMapReslice> resliceMap = vtkSmartPointer<mitkVtkImageMapReslice>::New();
	mitk::ExtractSliceFilter::Pointer slicerMap = mitk::ExtractSliceFilter::New(resliceMap);
	slicerMap->SetInput(workingImage);
	slicerMap->SetWorldGeometry(plane);
	slicerMap->SetVtkOutputRequest(true);
	slicerMap->Modified();
	slicerMap->Update();

	unsigned int* map = resliceMap->GetMap();

	/* ============= overwrite slice ============*/
	mitk::OverwriteSliceFilter::Pointer overwriter = mitk::OverwriteSliceFilter::New();
	overwriter->SetInput(workingImage);
	overwriter->SetInputMap(map);
	overwriter->SetInputSlice(slice);
	overwriter->Modified();
	overwriter->Update();

	/* ============= check ref == working ============*/
	bool areSame = true;
	mitk::Index3D id;
	id[0] = id[1] = id[2] = 0;
	for (int x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for (int y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for (int z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop;
			}
		}
	}
stop:
	MITK_TEST_CONDITION(areSame,"comparing images");

	/* ============= edit slice ============*/
  int idX = std::abs(VolumeSize-59);
	int idY = std::abs(VolumeSize-23);
	int idZ = 0;
	int component = 0;
	double val = 33.0;

	slice->SetScalarComponentFromDouble(idX,idY,idZ,component,val);

	/* ============= overwrite slice ============*/
	overwriter->Modified();
	overwriter->Update();

	/* ============= check ============*/
	areSame = true;

	int x,y,z;

	for ( x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for ( y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for ( z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop2;
			}
		}
	}
stop2:
	MITK_INFO << "index: [" << x << ", " << y << ", " << z << "]";
	MITK_TEST_CONDITION(x==idX && y==idY && z==sliceindex,"overwrited the right index");

}

static void OverwriteByPointerTest(mitk::Image* workingImage, mitk::Image* refImg)
{

	/* ============= setup plane ============*/
	int sliceindex = 55;//rand() % 32;
	bool isFrontside = true;
	bool isRotated = false;

	mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
	plane->InitializeStandardPlane(workingImage->GetGeometry(), mitk::PlaneGeometry::Transversal, sliceindex, isFrontside, isRotated);
	mitk::Point3D origin = plane->GetOrigin();
	mitk::Vector3D normal;
	normal = plane->GetNormal();
	normal.Normalize();
	origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5
	plane->SetOrigin(origin);

	/* ============= extract slice ============*/
	vtkSmartPointer<mitkVtkImageIdxReslice> resliceIdx = vtkSmartPointer<mitkVtkImageIdxReslice>::New();
	mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New(resliceIdx);
	slicer->SetInput(workingImage);
	slicer->SetWorldGeometry(plane);
	slicer->SetVtkOutputRequest(true);
	slicer->Modified();
	slicer->Update();

	vtkSmartPointer<vtkImageData> slice = vtkSmartPointer<vtkImageData>::New();
	slice = slicer->GetVtkOutput();

	/* ============= overwrite slice ============*/
	resliceIdx->SetOverwriteMode(true);
	resliceIdx->Modified();
	slicer->Modified();
	slicer->Update();//implicit overwrite

	/* ============= check ref == working ============*/
	bool areSame = true;
	mitk::Index3D id;
	id[0] = id[1] = id[2] = 0;
	for (int x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for (int y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for (int z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop;
			}
		}
	}
stop:
	MITK_TEST_CONDITION(areSame,"comparing images");

	/* ============= edit slice ============*/
	int idX = std::abs(VolumeSize-59);
	int idY = std::abs(VolumeSize-23);
	int idZ = 0;
	int component = 0;
	double val = 33.0;

	slice->SetScalarComponentFromDouble(idX,idY,idZ,component,val);

	/* ============= overwrite slice ============*/

	vtkSmartPointer<mitkVtkImageIdxReslice> resliceIdx2 = vtkSmartPointer<mitkVtkImageIdxReslice>::New();
	resliceIdx2->SetOverwriteMode(true);
	resliceIdx2->SetInputSlice(slice);
	mitk::ExtractSliceFilter::Pointer slicer2 = mitk::ExtractSliceFilter::New(resliceIdx2);
	slicer2->SetInput(workingImage);
	slicer2->SetWorldGeometry(plane);
	slicer2->SetVtkOutputRequest(true);
	slicer2->Modified();
	slicer2->Update();

	/* ============= check ============*/
	areSame = true;

	int x,y,z;

	for ( x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for ( y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for ( z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop2;
			}
		}
	}
stop2:
	MITK_INFO << "index: [" << x << ", " << y << ", " << z << "]";
	MITK_TEST_CONDITION(x==idX && y==idY && z==sliceindex,"overwrited the right index");
}

static void OverwriteByPointerForObliquePlaneTest(mitk::Image* workingImage, mitk::Image* refImg)
{

/*==============TEST WITHOUT MITK CONVERTION=============================*/

		/* ============= setup plane ============*/
	int sliceindex = (int)(VolumeSize/2);//rand() % 32;
	bool isFrontside = true;
	bool isRotated = false;

	mitk::PlaneGeometry::Pointer obliquePlane = mitk::PlaneGeometry::New();
	obliquePlane->InitializeStandardPlane(workingImage->GetGeometry(), mitk::PlaneGeometry::Transversal, sliceindex, isFrontside, isRotated);
	mitk::Point3D origin = obliquePlane->GetOrigin();
	mitk::Vector3D normal;
	normal = obliquePlane->GetNormal();
	normal.Normalize();
	origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5
	obliquePlane->SetOrigin(origin);

	mitk::Vector3D rotationVector = obliquePlane->GetAxisVector(0);
	rotationVector.Normalize();

	float degree = 45.0;

	mitk::RotationOperation* op = new mitk::RotationOperation(mitk::OpROTATE, obliquePlane->GetCenter(), rotationVector, degree);
	obliquePlane->ExecuteOperation(op);
	delete op;

	/* ============= extract slice ============*/
	mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New();
	slicer->SetInput(workingImage);
	slicer->SetWorldGeometry(obliquePlane);
	slicer->SetVtkOutputRequest(true);
	slicer->Modified();
	slicer->Update();

	vtkSmartPointer<vtkImageData> slice = vtkSmartPointer<vtkImageData>::New();
	slice = slicer->GetVtkOutput();

	/* ============= overwrite slice ============*/
	vtkSmartPointer<mitkVtkImageIdxReslice> resliceIdx = vtkSmartPointer<mitkVtkImageIdxReslice>::New();
	mitk::ExtractSliceFilter::Pointer overwriter = mitk::ExtractSliceFilter::New(resliceIdx);
	resliceIdx->SetOverwriteMode(true);
	resliceIdx->SetInputSlice(slice);
	resliceIdx->Modified();
	overwriter->SetInput(workingImage);
	overwriter->SetWorldGeometry(obliquePlane);
	overwriter->SetVtkOutputRequest(true);
	overwriter->Modified();
	overwriter->Update();

	/* ============= check ref == working ============*/
	bool areSame = true;
	mitk::Index3D id;
	id[0] = id[1] = id[2] = 0;
	for (int x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for (int y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for (int z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop;
			}
		}
	}
stop:
	MITK_TEST_CONDITION(areSame,"comparing images (no mitk convertion)");

/*==============TEST WITH MITK CONVERTION=============================*/

		/* ============= extract slice ============*/
	mitk::ExtractSliceFilter::Pointer slicer2 = mitk::ExtractSliceFilter::New();
	slicer2->SetInput(workingImage);
	slicer2->SetWorldGeometry(obliquePlane);
	slicer2->Modified();
	slicer2->Update();

	mitk::Image::Pointer sliceInMitk = slicer2->GetOutput();
	vtkSmartPointer<vtkImageData> slice2 = vtkSmartPointer<vtkImageData>::New();
	slice2 = sliceInMitk->GetVtkImageData();

	/* ============= overwrite slice ============*/
	vtkSmartPointer<mitkVtkImageIdxReslice> resliceIdx2 = vtkSmartPointer<mitkVtkImageIdxReslice>::New();
	mitk::ExtractSliceFilter::Pointer overwriter2 = mitk::ExtractSliceFilter::New(resliceIdx2);
	resliceIdx2->SetOverwriteMode(true);
	resliceIdx2->SetInputSlice(slice2);
	resliceIdx2->Modified();
	overwriter2->SetInput(workingImage);
	overwriter2->SetWorldGeometry(obliquePlane);
	overwriter2->SetVtkOutputRequest(true);
	overwriter2->Modified();
	overwriter2->Update();

	/* ============= check ref == working ============*/
	areSame = true;
	id[0] = id[1] = id[2] = 0;
	for (int x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for (int y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for (int z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop2;
			}
		}
	}
stop2:
	MITK_TEST_CONDITION(areSame,"comparing images (with mitk convertion)");

/*==============TEST EDIT WITHOUT MITK CONVERTION=============================*/

	/* ============= edit slice ============*/
	int idX = std::abs(VolumeSize-59);
	int idY = std::abs(VolumeSize-23);
	int idZ = 0;
	int component = 0;
	double val = 33.0;

	slice->SetScalarComponentFromDouble(idX,idY,idZ,component,val);

	/* ============= overwrite slice ============*/

	vtkSmartPointer<mitkVtkImageIdxReslice> resliceIdx3 = vtkSmartPointer<mitkVtkImageIdxReslice>::New();
	resliceIdx3->SetOverwriteMode(true);
	resliceIdx3->SetInputSlice(slice);
	mitk::ExtractSliceFilter::Pointer overwriter3 = mitk::ExtractSliceFilter::New(resliceIdx3);
	overwriter3->SetInput(workingImage);
	overwriter3->SetWorldGeometry(obliquePlane);
	overwriter3->SetVtkOutputRequest(true);
	overwriter3->Modified();
	overwriter3->Update();

	/* ============= check ============*/
	areSame = true;

	int x,y,z;

	for ( x = 0; x < VolumeSize; ++x){
		id[0]  = x;
		for ( y = 0; y < VolumeSize; ++y){
			id[1] = y;
			for ( z = 0; z < VolumeSize; ++z){
				id[2] = z;
				areSame = refImg->GetPixelValueByIndex(id) == workingImage->GetPixelValueByIndex(id);
				if(!areSame)
					goto stop3;
			}
		}
	}
stop3:
	MITK_INFO << "index: [" << x << ", " << y << ", " << z << "]";
	//MITK_TEST_CONDITION(x==idX && y==idY && z==sliceindex,"overwrited the right index");
}

/*================ #BEGIN test main ================*/
int mitkOverwriteSliceFilterTest(int argc, char* argv[])
{

	MITK_TEST_BEGIN("mitkOverwriteSliceFilterTest")

		typedef itk::Image<unsigned short, 3> ImageType;

		typedef itk::ImageRegionConstIterator< ImageType > ImageIterator;

		ImageType::Pointer image = ImageType::New();

		ImageType::IndexType start;
		start[0] = start[1] = start[2] = 0;

		ImageType::SizeType size;
		size[0] = size[1] = size[2] = VolumeSize;

		ImageType::RegionType imgRegion;
		imgRegion.SetSize(size);
		imgRegion.SetIndex(start);

		image->SetRegions(imgRegion);
		image->SetSpacing(1.0);
		image->Allocate();

		ImageIterator imageIterator( image, image->GetLargestPossibleRegion() );
		imageIterator.GoToBegin();

		unsigned short pixelValue = 0;

		//fill the image with distinct values
		while ( !imageIterator.IsAtEnd() )
		{
			image->SetPixel(imageIterator.GetIndex(), pixelValue);
			++imageIterator;
			++pixelValue;
		}
		/* end setup itk image */

		mitk::Image::Pointer refImage;
		CastToMitkImage(image, refImage);
		mitk::Image::Pointer workingImg;
		CastToMitkImage(image, workingImg);
		OverwriteByPointerTest(workingImg, refImage);

		//mitk::Image::Pointer workingImg2;
		//CastToMitkImage(image, workingImg2);
		//OverwriteByIndexShiftTest(workingImg2, refImage);

		mitk::Image::Pointer workingImg3;
		CastToMitkImage(image, workingImg3);
		OverwriteByPointerForObliquePlaneTest(workingImg3, refImage);

	MITK_TEST_END()
}
<|endoftext|>