<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Extension port manager takes care of managing the state of
// connecting and connected ports.
#include "ceee/ie/plugin/bho/extension_port_manager.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/values.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "ceee/ie/common/chrome_frame_host.h"
#include "ceee/ie/plugin/scripting/content_script_native_api.h"
#include "chrome/browser/automation/extension_automation_constants.h"

namespace ext = extension_automation_constants;

ExtensionPortManager::ExtensionPortManager() {
}

ExtensionPortManager::~ExtensionPortManager() {
}

void ExtensionPortManager::Initialize(IChromeFrameHost* chrome_frame_host) {
  chrome_frame_host_ = chrome_frame_host;
}

void ExtensionPortManager::CloseAll(IContentScriptNativeApi* instance) {
  DCHECK(instance != NULL);

  // TODO(siggi@chromium.org): Deal better with these cases. Connected
  //    ports probably ought to be closed, and connecting ports may
  //    need to hang around until we get the connected message, to be
  //    terminated at that point.
  ConnectedPortMap::iterator it(connected_ports_.begin());
  while (it != connected_ports_.end()) {
    if (it->second.instance = instance) {
      connected_ports_.erase(it++);
    } else {
      ++it;
    }
  }

  ConnectingPortMap::iterator jt(connecting_ports_.begin());
  while (jt != connecting_ports_.end()) {
    if (jt->second.instance = instance) {
      connecting_ports_.erase(jt++);
    } else {
      ++jt;
    }
  }
}

HRESULT ExtensionPortManager::OpenChannelToExtension(
    IContentScriptNativeApi* instance, const std::string& extension,
    const std::string& channel_name, Value* tab, int cookie) {
  int connection_id = next_connection_id_++;

  // Prepare the connection request.
  scoped_ptr<DictionaryValue> dict(new DictionaryValue());
  if (dict.get() == NULL)
    return E_OUTOFMEMORY;

  dict->SetInteger(ext::kAutomationRequestIdKey, ext::OPEN_CHANNEL);
  dict->SetInteger(ext::kAutomationConnectionIdKey, connection_id);
  dict->SetString(ext::kAutomationExtensionIdKey, extension);
  dict->SetString(ext::kAutomationChannelNameKey, channel_name);
  dict->Set(ext::kAutomationTabJsonKey, tab);

  // JSON encode it.
  std::string request_json;
  base::JSONWriter::Write(dict.get(), false, &request_json);
  // And fire it off.
  HRESULT hr = PostMessageToHost(request_json,
                                 ext::kAutomationPortRequestTarget);
  if (FAILED(hr))
    return hr;

  ConnectingPort connecting_port = { instance, cookie };
  connecting_ports_[connection_id] = connecting_port;

  return S_OK;
}

HRESULT ExtensionPortManager::PostMessage(int port_id,
                                          const std::string& message) {
  // Wrap the message for sending as a port request.
  scoped_ptr<DictionaryValue> dict(new DictionaryValue());
  if (dict.get() == NULL)
    return E_OUTOFMEMORY;

  dict->SetInteger(ext::kAutomationRequestIdKey, ext::POST_MESSAGE);
  dict->SetInteger(ext::kAutomationPortIdKey, port_id);
  dict->SetString(ext::kAutomationMessageDataKey, message);

  // JSON encode it.
  std::string message_json;
  base::JSONWriter::Write(dict.get(), false, &message_json);

  // And fire it off.
  return PostMessageToHost(message_json,
                           std::string(ext::kAutomationPortRequestTarget));
}

void ExtensionPortManager::OnPortMessage(BSTR message) {
  std::string message_json = CW2A(message);
  scoped_ptr<Value> value(base::JSONReader::Read(message_json, true));
  if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) {
    NOTREACHED();
    LOG(ERROR) << "Invalid message";
    return;
  }

  DictionaryValue* dict = static_cast<DictionaryValue*>(value.get());
  int request = -1;
  if (!dict->GetInteger(ext::kAutomationRequestIdKey, &request)) {
    NOTREACHED();
    LOG(ERROR) << "Request ID missing";
    return;
  }

  if (request == ext::CHANNEL_OPENED) {
    int connection_id = -1;
    if (!dict->GetInteger(ext::kAutomationConnectionIdKey, &connection_id)) {
      NOTREACHED();
      LOG(ERROR) << "Connection ID missing";
      return;
    }

    int port_id = -1;
    if (!dict->GetInteger(ext::kAutomationPortIdKey, &port_id)) {
      NOTREACHED();
      LOG(ERROR) << "Port ID missing";
      return;
    }

    ConnectingPortMap::iterator it(connecting_ports_.find(connection_id));
    if (it == connecting_ports_.end()) {
      // TODO(siggi@chromium.org): This can happen legitimately on a
      //    race between connect and document unload. We should
      //    probably respond with a close port message here.
      LOG(ERROR) << "No such connection id " << connection_id;
      return;
    }
    ConnectingPort port = it->second;
    connecting_ports_.erase(it);
    // Did it connect successfully?
    if (port_id != -1)
      connected_ports_[port_id].instance = port.instance;

    port.instance->OnChannelOpened(port.cookie, port_id);
    return;
  } else if (request == ext::POST_MESSAGE) {
    int port_id = -1;
    if (!dict->GetInteger(ext::kAutomationPortIdKey, &port_id)) {
      NOTREACHED();
      LOG(ERROR) << "No port id";
      return;
    }

    std::string data;
    if (!dict->GetString(ext::kAutomationMessageDataKey, &data)) {
      NOTREACHED();
      LOG(ERROR) << "No message data";
      return;
    }

    ConnectedPortMap::iterator it(connected_ports_.find(port_id));
    if (it == connected_ports_.end()) {
      NOTREACHED();
      LOG(ERROR) << "No such port " << port_id;
      return;
    }

    it->second.instance->OnPostMessage(port_id, data);
    return;
  } else if (request == ext::CHANNEL_CLOSED) {
    // TODO(siggi@chromium.org): handle correctly.
    return;
  }

  NOTREACHED();
}

HRESULT ExtensionPortManager::PostMessageToHost(const std::string& message,
                                                const std::string& target) {
  // Post our message through the ChromeFrameHost. We allow queueing,
  // because we don't synchronize to the destination extension loading.
  return chrome_frame_host_->PostMessage(CComBSTR(message.c_str()),
                                         CComBSTR(target.c_str()));
}
<commit_msg>Remove another redunant DCHECK that's taken to tripping.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Extension port manager takes care of managing the state of
// connecting and connected ports.
#include "ceee/ie/plugin/bho/extension_port_manager.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/values.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "ceee/ie/common/chrome_frame_host.h"
#include "ceee/ie/plugin/scripting/content_script_native_api.h"
#include "chrome/browser/automation/extension_automation_constants.h"

namespace ext = extension_automation_constants;

ExtensionPortManager::ExtensionPortManager() {
}

ExtensionPortManager::~ExtensionPortManager() {
}

void ExtensionPortManager::Initialize(IChromeFrameHost* chrome_frame_host) {
  chrome_frame_host_ = chrome_frame_host;
}

void ExtensionPortManager::CloseAll(IContentScriptNativeApi* instance) {
  DCHECK(instance != NULL);

  // TODO(siggi@chromium.org): Deal better with these cases. Connected
  //    ports probably ought to be closed, and connecting ports may
  //    need to hang around until we get the connected message, to be
  //    terminated at that point.
  ConnectedPortMap::iterator it(connected_ports_.begin());
  while (it != connected_ports_.end()) {
    if (it->second.instance = instance) {
      connected_ports_.erase(it++);
    } else {
      ++it;
    }
  }

  ConnectingPortMap::iterator jt(connecting_ports_.begin());
  while (jt != connecting_ports_.end()) {
    if (jt->second.instance = instance) {
      connecting_ports_.erase(jt++);
    } else {
      ++jt;
    }
  }
}

HRESULT ExtensionPortManager::OpenChannelToExtension(
    IContentScriptNativeApi* instance, const std::string& extension,
    const std::string& channel_name, Value* tab, int cookie) {
  int connection_id = next_connection_id_++;

  // Prepare the connection request.
  scoped_ptr<DictionaryValue> dict(new DictionaryValue());
  if (dict.get() == NULL)
    return E_OUTOFMEMORY;

  dict->SetInteger(ext::kAutomationRequestIdKey, ext::OPEN_CHANNEL);
  dict->SetInteger(ext::kAutomationConnectionIdKey, connection_id);
  dict->SetString(ext::kAutomationExtensionIdKey, extension);
  dict->SetString(ext::kAutomationChannelNameKey, channel_name);
  dict->Set(ext::kAutomationTabJsonKey, tab);

  // JSON encode it.
  std::string request_json;
  base::JSONWriter::Write(dict.get(), false, &request_json);
  // And fire it off.
  HRESULT hr = PostMessageToHost(request_json,
                                 ext::kAutomationPortRequestTarget);
  if (FAILED(hr))
    return hr;

  ConnectingPort connecting_port = { instance, cookie };
  connecting_ports_[connection_id] = connecting_port;

  return S_OK;
}

HRESULT ExtensionPortManager::PostMessage(int port_id,
                                          const std::string& message) {
  // Wrap the message for sending as a port request.
  scoped_ptr<DictionaryValue> dict(new DictionaryValue());
  if (dict.get() == NULL)
    return E_OUTOFMEMORY;

  dict->SetInteger(ext::kAutomationRequestIdKey, ext::POST_MESSAGE);
  dict->SetInteger(ext::kAutomationPortIdKey, port_id);
  dict->SetString(ext::kAutomationMessageDataKey, message);

  // JSON encode it.
  std::string message_json;
  base::JSONWriter::Write(dict.get(), false, &message_json);

  // And fire it off.
  return PostMessageToHost(message_json,
                           std::string(ext::kAutomationPortRequestTarget));
}

void ExtensionPortManager::OnPortMessage(BSTR message) {
  std::string message_json = CW2A(message);
  scoped_ptr<Value> value(base::JSONReader::Read(message_json, true));
  if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) {
    NOTREACHED();
    LOG(ERROR) << "Invalid message";
    return;
  }

  DictionaryValue* dict = static_cast<DictionaryValue*>(value.get());
  int request = -1;
  if (!dict->GetInteger(ext::kAutomationRequestIdKey, &request)) {
    NOTREACHED();
    LOG(ERROR) << "Request ID missing";
    return;
  }

  if (request == ext::CHANNEL_OPENED) {
    int connection_id = -1;
    if (!dict->GetInteger(ext::kAutomationConnectionIdKey, &connection_id)) {
      NOTREACHED();
      LOG(ERROR) << "Connection ID missing";
      return;
    }

    int port_id = -1;
    if (!dict->GetInteger(ext::kAutomationPortIdKey, &port_id)) {
      NOTREACHED();
      LOG(ERROR) << "Port ID missing";
      return;
    }

    ConnectingPortMap::iterator it(connecting_ports_.find(connection_id));
    if (it == connecting_ports_.end()) {
      // TODO(siggi@chromium.org): This can happen legitimately on a
      //    race between connect and document unload. We should
      //    probably respond with a close port message here.
      LOG(ERROR) << "No such connection id " << connection_id;
      return;
    }
    ConnectingPort port = it->second;
    connecting_ports_.erase(it);
    // Did it connect successfully?
    if (port_id != -1)
      connected_ports_[port_id].instance = port.instance;

    port.instance->OnChannelOpened(port.cookie, port_id);
    return;
  } else if (request == ext::POST_MESSAGE) {
    int port_id = -1;
    if (!dict->GetInteger(ext::kAutomationPortIdKey, &port_id)) {
      NOTREACHED();
      LOG(ERROR) << "No port id";
      return;
    }

    std::string data;
    if (!dict->GetString(ext::kAutomationMessageDataKey, &data)) {
      NOTREACHED();
      LOG(ERROR) << "No message data";
      return;
    }

    ConnectedPortMap::iterator it(connected_ports_.find(port_id));
    if (it == connected_ports_.end()) {
      LOG(ERROR) << "No such port " << port_id;
      return;
    }

    it->second.instance->OnPostMessage(port_id, data);
    return;
  } else if (request == ext::CHANNEL_CLOSED) {
    // TODO(siggi@chromium.org): handle correctly.
    return;
  }

  NOTREACHED();
}

HRESULT ExtensionPortManager::PostMessageToHost(const std::string& message,
                                                const std::string& target) {
  // Post our message through the ChromeFrameHost. We allow queueing,
  // because we don't synchronize to the destination extension loading.
  return chrome_frame_host_->PostMessage(CComBSTR(message.c_str()),
                                         CComBSTR(target.c_str()));
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>

#include <gtest/gtest.h>

#include "sixtracklib/testlib.h"

#include "sixtracklib/_impl/definitions.h"
#include "sixtracklib/common/impl/buffer_mem.h"

/* ========================================================================= */
/* ====  Test flat-memory based minimal buffer implementation                */

TEST( C99_CommonBufferMem, InitAndReserve )
{
    using size_t = ::st_buffer_size_t;

    std::vector< unsigned char > data_buffer( size_t{ 4096 }, uint8_t{ 0 } );
    auto begin = data_buffer.data();

    constexpr size_t const SLOTS_ID     = size_t{ 3 };
    constexpr size_t const OBJECTS_ID   = size_t{ 4 };
    constexpr size_t const DATAPTRS_ID  = size_t{ 5 };
    constexpr size_t const GARBAGE_ID   = size_t{ 6 };

    size_t const slot_size       = st_BUFFER_DEFAULT_SLOT_SIZE;

    size_t max_num_objects       = size_t{ 0 };
    size_t max_num_slots         = size_t{ 0 };
    size_t max_num_dataptrs      = size_t{ 0 };
    size_t max_num_garbage_range = size_t{ 0 };

    size_t predicted_size = st_BufferMem_calculate_buffer_length( begin,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, slot_size );

    ASSERT_TRUE( predicted_size > size_t{ 0 } );

    size_t current_buffer_size   = size_t{ 0 };

    int success = st_BufferMem_init( begin, &current_buffer_size,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, data_buffer.size(), slot_size );

    ASSERT_TRUE( success == 0 );
    ASSERT_TRUE( predicted_size == current_buffer_size );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, SLOTS_ID, slot_size ) == max_num_slots );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, OBJECTS_ID, slot_size ) == max_num_objects );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, DATAPTRS_ID, slot_size ) == max_num_dataptrs );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, GARBAGE_ID, slot_size ) == max_num_garbage_range );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, SLOTS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, OBJECTS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, DATAPTRS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, GARBAGE_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_buffer_length( begin, slot_size ) ==
        current_buffer_size );

    /* -------------------------------------------------------------------- */

    max_num_objects       = size_t{ 1 };
    max_num_slots         = size_t{ 8 };
    max_num_dataptrs      = size_t{ 0 };
    max_num_garbage_range = size_t{ 0 };

    predicted_size = st_BufferMem_calculate_buffer_length( begin,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, slot_size );

    ASSERT_TRUE( predicted_size > current_buffer_size );
    ASSERT_TRUE( predicted_size < data_buffer.size()  );

    ASSERT_TRUE( st_BufferMem_can_reserve( begin, &current_buffer_size,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, data_buffer.size(), slot_size ) );

    success = st_BufferMem_reserve( begin, &current_buffer_size,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, data_buffer.size(), slot_size );

    ASSERT_TRUE( success == 0 );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, SLOTS_ID, slot_size ) == max_num_slots );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, OBJECTS_ID, slot_size ) == max_num_objects );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, DATAPTRS_ID, slot_size ) == max_num_dataptrs );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, GARBAGE_ID, slot_size ) == max_num_garbage_range );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, SLOTS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, OBJECTS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, DATAPTRS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, GARBAGE_ID, slot_size ) == size_t{ 0 } );

}

/* ------------------------------------------------------------------------- */
/* end: tests/sixtracklib/common/test_buffer_mem.cpp */
<commit_msg>tests/sixtracklib/common: expand first unittest for the NS(BufferMem) based minimal buffer<commit_after>#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>

#include <gtest/gtest.h>

#include "sixtracklib/testlib.h"

#include "sixtracklib/_impl/definitions.h"
#include "sixtracklib/common/impl/buffer_mem.h"

/* ========================================================================= */
/* ====  Test flat-memory based minimal buffer implementation                */

TEST( C99_CommonBufferMem, InitAndReserve )
{
    using size_t = ::st_buffer_size_t;

    std::vector< unsigned char > data_buffer( size_t{ 4096 }, uint8_t{ 0 } );
    auto begin = data_buffer.data();

    constexpr size_t const SLOTS_ID     = size_t{ 3 };
    constexpr size_t const OBJECTS_ID   = size_t{ 4 };
    constexpr size_t const DATAPTRS_ID  = size_t{ 5 };
    constexpr size_t const GARBAGE_ID   = size_t{ 6 };
    constexpr size_t const slot_size    = st_BUFFER_DEFAULT_SLOT_SIZE;

    size_t max_num_objects              = size_t{ 0 };
    size_t max_num_slots                = size_t{ 0 };
    size_t max_num_dataptrs             = size_t{ 0 };
    size_t max_num_garbage_range        = size_t{ 0 };

    size_t predicted_size = st_BufferMem_calculate_buffer_length( begin,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, slot_size );

    ASSERT_TRUE( predicted_size > size_t{ 0 } );

    size_t current_buffer_size  = size_t{ 0 };

    int success = st_BufferMem_init( begin, &current_buffer_size,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, data_buffer.size(), slot_size );

    ASSERT_TRUE( success == 0 );
    ASSERT_TRUE( predicted_size == current_buffer_size );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, SLOTS_ID, slot_size ) == max_num_slots );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, OBJECTS_ID, slot_size ) == max_num_objects );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, DATAPTRS_ID, slot_size ) == max_num_dataptrs );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, GARBAGE_ID, slot_size ) == max_num_garbage_range );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, SLOTS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, OBJECTS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, DATAPTRS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, GARBAGE_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_buffer_length( begin, slot_size ) ==
        current_buffer_size );

    /* -------------------------------------------------------------------- */

    max_num_objects       = size_t{ 1 };
    max_num_slots         = size_t{ 8 };
    max_num_dataptrs      = size_t{ 0 };
    max_num_garbage_range = size_t{ 0 };

    predicted_size = st_BufferMem_calculate_buffer_length( begin,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, slot_size );

    ASSERT_TRUE( predicted_size > current_buffer_size );
    ASSERT_TRUE( predicted_size < data_buffer.size()  );

    ASSERT_TRUE( st_BufferMem_can_reserve( begin, &current_buffer_size,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, data_buffer.size(), slot_size ) );

    success = st_BufferMem_reserve( begin, &current_buffer_size,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, data_buffer.size(), slot_size );

    ASSERT_TRUE( success == 0 );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, SLOTS_ID, slot_size ) == max_num_slots );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, OBJECTS_ID, slot_size ) == max_num_objects );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, DATAPTRS_ID, slot_size ) == max_num_dataptrs );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, GARBAGE_ID, slot_size ) == max_num_garbage_range );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, SLOTS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, OBJECTS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, DATAPTRS_ID, slot_size ) == size_t{ 0 } );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, GARBAGE_ID, slot_size ) == size_t{ 0 } );

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

    using address_t     = ::st_buffer_addr_t;
    using ptr_to_addr_t = address_t*;

    std::vector< address_t >  cmp_slot_values( max_num_slots, address_t{ 0 } );

    address_t cnt = address_t{ 0 };

    ptr_to_addr_t slot_it = reinterpret_cast< ptr_to_addr_t >(
        st_BufferMem_get_ptr_to_section_data( begin, SLOTS_ID, slot_size ) );

    ptr_to_addr_t slot_end = slot_it;
    std::advance( slot_end, max_num_slots );

    auto cmp_slot_it = cmp_slot_values.begin();

    for( ; slot_it != slot_end ; ++slot_it, ++cnt, ++cmp_slot_it )
    {
        *slot_it     = cnt;
        *cmp_slot_it = cnt;
    }

    st_BufferMem_set_section_num_entities(
        begin, SLOTS_ID, max_num_slots, slot_size );

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

    using type_id_t     = ::st_object_type_id_t;
    using object_t      = ::st_Object;
    using ptr_to_obj_t  = object_t*;

    std::vector< object_t > cmp_object_values( max_num_objects, object_t{} );

    ptr_to_obj_t obj_it  = reinterpret_cast< ptr_to_obj_t >(
        st_BufferMem_get_ptr_to_section_data( begin, OBJECTS_ID, slot_size ) );

    ptr_to_obj_t  obj_end = obj_it;
    std::advance( obj_end, max_num_objects );

    auto cmp_obj_it = cmp_object_values.begin();

    type_id_t  type_id = type_id_t{ 1 };
    size_t size = sizeof( address_t );

    for( ; obj_it != obj_end ; ++obj_it, ++type_id, ++cmp_obj_it )
    {
        st_Object_preset( obj_it );
        st_Object_set_type_id( obj_it, type_id );
        st_Object_set_size( obj_it, size );

        *cmp_obj_it = *obj_it;
    }

    st_BufferMem_set_section_num_entities(
        begin, OBJECTS_ID, max_num_objects, slot_size );

    /* -------------------------------------------------------------------- */

    size_t cur_num_objects  = st_BufferMem_get_section_num_entities(
        begin, OBJECTS_ID, slot_size );

    size_t cur_num_slots    = st_BufferMem_get_section_num_entities(
        begin, SLOTS_ID, slot_size );

    size_t cur_num_dataptrs = st_BufferMem_get_section_num_entities(
        begin, DATAPTRS_ID, slot_size );

    size_t cur_num_garbage_range = st_BufferMem_get_section_num_entities(
        begin, GARBAGE_ID, slot_size );

    max_num_objects       += size_t{ 2 };
    max_num_slots         += size_t{ 8 };
    max_num_dataptrs      += size_t{ 4 };
    max_num_garbage_range += size_t{ 1 };

    predicted_size = st_BufferMem_calculate_buffer_length( begin,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, slot_size );

    ASSERT_TRUE( predicted_size > current_buffer_size );
    ASSERT_TRUE( predicted_size < data_buffer.size()  );

    ASSERT_TRUE( st_BufferMem_can_reserve( begin, &current_buffer_size,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, data_buffer.size(), slot_size ) );

    success = st_BufferMem_reserve( begin, &current_buffer_size,
        max_num_objects, max_num_slots, max_num_dataptrs,
            max_num_garbage_range, data_buffer.size(), slot_size );

    ASSERT_TRUE( success == 0 );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, SLOTS_ID, slot_size ) == max_num_slots );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, OBJECTS_ID, slot_size ) == max_num_objects );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, DATAPTRS_ID, slot_size ) == max_num_dataptrs );

    ASSERT_TRUE( st_BufferMem_get_section_max_num_entities(
        begin, GARBAGE_ID, slot_size ) == max_num_garbage_range );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, SLOTS_ID, slot_size ) == cur_num_slots );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, OBJECTS_ID, slot_size ) == cur_num_objects );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, DATAPTRS_ID, slot_size ) == cur_num_dataptrs );

    ASSERT_TRUE( st_BufferMem_get_section_num_entities(
        begin, GARBAGE_ID, slot_size ) == cur_num_garbage_range );

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

    slot_it = reinterpret_cast< ptr_to_addr_t >(
        st_BufferMem_get_ptr_to_section_data( begin, SLOTS_ID, slot_size ) );

    slot_end = reinterpret_cast< ptr_to_addr_t >(
        st_BufferMem_get_ptr_to_section_end( begin, SLOTS_ID, slot_size ) );

    ASSERT_TRUE( std::distance( slot_it, slot_end ) ==
        static_cast< std::ptrdiff_t >( st_BufferMem_get_section_num_entities(
            begin, SLOTS_ID, slot_size ) ) );

    cmp_slot_it = cmp_slot_values.begin();

    for( ; slot_it != slot_end ; ++slot_it, ++cmp_slot_it )
    {
        ASSERT_TRUE( *slot_it == *cmp_slot_it );
    }

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

    obj_it  = reinterpret_cast< ptr_to_obj_t >(
        st_BufferMem_get_ptr_to_section_data( begin, OBJECTS_ID, slot_size ) );

    obj_end = reinterpret_cast< ptr_to_obj_t >(
        st_BufferMem_get_ptr_to_section_end( begin, OBJECTS_ID, slot_size ) );

    ASSERT_TRUE( std::distance( obj_it, obj_end ) ==
        static_cast< std::ptrdiff_t >( st_BufferMem_get_section_num_entities(
            begin, OBJECTS_ID, slot_size ) ) );

    cmp_obj_it = cmp_object_values.begin();

    for( ; obj_it != obj_end ; ++obj_it, ++type_id, ++cmp_obj_it )
    {
        ASSERT_TRUE( st_Object_get_type_id( obj_it ) ==
                     st_Object_get_type_id( &( *cmp_obj_it ) ) );

        ASSERT_TRUE( st_Object_get_size( obj_it ) ==
                     st_Object_get_size( &( *cmp_obj_it ) ) );

        ASSERT_TRUE( st_Object_get_begin_addr( obj_it ) ==
                     st_Object_get_begin_addr( &( *cmp_obj_it ) ) );
    }
}

/* ------------------------------------------------------------------------- */
/* end: tests/sixtracklib/common/test_buffer_mem.cpp */
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    ModelToImageRegistration2.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

// Software Guide : BeginLatex
//
//  This example illustrates the use of the \doxygen{SpatialObject} as a
//  component of the registration framework in order to perform model based
//  registration. In this case, a SpatialObject is used for generating a
//  \doxygen{PointSet} whose points are located in a narrow band around the
//  edges of the SpatialObject. This PointSet is then used in order to perform
//  PointSet to Image registration.
//
// Software Guide : EndLatex

//  Software Guide : BeginLatex
//
//  In this example we use the \doxygen{BoxSpatialObject}, that is one of the
//  simplest SpatialObjects in ITK.
//
//  \index{itk::BoxSpatialObject!header}
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
#include "itkBoxSpatialObject.h"
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  The generation of the PointSet is done in two stages. First the
//  SpatialObject is rasterized in order to generate an image containing a
//  binary mask that represents the inside and outside of the SpatialObject.
//  Second, this mask is used for computing a distance map, and the points
//  close to the boundary of the mask are taken as elements of the final
//  PointSet. The pixel values associated to the point in the PointSet are the
//  values of distance from each point to the binary mask.  The first stage is
//  performed by the \doxygen{SpatialObjectToImageFilter}, while the second
//  stage is performed witht eh \doxygen{BinaryMaskToNarrowBandPointSetFilter}
//
//  \index{itk::Spatial\-Object\-To\-Image\-Filter!header}
//  \index{itk::Binary\-Mask\-To\-Narrow\-Band\-Point\-Set\-Filter!header}
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
#include "itkSpatialObjectToImageFilter.h"
#include "itkBinaryMaskToNarrowBandPointSetFilter.h"
//  Software Guide : EndCodeSnippet

#include "itkBinaryMaskToNarrowBandPointSetFilter.h"

#include "itkImage.h"
#include "itkPointSet.h"
#include "itkPointSetToImageRegistrationMethod.h"
#include "itkMeanSquaresPointSetToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkRigid2DTransform.h"
#include "itkRegularStepGradientDescentOptimizer.h"
#include "itkResampleImageFilter.h"

#include "itkImageFileReader.h"

//
// Observer to the optimizer
//
class CommandIterationUpdate : public itk::Command
{
public:
  typedef  CommandIterationUpdate   Self;
  typedef  itk::Command             Superclass;
  typedef  itk::SmartPointer<Self>  Pointer;
  itkNewMacro( Self );
protected:
  CommandIterationUpdate() {};
public:
  typedef   itk::RegularStepGradientDescentOptimizer  OptimizerType;
  typedef   const OptimizerType   *           OptimizerPointer;

  void Execute(itk::Object *caller, const itk::EventObject & event)
    {
      Execute( (const itk::Object *)caller, event);
    }

  void Execute(const itk::Object * object, const itk::EventObject & event)
    {
      OptimizerPointer optimizer =
        dynamic_cast< OptimizerPointer >( object );
      if( typeid( event ) != typeid( itk::IterationEvent ) )
        {
        return;
        }

      OptimizerType::DerivativeType gradient = optimizer->GetGradient();
      OptimizerType::ScalesType     scales   = optimizer->GetScales();

      double magnitude2 = 0.0;

      for(unsigned int i=0; i<gradient.size(); i++)
        {
        const double fc = gradient[i] / scales[i];
        magnitude2 += fc * fc;
        }

      const double gradientMagnitude = sqrt( magnitude2 );

      std::cout << optimizer->GetCurrentIteration() << "   ";
      std::cout << optimizer->GetValue() << "   ";
      std::cout << gradientMagnitude << "   ";
      std::cout << optimizer->GetCurrentPosition() << std::endl;
    }
};

int main( int argc, char * argv [] )
{

  if( argc < 2 )
    {
    std::cerr << "Missing argument" << std::endl;
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << " movingImageFileName [initialX initialY] " << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int Dimension = 2;

  typedef unsigned char MaskPixelType;

  typedef itk::Image< MaskPixelType, Dimension > MaskImageType;

  typedef itk::BoxSpatialObject< Dimension >    SpatialObjectType;

  typedef itk::SpatialObjectToImageFilter<
                              SpatialObjectType,
                              MaskImageType
                                >   SpatialObjectToImageFilterType;

  typedef itk::PointSet< float, Dimension >       FixedPointSetType;

  typedef itk::BinaryMaskToNarrowBandPointSetFilter<
                                    MaskImageType,
                                    FixedPointSetType
                                            >  NarrowBandFilterType;

  typedef  signed short   PixelType;

  typedef itk::Image< PixelType, Dimension >  ImageType;

  typedef  unsigned char       MaskPixelType;

  typedef itk::Image< MaskPixelType, Dimension >  MaskImageType;

  typedef itk::Rigid2DTransform< double  > TransformType;

  typedef TransformType::ParametersType          ParametersType;

  typedef itk::RegularStepGradientDescentOptimizer    OptimizerType;

  typedef itk::LinearInterpolateImageFunction<
                                    ImageType,
                                    double     > LinearInterpolatorType;

  typedef itk::MeanSquaresPointSetToImageMetric<
                                    FixedPointSetType,
                                    ImageType  >   MetricType;

  typedef OptimizerType::ScalesType       OptimizerScalesType;

  typedef itk::PointSetToImageRegistrationMethod<
                                    FixedPointSetType,
                                    ImageType  >   RegistrationType;

  typedef CommandIterationUpdate    IterationObserverType;

  typedef itk::ImageFileReader< ImageType >      ImageReaderType;

  SpatialObjectType::Pointer            spatialObject;

  TransformType::Pointer                transform;

  OptimizerType::Pointer                optimizer;

  IterationObserverType::Pointer        iterationObserver;

  LinearInterpolatorType::Pointer       linearInterpolator;

  MetricType::Pointer                   metric;

  RegistrationType::Pointer             registrationMethod;

  ImageReaderType::Pointer              movingImageReader;

  FixedPointSetType::Pointer            fixedPointSet;

  ImageType::ConstPointer               movingImage;

  SpatialObjectToImageFilterType::Pointer    rasterizationFilter;

  NarrowBandFilterType::Pointer      narrowBandPointSetFilter;

  metric              = MetricType::New();
  transform           = TransformType::New();
  optimizer           = OptimizerType::New();
  linearInterpolator  = LinearInterpolatorType::New();
  registrationMethod  = RegistrationType::New();
  iterationObserver   = IterationObserverType::New();

  spatialObject            = SpatialObjectType::New();
  rasterizationFilter      = SpatialObjectToImageFilterType::New();
  narrowBandPointSetFilter = NarrowBandFilterType::New();

  movingImageReader        = ImageReaderType::New();

  movingImageReader->SetFileName( argv[1] );

  try
    {
    movingImageReader->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Problem reading Moving image from = " << std::endl;
    std::cerr << argv[1] << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  movingImage = movingImageReader->GetOutput();

  SpatialObjectType::SizeType boxSize;
  boxSize[0] = 60;
  boxSize[1] = 60;

  spatialObject->SetSize( boxSize );

  ImageType::RegionType region =
                movingImage->GetLargestPossibleRegion();

  ImageType::SizeType   imageSize = region.GetSize();

  rasterizationFilter->SetInput( spatialObject );
  rasterizationFilter->SetSize( imageSize );
  rasterizationFilter->SetSpacing( movingImage->GetSpacing() );
  rasterizationFilter->SetOrigin( movingImage->GetOrigin() );

  narrowBandPointSetFilter->SetBandWidth( 5.0 );

  narrowBandPointSetFilter->SetInput(
                    rasterizationFilter->GetOutput() );

  narrowBandPointSetFilter->Update();

  fixedPointSet = narrowBandPointSetFilter->GetOutput();

  fixedPointSet->Print( std::cout );

  registrationMethod->SetOptimizer(     optimizer     );
  registrationMethod->SetInterpolator(  linearInterpolator  );
  registrationMethod->SetMetric(        metric        );
  registrationMethod->SetTransform(     transform     );

  registrationMethod->SetMovingImage(   movingImage  );
  registrationMethod->SetFixedPointSet( fixedPointSet );

  optimizer->SetMaximumStepLength( 1.00 );
  optimizer->SetMinimumStepLength( 0.001 );
  optimizer->SetNumberOfIterations( 300 );
  optimizer->SetRelaxationFactor( 0.90 );
  optimizer->SetGradientMagnitudeTolerance( 0.05 );

  optimizer->AddObserver( itk::IterationEvent(), iterationObserver );

  TransformType::TranslationType  initialTranslation;
  initialTranslation[0] = 0.0;
  initialTranslation[1] = 0.0;

  if( argc >= 4 )
    {
    initialTranslation[0] = atof( argv[2] );
    initialTranslation[1] = atof( argv[3] );
    }

  transform->SetIdentity();
  transform->SetTranslation( initialTranslation );

  registrationMethod->SetInitialTransformParameters(
                                  transform->GetParameters() );

  OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() );

  const double translationScale = 1.0 / 1000.0;

  optimizerScales[0] = 1.0;
  optimizerScales[1] = translationScale;
  optimizerScales[2] = translationScale;

  optimizer->SetScales( optimizerScales );

  try
    {
    registrationMethod->StartRegistration();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Problem found during the registration" << std::endl;
    std::cerr << argv[1] << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  ParametersType transformParameters =
         registrationMethod->GetLastTransformParameters();

  TransformType::OutputPointType center = transform->GetCenter();

  std::cout << "Registration parameter = " << std::endl;
  std::cout << "Rotation center = " << center << std::endl;
  std::cout << "Parameters = " << transformParameters << std::endl;

  return 0;
}

<commit_msg>ENH: Replacing the MeanSquares metric with Normalized correlation.      Setting the center of rotation to be the center of the BoxSpatialObject.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    ModelToImageRegistration2.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

// Software Guide : BeginLatex
//
//  This example illustrates the use of the \doxygen{SpatialObject} as a
//  component of the registration framework in order to perform model based
//  registration. In this case, a SpatialObject is used for generating a
//  \doxygen{PointSet} whose points are located in a narrow band around the
//  edges of the SpatialObject. This PointSet is then used in order to perform
//  PointSet to Image registration.
//
// Software Guide : EndLatex

//  Software Guide : BeginLatex
//
//  In this example we use the \doxygen{BoxSpatialObject}, that is one of the
//  simplest SpatialObjects in ITK.
//
//  \index{itk::BoxSpatialObject!header}
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
#include "itkBoxSpatialObject.h"
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  The generation of the PointSet is done in two stages. First the
//  SpatialObject is rasterized in order to generate an image containing a
//  binary mask that represents the inside and outside of the SpatialObject.
//  Second, this mask is used for computing a distance map, and the points
//  close to the boundary of the mask are taken as elements of the final
//  PointSet. The pixel values associated to the point in the PointSet are the
//  values of distance from each point to the binary mask.  The first stage is
//  performed by the \doxygen{SpatialObjectToImageFilter}, while the second
//  stage is performed witht eh \doxygen{BinaryMaskToNarrowBandPointSetFilter}
//
//  \index{itk::Spatial\-Object\-To\-Image\-Filter!header}
//  \index{itk::Binary\-Mask\-To\-Narrow\-Band\-Point\-Set\-Filter!header}
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
#include "itkSpatialObjectToImageFilter.h"
#include "itkBinaryMaskToNarrowBandPointSetFilter.h"
//  Software Guide : EndCodeSnippet

#include "itkBinaryMaskToNarrowBandPointSetFilter.h"

#include "itkImage.h"
#include "itkPointSet.h"
#include "itkPointSetToImageRegistrationMethod.h"
#include "itkNormalizedCorrelationPointSetToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkRigid2DTransform.h"
#include "itkRegularStepGradientDescentOptimizer.h"
#include "itkResampleImageFilter.h"

#include "itkImageFileReader.h"

//
// Observer to the optimizer
//
class CommandIterationUpdate : public itk::Command
{
public:
  typedef  CommandIterationUpdate   Self;
  typedef  itk::Command             Superclass;
  typedef  itk::SmartPointer<Self>  Pointer;
  itkNewMacro( Self );
protected:
  CommandIterationUpdate() {};
public:
  typedef   itk::RegularStepGradientDescentOptimizer  OptimizerType;
  typedef   const OptimizerType   *           OptimizerPointer;

  void Execute(itk::Object *caller, const itk::EventObject & event)
    {
      Execute( (const itk::Object *)caller, event);
    }

  void Execute(const itk::Object * object, const itk::EventObject & event)
    {
      OptimizerPointer optimizer =
        dynamic_cast< OptimizerPointer >( object );
      if( typeid( event ) != typeid( itk::IterationEvent ) )
        {
        return;
        }

      OptimizerType::DerivativeType gradient = optimizer->GetGradient();
      OptimizerType::ScalesType     scales   = optimizer->GetScales();

      double magnitude2 = 0.0;

      for(unsigned int i=0; i<gradient.size(); i++)
        {
        const double fc = gradient[i] / scales[i];
        magnitude2 += fc * fc;
        }

      const double gradientMagnitude = sqrt( magnitude2 );

      std::cout << optimizer->GetCurrentIteration() << "   ";
      std::cout << optimizer->GetValue() << "   ";
      std::cout << gradientMagnitude << "   ";
      std::cout << optimizer->GetCurrentPosition() << std::endl;
    }
};

int main( int argc, char * argv [] )
{

  if( argc < 2 )
    {
    std::cerr << "Missing argument" << std::endl;
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << " movingImageFileName [initialX initialY] " << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int Dimension = 2;

  typedef unsigned char MaskPixelType;

  typedef itk::Image< MaskPixelType, Dimension > MaskImageType;

  typedef itk::BoxSpatialObject< Dimension >    SpatialObjectType;

  typedef itk::SpatialObjectToImageFilter<
                              SpatialObjectType,
                              MaskImageType
                                >   SpatialObjectToImageFilterType;

  typedef itk::PointSet< float, Dimension >       FixedPointSetType;

  typedef itk::BinaryMaskToNarrowBandPointSetFilter<
                                    MaskImageType,
                                    FixedPointSetType
                                            >  NarrowBandFilterType;

  typedef  signed short   PixelType;

  typedef itk::Image< PixelType, Dimension >  ImageType;

  typedef  unsigned char       MaskPixelType;

  typedef itk::Image< MaskPixelType, Dimension >  MaskImageType;

  typedef itk::Rigid2DTransform< double  > TransformType;

  typedef TransformType::ParametersType          ParametersType;

  typedef itk::RegularStepGradientDescentOptimizer    OptimizerType;

  typedef itk::LinearInterpolateImageFunction<
                                    ImageType,
                                    double     > LinearInterpolatorType;

  typedef itk::NormalizedCorrelationPointSetToImageMetric<
                                    FixedPointSetType,
                                    ImageType  >   MetricType;

  typedef OptimizerType::ScalesType       OptimizerScalesType;

  typedef itk::PointSetToImageRegistrationMethod<
                                    FixedPointSetType,
                                    ImageType  >   RegistrationType;

  typedef CommandIterationUpdate    IterationObserverType;

  typedef itk::ImageFileReader< ImageType >      ImageReaderType;

  SpatialObjectType::Pointer            spatialObject;

  TransformType::Pointer                transform;

  OptimizerType::Pointer                optimizer;

  IterationObserverType::Pointer        iterationObserver;

  LinearInterpolatorType::Pointer       linearInterpolator;

  MetricType::Pointer                   metric;

  RegistrationType::Pointer             registrationMethod;

  ImageReaderType::Pointer              movingImageReader;

  FixedPointSetType::Pointer            fixedPointSet;

  ImageType::ConstPointer               movingImage;

  SpatialObjectToImageFilterType::Pointer    rasterizationFilter;

  NarrowBandFilterType::Pointer      narrowBandPointSetFilter;

  metric              = MetricType::New();
  transform           = TransformType::New();
  optimizer           = OptimizerType::New();
  linearInterpolator  = LinearInterpolatorType::New();
  registrationMethod  = RegistrationType::New();
  iterationObserver   = IterationObserverType::New();

  spatialObject            = SpatialObjectType::New();
  rasterizationFilter      = SpatialObjectToImageFilterType::New();
  narrowBandPointSetFilter = NarrowBandFilterType::New();

  movingImageReader        = ImageReaderType::New();

  movingImageReader->SetFileName( argv[1] );

  try
    {
    movingImageReader->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Problem reading Moving image from = " << std::endl;
    std::cerr << argv[1] << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  movingImage = movingImageReader->GetOutput();

  SpatialObjectType::SizeType boxSize;
  boxSize[0] = 60.0;  // mm
  boxSize[1] = 60.0;  // mm

  spatialObject->SetSize( boxSize );

  ImageType::RegionType region =
                movingImage->GetLargestPossibleRegion();

  ImageType::SizeType   imageSize = region.GetSize();

  rasterizationFilter->SetInput( spatialObject );
  rasterizationFilter->SetSize( imageSize );
  rasterizationFilter->SetSpacing( movingImage->GetSpacing() );
  rasterizationFilter->SetOrigin( movingImage->GetOrigin() );

  narrowBandPointSetFilter->SetBandWidth( 5.0 );

  narrowBandPointSetFilter->SetInput(
                    rasterizationFilter->GetOutput() );

  narrowBandPointSetFilter->Update();

  fixedPointSet = narrowBandPointSetFilter->GetOutput();

  fixedPointSet->Print( std::cout );

  registrationMethod->SetOptimizer(     optimizer     );
  registrationMethod->SetInterpolator(  linearInterpolator  );
  registrationMethod->SetMetric(        metric        );
  registrationMethod->SetTransform(     transform     );

  registrationMethod->SetMovingImage(   movingImage  );
  registrationMethod->SetFixedPointSet( fixedPointSet );

  optimizer->SetMaximumStepLength( 1.00 );
  optimizer->SetMinimumStepLength( 0.001 );
  optimizer->SetNumberOfIterations( 300 );
  optimizer->SetRelaxationFactor( 0.90 );
  optimizer->SetGradientMagnitudeTolerance( 0.05 );
  optimizer->MinimizeOn();

  optimizer->AddObserver( itk::IterationEvent(), iterationObserver );

  TransformType::TranslationType  initialTranslation;
  initialTranslation[0] = 0.0;
  initialTranslation[1] = 0.0;

  if( argc >= 4 )
    {
    initialTranslation[0] = atof( argv[2] );
    initialTranslation[1] = atof( argv[3] );
    }

  TransformType::OutputPointType rotationCenter;
  rotationCenter[0] = boxSize[0] / 2.0;
  rotationCenter[1] = boxSize[1] / 2.0;

  transform->SetIdentity();
  transform->SetCenter( rotationCenter );
  transform->SetTranslation( initialTranslation );

  registrationMethod->SetInitialTransformParameters(
                                  transform->GetParameters() );

  OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() );

  const double translationScale = 1.0 / 1000.0;

  optimizerScales[0] = 1.0;
  optimizerScales[1] = translationScale;
  optimizerScales[2] = translationScale;

  optimizer->SetScales( optimizerScales );

  try
    {
    registrationMethod->StartRegistration();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Problem found during the registration" << std::endl;
    std::cerr << argv[1] << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  ParametersType transformParameters =
         registrationMethod->GetLastTransformParameters();

  TransformType::OutputPointType center = transform->GetCenter();

  std::cout << "Registration parameter = " << std::endl;
  std::cout << "Rotation center = " << center << std::endl;
  std::cout << "Parameters = " << transformParameters << std::endl;

  return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: configurationhelper.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2005-09-30 10:26:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

//_______________________________________________
// includes

#ifndef _COMPHELPER_CONFIGURATIONHELPER_HXX_
#include <comphelper/configurationhelper.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

//_______________________________________________
// namespace

namespace comphelper{

namespace css = ::com::sun::star;

//_______________________________________________
// definitions

//-----------------------------------------------
css::uno::Reference< css::uno::XInterface > ConfigurationHelper::openConfig(const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR   ,
                                                                            const ::rtl::OUString&                                       sPackage,
                                                                                sal_Int32                                              eMode   )
{
    css::uno::Reference< css::lang::XMultiServiceFactory > xConfigProvider(
        xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider")), css::uno::UNO_QUERY_THROW);

    ::comphelper::SequenceAsVector< css::uno::Any > lParams;
    css::beans::PropertyValue                       aParam ;

    // set root path
    aParam.Name    = ::rtl::OUString::createFromAscii("nodepath");
    aParam.Value <<= sPackage;
    lParams.push_back(css::uno::makeAny(aParam));

    // enable all locales mode
    if ((eMode & ConfigurationHelper::E_ALL_LOCALES)==ConfigurationHelper::E_ALL_LOCALES)
    {
        aParam.Name    = ::rtl::OUString::createFromAscii("locale");
        aParam.Value <<= ::rtl::OUString::createFromAscii("*");
        lParams.push_back(css::uno::makeAny(aParam));
    }

    // enable lazy writing
    sal_Bool bLazy = ((eMode & ConfigurationHelper::E_LAZY_WRITE)==ConfigurationHelper::E_LAZY_WRITE);
    aParam.Name    = ::rtl::OUString::createFromAscii("lazywrite");
    aParam.Value   = css::uno::makeAny(bLazy);
    lParams.push_back(css::uno::makeAny(aParam));

    // open it
    css::uno::Reference< css::uno::XInterface > xCFG;

    sal_Bool bReadOnly = ((eMode & ConfigurationHelper::E_READONLY)==ConfigurationHelper::E_READONLY);
    if (bReadOnly)
        xCFG = xConfigProvider->createInstanceWithArguments(
                ::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationAccess"),
                lParams.getAsConstList());
    else
        xCFG = xConfigProvider->createInstanceWithArguments(
                ::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationUpdateAccess"),
                lParams.getAsConstList());

    return xCFG;
}

//-----------------------------------------------
css::uno::Any ConfigurationHelper::readRelativeKey(const css::uno::Reference< css::uno::XInterface > xCFG    ,
                                                   const ::rtl::OUString&                            sRelPath,
                                                   const ::rtl::OUString&                            sKey    )
{
    css::uno::Reference< css::container::XHierarchicalNameAccess > xAccess(xCFG, css::uno::UNO_QUERY_THROW);

    css::uno::Reference< css::beans::XPropertySet > xProps;
    xAccess->getByHierarchicalName(sRelPath) >>= xProps;
    if (!xProps.is())
    {
        ::rtl::OUStringBuffer sMsg(256);
        sMsg.appendAscii("The requested path \"");
        sMsg.append     (sRelPath               );
        sMsg.appendAscii("\" does not exists."  );

        throw css::container::NoSuchElementException(
                    sMsg.makeStringAndClear(),
                    css::uno::Reference< css::uno::XInterface >());
    }
    return xProps->getPropertyValue(sKey);
}

//-----------------------------------------------
void ConfigurationHelper::writeRelativeKey(const css::uno::Reference< css::uno::XInterface > xCFG    ,
                                           const ::rtl::OUString&                            sRelPath,
                                           const ::rtl::OUString&                            sKey    ,
                                           const css::uno::Any&                              aValue  )
{
    css::uno::Reference< css::container::XHierarchicalNameAccess > xAccess(xCFG, css::uno::UNO_QUERY_THROW);

    css::uno::Reference< css::beans::XPropertySet > xProps;
    xAccess->getByHierarchicalName(sRelPath) >>= xProps;
    if (!xProps.is())
    {
        ::rtl::OUStringBuffer sMsg(256);
        sMsg.appendAscii("The requested path \"");
        sMsg.append     (sRelPath               );
        sMsg.appendAscii("\" does not exists."  );

        throw css::container::NoSuchElementException(
                    sMsg.makeStringAndClear(),
                    css::uno::Reference< css::uno::XInterface >());
    }
    xProps->setPropertyValue(sKey, aValue);
}

//-----------------------------------------------
css::uno::Reference< css::uno::XInterface > ConfigurationHelper::makeSureSetNodeExists(const css::uno::Reference< css::uno::XInterface > xCFG         ,
                                                                                const ::rtl::OUString&                            sRelPathToSet,
                                                                                const ::rtl::OUString&                            sSetNode     )
{
    css::uno::Reference< css::container::XHierarchicalNameAccess > xAccess(xCFG, css::uno::UNO_QUERY_THROW);
    css::uno::Reference< css::container::XNameAccess > xSet;
    xAccess->getByHierarchicalName(sRelPathToSet) >>= xSet;
    if (!xSet.is())
    {
        ::rtl::OUStringBuffer sMsg(256);
        sMsg.appendAscii("The requested path \"");
        sMsg.append     (sRelPathToSet          );
        sMsg.appendAscii("\" does not exists."  );

        throw css::container::NoSuchElementException(
                    sMsg.makeStringAndClear(),
                    css::uno::Reference< css::uno::XInterface >());
    }

    css::uno::Reference< css::uno::XInterface > xNode;
    if (xSet->hasByName(sSetNode))
        xSet->getByName(sSetNode) >>= xNode;
    else
    {
        css::uno::Reference< css::lang::XSingleServiceFactory > xNodeFactory(xSet, css::uno::UNO_QUERY_THROW);
        xNode = xNodeFactory->createInstance();
        css::uno::Reference< css::container::XNameContainer > xSetReplace(xSet, css::uno::UNO_QUERY_THROW);
        xSetReplace->insertByName(sSetNode, css::uno::makeAny(xNode));
    }

    return xNode;
}

//-----------------------------------------------
css::uno::Any ConfigurationHelper::readDirectKey(const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR   ,
                                                 const ::rtl::OUString&                                       sPackage,
                                                 const ::rtl::OUString&                                       sRelPath,
                                                 const ::rtl::OUString&                                       sKey    ,
                                                       sal_Int32                                              eMode   )
{
    css::uno::Reference< css::uno::XInterface > xCFG = ConfigurationHelper::openConfig(xSMGR, sPackage, eMode);
    return ConfigurationHelper::readRelativeKey(xCFG, sRelPath, sKey);
}

//-----------------------------------------------
void ConfigurationHelper::writeDirectKey(const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR   ,
                                         const ::rtl::OUString&                                       sPackage,
                                         const ::rtl::OUString&                                       sRelPath,
                                         const ::rtl::OUString&                                       sKey    ,
                                         const css::uno::Any&                                         aValue  ,
                                               sal_Int32                                              eMode   )
{
    css::uno::Reference< css::uno::XInterface > xCFG = ConfigurationHelper::openConfig(xSMGR, sPackage, eMode);
    ConfigurationHelper::writeRelativeKey(xCFG, sRelPath, sKey, aValue);
    ConfigurationHelper::flush(xCFG);
}

//-----------------------------------------------
void ConfigurationHelper::flush(const css::uno::Reference< css::uno::XInterface >& xCFG)
{
    css::uno::Reference< css::util::XChangesBatch > xBatch(xCFG, css::uno::UNO_QUERY_THROW);
    xBatch->commitChanges();
}

} // namespace comphelper
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.98); FILE MERGED 2006/09/01 17:19:41 kaib 1.5.98.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: configurationhelper.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 17:10:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"

//_______________________________________________
// includes

#ifndef _COMPHELPER_CONFIGURATIONHELPER_HXX_
#include <comphelper/configurationhelper.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

//_______________________________________________
// namespace

namespace comphelper{

namespace css = ::com::sun::star;

//_______________________________________________
// definitions

//-----------------------------------------------
css::uno::Reference< css::uno::XInterface > ConfigurationHelper::openConfig(const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR   ,
                                                                            const ::rtl::OUString&                                       sPackage,
                                                                                sal_Int32                                              eMode   )
{
    css::uno::Reference< css::lang::XMultiServiceFactory > xConfigProvider(
        xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider")), css::uno::UNO_QUERY_THROW);

    ::comphelper::SequenceAsVector< css::uno::Any > lParams;
    css::beans::PropertyValue                       aParam ;

    // set root path
    aParam.Name    = ::rtl::OUString::createFromAscii("nodepath");
    aParam.Value <<= sPackage;
    lParams.push_back(css::uno::makeAny(aParam));

    // enable all locales mode
    if ((eMode & ConfigurationHelper::E_ALL_LOCALES)==ConfigurationHelper::E_ALL_LOCALES)
    {
        aParam.Name    = ::rtl::OUString::createFromAscii("locale");
        aParam.Value <<= ::rtl::OUString::createFromAscii("*");
        lParams.push_back(css::uno::makeAny(aParam));
    }

    // enable lazy writing
    sal_Bool bLazy = ((eMode & ConfigurationHelper::E_LAZY_WRITE)==ConfigurationHelper::E_LAZY_WRITE);
    aParam.Name    = ::rtl::OUString::createFromAscii("lazywrite");
    aParam.Value   = css::uno::makeAny(bLazy);
    lParams.push_back(css::uno::makeAny(aParam));

    // open it
    css::uno::Reference< css::uno::XInterface > xCFG;

    sal_Bool bReadOnly = ((eMode & ConfigurationHelper::E_READONLY)==ConfigurationHelper::E_READONLY);
    if (bReadOnly)
        xCFG = xConfigProvider->createInstanceWithArguments(
                ::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationAccess"),
                lParams.getAsConstList());
    else
        xCFG = xConfigProvider->createInstanceWithArguments(
                ::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationUpdateAccess"),
                lParams.getAsConstList());

    return xCFG;
}

//-----------------------------------------------
css::uno::Any ConfigurationHelper::readRelativeKey(const css::uno::Reference< css::uno::XInterface > xCFG    ,
                                                   const ::rtl::OUString&                            sRelPath,
                                                   const ::rtl::OUString&                            sKey    )
{
    css::uno::Reference< css::container::XHierarchicalNameAccess > xAccess(xCFG, css::uno::UNO_QUERY_THROW);

    css::uno::Reference< css::beans::XPropertySet > xProps;
    xAccess->getByHierarchicalName(sRelPath) >>= xProps;
    if (!xProps.is())
    {
        ::rtl::OUStringBuffer sMsg(256);
        sMsg.appendAscii("The requested path \"");
        sMsg.append     (sRelPath               );
        sMsg.appendAscii("\" does not exists."  );

        throw css::container::NoSuchElementException(
                    sMsg.makeStringAndClear(),
                    css::uno::Reference< css::uno::XInterface >());
    }
    return xProps->getPropertyValue(sKey);
}

//-----------------------------------------------
void ConfigurationHelper::writeRelativeKey(const css::uno::Reference< css::uno::XInterface > xCFG    ,
                                           const ::rtl::OUString&                            sRelPath,
                                           const ::rtl::OUString&                            sKey    ,
                                           const css::uno::Any&                              aValue  )
{
    css::uno::Reference< css::container::XHierarchicalNameAccess > xAccess(xCFG, css::uno::UNO_QUERY_THROW);

    css::uno::Reference< css::beans::XPropertySet > xProps;
    xAccess->getByHierarchicalName(sRelPath) >>= xProps;
    if (!xProps.is())
    {
        ::rtl::OUStringBuffer sMsg(256);
        sMsg.appendAscii("The requested path \"");
        sMsg.append     (sRelPath               );
        sMsg.appendAscii("\" does not exists."  );

        throw css::container::NoSuchElementException(
                    sMsg.makeStringAndClear(),
                    css::uno::Reference< css::uno::XInterface >());
    }
    xProps->setPropertyValue(sKey, aValue);
}

//-----------------------------------------------
css::uno::Reference< css::uno::XInterface > ConfigurationHelper::makeSureSetNodeExists(const css::uno::Reference< css::uno::XInterface > xCFG         ,
                                                                                const ::rtl::OUString&                            sRelPathToSet,
                                                                                const ::rtl::OUString&                            sSetNode     )
{
    css::uno::Reference< css::container::XHierarchicalNameAccess > xAccess(xCFG, css::uno::UNO_QUERY_THROW);
    css::uno::Reference< css::container::XNameAccess > xSet;
    xAccess->getByHierarchicalName(sRelPathToSet) >>= xSet;
    if (!xSet.is())
    {
        ::rtl::OUStringBuffer sMsg(256);
        sMsg.appendAscii("The requested path \"");
        sMsg.append     (sRelPathToSet          );
        sMsg.appendAscii("\" does not exists."  );

        throw css::container::NoSuchElementException(
                    sMsg.makeStringAndClear(),
                    css::uno::Reference< css::uno::XInterface >());
    }

    css::uno::Reference< css::uno::XInterface > xNode;
    if (xSet->hasByName(sSetNode))
        xSet->getByName(sSetNode) >>= xNode;
    else
    {
        css::uno::Reference< css::lang::XSingleServiceFactory > xNodeFactory(xSet, css::uno::UNO_QUERY_THROW);
        xNode = xNodeFactory->createInstance();
        css::uno::Reference< css::container::XNameContainer > xSetReplace(xSet, css::uno::UNO_QUERY_THROW);
        xSetReplace->insertByName(sSetNode, css::uno::makeAny(xNode));
    }

    return xNode;
}

//-----------------------------------------------
css::uno::Any ConfigurationHelper::readDirectKey(const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR   ,
                                                 const ::rtl::OUString&                                       sPackage,
                                                 const ::rtl::OUString&                                       sRelPath,
                                                 const ::rtl::OUString&                                       sKey    ,
                                                       sal_Int32                                              eMode   )
{
    css::uno::Reference< css::uno::XInterface > xCFG = ConfigurationHelper::openConfig(xSMGR, sPackage, eMode);
    return ConfigurationHelper::readRelativeKey(xCFG, sRelPath, sKey);
}

//-----------------------------------------------
void ConfigurationHelper::writeDirectKey(const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR   ,
                                         const ::rtl::OUString&                                       sPackage,
                                         const ::rtl::OUString&                                       sRelPath,
                                         const ::rtl::OUString&                                       sKey    ,
                                         const css::uno::Any&                                         aValue  ,
                                               sal_Int32                                              eMode   )
{
    css::uno::Reference< css::uno::XInterface > xCFG = ConfigurationHelper::openConfig(xSMGR, sPackage, eMode);
    ConfigurationHelper::writeRelativeKey(xCFG, sRelPath, sKey, aValue);
    ConfigurationHelper::flush(xCFG);
}

//-----------------------------------------------
void ConfigurationHelper::flush(const css::uno::Reference< css::uno::XInterface >& xCFG)
{
    css::uno::Reference< css::util::XChangesBatch > xBatch(xCFG, css::uno::UNO_QUERY_THROW);
    xBatch->commitChanges();
}

} // namespace comphelper
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <chrono>
#include <sys/stat.h>

#include "Image.h"
#include "Strategy.h"
#include "LabelData.h"
#include "RGBAConversions.h"
#include "utilityCL.h"

int main(int argc, const char *argv[]) {
  // Should RVO, want them as locals.
  cl::Context context = load_context();
  cl::Device device = load_device(&context);
  cl::Program program = load_cl_program(&context, &device);
  cl::CommandQueue queue = load_queue(&context, &device);

  if (argc != 2) {
    std::cerr << "Usage: " << argv[0] << " filename" << std::endl;
    return 0;
  }
  iml::Image rgba_image(argv[1]);
  if (!rgba_image) {
    fail("Image not loaded correctly, aborting.");
  }

  {
    int err = mkdir("out", 0777);
    if (err && errno != EEXIST) {
      fail("Couldn't creat output directory 'out'.");
    }
  }

  LabelData input(&rgba_image, rgb_above_100);

  std::vector<Strategy *> strats;
  strats.push_back(new CPUOnePass);
  strats.push_back(new GPUNeighbourPropagation);
  //strats.push_back(new GPUPlusPropagation);
  strats.push_back(new GPULineEditing);
  strats.push_back(new GPUKR);

  strats[0]->copy_to(&input, &context, &program, &queue);
  strats[0]->execute();
  LabelData correct = strats[0]->copy_from();

  std::cerr << "(Name of file)                   -- (Name of strategy)         "
               "      -- (Times "
               "in microseconds)";
#ifndef NDEBUG
  std::cerr << " -- (Times with prep/cleanup)";
#endif /* NDEBUG */
  std::cerr << std::endl;

  // Ensures kernel and queue is ready, as they would only be created once in
  // a usual program.
  for (auto &strat : strats) {
    // Make warmup not be exactly the same as input for risk of
    // optimization. A clear image is safe for labeling.
    LabelData warmup(input);
    warmup.clear();

    strat->copy_to(&warmup, &context, &program, &queue);
    strat->execute();
    strat->copy_from();
  }

  for (auto *strat : strats) {
    auto startwithprep = std::chrono::high_resolution_clock::now();
    strat->copy_to(&input, &context, &program, &queue);

    auto start = std::chrono::high_resolution_clock::now();
    strat->execute();
    auto end = std::chrono::high_resolution_clock::now();

    LabelData output = strat->copy_from();
    auto endwithprep = std::chrono::high_resolution_clock::now();

    auto ms = std::chrono::duration_cast<std::chrono::microseconds>(end - start)
                  .count();
    auto mswithprep = std::chrono::duration_cast<std::chrono::microseconds>(
                          endwithprep - startwithprep)
                          .count();

    std::cout << std::left << std::setw(32) << argv[1] << " -- "
              << std::setw(32) << strat->name() << " -- " << std::setw(23)
              << ms;
#ifndef NDEBUG
    std::cout << " -- " << mswithprep;
#endif /* NDEBUG */
    std::cout << std::endl;

#ifndef NDEBUG
    if (!valid_result(&output)) {
      std::cerr << "Strategy returned an invalid labeling" << std::endl;
    }
    if (!equivalent_result(&correct, &output)) {
      std::cerr << "Strategy returned an unexpected labeling." << std::endl;
    }
#endif /* NDEBUG */

#ifndef NDEBUG
    // Write to file
    iml::Image out(output.width, output.height);
    output.copy_to_image(out.data, mod8);
    std::string outname =
        "out/" + std::string(argv[1]) + " - " + strat->name() + ".png";
    iml::writepng(outname, &out);
#endif /* NDEBUG */
  }

  for (auto *strat : strats) {
    delete strat;
  }
}
<commit_msg>More debug info, correctly write image from folder<commit_after>#include <iostream>
#include <iomanip>
#include <chrono>
#include <sys/stat.h>
#include <algorithm>

#include "Image.h"
#include "Strategy.h"
#include "LabelData.h"
#include "RGBAConversions.h"
#include "utilityCL.h"

int main(int argc, const char *argv[]) {
  // Should RVO, want them as locals.
  cl::Context context = load_context();
  cl::Device device = load_device(&context);
  cl::Program program = load_cl_program(&context, &device);
  cl::CommandQueue queue = load_queue(&context, &device);

  if (argc != 2) {
    std::cerr << "Usage: " << argv[0] << " filename" << std::endl;
    return 0;
  }
  iml::Image rgba_image(argv[1]);
  if (!rgba_image) {
    fail("Image not loaded correctly, aborting.");
  }

  {
    int err = mkdir("out", 0777);
    if (err && errno != EEXIST) {
      fail("Couldn't creat output directory 'out'.");
    }
  }

  LabelData input(&rgba_image, rgb_above_100);
  #ifndef NDEBUG
  std::cerr << "Loaded input image into a LabelData" << std::endl;
  #endif /* NDEBUG */

  std::vector<Strategy *> strats;
  strats.push_back(new CPUOnePass);
  strats.push_back(new GPUNeighbourPropagation);
  //strats.push_back(new GPUPlusPropagation);
  strats.push_back(new GPULineEditing);
  //strats.push_back(new GPUKR);

  strats[0]->copy_to(&input, &context, &program, &queue);
  strats[0]->execute();
  LabelData correct = strats[0]->copy_from();

  // Ensures kernel and queue is ready, as they would only be created once in
  // a usual program.
  for (auto &strat : strats) {
    // Make warmup not be exactly the same as input for risk of
    // optimization. A clear image is safe for labeling.
    LabelData warmup(input);
    warmup.clear();

    #ifndef NDEBUG
    std::cerr << "Warmup with: " << strat->name() << std::endl;
    #endif /* NDEBUG */
    strat->copy_to(&warmup, &context, &program, &queue);
    strat->execute();
    strat->copy_from();
  }

  std::cerr << "(Name of file)                   -- (Name of strategy)         "
               "      -- (Times "
               "in microseconds)";
#ifndef NDEBUG
  std::cerr << " -- (Times with prep/cleanup)";
#endif /* NDEBUG */
  std::cerr << std::endl;

  for (auto *strat : strats) {
    auto startwithprep = std::chrono::high_resolution_clock::now();
    strat->copy_to(&input, &context, &program, &queue);

    auto start = std::chrono::high_resolution_clock::now();
    strat->execute();
    auto end = std::chrono::high_resolution_clock::now();

    LabelData output = strat->copy_from();
    auto endwithprep = std::chrono::high_resolution_clock::now();

    auto ms = std::chrono::duration_cast<std::chrono::microseconds>(end - start)
                  .count();
    auto mswithprep = std::chrono::duration_cast<std::chrono::microseconds>(
                          endwithprep - startwithprep)
                          .count();

    std::cout << std::left << std::setw(32) << argv[1] << " -- "
              << std::setw(32) << strat->name() << " -- " << std::setw(23)
              << ms;
#ifndef NDEBUG
    std::cout << " -- " << mswithprep;
#endif /* NDEBUG */
    std::cout << std::endl;

#ifndef NDEBUG
    if (!valid_result(&output)) {
      std::cerr << "Strategy returned an invalid labeling" << std::endl;
    }
    if (!equivalent_result(&correct, &output)) {
      std::cerr << "Strategy returned an unexpected labeling." << std::endl;
    }
#endif /* NDEBUG */

#ifndef NDEBUG
    // Write to file
    iml::Image out(output.width, output.height);
    output.copy_to_image(out.data, mod8);
    std::string cleaninput = argv[1];
    std::replace( cleaninput.begin(), cleaninput.end(), '/', '-');
    std::string outname =
        "out/" + cleaninput + " - " + strat->name() + ".png";
    iml::writepng(outname, &out);
#endif /* NDEBUG */
  }

  for (auto *strat : strats) {
    delete strat;
  }
}
<|endoftext|>


<commit_before>#include "ShipInputProcessingSystem.h"
#include "InputActionsBackendSystem.h"
#include "InputBackendSystem.h"
#include "Control.h"
#include <ValueClamp.h>
#include "AntTweakBarWrapper.h"
#include "HighlightSlotPacket.h"
#include "SimpleEventPacket.h"
#include "Cursor.h"
#include <Globals.h>

ShipInputProcessingSystem::ShipInputProcessingSystem(InputBackendSystem* p_inputBackend) :
										EntitySystem( SystemType::ShipInputProcessingSystem )
{
	m_angleInputMultiplier = 1000.0f;

	m_controllerEpsilon = 0.15f;
	m_editSwitchTrigReleased = true;
	m_inputBackend = p_inputBackend;
}

void ShipInputProcessingSystem::initialize()
{
	m_actionBackend = static_cast<InputActionsBackendSystem*>(m_world->getSystem(
		SystemType::InputActionsBackendSystem));

	AntTweakBarWrapper::getInstance()->addWriteVariable( AntTweakBarWrapper::INPUT,
		"ControllerEpsilon", TwType::TW_TYPE_FLOAT, getControllerEpsilonPointer(),
		"min=0.0 max=1.0 step=0.05" );

	AntTweakBarWrapper::getInstance()->addWriteVariable( AntTweakBarWrapper::INPUT,
		"MouseSensitivity", TwType::TW_TYPE_FLOAT, &m_angleInputMultiplier, "");
}

void ShipInputProcessingSystem::process()
{
	m_inputBackend->setMouseSensitivity(m_angleInputMultiplier);
	// Fetch the status of the various input methods.
	m_processedInput = readAllInput();

	// Apply correction vectors to the analogue sticks.
	//m_processedInput.horizontalInput += static_cast<float>(m_leftStickCorrection[0]);
	//m_processedInput.verticalInput += static_cast<float>(m_leftStickCorrection[1]);

	// Apply a threshold value to eliminate some of the analogue stick noise.
// 	if( abs(m_processedInput.horizontalInput) < m_controllerEpsilon )
// 		m_processedInput.horizontalInput = 0;
//
// 	if( abs(m_processedInput.verticalInput) < m_controllerEpsilon )
// 		m_processedInput.verticalInput = 0;
//
// 	if( abs(m_processedInput.strafeHorizontalInput) < m_controllerEpsilon )
// 		m_processedInput.strafeHorizontalInput = 0;
//
// 	if( abs(m_processedInput.strafeVerticalInput) < m_controllerEpsilon )
// 		m_processedInput.strafeVerticalInput = 0;

	// updateAntTweakBar(m_processedInput);
}

void ShipInputProcessingSystem::setCursorVisibility(bool p_show)
{
	if (p_show)
		m_inputBackend->getCursor()->show();
	else
		m_inputBackend->getCursor()->hide();
}

void ShipInputProcessingSystem::resetCursor()
{
	m_inputBackend->getCursor()->reset();
}

ShipInputProcessingSystem::ResultingInputForces& ShipInputProcessingSystem::getProcessedInput()
{
	return m_processedInput;
}

float* ShipInputProcessingSystem::getControllerEpsilonPointer()
{
	return &m_controllerEpsilon;
}

ShipInputProcessingSystem::RawInputForces ShipInputProcessingSystem::readAllInput()
{
	RawInputForces input;

	// rotate

	input.hPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_TURN_RIGHT);
	saturate(input.hPositive); // ?

	input.hNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_TURN_LEFT);
	saturate(input.hNegative); // ?

	input.vPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_TURN_DOWN);
	saturate(input.vPositive); // ?

	input.vNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_TURN_UP);
	saturate(input.vNegative); // ?

	// strafe

	input.shPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_STRAFE_RIGHT);
	saturate(input.shPositive);

	input.shNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_STRAFE_LEFT);
	saturate(input.shNegative);

	input.svPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_STRAFE_UP);
	saturate(input.svPositive);

	input.svNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_STRAFE_DOWN);
	saturate(input.svNegative);

	// edit mode rotate

	input.ehPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_EDIT_MODE_RIGHT);
	saturate(input.ehPositive);

	input.ehNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_EDIT_MODE_LEFT);
	saturate(input.ehNegative);

	input.evPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_EDIT_MODE_UP);
	saturate(input.evPositive);

	input.evNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_EDIT_MODE_DOWN);
	saturate(input.evNegative);

	// roll

	input.rRight = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_ROLL_RIGHT);
	saturate(input.rRight);

	input.rLeft = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_ROLL_LEFT);
	saturate(input.rLeft);

	// thrust

	input.thrust = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_THRUST_FORWARD);
	saturate(input.thrust);

	// edit mode toggle

	// edit mode trigger
	double editModeDeltaAction = m_actionBackend->getDeltaByAction(
		InputActionsBackendSystem::Actions_TRIGGER_EDIT_MODE);
	if(editModeDeltaAction != 0.0)
		input.toggleEditMode = true;

	return input;
}
<commit_msg>Forgot one save.<commit_after>#include "ShipInputProcessingSystem.h"
#include "InputActionsBackendSystem.h"
#include "InputBackendSystem.h"
#include "Control.h"
#include <ValueClamp.h>
#include "AntTweakBarWrapper.h"
#include "HighlightSlotPacket.h"
#include "SimpleEventPacket.h"
#include "Cursor.h"
#include <Globals.h>

ShipInputProcessingSystem::ShipInputProcessingSystem(InputBackendSystem* p_inputBackend) :
										EntitySystem( SystemType::ShipInputProcessingSystem )
{
	m_angleInputMultiplier = 1000.0f;

	m_controllerEpsilon = 0.15f;
	m_editSwitchTrigReleased = true;
	m_inputBackend = p_inputBackend;
}

void ShipInputProcessingSystem::initialize()
{
	m_actionBackend = static_cast<InputActionsBackendSystem*>(m_world->getSystem(
		SystemType::InputActionsBackendSystem));

	AntTweakBarWrapper::getInstance()->addWriteVariable( AntTweakBarWrapper::INPUT,
		"ControllerEpsilon", TwType::TW_TYPE_FLOAT, getControllerEpsilonPointer(),
		"min=0.0 max=1.0 step=0.05" );

	AntTweakBarWrapper::getInstance()->addWriteVariable( AntTweakBarWrapper::INPUT,
		"MouseSensitivity", TwType::TW_TYPE_FLOAT, &m_angleInputMultiplier, "");
}

void ShipInputProcessingSystem::process()
{
	m_inputBackend->setMouseSensitivity(m_angleInputMultiplier);
	// Fetch the status of the various input methods.
	m_processedInput = readAllInput();

	// Apply correction vectors to the analogue sticks.
	//m_processedInput.horizontalInput += static_cast<float>(m_leftStickCorrection[0]);
	//m_processedInput.verticalInput += static_cast<float>(m_leftStickCorrection[1]);

	// Apply a threshold value to eliminate some of the analogue stick noise.
// 	if( abs(m_processedInput.horizontalInput) < m_controllerEpsilon )
// 		m_processedInput.horizontalInput = 0;
//
// 	if( abs(m_processedInput.verticalInput) < m_controllerEpsilon )
// 		m_processedInput.verticalInput = 0;
//
// 	if( abs(m_processedInput.strafeHorizontalInput) < m_controllerEpsilon )
// 		m_processedInput.strafeHorizontalInput = 0;
//
// 	if( abs(m_processedInput.strafeVerticalInput) < m_controllerEpsilon )
// 		m_processedInput.strafeVerticalInput = 0;

	// updateAntTweakBar(m_processedInput);
}

void ShipInputProcessingSystem::setCursorVisibility(bool p_show)
{
	if (p_show)
		m_inputBackend->getCursor()->show();
	else
		m_inputBackend->getCursor()->hide();
}

void ShipInputProcessingSystem::resetCursor()
{
	m_inputBackend->getCursor()->reset();
}

ShipInputProcessingSystem::ResultingInputForces& ShipInputProcessingSystem::getProcessedInput()
{
	return m_processedInput;
}

float* ShipInputProcessingSystem::getControllerEpsilonPointer()
{
	return &m_controllerEpsilon;
}

ShipInputProcessingSystem::RawInputForces ShipInputProcessingSystem::readAllInput()
{
	RawInputForces input;

	// rotate

	input.hPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_TURN_RIGHT);
	saturate(input.hPositive); // ?

	input.hNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_TURN_LEFT);
	saturate(input.hNegative); // ?

	input.vPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_TURN_DOWN);
	saturate(input.vPositive); // ?

	input.vNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_TURN_UP);
	saturate(input.vNegative); // ?

	// strafe

	input.shPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_STRAFE_RIGHT);
	saturate(input.shPositive);

	input.shNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_STRAFE_LEFT);
	saturate(input.shNegative);

	input.svPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_STRAFE_UP);
	saturate(input.svPositive);

	input.svNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_STRAFE_DOWN);
	saturate(input.svNegative);

	// edit mode rotate

	input.ehPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_EDIT_MODE_RIGHT);
	saturate(input.ehPositive);

	input.ehNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_EDIT_MODE_LEFT);
	saturate(input.ehNegative);

	input.evPositive = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_EDIT_MODE_UP);
	saturate(input.evPositive);

	input.evNegative = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_EDIT_MODE_DOWN);
	saturate(input.evNegative);

	// roll

	input.rRight = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_ROLL_RIGHT);
	saturate(input.rRight);

	input.rLeft = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_ROLL_LEFT);
	saturate(input.rLeft);

	// thrust

	input.thrust = m_actionBackend->getStatusByAction(
		InputActionsBackendSystem::Actions_THRUST_FORWARD);
	saturate(input.thrust);

	// edit mode toggle
	double editModeToggle = m_actionBackend->getDeltaByAction(

	// edit mode trigger
	double editModeTrigger = m_actionBackend->getDeltaByAction(
		InputActionsBackendSystem::Actions_TRIGGER_EDIT_MODE);
	if(editModeTrigger != 0.0)
		input.toggleEditMode = true;

	return input;
}
<|endoftext|>